@north-light/cli 0.3.662 → 0.3.664

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 (35) hide show
  1. package/dist/clients/attach/viewer.js +1 -1
  2. package/dist/core/canvas/schema-pg/020-machine-calls-status-all.sql +8 -0
  3. package/dist/core/canvas/schema-version.d.ts +1 -1
  4. package/dist/core/canvas/schema-version.js +1 -1
  5. package/dist/core/grants/mirror.d.ts +16 -1
  6. package/dist/core/grants/mirror.js +7 -2
  7. package/dist/core/packages/directory-sync.js +4 -4
  8. package/dist/core/providers/bundles.js +2 -2
  9. package/dist/core/runtime/runner/machine/call.js +2 -2
  10. package/dist/core/runtime/runner/machine/executor.d.ts +7 -0
  11. package/dist/core/runtime/runner/machine/executor.js +1 -1
  12. package/dist/core/runtime/runner/machine/machine-executor.test.js +2 -2
  13. package/dist/core/runtime/runner/machine/ops.d.ts +14 -1
  14. package/dist/core/runtime/runner/machine/ops.js +1 -1
  15. package/dist/daemon/broker-signals/bus.d.ts +3 -2
  16. package/dist/daemon/broker-signals/bus.js +1 -1
  17. package/dist/daemon/crtrd.d.ts +4 -0
  18. package/dist/daemon/crtrd.js +12 -12
  19. package/dist/daemon/machine-daemon.js +1 -1
  20. package/dist/daemon/machine-link/client.d.ts +9 -0
  21. package/dist/daemon/machine-link/client.js +1 -1
  22. package/dist/daemon/machine-link/frames.d.ts +8 -0
  23. package/dist/daemon/machine-link/frames.js +1 -1
  24. package/dist/daemon/machine-link/holder.d.ts +11 -0
  25. package/dist/daemon/machine-link/holder.js +4 -4
  26. package/dist/daemon/peer/ingress.js +1 -1
  27. package/dist/daemon/reconcilers/grant-effects.d.ts +5 -4
  28. package/dist/daemon/reconcilers/grant-effects.js +1 -1
  29. package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.d.ts +5 -0
  30. package/dist/daemon/reconcilers/node-lifecycle/machine-sweep.js +4 -0
  31. package/dist/daemon/reconcilers/node-lifecycle/tick.d.ts +3 -0
  32. package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
  33. package/package.json +2 -2
  34. package/packages/crouter-identity/package.json +1 -1
  35. package/runtime.lock.json +13 -13
@@ -95,7 +95,7 @@ To prepare for this change:
95
95
  - If you want libpq compatibility now, use 'uselibpqcompat=true&sslmode=${t}'
96
96
 
97
97
  See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode definitions.`))}ott.exports=oB;oB.parse=oB;oB.toClientConfig=itt;oB.parseIntoClientConfig=BTn});var Zge=Q((xbi,utt)=>{"use strict";var DTn=J("dns"),ctt=UF(),att=stt().parse,hu=function(t,e,n){return e[t]?e[t]:(n===void 0?n=process.env["PG"+t.toUpperCase()]:n===!1||(n=process.env[n]),n||ctt[t])},MTn=function(){switch(process.env.PGSSLMODE){case"disable":return!1;case"prefer":case"require":case"verify-ca":case"verify-full":return!0;case"no-verify":return{rejectUnauthorized:!1}}return ctt.ssl},sB=function(t){return"'"+(""+t).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},Xd=function(t,e,n){let r=e[n];r!=null&&t.push(n+"="+sB(r))},Xge=class{constructor(e){if(e=typeof e=="string"?att(e):e||{},e.connectionString&&(e=Object.assign({},e,att(e.connectionString))),this.user=hu("user",e),this.database=hu("database",e),this.database===void 0&&(this.database=this.user),this.port=parseInt(hu("port",e),10),this.host=hu("host",e),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:hu("password",e)}),this.binary=hu("binary",e),this.options=hu("options",e),this.ssl=typeof e.ssl>"u"?MTn():e.ssl,typeof this.ssl=="string"&&this.ssl==="true"&&(this.ssl=!0),this.ssl==="no-verify"&&(this.ssl={rejectUnauthorized:!1}),this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this.sslnegotiation=hu("sslnegotiation",e,"PGSSLNEGOTIATION"),this.sslnegotiation!==void 0&&this.sslnegotiation!=="postgres"&&this.sslnegotiation!=="direct")throw new Error(`Invalid sslnegotiation value: "${this.sslnegotiation}". Valid values are "postgres" and "direct".`);if(this.sslnegotiation==="direct"&&!this.ssl)throw new Error("sslnegotiation=direct requires SSL to be enabled");this.client_encoding=hu("client_encoding",e),this.replication=hu("replication",e),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=hu("application_name",e,"PGAPPNAME"),this.fallback_application_name=hu("fallback_application_name",e,!1),this.statement_timeout=hu("statement_timeout",e,!1),this.lock_timeout=hu("lock_timeout",e,!1),this.idle_in_transaction_session_timeout=hu("idle_in_transaction_session_timeout",e,!1),this.query_timeout=hu("query_timeout",e,!1),e.connectionTimeoutMillis===void 0?this.connect_timeout=process.env.PGCONNECT_TIMEOUT||0:this.connect_timeout=Math.floor(e.connectionTimeoutMillis/1e3),e.keepAlive===!1?this.keepalives=0:e.keepAlive===!0&&(this.keepalives=1),typeof e.keepAliveInitialDelayMillis=="number"&&(this.keepalives_idle=Math.floor(e.keepAliveInitialDelayMillis/1e3))}getLibpqConnectionString(e){let n=[];Xd(n,this,"user"),Xd(n,this,"password"),Xd(n,this,"port"),Xd(n,this,"application_name"),Xd(n,this,"fallback_application_name"),Xd(n,this,"connect_timeout"),Xd(n,this,"options");let r=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(Xd(n,r,"sslmode"),Xd(n,r,"sslca"),Xd(n,r,"sslkey"),Xd(n,r,"sslcert"),Xd(n,r,"sslrootcert"),Xd(n,this,"sslnegotiation"),this.database&&n.push("dbname="+sB(this.database)),this.replication&&n.push("replication="+sB(this.replication)),this.host&&n.push("host="+sB(this.host)),this.isDomainSocket)return e(null,n.join(" "));this.client_encoding&&n.push("client_encoding="+sB(this.client_encoding)),DTn.lookup(this.host,function(i,o){return i?e(i,null):(n.push("hostaddr="+sB(o)),e(null,n.join(" ")))})}};utt.exports=Xge});var tAe=Q((bbi,dtt)=>{"use strict";var PTn=FF(),ltt=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,eAe=class{constructor(e,n){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=n,this.RowCtor=null,this.rowAsArray=e==="array",this.rowAsArray&&(this.parseRow=this._parseRowAsArray),this._prebuiltEmptyResultObject=null}addCommandComplete(e){let n;e.text?n=ltt.exec(e.text):n=ltt.exec(e.command),n&&(this.command=n[1],n[3]?(this.oid=parseInt(n[2],10),this.rowCount=parseInt(n[3],10)):n[2]&&(this.rowCount=parseInt(n[2],10)))}_parseRowAsArray(e){let n=new Array(e.length);for(let r=0,i=e.length;r<i;r++){let o=e[r];o!==null?n[r]=this._parsers[r](o):n[r]=null}return n}parseRow(e){let n={...this._prebuiltEmptyResultObject};for(let r=0,i=e.length;r<i;r++){let o=e[r],s=this.fields[r].name;if(o!==null){let a=this.fields[r].format==="binary"?Buffer.from(o):o;n[s]=this._parsers[r](a)}else n[s]=null}return n}addRow(e){this.rows.push(e)}addFields(e){this.fields=e,this.fields.length&&(this._parsers=new Array(e.length));let n=Object.create(null);for(let r=0;r<e.length;r++){let i=e[r];n[i.name]=null,this._types?this._parsers[r]=this._types.getTypeParser(i.dataTypeID,i.format||"text"):this._parsers[r]=PTn.getTypeParser(i.dataTypeID,i.format||"text")}this._prebuiltEmptyResultObject={...n}}};dtt.exports=eAe});var ftt=Q((Cbi,mtt)=>{"use strict";var{EventEmitter:NTn}=J("events"),ptt=tAe(),htt=YI(),nAe=class extends NTn{constructor(e,n,r){super(),e=htt.normalizeQueryConfig(e,n,r),this.text=e.text,this.values=e.values,this.rows=e.rows,this.types=e.types,this.name=e.name,this.queryMode=e.queryMode,this.binary=e.binary,this.portal=e.portal||"",this.callback=e.callback,this._rowMode=e.rowMode,process.domain&&e.callback&&(this.callback=process.domain.bind(e.callback)),this._result=new ptt(this._rowMode,this.types),this._results=this._result,this._canceledDueToError=!1}requiresPreparation(){return this.queryMode==="extended"||this.name||this.rows?!0:!this.text||!this.values?!1:this.values.length>0}_checkForMultirow(){this._result.command&&(Array.isArray(this._results)||(this._results=[this._result]),this._result=new ptt(this._rowMode,this._result._types),this._results.push(this._result))}handleRowDescription(e){this._checkForMultirow(),this._result.addFields(e.fields),this._accumulateRows=this.callback||!this.listeners("row").length}handleDataRow(e){let n;if(!this._canceledDueToError){try{n=this._result.parseRow(e.fields)}catch(r){this._canceledDueToError=r;return}this.emit("row",n,this._result),this._accumulateRows&&this._result.addRow(n)}}handleCommandComplete(e,n){this._checkForMultirow(),this._result.addCommandComplete(e),this.rows&&n.sync()}handleEmptyQuery(e){this.rows&&e.sync()}handleError(e,n){if(this._canceledDueToError&&(e=this._canceledDueToError,this._canceledDueToError=!1),this.callback)return this.callback(e);this.emit("error",e)}handleReadyForQuery(e){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,e);if(this.callback)try{this.callback(null,this._results)}catch(n){process.nextTick(()=>{throw n})}this.emit("end",this._results)}submit(e){if(typeof this.text!="string"&&typeof this.name!="string")return new Error("A query must have either text or a name. Supplying neither is unsupported.");let n=e.parsedStatements[this.name]||e.submittedNamedStatements[this.name];if(this.text&&n&&this.text!==n)return new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);if(this.values&&!Array.isArray(this.values))return new Error("Query values must be an array");if(this.requiresPreparation()){e.stream.cork&&e.stream.cork();try{this.prepare(e)}finally{e.stream.uncork&&e.stream.uncork()}}else e.query(this.text);return null}hasBeenParsed(e){return this.name&&(e.parsedStatements[this.name]!==void 0||e.submittedNamedStatements[this.name]!==void 0)}handlePortalSuspended(e){this._getRows(e,this.rows)}_getRows(e,n){e.execute({portal:this.portal,rows:n}),n?e.flush():e.sync()}prepare(e){this.hasBeenParsed(e)||(e.parse({text:this.text,name:this.name,types:this.types}),this.name&&(e.submittedNamedStatements[this.name]=this.text));try{e.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:htt.prepareValue})}catch(n){e.close({type:"S",name:this.name}),e.sync(),this.handleError(n,e);return}e.describe({type:"P",name:this.portal||""}),this._getRows(e,this.rows)}handleCopyInResponse(e){e.sendCopyFail("No source stream defined")}handleCopyData(e,n){}};mtt.exports=nAe});var AAe=Q($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.NoticeMessage=$n.DataRowMessage=$n.CommandCompleteMessage=$n.ReadyForQueryMessage=$n.NotificationResponseMessage=$n.BackendKeyDataMessage=$n.AuthenticationMD5Password=$n.ParameterStatusMessage=$n.ParameterDescriptionMessage=$n.RowDescriptionMessage=$n.Field=$n.CopyResponse=$n.CopyDataMessage=$n.DatabaseError=$n.copyDone=$n.emptyQuery=$n.replicationStart=$n.portalSuspended=$n.noData=$n.closeComplete=$n.bindComplete=$n.parseComplete=void 0;$n.parseComplete={name:"parseComplete",length:5};$n.bindComplete={name:"bindComplete",length:5};$n.closeComplete={name:"closeComplete",length:5};$n.noData={name:"noData",length:5};$n.portalSuspended={name:"portalSuspended",length:5};$n.replicationStart={name:"replicationStart",length:4};$n.emptyQuery={name:"emptyQuery",length:4};$n.copyDone={name:"copyDone",length:4};var rAe=class extends Error{constructor(e,n,r){super(e),this.length=n,this.name=r}};$n.DatabaseError=rAe;var iAe=class{constructor(e,n){this.length=e,this.chunk=n,this.name="copyData"}};$n.CopyDataMessage=iAe;var oAe=class{constructor(e,n,r,i){this.length=e,this.name=n,this.binary=r,this.columnTypes=new Array(i)}};$n.CopyResponse=oAe;var sAe=class{constructor(e,n,r,i,o,s,a){this.name=e,this.tableID=n,this.columnID=r,this.dataTypeID=i,this.dataTypeSize=o,this.dataTypeModifier=s,this.format=a}};$n.Field=sAe;var aAe=class{constructor(e,n){this.length=e,this.fieldCount=n,this.name="rowDescription",this.fields=new Array(this.fieldCount)}};$n.RowDescriptionMessage=aAe;var cAe=class{constructor(e,n){this.length=e,this.parameterCount=n,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}};$n.ParameterDescriptionMessage=cAe;var uAe=class{constructor(e,n,r){this.length=e,this.parameterName=n,this.parameterValue=r,this.name="parameterStatus"}};$n.ParameterStatusMessage=uAe;var lAe=class{constructor(e,n){this.length=e,this.salt=n,this.name="authenticationMD5Password"}};$n.AuthenticationMD5Password=lAe;var dAe=class{constructor(e,n,r){this.length=e,this.processID=n,this.secretKey=r,this.name="backendKeyData"}};$n.BackendKeyDataMessage=dAe;var pAe=class{constructor(e,n,r,i){this.length=e,this.processId=n,this.channel=r,this.payload=i,this.name="notification"}};$n.NotificationResponseMessage=pAe;var hAe=class{constructor(e,n){this.length=e,this.status=n,this.name="readyForQuery"}};$n.ReadyForQueryMessage=hAe;var mAe=class{constructor(e,n){this.length=e,this.text=n,this.name="commandComplete"}};$n.CommandCompleteMessage=mAe;var fAe=class{constructor(e,n){this.length=e,this.fields=n,this.name="dataRow",this.fieldCount=n.length}};$n.DataRowMessage=fAe;var gAe=class{constructor(e,n){this.length=e,this.message=n,this.name="notice"}};$n.NoticeMessage=gAe});var gtt=Q(z6=>{"use strict";Object.defineProperty(z6,"__esModule",{value:!0});z6.Writer=void 0;var yAe=class{constructor(e=256){this.size=e,this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(e)}ensure(e){if(this.buffer.length-this.offset<e){let r=this.buffer,i=r.length+(r.length>>1)+e;this.buffer=Buffer.allocUnsafe(i),r.copy(this.buffer,0,0,this.offset)}}addInt32(e){return this.ensure(4),this.buffer[this.offset++]=e>>>24&255,this.buffer[this.offset++]=e>>>16&255,this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addInt16(e){return this.ensure(2),this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addCString(e){if(!e)this.ensure(1);else{let n=Buffer.byteLength(e);this.ensure(n+1),this.buffer.write(e,this.offset,"utf-8"),this.offset+=n}return this.buffer[this.offset++]=0,this}addString(e=""){let n=Buffer.byteLength(e);return this.ensure(n),this.buffer.write(e,this.offset),this.offset+=n,this}addInt32PrefixedString(e){let n=Buffer.byteLength(e);this.ensure(4+n);let r=this.buffer,i=this.offset;return r[i++]=n>>>24&255,r[i++]=n>>>16&255,r[i++]=n>>>8&255,r[i++]=n>>>0&255,r.write(e,i,"utf-8"),this.offset=i+n,this}add(e){return this.ensure(e.length),e.copy(this.buffer,this.offset),this.offset+=e.length,this}reserveUnsafe(e){let n=this.offset;return this.ensure(e),this.offset+=e,n}join(e){if(e){this.buffer[this.headerPosition]=e;let n=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(n,this.headerPosition+1)}return this.buffer.slice(e?0:5,this.offset)}flush(e){let n=this.join(e);return this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(this.size),n}clear(){this.offset=5,this.headerPosition=0}};z6.Writer=yAe});var wtt=Q(K6=>{"use strict";Object.defineProperty(K6,"__esModule",{value:!0});K6.serialize=void 0;var Att=gtt(),Yi=new Att.Writer,LTn=t=>{Yi.addInt16(3).addInt16(0);for(let r of Object.keys(t))Yi.addCString(r).addCString(t[r]);Yi.addCString("client_encoding").addCString("UTF8");let e=Yi.addCString("").flush(),n=e.length+4;return new Att.Writer().addInt32(n).add(e).flush()},QTn=()=>{let t=Buffer.allocUnsafe(8);return t.writeInt32BE(8,0),t.writeInt32BE(80877103,4),t},OTn=t=>Yi.addCString(t).flush(112),FTn=function(t,e){return Yi.addCString(t).addInt32PrefixedString(e),Yi.flush(112)},UTn=function(t){return Yi.addString(t).flush(112)},$Tn=t=>Yi.addCString(t).flush(81),ytt=[],WTn=t=>{let e=t.name||"";e.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",e,e.length),console.error("This can cause conflicts and silent errors executing queries"));let n=t.types||ytt,r=n.length,i=Yi.addCString(e).addCString(t.text).addInt16(r);for(let o=0;o<r;o++)i.addInt32(n[o]);return Yi.flush(80)},HTn=function(t,e,n){let r=t.length;for(let i=0;i<r;i++){let o=e?e(t[i],i):t[i],s=0;o==null?Yi.addInt32(-1):o instanceof Buffer?(s=1,Yi.addInt32(o.length),Yi.add(o)):Yi.addInt32PrefixedString(o);let a=Yi.buffer;a[n++]=0,a[n++]=s}},GTn=(t={})=>{let e=t.portal||"",n=t.statement||"",r=t.binary||!1,i=t.values||ytt,o=i.length;Yi.addCString(e).addCString(n),Yi.addInt16(o);let s=Yi.reserveUnsafe(o*2);Yi.addInt16(o);try{HTn(i,t.valueMapper,s)}catch(a){throw Yi.clear(),a}return Yi.addInt16(1),Yi.addInt16(r?1:0),Yi.flush(66)},qTn=Buffer.from([69,0,0,0,9,0,0,0,0,0]),jTn=t=>{if(!t||!t.portal&&!t.rows)return qTn;let e=t.portal||"",n=t.rows||0,r=Buffer.byteLength(e),i=4+r+1+4,o=Buffer.allocUnsafe(1+i);return o[0]=69,o.writeInt32BE(i,1),o.write(e,5,"utf-8"),o[r+5]=0,o.writeUInt32BE(n,o.length-4),o},zTn=(t,e)=>{let n=Buffer.allocUnsafe(16);return n.writeInt32BE(16,0),n.writeInt16BE(1234,4),n.writeInt16BE(5678,6),n.writeInt32BE(t,8),n.writeInt32BE(e,12),n},wAe=(t,e)=>{let r=4+Buffer.byteLength(e)+1,i=Buffer.allocUnsafe(1+r);return i[0]=t,i.writeInt32BE(r,1),i.write(e,5,"utf-8"),i[r]=0,i},VTn=Yi.addCString("P").flush(68),KTn=Yi.addCString("S").flush(68),YTn=t=>t.name?wAe(68,`${t.type}${t.name||""}`):t.type==="P"?VTn:KTn,JTn=t=>{let e=`${t.type}${t.name||""}`;return wAe(67,e)},XTn=t=>Yi.add(t).flush(100),ZTn=t=>wAe(102,t),V6=t=>Buffer.from([t,0,0,0,4]),eRn=V6(72),tRn=V6(83),nRn=V6(88),rRn=V6(99),iRn={startup:LTn,password:OTn,requestSsl:QTn,sendSASLInitialResponseMessage:FTn,sendSCRAMClientFinalMessage:UTn,query:$Tn,parse:WTn,bind:GTn,execute:jTn,describe:YTn,close:JTn,flush:()=>eRn,sync:()=>tRn,end:()=>nRn,copyData:XTn,copyDone:()=>rRn,copyFail:ZTn,cancel:zTn};K6.serialize=iRn});var Ett=Q(Y6=>{"use strict";Object.defineProperty(Y6,"__esModule",{value:!0});Y6.BufferReader=void 0;var EAe=class{constructor(e=0){this.offset=e,this.buffer=Buffer.allocUnsafe(0),this.encoding="utf-8"}setBuffer(e,n){this.offset=e,this.buffer=n}int16(){let e=this.buffer.readInt16BE(this.offset);return this.offset+=2,e}byte(){let e=this.buffer[this.offset];return this.offset++,e}int32(){let e=this.buffer.readInt32BE(this.offset);return this.offset+=4,e}uint32(){let e=this.buffer.readUInt32BE(this.offset);return this.offset+=4,e}string(e){let n=this.buffer.toString(this.encoding,this.offset,this.offset+e);return this.offset+=e,n}cstring(){let e=this.offset,n=e;for(;this.buffer[n++];);return this.offset=n,this.buffer.toString(this.encoding,e,n-1)}bytes(e){let n=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,n}};Y6.BufferReader=EAe});var Itt=Q(J6=>{"use strict";Object.defineProperty(J6,"__esModule",{value:!0});J6.Parser=void 0;var cs=AAe(),oRn=Ett(),bAe=1,sRn=4,xtt=bAe+sRn,Zd=-1,xAe=Buffer.allocUnsafe(0),CAe=class{constructor(e){if(this.buffer=xAe,this.bufferLength=0,this.bufferOffset=0,this.reader=new oRn.BufferReader,e?.mode==="binary")throw new Error("Binary mode not supported yet");this.mode=e?.mode||"text"}parse(e,n){this.mergeBuffer(e);let r=this.bufferOffset+this.bufferLength,i=this.bufferOffset;for(;i+xtt<=r;){let o=this.buffer[i],s=this.buffer.readUInt32BE(i+bAe),a=bAe+s;if(a+i<=r){let c=this.handlePacket(i+xtt,o,s,this.buffer);n(c),i+=a}else break}i===r?(this.buffer=xAe,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=r-i,this.bufferOffset=i)}mergeBuffer(e){if(this.bufferLength>0){let n=this.bufferLength+e.byteLength;if(n+this.bufferOffset>this.buffer.byteLength){let i;if(n<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)i=this.buffer;else{let o=this.buffer.byteLength*2;for(;n>=o;)o*=2;i=Buffer.allocUnsafe(o)}this.buffer.copy(i,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=i,this.bufferOffset=0}e.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=n}else this.buffer=e,this.bufferOffset=0,this.bufferLength=e.byteLength}handlePacket(e,n,r,i){let{reader:o}=this;o.setBuffer(e,i);let s;switch(n){case 50:s=cs.bindComplete;break;case 49:s=cs.parseComplete;break;case 51:s=cs.closeComplete;break;case 110:s=cs.noData;break;case 115:s=cs.portalSuspended;break;case 99:s=cs.copyDone;break;case 87:s=cs.replicationStart;break;case 73:s=cs.emptyQuery;break;case 68:s=gRn(o);break;case 67:s=cRn(o);break;case 90:s=aRn(o);break;case 65:s=pRn(o);break;case 82:s=wRn(o,r);break;case 83:s=ARn(o);break;case 75:s=yRn(o);break;case 69:s=btt(o,"error");break;case 78:s=btt(o,"notice");break;case 84:s=hRn(o);break;case 116:s=fRn(o);break;case 71:s=lRn(o);break;case 72:s=dRn(o);break;case 100:s=uRn(o,r);break;default:return new cs.DatabaseError("received invalid response: "+n.toString(16),r,"error")}return o.setBuffer(0,xAe),s.length=r,s}};J6.Parser=CAe;var aRn=t=>{let e=t.string(1);return new cs.ReadyForQueryMessage(Zd,e)},cRn=t=>{let e=t.cstring();return new cs.CommandCompleteMessage(Zd,e)},uRn=(t,e)=>{let n=t.bytes(e-4);return new cs.CopyDataMessage(Zd,n)},lRn=t=>Ctt(t,"copyInResponse"),dRn=t=>Ctt(t,"copyOutResponse"),Ctt=(t,e)=>{let n=t.byte()!==0,r=t.int16(),i=new cs.CopyResponse(Zd,e,n,r);for(let o=0;o<r;o++)i.columnTypes[o]=t.int16();return i},pRn=t=>{let e=t.int32(),n=t.cstring(),r=t.cstring();return new cs.NotificationResponseMessage(Zd,e,n,r)},hRn=t=>{let e=t.int16(),n=new cs.RowDescriptionMessage(Zd,e);for(let r=0;r<e;r++)n.fields[r]=mRn(t);return n},mRn=t=>{let e=t.cstring(),n=t.uint32(),r=t.int16(),i=t.uint32(),o=t.int16(),s=t.int32(),a=t.int16()===0?"text":"binary";return new cs.Field(e,n,r,i,o,s,a)},fRn=t=>{let e=t.int16(),n=new cs.ParameterDescriptionMessage(Zd,e);for(let r=0;r<e;r++)n.dataTypeIDs[r]=t.uint32();return n},gRn=t=>{let e=t.int16(),n=new Array(e);for(let r=0;r<e;r++){let i=t.int32();n[r]=i===-1?null:t.string(i)}return new cs.DataRowMessage(Zd,n)},ARn=t=>{let e=t.cstring(),n=t.cstring();return new cs.ParameterStatusMessage(Zd,e,n)},yRn=t=>{let e=t.int32(),n=t.int32();return new cs.BackendKeyDataMessage(Zd,e,n)},wRn=(t,e)=>{let n=t.int32(),r={name:"authenticationOk",length:e};switch(n){case 0:break;case 3:r.length===8&&(r.name="authenticationCleartextPassword");break;case 5:if(r.length===12){r.name="authenticationMD5Password";let i=t.bytes(4);return new cs.AuthenticationMD5Password(Zd,i)}break;case 10:{r.name="authenticationSASL",r.mechanisms=[];let i;do i=t.cstring(),i&&r.mechanisms.push(i);while(i)}break;case 11:r.name="authenticationSASLContinue",r.data=t.string(e-8);break;case 12:r.name="authenticationSASLFinal",r.data=t.string(e-8);break;default:throw new Error("Unknown authenticationOk message type "+n)}return r},btt=(t,e)=>{let n={},r=t.string(1);for(;r!=="\0";)n[r]=t.cstring(),r=t.string(1);let i=n.M,o=e==="notice"?new cs.NoticeMessage(Zd,i):new cs.DatabaseError(i,Zd,e);return o.severity=n.S,o.code=n.C,o.detail=n.D,o.hint=n.H,o.position=n.P,o.internalPosition=n.p,o.internalQuery=n.q,o.where=n.W,o.schema=n.s,o.table=n.t,o.column=n.c,o.dataType=n.d,o.constraint=n.n,o.file=n.F,o.line=n.L,o.routine=n.R,o}});var IAe=Q(ZI=>{"use strict";Object.defineProperty(ZI,"__esModule",{value:!0});ZI.DatabaseError=ZI.serialize=void 0;ZI.parse=CRn;var ERn=AAe();Object.defineProperty(ZI,"DatabaseError",{enumerable:!0,get:function(){return ERn.DatabaseError}});var xRn=wtt();Object.defineProperty(ZI,"serialize",{enumerable:!0,get:function(){return xRn.serialize}});var bRn=Itt();function CRn(t,e){let n=new bRn.Parser;return t.on("data",r=>n.parse(r,e)),new Promise(r=>t.on("end",()=>r()))}});var vtt=Q(vAe=>{"use strict";Object.defineProperty(vAe,"__esModule",{value:!0});vAe.default={}});var _tt=Q((Bbi,Stt)=>{var{getStream:IRn,getSecureStream:vRn}=TRn();Stt.exports={getStream:IRn,getSecureStream:vRn};function SRn(){function t(n){let r=J("net");return new r.Socket}function e(n){return J("tls").connect(n)}return{getStream:t,getSecureStream:e}}function _Rn(){function t(n){let{CloudflareSocket:r}=vtt();return new r(n)}function e(n){return n.socket.startTls(n),n.socket}return{getStream:t,getSecureStream:e}}function kRn(){if(typeof navigator=="object"&&navigator!==null&&typeof navigator.userAgent=="string")return navigator.userAgent==="Cloudflare-Workers";if(typeof Response=="function"){let t=new Response(null,{cf:{thing:!0}});if(typeof t.cf=="object"&&t.cf!==null&&t.cf.thing)return!0}return!1}function TRn(){return kRn()?_Rn():SRn()}});var _Ae=Q((Dbi,Ttt)=>{"use strict";var RRn=J("events").EventEmitter,{parse:BRn,serialize:sc}=IAe(),ktt=_tt(),{getStream:DRn}=ktt,MRn=sc.flush(),PRn=sc.sync(),NRn=sc.end(),SAe=class extends RRn{constructor(e){super(),e=e||{},this.stream=e.stream||DRn(e.ssl),typeof this.stream=="function"&&(this.stream=this.stream(e)),this._keepAlive=e.keepAlive,this._keepAliveInitialDelayMillis=e.keepAliveInitialDelayMillis,this.parsedStatements={},this.submittedNamedStatements={},this.ssl=e.ssl||!1,this.sslNegotiation=e.sslNegotiation||"postgres",this._ending=!1,this._emitMessage=!1;let n=this;this.on("newListener",function(r){r==="message"&&(n._emitMessage=!0)})}connect(e,n){let r=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(e,n),this.stream.once("connect",function(){r._keepAlive&&r.stream.setKeepAlive(!0,r._keepAliveInitialDelayMillis),r.emit("connect")});let i=function(o){r._ending&&(o.code==="ECONNRESET"||o.code==="EPIPE")||r.emit("error",o)};if(this.stream.on("error",i),this.stream.on("close",function(){r.emit("end")}),!this.ssl)return this.attachListeners(this.stream);if(this.sslNegotiation==="direct")return this.stream.once("connect",function(){r.upgradeToSSL(n,i)});this.stream.once("data",function(o){switch(o.toString("utf8")){case"S":break;case"N":return r.stream.end(),r.emit("error",new Error("The server does not support SSL connections"));default:return r.stream.end(),r.emit("error",new Error("There was an error establishing an SSL connection"))}r.upgradeToSSL(n,i)})}upgradeToSSL(e,n){let r=this,i={socket:r.stream,host:e};r.ssl!==!0&&(Object.assign(i,r.ssl),"key"in r.ssl&&(i.key=r.ssl.key)),r.sslNegotiation==="direct"&&(i.ALPNProtocols=["postgresql"]);let o=J("net");o.isIP&&o.isIP(e)===0&&(i.servername=e);try{r.stream=ktt.getSecureStream(i)}catch(s){return r.emit("error",s)}r.attachListeners(r.stream),r.stream.on("error",n),r.emit("sslconnect")}attachListeners(e){BRn(e,n=>{let r=n.name==="error"?"errorMessage":n.name;this._emitMessage&&this.emit("message",n),this.emit(r,n)})}requestSsl(){this.stream.write(sc.requestSsl())}startup(e){this.stream.write(sc.startup(e))}cancel(e,n){this._send(sc.cancel(e,n))}password(e){this._send(sc.password(e))}sendSASLInitialResponseMessage(e,n){this._send(sc.sendSASLInitialResponseMessage(e,n))}sendSCRAMClientFinalMessage(e){this._send(sc.sendSCRAMClientFinalMessage(e))}_send(e){return this.stream.writable?this.stream.write(e):!1}query(e){this._send(sc.query(e))}parse(e){this._send(sc.parse(e))}bind(e){this._send(sc.bind(e))}execute(e){this._send(sc.execute(e))}flush(){this.stream.writable&&this.stream.write(MRn)}sync(){this._send(PRn)}ref(){this.stream.ref()}unref(){this.stream.unref()}end(){if(this._ending=!0,!this._connecting||!this.stream.writable){this.stream.end();return}return this.stream.write(NRn,()=>{this.stream.end()})}close(e){this._send(sc.close(e))}describe(e){this._send(sc.describe(e))}sendCopyFromChunk(e){this._send(sc.copyData(e))}endCopyFrom(){this._send(sc.copyDone())}sendCopyFail(e){this._send(sc.copyFail(e))}};Ttt.exports=SAe});var Mtt=Q((Mbi,Dtt)=>{"use strict";var{Transform:LRn}=J("stream"),{StringDecoder:QRn}=J("string_decoder"),pE=Symbol("last"),X6=Symbol("decoder");function ORn(t,e,n){let r;if(this.overflow){if(r=this[X6].write(t).split(this.matcher),r.length===1)return n();r.shift(),this.overflow=!1}else this[pE]+=this[X6].write(t),r=this[pE].split(this.matcher);this[pE]=r.pop();for(let i=0;i<r.length;i++)try{Btt(this,this.mapper(r[i]))}catch(o){return n(o)}if(this.overflow=this[pE].length>this.maxLength,this.overflow&&!this.skipOverflow){n(new Error("maximum buffer reached"));return}n()}function FRn(t){if(this[pE]+=this[X6].end(),this[pE])try{Btt(this,this.mapper(this[pE]))}catch(e){return t(e)}t()}function Btt(t,e){e!==void 0&&t.push(e)}function Rtt(t){return t}function URn(t,e,n){switch(t=t||/\r?\n/,e=e||Rtt,n=n||{},arguments.length){case 1:typeof t=="function"?(e=t,t=/\r?\n/):typeof t=="object"&&!(t instanceof RegExp)&&!t[Symbol.split]&&(n=t,t=/\r?\n/);break;case 2:typeof t=="function"?(n=e,e=t,t=/\r?\n/):typeof e=="object"&&(n=e,e=Rtt)}n=Object.assign({},n),n.autoDestroy=!0,n.transform=ORn,n.flush=FRn,n.readableObjectMode=!0;let r=new LRn(n);return r[pE]="",r[X6]=new QRn("utf8"),r.matcher=t,r.mapper=e,r.maxLength=n.maxLength,r.skipOverflow=n.skipOverflow||!1,r.overflow=!1,r._destroy=function(i,o){this._writableState.errorEmitted=!1,o(i)},r}Dtt.exports=URn});var Ltt=Q((Pbi,H0)=>{"use strict";var Ptt=J("path"),$Rn=J("stream").Stream,WRn=Mtt(),Ntt=J("util"),HRn=5432,Z6=process.platform==="win32",WF=process.stderr,GRn=56,qRn=7,jRn=61440,zRn=32768;function VRn(t){return(t&jRn)==zRn}var aB=["host","port","database","user","password"],kAe=aB.length,KRn=aB[kAe-1];function TAe(){var t=WF instanceof $Rn&&WF.writable===!0;if(t){var e=Array.prototype.slice.call(arguments).concat(`
98
- `);WF.write(Ntt.format.apply(Ntt,e))}}Object.defineProperty(H0.exports,"isWin",{get:function(){return Z6},set:function(t){Z6=t}});H0.exports.warnTo=function(t){var e=WF;return WF=t,e};H0.exports.getFileName=function(t){var e=t||process.env,n=e.PGPASSFILE||(Z6?Ptt.join(e.APPDATA||"./","postgresql","pgpass.conf"):Ptt.join(e.HOME||"./",".pgpass"));return n};H0.exports.usePgPass=function(t,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:Z6?!0:(e=e||"<unkn>",VRn(t.mode)?t.mode&(GRn|qRn)?(TAe('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(TAe('WARNING: password file "%s" is not a plain file',e),!1))};var YRn=H0.exports.match=function(t,e){return aB.slice(0,-1).reduce(function(n,r,i){return i==1&&Number(t[r]||HRn)===Number(e[r])?n&&!0:n&&(e[r]==="*"||e[r]===t[r])},!0)};H0.exports.getPassword=function(t,e,n){var r,i=e.pipe(WRn());function o(c){var u=JRn(c);u&&XRn(u)&&YRn(t,u)&&(r=u[KRn],i.end())}var s=function(){e.destroy(),n(r)},a=function(c){e.destroy(),TAe("WARNING: error on reading file: %s",c),n(void 0)};e.on("error",a),i.on("data",o).on("end",s).on("error",a)};var JRn=H0.exports.parseLine=function(t){if(t.length<11||t.match(/^\s+#/))return null;for(var e="",n="",r=0,i=0,o=0,s={},a=!1,c=function(l,d,p){var h=t.substring(d,p);Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE")||(h=h.replace(/\\([:\\])/g,"$1")),s[aB[l]]=h},u=0;u<t.length-1;u+=1){if(e=t.charAt(u+1),n=t.charAt(u),a=r==kAe-1,a){c(r,i);break}u>=0&&e==":"&&n!=="\\"&&(c(r,i,u+1),i=u+2,r+=1)}return s=Object.keys(s).length===kAe?s:null,s},XRn=H0.exports.isValidEntry=function(t){for(var e={0:function(s){return s.length>0},1:function(s){return s==="*"?!0:(s=Number(s),isFinite(s)&&s>0&&s<9007199254740992&&Math.floor(s)===s)},2:function(s){return s.length>0},3:function(s){return s.length>0},4:function(s){return s.length>0}},n=0;n<aB.length;n+=1){var r=e[n],i=t[aB[n]]||"",o=r(i);if(!o)return!1}return!0}});var Ott=Q((Lbi,RAe)=>{"use strict";var Nbi=J("path"),Qtt=J("fs"),eV=Ltt();RAe.exports=function(t,e){var n=eV.getFileName();Qtt.stat(n,function(r,i){if(r||!eV.usePgPass(i,n))return e(void 0);var o=Qtt.createReadStream(n);eV.getPassword(t,o,e)})};RAe.exports.warnTo=eV.warnTo});var Wtt=Q((Qbi,$tt)=>{var ZRn=J("events").EventEmitter,Ftt=YI(),HF=J("util"),tV=ntt(),eBn=j6(),tBn=Zge(),BAe=ftt(),nBn=UF(),rBn=_Ae(),iBn=Vge(),Utt=HF.deprecate(()=>{},"Client.activeQuery is deprecated and will be removed in pg@9.0"),oBn=HF.deprecate(()=>{},"Client.queryQueue is deprecated and will be removed in pg@9.0."),sBn=HF.deprecate(()=>{},"pgpass support is deprecated and will be removed in pg@9.0. You can provide an async function as the password property to the Client/Pool constructor that returns a password instead. Within this function you can call the pgpass module in your own code."),aBn=HF.deprecate(()=>{},"Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0."),cBn=HF.deprecate(()=>{},"Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead.");function uBn(t,e){if(typeof t=="number")return Number.isFinite(t)?t:e;if(typeof t=="string"&&t.trim()!==""){let n=Number(t);return Number.isFinite(n)?n:e}return e}var nV=class extends ZRn{constructor(e){super(),this.connectionParameters=new tBn(e),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;let n=e||{};n.Promise&&aBn(),this._Promise=n.Promise||global.Promise,this._types=new eBn(n.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this._activeQuery=null,this._txStatus=null,this.enableChannelBinding=!!n.enableChannelBinding,this.scramMaxIterations=uBn(n.scramMaxIterations,tV.DEFAULT_MAX_SCRAM_ITERATIONS),this.connection=n.connection||new rBn({stream:n.stream,ssl:this.connectionParameters.ssl,sslNegotiation:this.connectionParameters.sslnegotiation,keepAlive:n.keepAlive||!1,keepAliveInitialDelayMillis:n.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this._queryQueue=[],this._sentQueryQueue=[],this.pipeline=!!n.pipeline,this.binary=n.binary||nBn.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.sslNegotiation=this.connectionParameters.sslnegotiation||"postgres",this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=n.connectionTimeoutMillis||0}get activeQuery(){return Utt(),this._activeQuery}set activeQuery(e){Utt(),this._activeQuery=e}_getActiveQuery(){return this._activeQuery}_errorAllQueries(e){let n=i=>{process.nextTick(()=>{i.handleError(e,this.connection)})},r=this._getActiveQuery();r&&(n(r),this._activeQuery=null),this._sentQueryQueue.forEach(n),this._sentQueryQueue.length=0,this._queryQueue.forEach(n),this._queryQueue.length=0}_connect(e){let n=this,r=this.connection;if(this._connectionCallback=e,this._connecting||this._connected){let i=new Error("Client has already been connected. You cannot reuse a client.");process.nextTick(()=>{e(i)});return}this._connecting=!0,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{r._ending=!0,r.stream.destroy(new Error("timeout expired"))},this._connectionTimeoutMillis),this.connectionTimeoutHandle.unref&&this.connectionTimeoutHandle.unref()),this.host&&this.host.indexOf("/")===0?r.connect(this.host+"/.s.PGSQL."+this.port):r.connect(this.port,this.host),r.on("connect",function(){n.ssl?n.sslNegotiation!=="direct"&&r.requestSsl():r.startup(n.getStartupConf())}),r.on("sslconnect",function(){r.startup(n.getStartupConf())}),this._attachListeners(r),r.once("end",()=>{let i=this._ending?new Error("Connection terminated"):new Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(i),this._ended=!0,this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(i):this._handleErrorEvent(i):this._connectionError||this._handleErrorEvent(i)),process.nextTick(()=>{this.emit("end")})})}connect(e){if(e){this._connect(e);return}return new this._Promise((n,r)=>{this._connect(i=>{i?r(i):n(this)})})}_attachListeners(e){e.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),e.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),e.on("authenticationSASL",this._handleAuthSASL.bind(this)),e.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),e.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),e.on("backendKeyData",this._handleBackendKeyData.bind(this)),e.on("error",this._handleErrorEvent.bind(this)),e.on("errorMessage",this._handleErrorMessage.bind(this)),e.on("readyForQuery",this._handleReadyForQuery.bind(this)),e.on("notice",this._handleNotice.bind(this)),e.on("rowDescription",this._handleRowDescription.bind(this)),e.on("dataRow",this._handleDataRow.bind(this)),e.on("portalSuspended",this._handlePortalSuspended.bind(this)),e.on("emptyQuery",this._handleEmptyQuery.bind(this)),e.on("commandComplete",this._handleCommandComplete.bind(this)),e.on("parseComplete",this._handleParseComplete.bind(this)),e.on("copyInResponse",this._handleCopyInResponse.bind(this)),e.on("copyData",this._handleCopyData.bind(this)),e.on("notification",this._handleNotification.bind(this))}_getPassword(e){let n=this.connection;if(typeof this.password=="function")this._Promise.resolve().then(()=>this.password(this.connectionParameters)).then(r=>{if(r!==void 0){if(typeof r!="string"){n.emit("error",new TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=r}else this.connectionParameters.password=this.password=null;e()}).catch(r=>{n.emit("error",r)});else if(this.password!==null)e();else try{Ott()(this.connectionParameters,i=>{i!==void 0&&(sBn(),this.connectionParameters.password=this.password=i),e()})}catch(r){this.emit("error",r)}}_handleAuthCleartextPassword(e){this._getPassword(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){this._getPassword(async()=>{try{let n=await iBn.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(n)}catch(n){this.emit("error",n)}})}_handleAuthSASL(e){this._getPassword(()=>{try{this.saslSession=tV.startSession(e.mechanisms,this.enableChannelBinding&&this.connection.stream,this.scramMaxIterations),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(n){this.connection.emit("error",n)}})}async _handleAuthSASLContinue(e){try{await tV.continueSession(this.saslSession,this.password,e.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(n){this.connection.emit("error",n)}}_handleAuthSASLFinal(e){try{tV.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(n){this.connection.emit("error",n)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let n=this._getActiveQuery();this._activeQuery=null,this._txStatus=e?.status??null,this.readyForQuery=!0,n&&n.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit("error",e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit("error",e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let n=this._getActiveQuery();if(!n){this._handleErrorEvent(e);return}this._activeQuery=null,n.name&&delete this.connection.submittedNamedStatements[n.name],n.handleError(e,this.connection)}_handleRowDescription(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected rowDescription message from backend.");this._handleErrorEvent(r);return}n.handleRowDescription(e)}_handleDataRow(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected dataRow message from backend.");this._handleErrorEvent(r);return}n.handleDataRow(e)}_handlePortalSuspended(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected portalSuspended message from backend.");this._handleErrorEvent(r);return}n.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected emptyQuery message from backend.");this._handleErrorEvent(r);return}n.handleEmptyQuery(this.connection)}_handleCommandComplete(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected commandComplete message from backend.");this._handleErrorEvent(r);return}n.handleCommandComplete(e,this.connection)}_handleParseComplete(){let e=this._getActiveQuery();if(e==null){let n=new Error("Received unexpected parseComplete message from backend.");this._handleErrorEvent(n);return}e.name&&(this.connection.parsedStatements[e.name]=e.text,delete this.connection.submittedNamedStatements[e.name])}_handleCopyInResponse(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected copyInResponse message from backend.");this._handleErrorEvent(r);return}n.handleCopyInResponse(this.connection)}_handleCopyData(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected copyData message from backend.");this._handleErrorEvent(r);return}n.handleCopyData(e,this.connection)}_handleNotification(e){this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){let e=this.connectionParameters,n={user:e.user,database:e.database},r=e.application_name||e.fallback_application_name;return r&&(n.application_name=r),e.replication&&(n.replication=""+e.replication),e.statement_timeout&&(n.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(n.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(n.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(n.options=e.options),n}cancel(e,n){if(e.activeQuery===n){let r=this.connection;this.host&&this.host.indexOf("/")===0?r.connect(this.host+"/.s.PGSQL."+this.port):r.connect(this.port,this.host),r.on("connect",function(){r.cancel(e.processID,e.secretKey)})}else e._queryQueue.indexOf(n)!==-1?e._queryQueue.splice(e._queryQueue.indexOf(n),1):e._sentQueryQueue.indexOf(n)!==-1&&(n.callback=()=>{})}setTypeParser(e,n,r){return this._types.setTypeParser(e,n,r)}getTypeParser(e,n){return this._types.getTypeParser(e,n)}escapeIdentifier(e){return Ftt.escapeIdentifier(e)}escapeLiteral(e){return Ftt.escapeLiteral(e)}_pulseQueryQueue(){if(this.pipeline){this._pulsePipelinedQueryQueue();return}if(this.readyForQuery===!0){this._activeQuery=this._queryQueue.shift();let e=this._getActiveQuery();if(e){this.readyForQuery=!1,this.hasExecuted=!0;let n=e.submit(this.connection);n&&process.nextTick(()=>{e.handleError(n,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this._activeQuery=null,this.emit("drain"))}}_pulsePipelinedQueryQueue(){if(!(!this._connected||!this._queryable)){for(;this._queryQueue.length>0;){let e=this._queryQueue.shift();this.hasExecuted=!0;let n=e.submit(this.connection);if(n){process.nextTick(()=>{e.handleError(n,this.connection)});continue}this._sentQueryQueue.push(e)}this.readyForQuery&&!this._activeQuery&&this._sentQueryQueue.length>0&&(this._activeQuery=this._sentQueryQueue.shift(),this.readyForQuery=!1),!this._activeQuery&&this._sentQueryQueue.length===0&&this._queryQueue.length===0&&this.hasExecuted&&this.emit("drain")}}query(e,n,r){let i,o;if(e==null)throw new TypeError("Client was passed a null or undefined query");if(typeof e.submit=="function")o=i=e,i.callback||(typeof n=="function"?i.callback=n:r&&(i.callback=r));else if(i=new BAe(e,n,r),!i.callback)o=new this._Promise((a,c)=>{i.callback=(u,l)=>u?c(u):a(l)}).catch(a=>{throw Error.captureStackTrace(a),a});else if(typeof i.callback!="function")throw new TypeError("callback is not a function");let s=e.query_timeout||this.connectionParameters.query_timeout;if(s){let a=i.callback||(()=>{}),c=setTimeout(()=>{let u=new Error("Query read timeout");process.nextTick(()=>{i.handleError(u,this.connection)}),a(u),i.callback=()=>{};let l=this._queryQueue.indexOf(i);if(l>-1)this._queryQueue.splice(l,1);else if(this.pipeline){this.connection.stream.destroy();return}this._pulseQueryQueue()},s);i.callback=(u,l)=>{clearTimeout(c),a(u,l)}}if(this.binary&&!i.binary&&(i.binary=!0),i._result&&!i._result._types&&(i._result._types=this._types),this.pipeline){let a=typeof e.submit=="function"&&!(i instanceof BAe)?"Custom query classes such as pg-cursor and pg-query-stream are":i.rows?"The `rows` option is":null;if(a)return process.nextTick(()=>{i.handleError(new Error(`${a} not supported in pipeline mode`),this.connection)}),o}return this._queryable?this._ending?(process.nextTick(()=>{i.handleError(new Error("Client was closed and is not queryable"),this.connection)}),o):(this._queryQueue.length>0&&!this.pipeline&&cBn(),this._queryQueue.push(i),this._pulseQueryQueue(),o):(process.nextTick(()=>{i.handleError(new Error("Client has encountered a connection error and is not queryable"),this.connection)}),o)}ref(){this.connection.ref()}unref(){this.connection.unref()}getTransactionStatus(){return this._txStatus}end(e){if(this._ending=!0,!this.connection._connecting||this._ended)if(e){e();return}else return this._Promise.resolve();if(this._queryable?this.pipeline&&(this._getActiveQuery()||this._sentQueryQueue.length>0||this._queryQueue.length>0)?this.once("drain",()=>this.connection.end()):this._getActiveQuery()?this.connection.stream.destroy():this.connection.end():this.connection.stream.destroy(),e)this.connection.once("end",e);else return new this._Promise(n=>{this.connection.once("end",n)})}get queryQueue(){return oBn(),this._queryQueue}};nV.Query=BAe;$tt.exports=nV});var qtt=Q((Obi,Gtt)=>{"use strict";var lBn=J("events").EventEmitter,DAe=function(){},Htt=(t,e)=>{let n=t.findIndex(e);return n===-1?void 0:t.splice(n,1)[0]},MAe=class{constructor(e,n,r){this.client=e,this.idleListener=n,this.timeoutId=r}},cB=class{constructor(e){this.callback=e}};function dBn(){throw new Error("Release called on client which has already been released to the pool.")}function rV(t,e){if(e)return{callback:e,result:void 0};let n,r,i=function(s,a){s?n(s):r(a)},o=new t(function(s,a){r=s,n=a}).catch(s=>{throw Error.captureStackTrace(s),s});return{callback:i,result:o}}function pBn(t,e){return function n(r){r.client=e,e.removeListener("error",n),e.on("error",()=>{t.log("additional client error after disconnection due to error",r)}),t._remove(e),t.emit("error",r,e)}}var PAe=class extends lBn{constructor(e,n){super(),this.options=Object.assign({},e),e!=null&&"password"in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.min=this.options.min||0,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||n||NAe().Client,this.Promise=this.options.Promise||global.Promise,typeof this.options.idleTimeoutMillis>"u"&&(this.options.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_promiseTry(e){let n=this.Promise;return typeof n.try=="function"?n.try(e):new n(r=>r(e()))}_isFull(){return this._clients.length>=this.options.max}_isAboveMin(){return this._clients.length>this.options.min}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){this.log("pulse queue on ending"),this._idle.length&&this._idle.slice().map(n=>{this._remove(n.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let n=this._idle.pop();clearTimeout(n.timeoutId);let r=n.client;r.ref&&r.ref();let i=n.idleListener;return this._acquireClient(r,e,i,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpected condition")}_remove(e,n){let r=Htt(this._idle,o=>o.client===e);r!==void 0&&clearTimeout(r.timeoutId),this._clients=this._clients.filter(o=>o!==e);let i=this;e.end(()=>{i.emit("remove",e),typeof n=="function"&&n()})}connect(e){if(this.ending){let i=new Error("Cannot use a pool after calling end on the pool");return e?e(i):this.Promise.reject(i)}let n=rV(this.Promise,e),r=n.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new cB(n.callback)),r;let i=(a,c,u)=>{clearTimeout(s),n.callback(a,c,u)},o=new cB(i),s=setTimeout(()=>{Htt(this._pendingQueue,a=>a.callback===i),o.timedOut=!0,n.callback(new Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return s.unref&&s.unref(),this._pendingQueue.push(o),r}return this.newClient(new cB(n.callback)),r}newClient(e){let n=new this.Client(this.options);this._clients.push(n);let r=pBn(this,n);this.log("checking client timeout");let i,o=!1;this.options.connectionTimeoutMillis&&(i=setTimeout(()=>{n.connection?(this.log("ending client due to timeout"),o=!0,n.connection.stream.destroy()):n.isConnected()||(this.log("ending client due to timeout"),o=!0,n.end())},this.options.connectionTimeoutMillis)),this.log("connecting new client"),n.connect(s=>{if(i&&clearTimeout(i),n.on("error",r),s)this.log("client failed to connect",s),this._clients=this._clients.filter(a=>a!==n),o&&(s=new Error("Connection terminated due to connection timeout",{cause:s})),this._pulseQueue(),e.timedOut||e.callback(s,void 0,DAe);else{if(this.log("new client connected"),this.options.onConnect){this._promiseTry(()=>this.options.onConnect(n)).then(()=>{this._afterConnect(n,e,r)},a=>{this._clients=this._clients.filter(c=>c!==n),n.end(()=>{this._pulseQueue(),e.timedOut||e.callback(a,void 0,DAe)})});return}return this._afterConnect(n,e,r)}})}_afterConnect(e,n,r){if(this.options.maxLifetimeSeconds!==0){let i=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired.add(e),this._idle.findIndex(s=>s.client===e)!==-1&&this._acquireClient(e,new cB((s,a,c)=>c()),r,!1)},this.options.maxLifetimeSeconds*1e3);i.unref(),e.once("end",()=>clearTimeout(i))}return this._acquireClient(e,n,r,!0)}_acquireClient(e,n,r,i){i&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,r),e.removeListener("error",r),n.timedOut?i&&this.options.verify?this.options.verify(e,e.release):e.release():i&&this.options.verify?this.options.verify(e,o=>{if(o)return e.release(o),n.callback(o,void 0,DAe);n.callback(void 0,e,e.release)}):n.callback(void 0,e,e.release)}_releaseOnce(e,n){let r=!1;return i=>{r&&dBn(),r=!0,this._release(e,n,i)}}_release(e,n,r){if(e.on("error",n),e._poolUseCount=(e._poolUseCount||0)+1,this.emit("release",r,e),r||this.ending||!e._queryable||e._ending||e._poolUseCount>=this.options.maxUses)return e._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(e,this._pulseQueue.bind(this));if(this._expired.has(e))return this.log("remove expired client"),this._expired.delete(e),this._remove(e,this._pulseQueue.bind(this));let o;this.options.idleTimeoutMillis&&this._isAboveMin()&&(o=setTimeout(()=>{this._isAboveMin()&&(this.log("remove idle client"),this._remove(e,this._pulseQueue.bind(this)))},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&o.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new MAe(e,n,o)),this._pulseQueue()}query(e,n,r){if(typeof e=="function"){let o=rV(this.Promise,e);return setImmediate(function(){return o.callback(new Error("Passing a function as the first parameter to pool.query is not supported"))}),o.result}typeof n=="function"&&(r=n,n=void 0);let i=rV(this.Promise,r);return r=i.callback,this.connect((o,s)=>{if(o)return r(o);let a=!1,c=u=>{a||(a=!0,s.release(u),r(u))};s.once("error",c),this.log("dispatching query");try{s.query(e,n,(u,l)=>{if(this.log("query dispatched"),s.removeListener("error",c),!a)return a=!0,s.release(u),u?r(u):r(void 0,l)})}catch(u){return s.release(u),r(u)}}),i.result}end(e){if(this.log("ending"),this.ending){let r=new Error("Called end on pool more than once");return e?e(r):this.Promise.reject(r)}this.ending=!0;let n=rV(this.Promise,e);return this._endCallback=n.callback,this._pulseQueue(),n.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,n)=>e+(this._expired.has(n)?1:0),0)}get totalCount(){return this._clients.length}};Gtt.exports=PAe});var Vtt=Q((Fbi,ztt)=>{"use strict";var jtt=J("events").EventEmitter,hBn=J("util"),LAe=YI(),uB=ztt.exports=function(t,e,n){jtt.call(this),t=LAe.normalizeQueryConfig(t,e,n),this.text=t.text,this.values=t.values,this.name=t.name,this.queryMode=t.queryMode,this.callback=t.callback,this.state="new",this._arrayMode=t.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(r){r==="row"&&(this._emitRowEvents=!0)}.bind(this))};hBn.inherits(uB,jtt);var mBn={sqlState:"code",statementPosition:"position",messagePrimary:"message",messageDetail:"detail",messageHint:"hint",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};uB.prototype.handleError=function(t){let e=this.native&&this.native.pq.resultErrorFields();if(e)for(let n in e){let r=mBn[n]||n;t[r]=e[n]}this.callback?this.callback(t):this.emit("error",t),this.state="error"};uB.prototype.then=function(t,e){return this._getPromise().then(t,e)};uB.prototype.catch=function(t){return this._getPromise().catch(t)};uB.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(t,e){this._once("end",t),this._once("error",e)}.bind(this)),this._promise)};uB.prototype.submit=function(t){this.state="running";let e=this;this.native=t.native,t.native.arrayMode=this._arrayMode;let n=function(r,i,o){if(t.native.arrayMode=!1,setImmediate(function(){e.emit("_done")}),r)return e.handleError(r);e._emitRowEvents&&(o.length>1?i.forEach((s,a)=>{s.forEach(c=>{e.emit("row",c,o[a])})}):i.forEach(function(s){e.emit("row",s,o)})),e.state="end",e.emit("end",o),e.callback&&e.callback(null,o)};if(process.domain&&(n=process.domain.bind(n)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));let r=(this.values||[]).map(LAe.prepareValue);if(t.namedQueries[this.name]!==void 0){if(this.text&&t.namedQueries[this.name]!==this.text){let i=new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return n(i)}return t.native.execute(this.name,r,n)}return t.native.prepare(this.name,this.text,r.length,function(i){return i?n(i):(t.namedQueries[e.name]=e.text,e.native.execute(e.name,r,n))})}else if(this.values){if(!Array.isArray(this.values)){let i=new Error("Query values must be an array");return n(i)}let r=this.values.map(LAe.prepareValue);t.native.query(this.text,r,n)}else this.queryMode==="extended"?t.native.query(this.text,[],n):t.native.query(this.text,n)}});var Ztt=Q((Ubi,Xtt)=>{var fBn=J("util"),Ktt;try{Ktt=J("pg-native")}catch(t){throw t}var gBn=j6(),Ytt=J("events").EventEmitter,ABn=J("util"),yBn=Zge(),Jtt=Vtt(),wBn=fBn.deprecate(()=>{},"Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead."),Fc=Xtt.exports=function(t){Ytt.call(this),t=t||{},this._Promise=t.Promise||global.Promise,this._types=new gBn(t.types),this.native=new Ktt({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0,this.pipeline=!!t.pipeline,this._pipelineInFlight=!1;let e=this.connectionParameters=new yBn(t);t.nativeConnectionString&&(e.nativeConnectionString=t.nativeConnectionString),this.user=e.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),this.database=e.database,this.host=e.host,this.port=e.port,this.namedQueries={}};Fc.Query=Jtt;ABn.inherits(Fc,Ytt);Fc.prototype._errorAllQueries=function(t){let e=n=>{process.nextTick(()=>{n.native=this.native,n.handleError(t)})};this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(e),this._queryQueue.length=0};Fc.prototype._connect=function(t){let e=this;if(this._connecting){process.nextTick(()=>t(new Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(n,r){if(e.connectionParameters.nativeConnectionString&&(r=e.connectionParameters.nativeConnectionString),n)return t(n);e.native.connect(r,function(i){if(i)return e.native.end(),t(i);e._connected=!0,e.native.on("error",function(o){e._queryable=!1,e._errorAllQueries(o),e.emit("error",o)}),e.native.on("notification",function(o){e.emit("notification",{channel:o.relname,payload:o.extra})}),e.emit("connect"),e._pulseQueryQueue(!0),t(null,this)})})};Fc.prototype.connect=function(t){if(t){this._connect(t);return}return new this._Promise((e,n)=>{this._connect(r=>{r?n(r):e(this)})})};Fc.prototype.query=function(t,e,n){let r,i,o,s,a;if(t==null)throw new TypeError("Client was passed a null or undefined query");if(typeof t.submit=="function")o=t.query_timeout||this.connectionParameters.query_timeout,i=r=t,typeof e=="function"&&(t.callback=e);else if(o=t.query_timeout||this.connectionParameters.query_timeout,r=new Jtt(t,e,n),!r.callback){let c,u;i=new this._Promise((l,d)=>{c=l,u=d}).catch(l=>{throw Error.captureStackTrace(l),l}),r.callback=(l,d)=>l?u(l):c(d)}return o&&(a=r.callback||(()=>{}),s=setTimeout(()=>{let c=new Error("Query read timeout");process.nextTick(()=>{r.handleError(c,this.connection)}),a(c),r.callback=()=>{};let u=this._queryQueue.indexOf(r);u>-1&&this._queryQueue.splice(u,1),this._pulseQueryQueue()},o),r.callback=(c,u)=>{clearTimeout(s),a(c,u)}),this._queryable?this._ending?(r.native=this.native,process.nextTick(()=>{r.handleError(new Error("Client was closed and is not queryable"))}),i):(this._queryQueue.length>0&&!this.pipeline&&wBn(),this._queryQueue.push(r),this._pulseQueryQueue(),i):(r.native=this.native,process.nextTick(()=>{r.handleError(new Error("Client has encountered a connection error and is not queryable"))}),i)};Fc.prototype.end=function(t){let e=this;this._ending=!0,this._connecting&&!this._connected&&this.once("connect",()=>{this.end(()=>{})});let n;t||(n=new this._Promise(function(i,o){t=s=>s?o(s):i()}));let r=function(){e.native.end(function(){e._connected=!1,e._errorAllQueries(new Error("Connection terminated")),process.nextTick(()=>{e.emit("end"),t&&t()})})};return this.pipeline&&(this._pipelineInFlight||this._queryQueue.length>0)?this.once("drain",r):r(),n};Fc.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};Fc.prototype._pulseQueryQueue=function(t){if(!this._connected)return;if(this.pipeline&&!t)return this._pulsePipelinedQueryQueue();if(this._hasActiveQuery())return;let e=this._queryQueue.shift();if(!e){t||this.emit("drain");return}this._activeQuery=e,e.submit(this);let n=this;e.once("_done",function(){n._pulseQueryQueue()})};Fc.prototype._pulsePipelinedQueryQueue=function(){if(!this._connected||this._pipelineInFlight)return;if(this._queryQueue.length===0){this.hasExecuted&&this.emit("drain");return}this._pipelineInFlight=!0;let t=this,e=[],n=[],r=YI();for(;this._queryQueue.length>0;){let i=this._queryQueue.shift();this.hasExecuted=!0,n.push(i);let o=i.values?i.values.map(r.prepareValue):null,s={text:i.text,name:i.name,arrayMode:i._arrayMode};o&&(s.values=o),i.name&&this.namedQueries[i.name]&&(s._alreadyPrepared=!0),e.push(s)}this.native.pipeline(e,function(i,o){if(t._pipelineInFlight=!1,i){t._connected=!1,t._queryable=!1;for(let s=0;s<n.length;s++){let a=n[s];a.native=t.native,a.handleError(i)}t._errorAllQueries(i),t.emit("error",i),t.emit("end");return}for(let s=0;s<n.length;s++){let a=n[s],c=o[s];a.native=t.native,c.err?a.handleError(c.err):(a.name&&(t.namedQueries[a.name]=a.text),a.state="end",a.emit("end",c.result),a.callback&&a.callback(null,c.result)),setImmediate(function(){a.emit("_done")})}t._pulsePipelinedQueryQueue()})};Fc.prototype.cancel=function(t){this._activeQuery===t?this.native.cancel(function(){}):this._queryQueue.indexOf(t)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(t),1)};Fc.prototype.ref=function(){};Fc.prototype.unref=function(){};Fc.prototype.setTypeParser=function(t,e,n){return this._types.setTypeParser(t,e,n)};Fc.prototype.getTypeParser=function(t,e){return this._types.getTypeParser(t,e)};Fc.prototype.isConnected=function(){return this._connected};Fc.prototype.getTransactionStatus=function(){return this.native.getTransactionStatus()}});var QAe=Q(($bi,ent)=>{"use strict";ent.exports=Ztt()});var NAe=Q((Hbi,iV)=>{"use strict";var EBn=Wtt(),xBn=UF(),bBn=_Ae(),CBn=tAe(),IBn=YI(),vBn=qtt(),SBn=j6(),{DatabaseError:_Bn}=IAe(),{escapeIdentifier:kBn,escapeLiteral:TBn}=YI(),RBn=t=>class extends vBn{constructor(n){super(n,t)}},tnt=function(t){this.defaults=xBn,this.Client=t,this.Query=this.Client.Query,this.Pool=RBn(this.Client),this._pools=[],this.Connection=bBn,this.types=FF(),this.DatabaseError=_Bn,this.TypeOverrides=SBn,this.escapeIdentifier=kBn,this.escapeLiteral=TBn,this.Result=CBn,this.utils=IBn},nnt=EBn,rnt=!1;try{rnt=!!process.env.NODE_PG_FORCE_NATIVE}catch{}rnt&&(nnt=QAe());iV.exports=new tnt(nnt);Object.defineProperty(iV.exports,"native",{configurable:!0,enumerable:!1,get(){let t=null;try{t=new tnt(QAe())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(iV.exports,"native",{value:t}),t}})});var ep,Gbi,qbi,jbi,zbi,Vbi,Kbi,Ybi,Jbi,Xbi,Zbi,eCi,int,ont=y(()=>{ep=an(NAe(),1),Gbi=ep.default.Client,qbi=ep.default.Pool,jbi=ep.default.Connection,zbi=ep.default.types,Vbi=ep.default.Query,Kbi=ep.default.DatabaseError,Ybi=ep.default.escapeIdentifier,Jbi=ep.default.escapeLiteral,Xbi=ep.default.Result,Zbi=ep.default.TypeOverrides,eCi=ep.default.defaults,int=ep.default});var BBn,DBn,OAe,rCi,snt=y(()=>{"use strict";ont();BBn=["mail","node","grant","run_event","report","structured_request","queue","spend_limits","environment_image","fault_retry","settings","machine","machine_call","document"],DBn=new Set(BBn),OAe=class{dirty=new Map;subscribers=new Set;scheduled;checkIntervalMs;checkTimeoutMs;reconnectMs;constructor(e={}){this.checkIntervalMs=e.checkIntervalMs??3e4,this.checkTimeoutMs=e.checkTimeoutMs??1e4,this.reconnectMs=e.reconnectMs??1e3}async subscribe(e,n={}){let r={listener:e,kinds:new Set(n.kinds??["mail","node"]),onListenStart:n.onListenStart};return this.subscribers.add(r),this.listener!==void 0&&r.onListenStart!==void 0&&queueMicrotask(()=>{this.subscribers.has(r)&&this.callListenStart(r)}),()=>{this.subscribers.delete(r)}}markMail(e){this.mark("mail",e)}markNode(e){this.mark("node",e)}markSignal(e,n){this.mark(e,n)}mark(e,n){let r=`${e}:${n}`;this.dirty.has(r)||this.dirty.set(r,{id:n,kind:e}),this.scheduled??=setImmediate(()=>this.flush())}flush(){this.scheduled=void 0;let e=[...this.dirty.values()];this.dirty.clear();for(let{id:n,kind:r}of e)for(let i of this.subscribers)if(i.kinds.has(r))try{i.listener(n,r)}catch{}}callListenStart(e){try{e.onListenStart?.()}catch{}}async listen(e){this.listener!==void 0||this.listening!==void 0||(this.url=e,this.listening=this.connectListener().finally(()=>{this.listening=void 0}),await this.listening)}listener;listening;url;reconnect;check;async connectListener(){let e=new int.Client({connectionString:this.url,application_name:`crtr-signal-${process.pid}`,keepAlive:!0});e.on("notification",r=>{let i=r.payload??"",o=i.indexOf(":");if(o<0)return;let s=i.slice(0,o);DBn.has(s)&&this.mark(s,i.slice(o+1))});let n=()=>{this.listener===e&&(this.dropListener(e),this.scheduleReconnect())};e.on("error",n),e.on("end",n);try{await e.connect(),await e.query("LISTEN crtr_signal")}catch(r){throw e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{}),r}if(this.url===void 0){e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{});return}this.listener=e,this.startChecks(e,n);for(let r of[...this.subscribers])this.callListenStart(r)}startChecks(e,n){this.stopChecks(),this.check=setInterval(()=>{if(this.listener!==e)return;let r,i=new Promise((o,s)=>{r=setTimeout(()=>s(new Error("listen connection check timed out")),this.checkTimeoutMs)});Promise.race([e.query("SELECT 1"),i]).catch(()=>n()).finally(()=>clearTimeout(r))},this.checkIntervalMs),this.check.unref()}stopChecks(){this.check!==void 0&&clearInterval(this.check),this.check=void 0}dropListener(e){this.listener=void 0,this.stopChecks(),e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{})}scheduleReconnect(){this.url===void 0||this.reconnect!==void 0||(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.url!==void 0&&(this.listening=this.connectListener().catch(()=>this.scheduleReconnect()).finally(()=>{this.listening=void 0}))},this.reconnectMs))}close(){this.url=void 0,this.reconnect!==void 0&&clearTimeout(this.reconnect),this.reconnect=void 0,this.stopChecks();let e=this.listener;return this.listener=void 0,this.scheduled!==void 0&&clearImmediate(this.scheduled),this.scheduled=void 0,this.dirty.clear(),this.subscribers.clear(),e===void 0?Promise.resolve():(e.removeAllListeners("notification"),e.removeAllListeners("error"),e.on("error",()=>{}),e.end().catch(()=>{}))}},rCi=new OAe});var ant=y(()=>{"use strict";MF()});function QBn(t){switch(t){case NBn:return"context-nudge";case MBn:return"bearings";case LBn:return"review-boundary";case PBn:return"situational";default:return}}function UAe(t){return t.replace(/&(?:amp|lt|gt|quot|apos);/g,e=>({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&apos;":"'"})[e])}function FAe(t){let e={};oV.lastIndex=0;let n=0;for(;n<t.length&&!/^\s*$/.test(t.slice(n));){oV.lastIndex=n;let r=oV.exec(t);if(r===null)return null;let[,i,o,s]=r;if(i===void 0||Object.hasOwn(e,i))return null;e[i]=UAe(o??s??""),n=oV.lastIndex}return e}function $Ae(t){return typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.filter(e=>typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(""):""}function OBn(t){let e=[],n=/<from\b([^>]*)>([\s\S]*?)<\/from>/g;for(let r of t.matchAll(n)){let i=FAe(r[1]??"");if(i?.id===void 0)continue;let o=[],s=r[2]??"",a=/<entry\b([^>]*)>([\s\S]*?)<\/entry>/g;for(let u of s.matchAll(a)){let l=FAe(u[1]??"");if(l?.kind===void 0)continue;let d=l.disposition==="human-answer"||l.disposition==="human-canceled"?l.disposition:"report";o.push({kind:l.kind,disposition:d,body:UAe(u[2]??""),...l.ref===void 0?{}:{ref:l.ref}})}let c=i.updates===void 0?Number.NaN:Number(i.updates);e.push({id:i.id,updates:Number.isFinite(c)?c:o.length,finished:i.finished==="true"||o.some(u=>u.kind==="final"),entries:o})}return e}function FBn(t,e,n,r){return{kind:t,facts:e,body:n,senders:r}}function pnt(t){let e=/^<runtime\b([^>]*)>/.exec(t);if(e===null||!t.endsWith("</runtime>"))return null;let n=FAe(e[1]??"");if(n?.kind===void 0)return null;let r=t.slice(e[0].length,-10),{kind:i,...o}=n,s=Object.freeze(o),a=i.includes(":")?UAe(r):r;return FBn(i,s,a,i==="inbox"?OBn(a):[])}function lB(t){let e=$Ae(t),n=pnt(e);if(n!==null)return n;if(t.role!=="custom")return null;let r=QBn(t.customType);return r===void 0?null:{kind:r,facts:Object.freeze({}),body:e,senders:[]}}function ev(t){return t.disposition==="human-answer"&&pnt(t.body.trim())===null}var MBn,PBn,NBn,LBn,cnt,unt,lnt,dnt,oV,tv=y(()=>{"use strict";MBn="crtr-context",PBn="crtr-situational-context",NBn="crtr-context-nudge",LBn="crtr-review-boundary",cnt="Provider credentials were just updated (a new login landed). Your previous turn stopped on a provider authentication failure. Continue from where you left off and retry the work that failed.",unt="The network connection is back online. Your previous turn stopped on a connection error (the network was down). Continue from where you left off and retry the work that failed.",lnt="Your previous turn stopped on a connection error reaching the model provider. Retrying now: continue from where you left off and retry the work that failed.",dnt="Your previous turn stopped on a provider fault. Continue from where you left off and retry the work that failed.";oV=/\s+([A-Za-z_:][A-Za-z0-9_:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/gy});var hnt=y(()=>{"use strict";tv()});function UBn(){let t=process.env.CRTR_API_URL;if(!(t===void 0||t==="")){if(!/^https?:\/\//.test(t))throw new Error(`CRTR_API_URL must be an http(s) URL: ${t}`);return t}}function DF(){let t=UBn();if(t===void 0)return lE({autostart:!1});let e=cet();if(e===void 0)throw new Error("broker has no node token for CRTR_API_URL");return new kg({baseUrl:t,headers:{authorization:`Bearer ${e}`}})}function mnt(t,e){return DF().appendNodeLog(t,{record:e,expected_execution_id:$Bn()})}function $Bn(){let t=kJe();if(t===void 0||t==="")throw new Error("broker launch is missing CRTR_EXECUTION_ID");return t}async function fnt(t,e){return DF().recordNodeFault(t,e)}async function gnt(t,e={}){return DF().clearNodeFault(t,{...e.link===void 0?{}:{link:e.link},...e.preserveEpisode===void 0?{}:{preserve_episode:e.preserveEpisode}}).then(n=>n.cleared)}var MF=y(()=>{"use strict";F6();uet();U6();_g();Pge();du();pet();nv();snt();ant();hnt()});function HBn(t,e){Ant=Ant.then(async()=>{try{let{appended:n}=await mnt(t,e);n||process.stderr.write(`[broker] log.jsonl refused record: ${e}
98
+ `);WF.write(Ntt.format.apply(Ntt,e))}}Object.defineProperty(H0.exports,"isWin",{get:function(){return Z6},set:function(t){Z6=t}});H0.exports.warnTo=function(t){var e=WF;return WF=t,e};H0.exports.getFileName=function(t){var e=t||process.env,n=e.PGPASSFILE||(Z6?Ptt.join(e.APPDATA||"./","postgresql","pgpass.conf"):Ptt.join(e.HOME||"./",".pgpass"));return n};H0.exports.usePgPass=function(t,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:Z6?!0:(e=e||"<unkn>",VRn(t.mode)?t.mode&(GRn|qRn)?(TAe('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(TAe('WARNING: password file "%s" is not a plain file',e),!1))};var YRn=H0.exports.match=function(t,e){return aB.slice(0,-1).reduce(function(n,r,i){return i==1&&Number(t[r]||HRn)===Number(e[r])?n&&!0:n&&(e[r]==="*"||e[r]===t[r])},!0)};H0.exports.getPassword=function(t,e,n){var r,i=e.pipe(WRn());function o(c){var u=JRn(c);u&&XRn(u)&&YRn(t,u)&&(r=u[KRn],i.end())}var s=function(){e.destroy(),n(r)},a=function(c){e.destroy(),TAe("WARNING: error on reading file: %s",c),n(void 0)};e.on("error",a),i.on("data",o).on("end",s).on("error",a)};var JRn=H0.exports.parseLine=function(t){if(t.length<11||t.match(/^\s+#/))return null;for(var e="",n="",r=0,i=0,o=0,s={},a=!1,c=function(l,d,p){var h=t.substring(d,p);Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE")||(h=h.replace(/\\([:\\])/g,"$1")),s[aB[l]]=h},u=0;u<t.length-1;u+=1){if(e=t.charAt(u+1),n=t.charAt(u),a=r==kAe-1,a){c(r,i);break}u>=0&&e==":"&&n!=="\\"&&(c(r,i,u+1),i=u+2,r+=1)}return s=Object.keys(s).length===kAe?s:null,s},XRn=H0.exports.isValidEntry=function(t){for(var e={0:function(s){return s.length>0},1:function(s){return s==="*"?!0:(s=Number(s),isFinite(s)&&s>0&&s<9007199254740992&&Math.floor(s)===s)},2:function(s){return s.length>0},3:function(s){return s.length>0},4:function(s){return s.length>0}},n=0;n<aB.length;n+=1){var r=e[n],i=t[aB[n]]||"",o=r(i);if(!o)return!1}return!0}});var Ott=Q((Lbi,RAe)=>{"use strict";var Nbi=J("path"),Qtt=J("fs"),eV=Ltt();RAe.exports=function(t,e){var n=eV.getFileName();Qtt.stat(n,function(r,i){if(r||!eV.usePgPass(i,n))return e(void 0);var o=Qtt.createReadStream(n);eV.getPassword(t,o,e)})};RAe.exports.warnTo=eV.warnTo});var Wtt=Q((Qbi,$tt)=>{var ZRn=J("events").EventEmitter,Ftt=YI(),HF=J("util"),tV=ntt(),eBn=j6(),tBn=Zge(),BAe=ftt(),nBn=UF(),rBn=_Ae(),iBn=Vge(),Utt=HF.deprecate(()=>{},"Client.activeQuery is deprecated and will be removed in pg@9.0"),oBn=HF.deprecate(()=>{},"Client.queryQueue is deprecated and will be removed in pg@9.0."),sBn=HF.deprecate(()=>{},"pgpass support is deprecated and will be removed in pg@9.0. You can provide an async function as the password property to the Client/Pool constructor that returns a password instead. Within this function you can call the pgpass module in your own code."),aBn=HF.deprecate(()=>{},"Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0."),cBn=HF.deprecate(()=>{},"Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead.");function uBn(t,e){if(typeof t=="number")return Number.isFinite(t)?t:e;if(typeof t=="string"&&t.trim()!==""){let n=Number(t);return Number.isFinite(n)?n:e}return e}var nV=class extends ZRn{constructor(e){super(),this.connectionParameters=new tBn(e),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;let n=e||{};n.Promise&&aBn(),this._Promise=n.Promise||global.Promise,this._types=new eBn(n.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this._activeQuery=null,this._txStatus=null,this.enableChannelBinding=!!n.enableChannelBinding,this.scramMaxIterations=uBn(n.scramMaxIterations,tV.DEFAULT_MAX_SCRAM_ITERATIONS),this.connection=n.connection||new rBn({stream:n.stream,ssl:this.connectionParameters.ssl,sslNegotiation:this.connectionParameters.sslnegotiation,keepAlive:n.keepAlive||!1,keepAliveInitialDelayMillis:n.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this._queryQueue=[],this._sentQueryQueue=[],this.pipeline=!!n.pipeline,this.binary=n.binary||nBn.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.sslNegotiation=this.connectionParameters.sslnegotiation||"postgres",this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=n.connectionTimeoutMillis||0}get activeQuery(){return Utt(),this._activeQuery}set activeQuery(e){Utt(),this._activeQuery=e}_getActiveQuery(){return this._activeQuery}_errorAllQueries(e){let n=i=>{process.nextTick(()=>{i.handleError(e,this.connection)})},r=this._getActiveQuery();r&&(n(r),this._activeQuery=null),this._sentQueryQueue.forEach(n),this._sentQueryQueue.length=0,this._queryQueue.forEach(n),this._queryQueue.length=0}_connect(e){let n=this,r=this.connection;if(this._connectionCallback=e,this._connecting||this._connected){let i=new Error("Client has already been connected. You cannot reuse a client.");process.nextTick(()=>{e(i)});return}this._connecting=!0,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{r._ending=!0,r.stream.destroy(new Error("timeout expired"))},this._connectionTimeoutMillis),this.connectionTimeoutHandle.unref&&this.connectionTimeoutHandle.unref()),this.host&&this.host.indexOf("/")===0?r.connect(this.host+"/.s.PGSQL."+this.port):r.connect(this.port,this.host),r.on("connect",function(){n.ssl?n.sslNegotiation!=="direct"&&r.requestSsl():r.startup(n.getStartupConf())}),r.on("sslconnect",function(){r.startup(n.getStartupConf())}),this._attachListeners(r),r.once("end",()=>{let i=this._ending?new Error("Connection terminated"):new Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(i),this._ended=!0,this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(i):this._handleErrorEvent(i):this._connectionError||this._handleErrorEvent(i)),process.nextTick(()=>{this.emit("end")})})}connect(e){if(e){this._connect(e);return}return new this._Promise((n,r)=>{this._connect(i=>{i?r(i):n(this)})})}_attachListeners(e){e.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),e.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),e.on("authenticationSASL",this._handleAuthSASL.bind(this)),e.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),e.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),e.on("backendKeyData",this._handleBackendKeyData.bind(this)),e.on("error",this._handleErrorEvent.bind(this)),e.on("errorMessage",this._handleErrorMessage.bind(this)),e.on("readyForQuery",this._handleReadyForQuery.bind(this)),e.on("notice",this._handleNotice.bind(this)),e.on("rowDescription",this._handleRowDescription.bind(this)),e.on("dataRow",this._handleDataRow.bind(this)),e.on("portalSuspended",this._handlePortalSuspended.bind(this)),e.on("emptyQuery",this._handleEmptyQuery.bind(this)),e.on("commandComplete",this._handleCommandComplete.bind(this)),e.on("parseComplete",this._handleParseComplete.bind(this)),e.on("copyInResponse",this._handleCopyInResponse.bind(this)),e.on("copyData",this._handleCopyData.bind(this)),e.on("notification",this._handleNotification.bind(this))}_getPassword(e){let n=this.connection;if(typeof this.password=="function")this._Promise.resolve().then(()=>this.password(this.connectionParameters)).then(r=>{if(r!==void 0){if(typeof r!="string"){n.emit("error",new TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=r}else this.connectionParameters.password=this.password=null;e()}).catch(r=>{n.emit("error",r)});else if(this.password!==null)e();else try{Ott()(this.connectionParameters,i=>{i!==void 0&&(sBn(),this.connectionParameters.password=this.password=i),e()})}catch(r){this.emit("error",r)}}_handleAuthCleartextPassword(e){this._getPassword(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){this._getPassword(async()=>{try{let n=await iBn.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(n)}catch(n){this.emit("error",n)}})}_handleAuthSASL(e){this._getPassword(()=>{try{this.saslSession=tV.startSession(e.mechanisms,this.enableChannelBinding&&this.connection.stream,this.scramMaxIterations),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(n){this.connection.emit("error",n)}})}async _handleAuthSASLContinue(e){try{await tV.continueSession(this.saslSession,this.password,e.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(n){this.connection.emit("error",n)}}_handleAuthSASLFinal(e){try{tV.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(n){this.connection.emit("error",n)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let n=this._getActiveQuery();this._activeQuery=null,this._txStatus=e?.status??null,this.readyForQuery=!0,n&&n.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit("error",e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit("error",e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let n=this._getActiveQuery();if(!n){this._handleErrorEvent(e);return}this._activeQuery=null,n.name&&delete this.connection.submittedNamedStatements[n.name],n.handleError(e,this.connection)}_handleRowDescription(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected rowDescription message from backend.");this._handleErrorEvent(r);return}n.handleRowDescription(e)}_handleDataRow(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected dataRow message from backend.");this._handleErrorEvent(r);return}n.handleDataRow(e)}_handlePortalSuspended(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected portalSuspended message from backend.");this._handleErrorEvent(r);return}n.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected emptyQuery message from backend.");this._handleErrorEvent(r);return}n.handleEmptyQuery(this.connection)}_handleCommandComplete(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected commandComplete message from backend.");this._handleErrorEvent(r);return}n.handleCommandComplete(e,this.connection)}_handleParseComplete(){let e=this._getActiveQuery();if(e==null){let n=new Error("Received unexpected parseComplete message from backend.");this._handleErrorEvent(n);return}e.name&&(this.connection.parsedStatements[e.name]=e.text,delete this.connection.submittedNamedStatements[e.name])}_handleCopyInResponse(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected copyInResponse message from backend.");this._handleErrorEvent(r);return}n.handleCopyInResponse(this.connection)}_handleCopyData(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected copyData message from backend.");this._handleErrorEvent(r);return}n.handleCopyData(e,this.connection)}_handleNotification(e){this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){let e=this.connectionParameters,n={user:e.user,database:e.database},r=e.application_name||e.fallback_application_name;return r&&(n.application_name=r),e.replication&&(n.replication=""+e.replication),e.statement_timeout&&(n.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(n.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(n.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(n.options=e.options),n}cancel(e,n){if(e.activeQuery===n){let r=this.connection;this.host&&this.host.indexOf("/")===0?r.connect(this.host+"/.s.PGSQL."+this.port):r.connect(this.port,this.host),r.on("connect",function(){r.cancel(e.processID,e.secretKey)})}else e._queryQueue.indexOf(n)!==-1?e._queryQueue.splice(e._queryQueue.indexOf(n),1):e._sentQueryQueue.indexOf(n)!==-1&&(n.callback=()=>{})}setTypeParser(e,n,r){return this._types.setTypeParser(e,n,r)}getTypeParser(e,n){return this._types.getTypeParser(e,n)}escapeIdentifier(e){return Ftt.escapeIdentifier(e)}escapeLiteral(e){return Ftt.escapeLiteral(e)}_pulseQueryQueue(){if(this.pipeline){this._pulsePipelinedQueryQueue();return}if(this.readyForQuery===!0){this._activeQuery=this._queryQueue.shift();let e=this._getActiveQuery();if(e){this.readyForQuery=!1,this.hasExecuted=!0;let n=e.submit(this.connection);n&&process.nextTick(()=>{e.handleError(n,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this._activeQuery=null,this.emit("drain"))}}_pulsePipelinedQueryQueue(){if(!(!this._connected||!this._queryable)){for(;this._queryQueue.length>0;){let e=this._queryQueue.shift();this.hasExecuted=!0;let n=e.submit(this.connection);if(n){process.nextTick(()=>{e.handleError(n,this.connection)});continue}this._sentQueryQueue.push(e)}this.readyForQuery&&!this._activeQuery&&this._sentQueryQueue.length>0&&(this._activeQuery=this._sentQueryQueue.shift(),this.readyForQuery=!1),!this._activeQuery&&this._sentQueryQueue.length===0&&this._queryQueue.length===0&&this.hasExecuted&&this.emit("drain")}}query(e,n,r){let i,o;if(e==null)throw new TypeError("Client was passed a null or undefined query");if(typeof e.submit=="function")o=i=e,i.callback||(typeof n=="function"?i.callback=n:r&&(i.callback=r));else if(i=new BAe(e,n,r),!i.callback)o=new this._Promise((a,c)=>{i.callback=(u,l)=>u?c(u):a(l)}).catch(a=>{throw Error.captureStackTrace(a),a});else if(typeof i.callback!="function")throw new TypeError("callback is not a function");let s=e.query_timeout||this.connectionParameters.query_timeout;if(s){let a=i.callback||(()=>{}),c=setTimeout(()=>{let u=new Error("Query read timeout");process.nextTick(()=>{i.handleError(u,this.connection)}),a(u),i.callback=()=>{};let l=this._queryQueue.indexOf(i);if(l>-1)this._queryQueue.splice(l,1);else if(this.pipeline){this.connection.stream.destroy();return}this._pulseQueryQueue()},s);i.callback=(u,l)=>{clearTimeout(c),a(u,l)}}if(this.binary&&!i.binary&&(i.binary=!0),i._result&&!i._result._types&&(i._result._types=this._types),this.pipeline){let a=typeof e.submit=="function"&&!(i instanceof BAe)?"Custom query classes such as pg-cursor and pg-query-stream are":i.rows?"The `rows` option is":null;if(a)return process.nextTick(()=>{i.handleError(new Error(`${a} not supported in pipeline mode`),this.connection)}),o}return this._queryable?this._ending?(process.nextTick(()=>{i.handleError(new Error("Client was closed and is not queryable"),this.connection)}),o):(this._queryQueue.length>0&&!this.pipeline&&cBn(),this._queryQueue.push(i),this._pulseQueryQueue(),o):(process.nextTick(()=>{i.handleError(new Error("Client has encountered a connection error and is not queryable"),this.connection)}),o)}ref(){this.connection.ref()}unref(){this.connection.unref()}getTransactionStatus(){return this._txStatus}end(e){if(this._ending=!0,!this.connection._connecting||this._ended)if(e){e();return}else return this._Promise.resolve();if(this._queryable?this.pipeline&&(this._getActiveQuery()||this._sentQueryQueue.length>0||this._queryQueue.length>0)?this.once("drain",()=>this.connection.end()):this._getActiveQuery()?this.connection.stream.destroy():this.connection.end():this.connection.stream.destroy(),e)this.connection.once("end",e);else return new this._Promise(n=>{this.connection.once("end",n)})}get queryQueue(){return oBn(),this._queryQueue}};nV.Query=BAe;$tt.exports=nV});var qtt=Q((Obi,Gtt)=>{"use strict";var lBn=J("events").EventEmitter,DAe=function(){},Htt=(t,e)=>{let n=t.findIndex(e);return n===-1?void 0:t.splice(n,1)[0]},MAe=class{constructor(e,n,r){this.client=e,this.idleListener=n,this.timeoutId=r}},cB=class{constructor(e){this.callback=e}};function dBn(){throw new Error("Release called on client which has already been released to the pool.")}function rV(t,e){if(e)return{callback:e,result:void 0};let n,r,i=function(s,a){s?n(s):r(a)},o=new t(function(s,a){r=s,n=a}).catch(s=>{throw Error.captureStackTrace(s),s});return{callback:i,result:o}}function pBn(t,e){return function n(r){r.client=e,e.removeListener("error",n),e.on("error",()=>{t.log("additional client error after disconnection due to error",r)}),t._remove(e),t.emit("error",r,e)}}var PAe=class extends lBn{constructor(e,n){super(),this.options=Object.assign({},e),e!=null&&"password"in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.min=this.options.min||0,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||n||NAe().Client,this.Promise=this.options.Promise||global.Promise,typeof this.options.idleTimeoutMillis>"u"&&(this.options.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_promiseTry(e){let n=this.Promise;return typeof n.try=="function"?n.try(e):new n(r=>r(e()))}_isFull(){return this._clients.length>=this.options.max}_isAboveMin(){return this._clients.length>this.options.min}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){this.log("pulse queue on ending"),this._idle.length&&this._idle.slice().map(n=>{this._remove(n.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let n=this._idle.pop();clearTimeout(n.timeoutId);let r=n.client;r.ref&&r.ref();let i=n.idleListener;return this._acquireClient(r,e,i,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpected condition")}_remove(e,n){let r=Htt(this._idle,o=>o.client===e);r!==void 0&&clearTimeout(r.timeoutId),this._clients=this._clients.filter(o=>o!==e);let i=this;e.end(()=>{i.emit("remove",e),typeof n=="function"&&n()})}connect(e){if(this.ending){let i=new Error("Cannot use a pool after calling end on the pool");return e?e(i):this.Promise.reject(i)}let n=rV(this.Promise,e),r=n.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new cB(n.callback)),r;let i=(a,c,u)=>{clearTimeout(s),n.callback(a,c,u)},o=new cB(i),s=setTimeout(()=>{Htt(this._pendingQueue,a=>a.callback===i),o.timedOut=!0,n.callback(new Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return s.unref&&s.unref(),this._pendingQueue.push(o),r}return this.newClient(new cB(n.callback)),r}newClient(e){let n=new this.Client(this.options);this._clients.push(n);let r=pBn(this,n);this.log("checking client timeout");let i,o=!1;this.options.connectionTimeoutMillis&&(i=setTimeout(()=>{n.connection?(this.log("ending client due to timeout"),o=!0,n.connection.stream.destroy()):n.isConnected()||(this.log("ending client due to timeout"),o=!0,n.end())},this.options.connectionTimeoutMillis)),this.log("connecting new client"),n.connect(s=>{if(i&&clearTimeout(i),n.on("error",r),s)this.log("client failed to connect",s),this._clients=this._clients.filter(a=>a!==n),o&&(s=new Error("Connection terminated due to connection timeout",{cause:s})),this._pulseQueue(),e.timedOut||e.callback(s,void 0,DAe);else{if(this.log("new client connected"),this.options.onConnect){this._promiseTry(()=>this.options.onConnect(n)).then(()=>{this._afterConnect(n,e,r)},a=>{this._clients=this._clients.filter(c=>c!==n),n.end(()=>{this._pulseQueue(),e.timedOut||e.callback(a,void 0,DAe)})});return}return this._afterConnect(n,e,r)}})}_afterConnect(e,n,r){if(this.options.maxLifetimeSeconds!==0){let i=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired.add(e),this._idle.findIndex(s=>s.client===e)!==-1&&this._acquireClient(e,new cB((s,a,c)=>c()),r,!1)},this.options.maxLifetimeSeconds*1e3);i.unref(),e.once("end",()=>clearTimeout(i))}return this._acquireClient(e,n,r,!0)}_acquireClient(e,n,r,i){i&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,r),e.removeListener("error",r),n.timedOut?i&&this.options.verify?this.options.verify(e,e.release):e.release():i&&this.options.verify?this.options.verify(e,o=>{if(o)return e.release(o),n.callback(o,void 0,DAe);n.callback(void 0,e,e.release)}):n.callback(void 0,e,e.release)}_releaseOnce(e,n){let r=!1;return i=>{r&&dBn(),r=!0,this._release(e,n,i)}}_release(e,n,r){if(e.on("error",n),e._poolUseCount=(e._poolUseCount||0)+1,this.emit("release",r,e),r||this.ending||!e._queryable||e._ending||e._poolUseCount>=this.options.maxUses)return e._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(e,this._pulseQueue.bind(this));if(this._expired.has(e))return this.log("remove expired client"),this._expired.delete(e),this._remove(e,this._pulseQueue.bind(this));let o;this.options.idleTimeoutMillis&&this._isAboveMin()&&(o=setTimeout(()=>{this._isAboveMin()&&(this.log("remove idle client"),this._remove(e,this._pulseQueue.bind(this)))},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&o.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new MAe(e,n,o)),this._pulseQueue()}query(e,n,r){if(typeof e=="function"){let o=rV(this.Promise,e);return setImmediate(function(){return o.callback(new Error("Passing a function as the first parameter to pool.query is not supported"))}),o.result}typeof n=="function"&&(r=n,n=void 0);let i=rV(this.Promise,r);return r=i.callback,this.connect((o,s)=>{if(o)return r(o);let a=!1,c=u=>{a||(a=!0,s.release(u),r(u))};s.once("error",c),this.log("dispatching query");try{s.query(e,n,(u,l)=>{if(this.log("query dispatched"),s.removeListener("error",c),!a)return a=!0,s.release(u),u?r(u):r(void 0,l)})}catch(u){return s.release(u),r(u)}}),i.result}end(e){if(this.log("ending"),this.ending){let r=new Error("Called end on pool more than once");return e?e(r):this.Promise.reject(r)}this.ending=!0;let n=rV(this.Promise,e);return this._endCallback=n.callback,this._pulseQueue(),n.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,n)=>e+(this._expired.has(n)?1:0),0)}get totalCount(){return this._clients.length}};Gtt.exports=PAe});var Vtt=Q((Fbi,ztt)=>{"use strict";var jtt=J("events").EventEmitter,hBn=J("util"),LAe=YI(),uB=ztt.exports=function(t,e,n){jtt.call(this),t=LAe.normalizeQueryConfig(t,e,n),this.text=t.text,this.values=t.values,this.name=t.name,this.queryMode=t.queryMode,this.callback=t.callback,this.state="new",this._arrayMode=t.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(r){r==="row"&&(this._emitRowEvents=!0)}.bind(this))};hBn.inherits(uB,jtt);var mBn={sqlState:"code",statementPosition:"position",messagePrimary:"message",messageDetail:"detail",messageHint:"hint",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};uB.prototype.handleError=function(t){let e=this.native&&this.native.pq.resultErrorFields();if(e)for(let n in e){let r=mBn[n]||n;t[r]=e[n]}this.callback?this.callback(t):this.emit("error",t),this.state="error"};uB.prototype.then=function(t,e){return this._getPromise().then(t,e)};uB.prototype.catch=function(t){return this._getPromise().catch(t)};uB.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(t,e){this._once("end",t),this._once("error",e)}.bind(this)),this._promise)};uB.prototype.submit=function(t){this.state="running";let e=this;this.native=t.native,t.native.arrayMode=this._arrayMode;let n=function(r,i,o){if(t.native.arrayMode=!1,setImmediate(function(){e.emit("_done")}),r)return e.handleError(r);e._emitRowEvents&&(o.length>1?i.forEach((s,a)=>{s.forEach(c=>{e.emit("row",c,o[a])})}):i.forEach(function(s){e.emit("row",s,o)})),e.state="end",e.emit("end",o),e.callback&&e.callback(null,o)};if(process.domain&&(n=process.domain.bind(n)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));let r=(this.values||[]).map(LAe.prepareValue);if(t.namedQueries[this.name]!==void 0){if(this.text&&t.namedQueries[this.name]!==this.text){let i=new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return n(i)}return t.native.execute(this.name,r,n)}return t.native.prepare(this.name,this.text,r.length,function(i){return i?n(i):(t.namedQueries[e.name]=e.text,e.native.execute(e.name,r,n))})}else if(this.values){if(!Array.isArray(this.values)){let i=new Error("Query values must be an array");return n(i)}let r=this.values.map(LAe.prepareValue);t.native.query(this.text,r,n)}else this.queryMode==="extended"?t.native.query(this.text,[],n):t.native.query(this.text,n)}});var Ztt=Q((Ubi,Xtt)=>{var fBn=J("util"),Ktt;try{Ktt=J("pg-native")}catch(t){throw t}var gBn=j6(),Ytt=J("events").EventEmitter,ABn=J("util"),yBn=Zge(),Jtt=Vtt(),wBn=fBn.deprecate(()=>{},"Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead."),Fc=Xtt.exports=function(t){Ytt.call(this),t=t||{},this._Promise=t.Promise||global.Promise,this._types=new gBn(t.types),this.native=new Ktt({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0,this.pipeline=!!t.pipeline,this._pipelineInFlight=!1;let e=this.connectionParameters=new yBn(t);t.nativeConnectionString&&(e.nativeConnectionString=t.nativeConnectionString),this.user=e.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),this.database=e.database,this.host=e.host,this.port=e.port,this.namedQueries={}};Fc.Query=Jtt;ABn.inherits(Fc,Ytt);Fc.prototype._errorAllQueries=function(t){let e=n=>{process.nextTick(()=>{n.native=this.native,n.handleError(t)})};this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(e),this._queryQueue.length=0};Fc.prototype._connect=function(t){let e=this;if(this._connecting){process.nextTick(()=>t(new Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(n,r){if(e.connectionParameters.nativeConnectionString&&(r=e.connectionParameters.nativeConnectionString),n)return t(n);e.native.connect(r,function(i){if(i)return e.native.end(),t(i);e._connected=!0,e.native.on("error",function(o){e._queryable=!1,e._errorAllQueries(o),e.emit("error",o)}),e.native.on("notification",function(o){e.emit("notification",{channel:o.relname,payload:o.extra})}),e.emit("connect"),e._pulseQueryQueue(!0),t(null,this)})})};Fc.prototype.connect=function(t){if(t){this._connect(t);return}return new this._Promise((e,n)=>{this._connect(r=>{r?n(r):e(this)})})};Fc.prototype.query=function(t,e,n){let r,i,o,s,a;if(t==null)throw new TypeError("Client was passed a null or undefined query");if(typeof t.submit=="function")o=t.query_timeout||this.connectionParameters.query_timeout,i=r=t,typeof e=="function"&&(t.callback=e);else if(o=t.query_timeout||this.connectionParameters.query_timeout,r=new Jtt(t,e,n),!r.callback){let c,u;i=new this._Promise((l,d)=>{c=l,u=d}).catch(l=>{throw Error.captureStackTrace(l),l}),r.callback=(l,d)=>l?u(l):c(d)}return o&&(a=r.callback||(()=>{}),s=setTimeout(()=>{let c=new Error("Query read timeout");process.nextTick(()=>{r.handleError(c,this.connection)}),a(c),r.callback=()=>{};let u=this._queryQueue.indexOf(r);u>-1&&this._queryQueue.splice(u,1),this._pulseQueryQueue()},o),r.callback=(c,u)=>{clearTimeout(s),a(c,u)}),this._queryable?this._ending?(r.native=this.native,process.nextTick(()=>{r.handleError(new Error("Client was closed and is not queryable"))}),i):(this._queryQueue.length>0&&!this.pipeline&&wBn(),this._queryQueue.push(r),this._pulseQueryQueue(),i):(r.native=this.native,process.nextTick(()=>{r.handleError(new Error("Client has encountered a connection error and is not queryable"))}),i)};Fc.prototype.end=function(t){let e=this;this._ending=!0,this._connecting&&!this._connected&&this.once("connect",()=>{this.end(()=>{})});let n;t||(n=new this._Promise(function(i,o){t=s=>s?o(s):i()}));let r=function(){e.native.end(function(){e._connected=!1,e._errorAllQueries(new Error("Connection terminated")),process.nextTick(()=>{e.emit("end"),t&&t()})})};return this.pipeline&&(this._pipelineInFlight||this._queryQueue.length>0)?this.once("drain",r):r(),n};Fc.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};Fc.prototype._pulseQueryQueue=function(t){if(!this._connected)return;if(this.pipeline&&!t)return this._pulsePipelinedQueryQueue();if(this._hasActiveQuery())return;let e=this._queryQueue.shift();if(!e){t||this.emit("drain");return}this._activeQuery=e,e.submit(this);let n=this;e.once("_done",function(){n._pulseQueryQueue()})};Fc.prototype._pulsePipelinedQueryQueue=function(){if(!this._connected||this._pipelineInFlight)return;if(this._queryQueue.length===0){this.hasExecuted&&this.emit("drain");return}this._pipelineInFlight=!0;let t=this,e=[],n=[],r=YI();for(;this._queryQueue.length>0;){let i=this._queryQueue.shift();this.hasExecuted=!0,n.push(i);let o=i.values?i.values.map(r.prepareValue):null,s={text:i.text,name:i.name,arrayMode:i._arrayMode};o&&(s.values=o),i.name&&this.namedQueries[i.name]&&(s._alreadyPrepared=!0),e.push(s)}this.native.pipeline(e,function(i,o){if(t._pipelineInFlight=!1,i){t._connected=!1,t._queryable=!1;for(let s=0;s<n.length;s++){let a=n[s];a.native=t.native,a.handleError(i)}t._errorAllQueries(i),t.emit("error",i),t.emit("end");return}for(let s=0;s<n.length;s++){let a=n[s],c=o[s];a.native=t.native,c.err?a.handleError(c.err):(a.name&&(t.namedQueries[a.name]=a.text),a.state="end",a.emit("end",c.result),a.callback&&a.callback(null,c.result)),setImmediate(function(){a.emit("_done")})}t._pulsePipelinedQueryQueue()})};Fc.prototype.cancel=function(t){this._activeQuery===t?this.native.cancel(function(){}):this._queryQueue.indexOf(t)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(t),1)};Fc.prototype.ref=function(){};Fc.prototype.unref=function(){};Fc.prototype.setTypeParser=function(t,e,n){return this._types.setTypeParser(t,e,n)};Fc.prototype.getTypeParser=function(t,e){return this._types.getTypeParser(t,e)};Fc.prototype.isConnected=function(){return this._connected};Fc.prototype.getTransactionStatus=function(){return this.native.getTransactionStatus()}});var QAe=Q(($bi,ent)=>{"use strict";ent.exports=Ztt()});var NAe=Q((Hbi,iV)=>{"use strict";var EBn=Wtt(),xBn=UF(),bBn=_Ae(),CBn=tAe(),IBn=YI(),vBn=qtt(),SBn=j6(),{DatabaseError:_Bn}=IAe(),{escapeIdentifier:kBn,escapeLiteral:TBn}=YI(),RBn=t=>class extends vBn{constructor(n){super(n,t)}},tnt=function(t){this.defaults=xBn,this.Client=t,this.Query=this.Client.Query,this.Pool=RBn(this.Client),this._pools=[],this.Connection=bBn,this.types=FF(),this.DatabaseError=_Bn,this.TypeOverrides=SBn,this.escapeIdentifier=kBn,this.escapeLiteral=TBn,this.Result=CBn,this.utils=IBn},nnt=EBn,rnt=!1;try{rnt=!!process.env.NODE_PG_FORCE_NATIVE}catch{}rnt&&(nnt=QAe());iV.exports=new tnt(nnt);Object.defineProperty(iV.exports,"native",{configurable:!0,enumerable:!1,get(){let t=null;try{t=new tnt(QAe())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(iV.exports,"native",{value:t}),t}})});var ep,Gbi,qbi,jbi,zbi,Vbi,Kbi,Ybi,Jbi,Xbi,Zbi,eCi,int,ont=y(()=>{ep=an(NAe(),1),Gbi=ep.default.Client,qbi=ep.default.Pool,jbi=ep.default.Connection,zbi=ep.default.types,Vbi=ep.default.Query,Kbi=ep.default.DatabaseError,Ybi=ep.default.escapeIdentifier,Jbi=ep.default.escapeLiteral,Xbi=ep.default.Result,Zbi=ep.default.TypeOverrides,eCi=ep.default.defaults,int=ep.default});var BBn,DBn,OAe,rCi,snt=y(()=>{"use strict";ont();BBn=["mail","node","grant","run_event","report","structured_request","queue","spend_limits","environment_image","fault_retry","settings","machine","machine_call","document","execution_exit"],DBn=new Set(BBn),OAe=class{dirty=new Map;subscribers=new Set;scheduled;checkIntervalMs;checkTimeoutMs;reconnectMs;constructor(e={}){this.checkIntervalMs=e.checkIntervalMs??3e4,this.checkTimeoutMs=e.checkTimeoutMs??1e4,this.reconnectMs=e.reconnectMs??1e3}async subscribe(e,n={}){let r={listener:e,kinds:new Set(n.kinds??["mail","node"]),onListenStart:n.onListenStart};return this.subscribers.add(r),this.listener!==void 0&&r.onListenStart!==void 0&&queueMicrotask(()=>{this.subscribers.has(r)&&this.callListenStart(r)}),()=>{this.subscribers.delete(r)}}markMail(e){this.mark("mail",e)}markNode(e){this.mark("node",e)}markSignal(e,n){this.mark(e,n)}mark(e,n){let r=`${e}:${n}`;this.dirty.has(r)||this.dirty.set(r,{id:n,kind:e}),this.scheduled??=setImmediate(()=>this.flush())}flush(){this.scheduled=void 0;let e=[...this.dirty.values()];this.dirty.clear();for(let{id:n,kind:r}of e)for(let i of this.subscribers)if(i.kinds.has(r))try{i.listener(n,r)}catch{}}callListenStart(e){try{e.onListenStart?.()}catch{}}async listen(e){this.listener!==void 0||this.listening!==void 0||(this.url=e,this.listening=this.connectListener().finally(()=>{this.listening=void 0}),await this.listening)}listener;listening;url;reconnect;check;async connectListener(){let e=new int.Client({connectionString:this.url,application_name:`crtr-signal-${process.pid}`,keepAlive:!0});e.on("notification",r=>{let i=r.payload??"",o=i.indexOf(":");if(o<0)return;let s=i.slice(0,o);DBn.has(s)&&this.mark(s,i.slice(o+1))});let n=()=>{this.listener===e&&(this.dropListener(e),this.scheduleReconnect())};e.on("error",n),e.on("end",n);try{await e.connect(),await e.query("LISTEN crtr_signal")}catch(r){throw e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{}),r}if(this.url===void 0){e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{});return}this.listener=e,this.startChecks(e,n);for(let r of[...this.subscribers])this.callListenStart(r)}startChecks(e,n){this.stopChecks(),this.check=setInterval(()=>{if(this.listener!==e)return;let r,i=new Promise((o,s)=>{r=setTimeout(()=>s(new Error("listen connection check timed out")),this.checkTimeoutMs)});Promise.race([e.query("SELECT 1"),i]).catch(()=>n()).finally(()=>clearTimeout(r))},this.checkIntervalMs),this.check.unref()}stopChecks(){this.check!==void 0&&clearInterval(this.check),this.check=void 0}dropListener(e){this.listener=void 0,this.stopChecks(),e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{})}scheduleReconnect(){this.url===void 0||this.reconnect!==void 0||(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.url!==void 0&&(this.listening=this.connectListener().catch(()=>this.scheduleReconnect()).finally(()=>{this.listening=void 0}))},this.reconnectMs))}close(){this.url=void 0,this.reconnect!==void 0&&clearTimeout(this.reconnect),this.reconnect=void 0,this.stopChecks();let e=this.listener;return this.listener=void 0,this.scheduled!==void 0&&clearImmediate(this.scheduled),this.scheduled=void 0,this.dirty.clear(),this.subscribers.clear(),e===void 0?Promise.resolve():(e.removeAllListeners("notification"),e.removeAllListeners("error"),e.on("error",()=>{}),e.end().catch(()=>{}))}},rCi=new OAe});var ant=y(()=>{"use strict";MF()});function QBn(t){switch(t){case NBn:return"context-nudge";case MBn:return"bearings";case LBn:return"review-boundary";case PBn:return"situational";default:return}}function UAe(t){return t.replace(/&(?:amp|lt|gt|quot|apos);/g,e=>({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&apos;":"'"})[e])}function FAe(t){let e={};oV.lastIndex=0;let n=0;for(;n<t.length&&!/^\s*$/.test(t.slice(n));){oV.lastIndex=n;let r=oV.exec(t);if(r===null)return null;let[,i,o,s]=r;if(i===void 0||Object.hasOwn(e,i))return null;e[i]=UAe(o??s??""),n=oV.lastIndex}return e}function $Ae(t){return typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.filter(e=>typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(""):""}function OBn(t){let e=[],n=/<from\b([^>]*)>([\s\S]*?)<\/from>/g;for(let r of t.matchAll(n)){let i=FAe(r[1]??"");if(i?.id===void 0)continue;let o=[],s=r[2]??"",a=/<entry\b([^>]*)>([\s\S]*?)<\/entry>/g;for(let u of s.matchAll(a)){let l=FAe(u[1]??"");if(l?.kind===void 0)continue;let d=l.disposition==="human-answer"||l.disposition==="human-canceled"?l.disposition:"report";o.push({kind:l.kind,disposition:d,body:UAe(u[2]??""),...l.ref===void 0?{}:{ref:l.ref}})}let c=i.updates===void 0?Number.NaN:Number(i.updates);e.push({id:i.id,updates:Number.isFinite(c)?c:o.length,finished:i.finished==="true"||o.some(u=>u.kind==="final"),entries:o})}return e}function FBn(t,e,n,r){return{kind:t,facts:e,body:n,senders:r}}function pnt(t){let e=/^<runtime\b([^>]*)>/.exec(t);if(e===null||!t.endsWith("</runtime>"))return null;let n=FAe(e[1]??"");if(n?.kind===void 0)return null;let r=t.slice(e[0].length,-10),{kind:i,...o}=n,s=Object.freeze(o),a=i.includes(":")?UAe(r):r;return FBn(i,s,a,i==="inbox"?OBn(a):[])}function lB(t){let e=$Ae(t),n=pnt(e);if(n!==null)return n;if(t.role!=="custom")return null;let r=QBn(t.customType);return r===void 0?null:{kind:r,facts:Object.freeze({}),body:e,senders:[]}}function ev(t){return t.disposition==="human-answer"&&pnt(t.body.trim())===null}var MBn,PBn,NBn,LBn,cnt,unt,lnt,dnt,oV,tv=y(()=>{"use strict";MBn="crtr-context",PBn="crtr-situational-context",NBn="crtr-context-nudge",LBn="crtr-review-boundary",cnt="Provider credentials were just updated (a new login landed). Your previous turn stopped on a provider authentication failure. Continue from where you left off and retry the work that failed.",unt="The network connection is back online. Your previous turn stopped on a connection error (the network was down). Continue from where you left off and retry the work that failed.",lnt="Your previous turn stopped on a connection error reaching the model provider. Retrying now: continue from where you left off and retry the work that failed.",dnt="Your previous turn stopped on a provider fault. Continue from where you left off and retry the work that failed.";oV=/\s+([A-Za-z_:][A-Za-z0-9_:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/gy});var hnt=y(()=>{"use strict";tv()});function UBn(){let t=process.env.CRTR_API_URL;if(!(t===void 0||t==="")){if(!/^https?:\/\//.test(t))throw new Error(`CRTR_API_URL must be an http(s) URL: ${t}`);return t}}function DF(){let t=UBn();if(t===void 0)return lE({autostart:!1});let e=cet();if(e===void 0)throw new Error("broker has no node token for CRTR_API_URL");return new kg({baseUrl:t,headers:{authorization:`Bearer ${e}`}})}function mnt(t,e){return DF().appendNodeLog(t,{record:e,expected_execution_id:$Bn()})}function $Bn(){let t=kJe();if(t===void 0||t==="")throw new Error("broker launch is missing CRTR_EXECUTION_ID");return t}async function fnt(t,e){return DF().recordNodeFault(t,e)}async function gnt(t,e={}){return DF().clearNodeFault(t,{...e.link===void 0?{}:{link:e.link},...e.preserveEpisode===void 0?{}:{preserve_episode:e.preserveEpisode}}).then(n=>n.cleared)}var MF=y(()=>{"use strict";F6();uet();U6();_g();Pge();du();pet();nv();snt();ant();hnt()});function HBn(t,e){Ant=Ant.then(async()=>{try{let{appended:n}=await mnt(t,e);n||process.stderr.write(`[broker] log.jsonl refused record: ${e}
99
99
  `)}catch(n){process.stderr.write(`[broker] log.jsonl append failed (${n instanceof Error?n.message:String(n)}): ${e}
100
100
  `)}})}function ql(t){let e=N6();if(e===void 0)return!1;if(e.component==="broker"&&e.node_id!==void 0&&t.node_id!==void 0&&t.node_id!==e.node_id)throw new TypeError(`broker event target node_id must match bound node_id; received ${t.node_id}`);if(t.level==="debug"&&process.env.CRTR_LOG!=="debug")return!1;let n=CZe({...t,component:e.component,...e.node_id===void 0?{}:{node_id:e.node_id},...e.stream_id===void 0?{}:{stream_id:e.stream_id}}),r=vZe(n);return e.component==="broker"&&e.node_id!==void 0&&(WBn??=LI())?(HBn(e.node_id,r),!0):e.component==="daemon"?gZe(e.path,r):I6(e.path,r)}var WBn,Ant,nv=y(()=>{"use strict";oge();IZe();SZe();Ige();du();MF();Ant=Promise.resolve()});var ynt,wnt=y(()=>{"use strict";nv();ynt={sandboxUsdPerGbHour:"CRTR_LEDGER_SANDBOX_USD_PER_GB_HOUR",sandboxStandbyS:"CRTR_LEDGER_SANDBOX_STANDBY_S",storageUsdPerGbMonth:"CRTR_LEDGER_STORAGE_USD_PER_GB_MONTH",sandboxDiskUsdPerGbMonth:"CRTR_LEDGER_SANDBOX_DISK_USD_PER_GB_MONTH",infraFreeUsdPerMonth:"CRTR_LEDGER_INFRA_FREE_USD_PER_MONTH",takePct:"CRTR_LEDGER_TAKE_PCT",r2Move:"CRTR_LEDGER_R2_MOVE"}});var Ent=y(()=>{"use strict"});var WAe=y(()=>{"use strict"});import{createHash as GBn}from"node:crypto";function Cnt(t){return t===void 0?"absent":GBn("sha256").update(JSON.stringify(t)).digest("hex")}function Int(t,e){bnt.set(t,e)}function sV(){let t;try{t=dge()}catch(n){if(n instanceof _F)return xnt();if(n instanceof SF)return HAe??xnt();throw n}let e=bnt.get(t);if(e!==void 0)return e;if(HAe!==void 0)return HAe;throw new GAe(t)}function vnt(t){qBn=t}function Snt(t){jBn=t}function aV(t){let e=sV().settings[t];return{settings:e===void 0?null:structuredClone(e),revision:Cnt(e)}}function _nt(t){let e=sV().state[t];return e===void 0?{marketplaces:{},plugins:{},activeCanvas:null}:structuredClone(e)}function knt(){return structuredClone(sV().profiles)}function Tnt(t){let e=sV().profiles.find(n=>n.profileId===t);return e===void 0?null:structuredClone(e)}var GF,GAe,bnt,xnt,HAe,qBn,jBn,qF=y(()=>{"use strict";XR();GF=class extends Error{constructor(){super("settings changed since the supplied revision"),this.name="SettingsRevisionConflictError"}},GAe=class extends Error{constructor(e){super(`settings for ${e} are not loaded in this process`),this.name="PersonSettingsNotLoadedError"}},bnt=new Map;xnt=()=>({profiles:[],defaults:{},settings:{},state:{},apps:{}});qBn=async()=>{throw new Error("no settings transport installed in this process")}});var Rnt=y(()=>{"use strict"});function VBn(t){return t.grantee??"app:terminal"}function KBn(t){if(!Bnt.test(t))throw JR(`invalid profile id: ${t}`,{received:t,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}function cV(t){KBn(t);let e=Tnt(t);if(e===null)throw b6(`profile not found: ${t}`,{received:t});return QZe(VBn(e.manifest),t).dir}function YBn(){return{entries:knt(),unreadableIds:[]}}function uV(){return YBn().entries}function JBn(t){let e=uV(),n=XBn(e,t,Dnt);return n?{kind:"resolved",entry:n}:{kind:"absent"}}function XBn(t,e,n){if(Bnt.test(e)){let i=t.find(o=>n(o).profileId===e);if(i!==void 0)return i}let r=t.filter(i=>n(i).name===e);if(r.length===1)return r[0];if(r.length>1){let i=r.map(o=>n(o).profileId);throw cZe(`profile name "${e}" matches ${i.length} profiles: ${i.join(", ")}`,{received:e,candidates:i,next:`Re-run with one exact profile id: ${i.join(", ")}.`})}return null}function ZBn(t,e,n){let r=t.map(i=>`${n(i).profileId} (${n(i).name})`);return b6(`profile not found: ${e}`,{received:e,available:r,next:r.length>0?`Re-run with one of the profiles on this host: ${r.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}function hE(t){let e=JBn(t);if(e.kind==="resolved")return e.entry;throw ZBn(uV(),t,Dnt)}var Bnt,Dnt,dB=y(()=>{"use strict";pu();W0();WAe();$l();qF();uh();Rnt();XR();Bnt=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/;Dnt=t=>({profileId:t.profileId,name:t.manifest.name})});import{homedir as Mnt}from"node:os";import{existsSync as e1n,statSync as t1n}from"node:fs";import{join as lV,resolve as Pnt,dirname as n1n,sep as qAe}from"node:path";function tp(){return lV(vg(),"scope")}function r1n(t,e){if(!e1n(t)||Ym(t)===Ym(lV(Mnt(),UI))||Ym(t).startsWith(`${Ym(fge())}${qAe}`)&&t.endsWith(`${qAe}home${qAe}${UI}`)||!LI()&&(Ym(t)===Ym(e)||Ym(t)===Ym(D6())))return!1;try{return t1n(t).isDirectory()}catch{return!1}}function i1n(t=process.cwd()){return Nnt(t)[0]??null}function o1n(t,e){let n=[],r=Ym(Mnt()),i=Pnt(t);for(;;){let o=lV(i,UI);if(r1n(o,e)&&n.push(o),Ym(i)===r)return n;let s=n1n(i);if(s===i)return n;i=s}}function Nnt(t=process.cwd(),e=bfe()||null){return s1n(t,e)}function s1n(t,e){let n=Pnt(t),r=tp(),i=[n];if(!LI()&&e!==null&&e!=="")try{let{manifest:a}=hE(e);for(let c of a.projects)i.push(c.path)}catch{}let o=new Set,s=[];for(let a of i)for(let c of o1n(a,r))o.has(c)||(o.add(c),s.push(c));return s}function Lnt(t){return i1n(t)}function G0(t){return t==="builtin"?null:t==="user"?tp():Lnt()}function Qnt(t){let e=t==="user"?vg():G0(t);return e?lV(e,"plugins"):null}var rv=y(()=>{"use strict";du();pu();Ent();uh();dB();$l();W0()});import{join as a1n}from"node:path";function c1n(t){return a1n(t,oZe,sZe)}function u1n(t){let e;try{e=jI(t)}catch(n){return{status:"broken",error:n instanceof Error?n.message:String(n)}}return e===null?{status:"absent"}:typeof e!="object"||Array.isArray(e)?{status:"broken",error:"manifest is not a JSON object"}:{status:"ok",manifest:e}}function l1n(t){return u1n(c1n(t))}function Ont(t){let e=l1n(t);return e.status==="ok"?e.manifest:null}var jAe=y(()=>{"use strict";pu();$l()});import{existsSync as d1n,mkdirSync as p1n,readdirSync as Unt,rmSync as $nt,rmdirSync as h1n,statSync as m1n,unlinkSync as f1n,writeFileSync as g1n}from"node:fs";import{randomUUID as A1n}from"node:crypto";function Hnt(t){return Math.min(t*2,y1n)}function Gnt(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function VAe(t,e){return`${t}/${zAe}${e}`}function KAe(t){try{return Unt(t).find(e=>e.startsWith(zAe))?.slice(zAe.length)??null}catch{return null}}function qnt(t){let e=Number(t.split(".",1)[0]);if(!Number.isSafeInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}function x1n(t){try{return Unt(t).length===0}catch{return!1}}function b1n(t){try{return Date.now()-m1n(t).mtimeMs}catch{return 0}}function C1n(t,e){let n=KAe(t);if(n!==null){if(qnt(n))return;try{f1n(VAe(t,n))}catch(r){if(r.code==="ENOENT")return;throw r}}else{if(b1n(t)<=e)return;if(!x1n(t)){$nt(t,{recursive:!0,force:!0});return}}try{h1n(t)}catch(r){let i=r.code;if(i!=="ENOENT"&&i!=="ENOTEMPTY"&&i!=="EEXIST")throw r}}function pB(t){let e=KAe(t);if(e===null)return null;let n=Number(e.split(".",1)[0]);return Number.isSafeInteger(n)&&n>0?n:null}function jnt(t,e){let n=Date.now()+e,r=Wnt;for(;;){let i=KAe(t);if(i===null||Number(i.split(".",1)[0])===process.pid||!qnt(i))return;let o=n-Date.now();if(o<=0)return;Gnt(Math.min(r,o)),r=Hnt(r)}}function Fnt(t,e){let n=`${process.pid}.${A1n()}`;try{return p1n(t,{mode:448}),g1n(VAe(t,n),"",{flag:"wx",mode:384}),{path:t,token:n}}catch(r){if(r.code!=="EEXIST")throw r;return C1n(t,e),null}}function iv(t,e,n={}){let r=n.staleMs??w1n,i=Date.now()+(n.timeoutMs??E1n),o=Wnt,s=Fnt(t,r);for(;s===null;){if(Date.now()>=i)throw n.timeoutError?.()??new Error(`timed out waiting for the exclusive lock: ${t}`);Gnt(Math.min(o,Math.max(0,i-Date.now()))),o=Hnt(o),s=Fnt(t,r)}try{return e()}finally{d1n(VAe(s.path,s.token))&&$nt(s.path,{recursive:!0,force:!0})}}var zAe,Wnt,y1n,w1n,E1n,mE=y(()=>{"use strict";zAe="owner.",Wnt=10,y1n=250,w1n=3e4,E1n=5e3});import{join as I1n}from"node:path";function znt(t,e){return I1n(t,"tmp",`${e}.swap.lock`)}function Vnt(t,e){let n=pB(znt(t,e));return n!==null&&n!==process.pid}function Knt(t,e){jnt(znt(t,e),v1n)}var v1n,Ynt=y(()=>{"use strict";mE();v1n=2e3});import{join as YAe}from"node:path";function S1n(t,e){let n=t==="user"?aV("user").settings:jI(YAe(e,w6));return n&&n.plugins&&typeof n.plugins=="object"?n.plugins:{}}function _1n(t,e,n){let r=Object.keys(e);return r.every(i=>n.has(i))?[]:r.filter(i=>!n.has(i)&&Vnt(t,i))}function dV(t,e){if(t==="user"&&k6())return[];let n=t!=="user"?YAe(e,"plugins"):Qnt("user");if(n===void 0||!hge(n))return[];let r=S1n(t,e),i=Jnt(t,n,r),o=_1n(e,r,new Set(i.map(s=>s.name)));if(o.length===0)return i;for(let s of o)Knt(e,s);return Jnt(t,n,r)}function Jnt(t,e,n){let r=[];for(let i of mge(e)){let o=YAe(e,i),s=Ont(o);if(!s)continue;let a=n[i],c=typeof a?.version=="string"?a.version:s.version;r.push({name:i,scope:t,root:o,manifest:s,enabled:typeof a?.enabled=="boolean"?a.enabled:!0,sourceMarketplace:typeof a?.source_marketplace=="string"?a.source_marketplace:void 0,version:c})}return r}var pV=y(()=>{"use strict";pu();$l();jAe();Ynt();XR();qF();rv()});import{existsSync as k1n,realpathSync as T1n}from"node:fs";import{basename as R1n,dirname as B1n,join as OIi,resolve as Xnt}from"node:path";function hB(t){let e=Xnt(t),n=e,r=[];for(;!k1n(n);){let i=B1n(n);if(i===n)return e;r.unshift(R1n(n)),n=i}return Xnt(T1n(n),...r)}var Znt=y(()=>{"use strict"});function D1n(t){let e=Ki.indexOf(t);return`less ${Ki.map((r,i)=>i===e?"\u25CF":"\u25CB").map((r,i)=>i===0?r:`${i<=e?"\u2501\u2501\u2501\u2501":"\u2500\u2500\u2500\u2500"}${r}`).join("")} more ${hV[t]}`}function jF(t,e,n){let r=t.indexOf(e),i=r>=0?r:0;return t[(i+n+t.length)%t.length]}function JAe(t,e,n){let r=t.indexOf(e);return r>=0?t[(r+n+t.length)%t.length]:n>=0?t.find(i=>i>e)??t[0]:[...t].reverse().find(i=>i<e)??t[t.length-1]}function ov(t,e){return t==="true"?!0:t==="false"?!1:`${e} must be true or false`}function rrt(t,e){if(!/^\d+$/.test(t))return`${e} must be an integer >= 0`;let n=Number(t);return Number.isSafeInteger(n)?n:`${e} must be an integer >= 0`}function ert(t,e){let n=rrt(t,e);return typeof n=="string"||n<1?`${e} must be an integer >= 1`:n}function nrt(t,e){let n=t.providerOptions[e];if(n!==void 0)return n;let r={};return t.providerOptions[e]=r,r}function Q1n(){let t=[];for(let e of Object.values(irt))e.surface==="settings"&&("setting"in e?t.push(e.setting):t.push(...Object.values(e.settings)));return t.sort((e,n)=>e.order-n.order)}var hV,trt,M1n,P1n,zF,N1n,irt,L1n,$Ii,XAe=y(()=>{"use strict";pu();hV={replies:"Replies only",summaries:"Messages + summaries",tools:"Tool calls",previews:"Previews",full:"Full"};trt=[!1,"notify","apply"],M1n=[0,1,6,12,24,48,72,168],P1n=[1,2,3,4,5,6,8,10,12],zF="openai-codex";N1n=[1,2,3,4,5,6],irt={schema_version:{surface:"specialized",owner:"internal schema migration"},marketplaces:{surface:"specialized",owner:"Plugins and pkg market commands"},plugins:{surface:"specialized",owner:"Plugins tab and pkg plugin commands"},auto_update:{surface:"settings",settings:{crtr:{key:"auto_update.crtr",label:"crouter updates",description:"Notify about crouter releases, install them automatically, or turn checks off.",valueConstraint:"true|false|notify|apply; true stores notify",applies:"Applies on the next crouter command.",group:"updates",order:70,format:t=>t.auto_update.crtr===!1?"off":t.auto_update.crtr,cycle:(t,e)=>{t.auto_update.crtr=jF(trt,t.auto_update.crtr,e)},setFromString:(t,e)=>{let n=e==="true"?"notify":e;return n!=="notify"&&n!=="apply"&&n!=="false"?"auto_update.crtr must be notify, apply, or false":(t.auto_update.crtr=n==="false"?!1:n,null)}},content:{key:"auto_update.content",label:"Content updates",description:"Notify about plugin and marketplace updates, apply them automatically, or turn checks off.",valueConstraint:"false|notify|apply",applies:"Applies on the next crouter command.",group:"updates",order:80,format:t=>t.auto_update.content===!1?"off":t.auto_update.content,cycle:(t,e)=>{t.auto_update.content=jF(trt,t.auto_update.content,e)},setFromString:(t,e)=>e!=="notify"&&e!=="apply"&&e!=="false"?"auto_update.content must be notify, apply, or false":(t.auto_update.content=e==="false"?!1:e,null)},interval_hours:{key:"auto_update.interval_hours",label:"Update interval",description:"Minimum hours between automatic update checks. Zero checks on every command.",valueConstraint:"integer >= 0",applies:"Applies on the next crouter command.",group:"updates",order:90,format:t=>`${t.auto_update.interval_hours}h`,cycle:(t,e)=>{t.auto_update.interval_hours=JAe(M1n,t.auto_update.interval_hours,e)},setFromString:(t,e)=>{let n=rrt(e,"auto_update.interval_hours");return typeof n=="string"?n:(t.auto_update.interval_hours=n,null)}}}},max_panes_per_window:{surface:"settings",setting:{key:"max_panes_per_window",label:"Maximum panes",description:"Maximum human-review panes placed in one tmux window before using another window.",valueConstraint:"integer >= 1",applies:"Applies to the next pane placement.",group:"panes",order:20,format:t=>String(t.max_panes_per_window),cycle:(t,e)=>{t.max_panes_per_window=JAe(P1n,t.max_panes_per_window,e)},setFromString:(t,e)=>{let n=ert(e,"max_panes_per_window");return typeof n=="string"?n:(t.max_panes_per_window=n,null)}}},auto_open_child_viewers:{surface:"settings",setting:{key:"auto_open_child_viewers",label:"Open child panes",description:"Open each managed child beside its watched parent. Off keeps new children running in the background.",valueConstraint:"true|false",applies:"Applies to the next managed child created; independent roots still open their attended viewer.",group:"panes",order:10,format:t=>t.auto_open_child_viewers?"on":"off",cycle:t=>{t.auto_open_child_viewers=!t.auto_open_child_viewers},setFromString:(t,e)=>{let n=ov(e,"auto_open_child_viewers");return typeof n=="string"?n:(t.auto_open_child_viewers=n,null)}}},brokerThresholds:{surface:"specialized",owner:"Broker limits tab"},lifecycle:{surface:"specialized",owner:"sys config set lifecycle.unattendedParkMs"},completion_bell:{surface:"settings",setting:{key:"completion_bell",label:"Completion bell",description:"Ring a short sound when the node in an attached viewer finishes a turn.",valueConstraint:"true|false",applies:"Applies on the next turn end.",group:"display",order:41,format:t=>t.completion_bell?"on":"off",cycle:t=>{t.completion_bell=!t.completion_bell},setFromString:(t,e)=>{let n=ov(e,"completion_bell");return typeof n=="string"?n:(t.completion_bell=n,null)}}},working_gerunds:{surface:"specialized",owner:"sys config set working_gerunds"},whip_mode:{surface:"settings",setting:{key:"whip_mode",label:"Whip mode",description:"Play the whip animation when you send a prompt and when a viewer opens for an agent with an initial prompt.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:39,format:t=>t.whip_mode?"on":"off",cycle:t=>{t.whip_mode=!t.whip_mode},setFromString:(t,e)=>{let n=ov(e,"whip_mode");return typeof n=="string"?n:(t.whip_mode=n,null)}}},page_surface:{surface:"settings",setting:{key:"page_surface",label:"Page human surface",description:"This host reads pages in a browser rather than a terminal. Agents are told the page module runs as written, HTML pages are offered, and document review and live display leave the command tree.",valueConstraint:"true|false",applies:"Applies when human command help is assembled.",group:"display",order:37,format:t=>t.page_surface?"on":"off",cycle:t=>{t.page_surface=!t.page_surface},setFromString:(t,e)=>{let n=ov(e,"page_surface");return typeof n=="string"?n:(t.page_surface=n,null)}}},whip_messages:{surface:"specialized",owner:"sys config set whip_messages"},whip_message_mode:{surface:"settings",setting:{key:"whip_message_mode",label:"Whip message",description:"What the whip action sends: a random line from whip_messages, or the fixed \u201CGo faster\u201D.",valueConstraint:$I.join("|"),applies:"Applies on the next attach.",group:"display",order:40,format:t=>t.whip_message_mode==="go-faster"?"go faster":"random",cycle:(t,e)=>{t.whip_message_mode=jF($I,t.whip_message_mode,e)},setFromString:(t,e)=>$I.includes(e)?(t.whip_message_mode=e,null):`whip_message_mode must be one of: ${$I.join("|")}`}},mouse_mode_default:{surface:"settings",setting:{key:"mouse_mode_default",label:"Default mouse mode",description:"Initial mouse wheel scrolling for each attached viewer.",valueConstraint:WI.join("|"),applies:"Applies on the next attach.",group:"display",order:38,format:t=>t.mouse_mode_default==="tmux"?"follow tmux":t.mouse_mode_default,cycle:(t,e)=>{t.mouse_mode_default=jF(WI,t.mouse_mode_default,e)},setFromString:(t,e)=>WI.includes(e)?(t.mouse_mode_default=e,null):`mouse_mode_default must be one of: ${WI.join("|")}`}},live_cycles:{surface:"settings",setting:{key:"live_cycles",label:"Live cycles",description:"Trailing refresh cycles rendered at full fidelity; older cycles condense to text.",valueConstraint:"integer >= 1",applies:"Applies on the next attach.",group:"display",order:50,format:t=>String(t.live_cycles),cycle:(t,e)=>{t.live_cycles=JAe(N1n,t.live_cycles,e)},setFromString:(t,e)=>{let n=ert(e,"live_cycles");return typeof n=="string"?n:(t.live_cycles=n,null)}}},condensed_history:{surface:"settings",setting:{key:"condensed_history",label:"Condensed history",description:"Messages retained from condensed cycles. Tool calls are never kept.",valueConstraint:HI.join("|"),applies:"Applies on the next attach.",group:"display",order:60,format:t=>t.condensed_history,cycle:(t,e)=>{t.condensed_history=jF(HI,t.condensed_history,e)},setFromString:(t,e)=>HI.includes(e)?(t.condensed_history=e,null):`condensed_history must be one of: ${HI.join("|")}`}},bash_tool_purpose:{surface:"settings",setting:{key:"bash_tool_purpose",label:"Bash purpose field",description:"Expose the optional purpose label to agents in the bash tool schema. Off removes the field without disabling the bash valve.",valueConstraint:"true|false",applies:"Applies on the next node session.",group:"display",order:25,format:t=>t.bash_tool_purpose?"on":"off",cycle:t=>{t.bash_tool_purpose=!t.bash_tool_purpose},setFromString:(t,e)=>{let n=ov(e,"bash_tool_purpose");return typeof n=="string"?n:(t.bash_tool_purpose=n,null)}}},verbosity:{surface:"settings",setting:{key:"verbosity",label:"Verbosity",description:"How much of a transcript the viewer shows, from one rewritten reply per message to every tool call untruncated. Ctrl+O shows more and Ctrl+Shift+O less in the open viewer only; this sets where every viewer starts.",valueConstraint:Ki.join("|"),applies:"Applies on the next attach.",group:"display",order:30,format:t=>t.verbosity,display:t=>D1n(t.verbosity),cycle:(t,e)=>{let n=Ki.indexOf(t.verbosity)+e;t.verbosity=Ki[Math.max(0,Math.min(Ki.length-1,n))]},setFromString:(t,e)=>Ki.includes(e)?(t.verbosity=e,null):`verbosity must be one of: ${Ki.join("|")}`}},document_port:{surface:"settings",setting:{key:"document_port",label:"Document browser port",description:"Fixed localhost port where crtrd serves editable document pages.",valueConstraint:"1-65535",applies:"Applies after daemon handover and on the next attach.",group:"display",order:37.5,format:t=>String(t.document_port),cycle:(t,e)=>{t.document_port=Math.max(1,Math.min(65535,t.document_port+e))},setFromString:(t,e)=>{let n=Number(e);return!/^\d+$/.test(e)||!Number.isInteger(n)||n<1||n>65535?"document_port must be an integer from 1 to 65535":(t.document_port=n,null)}}},detailed_tool_recaps:{surface:"settings",setting:{key:"detailed_tool_recaps",label:"Detailed tool recaps",description:"Show each document read and edited file in folded tool recaps. Off shows a compact count line instead.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:36,format:t=>t.detailed_tool_recaps?"on":"off",cycle:t=>{t.detailed_tool_recaps=!t.detailed_tool_recaps},setFromString:(t,e)=>{let n=ov(e,"detailed_tool_recaps");return typeof n=="string"?n:(t.detailed_tool_recaps=n,null)}}},keybindings:{surface:"specialized",owner:"Keybindings tab"},tmux_passthrough:{surface:"specialized",owner:"Keybindings tab"},providerOptions:{surface:"settings",settings:{"openai-codex.fastMode":{key:`providerOptions.${zF}.fastMode`,label:"Codex fast mode",description:"Serve Codex turns at the ChatGPT priority tier: about 1.5x faster generation for about 2x the credits. Displayed cost does not reflect the premium.",valueConstraint:"true|false",applies:"Applies on each node's next turn.",group:"providers",order:40,format:t=>t.providerOptions[zF]?.fastMode?"on":"off",cycle:t=>{let e=nrt(t,zF);e.fastMode=!e.fastMode},setFromString:(t,e)=>{let n=ov(e,`providerOptions.${zF}.fastMode`);return typeof n=="string"?n:(nrt(t,zF).fastMode=n,null)}}}},modelLadders:{surface:"specialized",owner:"Models tab"},modelRoutes:{surface:"specialized",owner:"Models route declarations"},modelRouting:{surface:"specialized",owner:"Models route declarations"},kinds:{surface:"specialized",owner:"Models tab and kind registry"},page_components:{surface:"specialized",owner:"Page component catalog: product-registered page component kinds"},remoteCanvas:{surface:"specialized",owner:"canvas config commands"},api:{surface:"specialized",owner:"sys connect"},paths:{surface:"specialized",owner:"runtime layout"},store:{surface:"specialized",owner:"daemon conversation store"},runtime:{surface:"specialized",owner:"app-facing listener"},spawnEnv:{surface:"specialized",owner:"spawn environment allow-list"},bin:{surface:"specialized",owner:"bare-binary contributions on every node PATH"},humanActions:{surface:"specialized",owner:"scope-configured human completion actions"}},L1n=Object.keys(irt);$Ii=Q1n()});function VF(t){return t.split("-").map(e=>e===""?"":`${e[0].toUpperCase()}${e.slice(1)}`).join("")}function fB(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}function mB(t,e,n,r){if(t!==void 0){if(typeof t!="string"||t.trim()==="")throw new Error(`${n}[${r}].${e} must be a non-empty string; received ${fB(t)}`);return t.trim()}}function n0e(t,e="page_components"){if(t===void 0)return[];if(!Array.isArray(t))throw new Error(`${e} must be an array; received ${fB(t)}`);let n=new Set,r=new Set;return t.map((i,o)=>{let s;if(typeof i=="string")s={kind:i.trim()};else if(i!==null&&typeof i=="object"&&!Array.isArray(i)){let u=i,l=Object.keys(u).filter(d=>!["kind","description","useWhen","doc","display"].includes(d));if(l.length>0)throw new Error(`${e}[${o}] has unknown field(s): ${l.join(", ")}`);if(typeof u.kind!="string")throw new Error(`${e}[${o}].kind must be a string; offending entry: ${fB(i)}`);if(u.display!==void 0&&typeof u.display!="boolean")throw new Error(`${e}[${o}].display must be a boolean; offending entry: ${fB(i)}`);s={kind:u.kind.trim(),...mB(u.description,"description",e,o)===void 0?{}:{description:mB(u.description,"description",e,o)},...mB(u.useWhen,"useWhen",e,o)===void 0?{}:{useWhen:mB(u.useWhen,"useWhen",e,o)},...mB(u.doc,"doc",e,o)===void 0?{}:{doc:mB(u.doc,"doc",e,o)},...u.display===!0?{display:!0}:{}}}else throw new Error(`${e}[${o}] must be a string or component object; offending entry: ${fB(i)}`);let a=s.kind;if(!F1n.test(a))throw new Error(`${e}[${o}] has invalid page kind ${fB(a)}; expected /^[a-z][a-z0-9-]{0,63}$/`);if(U1n.has(a)||O1n.includes(a))throw new Error(`${e}[${o}] collides with built-in page kind "${a}"`);if(n.has(a))throw new Error(`${e}[${o}] duplicates page kind "${a}"`);let c=VF(a);if(mV.has(c))throw new Error(`${e}[${o}] kind "${a}" derives JSX tag "${c}", which collides with a built-in page component`);if(r.has(c))throw new Error(`${e}[${o}] kind "${a}" derives JSX tag "${c}", which duplicates another product page component`);return n.add(a),r.add(c),s})}function srt(t){let e=new Map,n=new Map,r=[];for(let i of t)for(let o of i.components){let s=e.get(o.kind);if(s!==void 0)throw new Error(`page component kind "${o.kind}" is registered by both ${s} and ${i.origin}`);let a=VF(o.kind),c=n.get(a);if(c!==void 0)throw new Error(`page component kind "${o.kind}" (${i.origin}) derives JSX tag "${a}", which duplicates kind "${c.kind}" from ${c.origin}`);e.set(o.kind,i.origin),n.set(a,{kind:o.kind,origin:i.origin}),r.push(o)}return r}function art(t,e){return e.find(n=>n.kind===t)}var ZAe,O1n,F1n,U1n,ort,e0e,mV,t0e,KF=y(()=>{"use strict";ZAe=["options","text","table","cards","chart"],O1n=["page","step"],F1n=/^[a-z][a-z0-9-]{0,63}$/,U1n=new Set(ZAe),ort=[{kind:"page",tag:"Page",description:"the page itself: title, subtitle, and every step it contains",useWhen:"use as the single root element every page returns",builtin:!0,structural:!0},{kind:"step",tag:"Step",description:"one step inside a Page",useWhen:"use for each step the user sees and completes in sequence",builtin:!0,structural:!0},{kind:"options",tag:"UserQuestion",description:"known alternatives with single or multiple selection",useWhen:"use when the user picks among known alternatives, optionally with freetext",builtin:!0,structural:!1},{kind:"text",tag:"UserText",description:"writing surface whose answer is the text the user hands back",useWhen:"use when you need prose from the user \u2014 a value they write, or a draft they revise; prose they only read is a plain element",builtin:!0,structural:!1},{kind:"table",tag:"UserTable",description:"rows and columns with optional selection",useWhen:"use when structured records are easiest to compare in rows and columns",builtin:!0,structural:!1},{kind:"cards",tag:"UserCards",description:"visual records with optional selection",useWhen:"use when the user compares or picks richer items than a compact option list can carry",builtin:!0,structural:!1},{kind:"chart",tag:"Chart",description:"line, bar, or area data visualization",useWhen:"use when shape, trend, or magnitude matters more than exact tabular values",builtin:!0,structural:!1}];e0e=Object.fromEntries(ort.filter(t=>!t.structural).map(t=>[t.tag,t.kind])),mV=new Set(ort.map(t=>t.tag)),t0e=new Set(["Card","CardHeader","CardTitle","CardDescription","CardContent","CardFooter","CardAction","Badge","Button","Separator","Progress","Alert","AlertTitle","AlertDescription","Table","TableHeader","TableBody","TableFooter","TableRow","TableHead","TableCell","TableCaption","Tabs","TabsList","TabsTrigger","TabsContent","Accordion","AccordionItem","AccordionTrigger","AccordionContent"])});import{basename as prt,join as hrt}from"node:path";import{existsSync as W1n,mkdirSync as VIi,statSync as KIi}from"node:fs";function H1n(t){return hrt(t,w6)}function G1n(t){return hrt(t,aZe)}function mrt(t){let e=hB(t),n=hB(tp());if(e===n)return{key:"user",kind:"user",root:n};if(prt(e)===".crouter")return{key:"project",kind:"project",root:e};for(let r of uV()){let i=hB(cV(r.profileId));if(e===i)return{key:`profile:${r.profileId}`,kind:"profile",root:i,profileId:r.profileId}}throw new Error(`settings root is not a recognized owner: ${t}`)}function frt(t){if(prt(t)===".crouter"){let e;try{e=hB(t)}catch(n){if(n.code==="ENOENT")return null;throw n}if(e!==hB(tp()))return jI(H1n(t))}return aV(mrt(t).key).settings}function Wl(t){let e=q1n[j1n];if(e){if(t!=="user")throw new Error(`broker config snapshot has no ${t} scope`);return e.user}let n=G0(t);return n?z1n(n):x6()}function z1n(t){let e=frt(t);return e?wDn(e):x6()}function V1n(t){let e=jI(G1n(t));return{marketplaces:e?.marketplaces??{},plugins:e?.plugins??{},activeCanvas:e?.activeCanvas??null,...e?.last_self_check===void 0?{}:{last_self_check:e.last_self_check}}}function grt(t){let e=G0(t);return e?t==="project"?W1n(e)?V1n(e):ige():_nt(mrt(e).key):ige()}function K1n(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))Array.isArray(r)&&r.every(i=>typeof i=="string")&&(e[n]=[...r]);return e}function gB(t){return Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string"&&FI.has(e)&&Y1n.has(e)))]:[]}function J1n(t,e=rge()){let n=e;if(t===null||typeof t!="object")return n;let r=t,i={anthropic:{...n.anthropic},openai:{...n.openai},...n.defaultProvider!==void 0?{defaultProvider:n.defaultProvider}:{}};(r.defaultProvider==="anthropic"||r.defaultProvider==="openai")&&(i.defaultProvider=r.defaultProvider);for(let o of["anthropic","openai"]){let s=r[o];if(!(s===null||typeof s!="object"))for(let[a,c]of Object.entries(s))(a==="ultra"||a==="strong"||a==="medium"||a==="light")&&typeof c=="string"&&(i[o][a]=c)}return i}function Art(t){return t==="ultra"||t==="strong"||t==="medium"||t==="light"}function r0e(){return Object.create(null)}function fV(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Z1n(t){let e=r0e();for(let[n,r]of Object.entries(t??{}))fV(e,n,r);return e}function YF(t,e){ql({level:"warn",event:"config.model_routes.invalid",fields:{route_id:t,rule:e}})}function eDn(t,e={}){let n=Z1n(e);if(t===null||typeof t!="object"||Array.isArray(t))return n;for(let[r,i]of Object.entries(t)){if(r.trim()===""){YF(r,"route id must be a non-empty string");continue}if(i===null||typeof i!="object"||Array.isArray(i)){YF(r,"route must be an object");continue}let o=i,s=n[r],a={...s},c;for(let u of["family","credentialSource","providerId"]){let l=o[u];if(l!==void 0){if(typeof l!="string"||l.trim()===""){c=`${u} must be a non-empty string`;break}a[u]=l}}if(c===void 0&&o.models!==void 0)if(o.models===null||typeof o.models!="object"||Array.isArray(o.models))c="models must be an object";else{let u={...s?.models};for(let[l,d]of Object.entries(o.models)){if(!Art(l)){c=`models.${l} is not a model strength`;break}if(typeof d!="string"||d.trim()===""){c=`models.${l} must be a non-empty provider/id ref`;break}let p=d.indexOf("/");if(p<=0||p===d.length-1){c=`models.${l} must be provider/id`;break}u[l]=d}a.models=u}if(c===void 0&&a.models!==void 0&&a.providerId!==void 0){for(let[u,l]of Object.entries(a.models))if(l.slice(0,l.indexOf("/"))!==a.providerId){c=`models.${u} provider prefix must equal providerId`;break}}if(c!==void 0){YF(r,c);continue}fV(n,r,a)}return n}function tDn(t){let e=r0e(),n=r0e();for(let[r,i]of Object.entries(t)){if(i.family===void 0||i.credentialSource===void 0||i.providerId===void 0||i.models===void 0){YF(r,"route must include family, credentialSource, providerId, and models");continue}let o=X1n.filter(s=>i.models[s]===void 0);if(o.length>0){YF(r,`incomplete route; missing strengths: ${o.join(", ")}`),fV(n,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models});continue}fV(e,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models})}return{complete:e,legacy:n}}function nDn(t,e){if(t===void 0||t===null||typeof t!="object"||Array.isArray(t))return e;let n=t,r=o=>Array.isArray(o)&&o.every(s=>typeof s=="string"&&s.trim()!=="")?[...o]:void 0,i=Array.isArray(n.strengthFallback)&&n.strengthFallback.every(o=>Art(o))?[...n.strengthFallback]:void 0;return{...r(n.credentialSourceOrder)!==void 0?{credentialSourceOrder:r(n.credentialSourceOrder)}:{},...r(n.familyOrder)!==void 0?{familyOrder:r(n.familyOrder)}:{},...i!==void 0?{strengthFallback:i}:{}}}function rDn(t){return t!==""&&t.replace(/\*/g,"")===""}function iDn(t,e=[]){let n=t,r=Array.isArray(n?.allow)?n.allow.filter(i=>typeof i=="string"):[];for(let i of r)if(rDn(i))throw new Error(`spawnEnv.allow: "${i}" matches every env var name (inherit-all) \u2014 this is exactly the leak the spawn-env boundary closes. Name the specific vars/prefixes you actually need instead (e.g. "AWS_*", "GIT_ASKPASS").`);return{allow:[...new Set([...e,...r])]}}function oDn(t,e={}){let n={};for(let[r,i]of Object.entries(e))n[r]={...i};if(t!==null&&typeof t=="object")for(let[r,i]of Object.entries(t)){if(i===null||typeof i!="object")continue;let o={...n[r]},s=i.fastMode;typeof s=="boolean"&&(o.fastMode=s),n[r]=o}return n}function aDn(t,e){if(e==="bin"&&sDn.has(t))return`${e}.${t} is reserved by crouter \u2014 pick another bare command name`;if(!crt.test(t))return`${e}.${t} is not a safe bare command name (expected ${crt.source})`}function cDn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))aDn(n,"bin")===void 0&&(typeof r!="string"||r.trim()===""||(e[n]=r));return e}function uDn(t){if(t===null||typeof t!="object"||Array.isArray(t))return[{name:"humanActions",reason:"humanActions must be a JSON object mapping action names to {argv, cwd}",block:!0}];let e=[];for(let[n,r]of Object.entries(t)){let i=[];if(urt.test(n)||i.push(`action name must match ${urt.source}`),r===null||typeof r!="object"||Array.isArray(r))i.push("action must be an object with argv and cwd");else{let o=r,s=Object.keys(o).filter(a=>a!=="argv"&&a!=="cwd");s.length>0&&i.push(`action has unsupported field${s.length===1?"":"s"}: ${s.join(", ")}`),(!Array.isArray(o.argv)||o.argv.length===0||!o.argv.every(a=>typeof a=="string"&&a.length>0))&&i.push("argv must be a non-empty array of non-empty strings"),(typeof o.cwd!="string"||o.cwd.length===0)&&i.push("cwd is required and must be a non-empty string")}i.length>0&&e.push({name:n,reason:i.join("; ")})}return e}function lDn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e=new Set(uDn(t).map(r=>r.name)),n={};for(let[r,i]of Object.entries(t)){if(e.has(r))continue;let o=i;n[r]={argv:[...o.argv],cwd:o.cwd}}return n}function dDn(t){if(t===null||typeof t!="object")return null;let e=t,n={};typeof e.whenToUse=="string"&&e.whenToUse.trim()!==""&&(n.whenToUse=e.whenToUse),typeof e.model=="string"&&e.model.trim()!==""&&(n.model=e.model),typeof e.orchestratorModel=="string"&&e.orchestratorModel.trim()!==""&&(n.orchestratorModel=e.orchestratorModel);let r=i=>Array.isArray(i)&&i.every(o=>typeof o=="string");return r(e.tools)&&(n.tools=e.tools),r(e.extensions)&&(n.extensions=e.extensions),r(e.availableTo)&&(n.availableTo=e.availableTo),Object.keys(n).length>0?n:null}function pDn(t,e=nge()){let n={...e};if(t!==null&&typeof t=="object")for(let[r,i]of Object.entries(t)){let o=dDn(i);if(o===null)continue;let s=n[r];s!==void 0?n[r]={...s,...o}:o.whenToUse!==void 0&&(n[r]=o)}return n}function gV(){let t=[{origin:"config.json",components:Wl("user").page_components}],e=G0("user");if(e!==null){let n=dV("user",e).filter(r=>r.enabled&&r.manifest.page_components!==void 0).sort((r,i)=>r.name.localeCompare(i.name));for(let r of n){let i=`plugin "${r.name}" page_components`;t.push({origin:`plugin "${r.name}"`,components:n0e(r.manifest.page_components,i)})}}return srt(t)}function hDn(t){if(t===null||typeof t!="object")return null;let e=t;if(typeof e.previewEndpoint!="string"||e.previewEndpoint.trim()===""||typeof e.relayTokenRef!="string"||e.relayTokenRef.trim()==="")return null;let n={previewEndpoint:e.previewEndpoint,relayTokenRef:e.relayTokenRef};return typeof e.cpOrigin=="string"&&e.cpOrigin.trim()!==""&&(n.cpOrigin=e.cpOrigin),n}function mDn(t,e=tge()){let n={...e.targets};if(t!==null&&typeof t=="object"){let r=t;if(r.targets!==null&&typeof r.targets=="object")for(let[i,o]of Object.entries(r.targets)){let s=hDn(o);s!==null&&(n[i]=s)}}return{targets:n}}function lrt(t,e){return t===!0?"notify":t===!1?!1:t==="notify"||t==="apply"?t:e}function JF(t,e){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=1?t:e}function fDn(t,e){let n=t!==null&&typeof t=="object"?t:{},r=JF(n.warning,e.warning),i=JF(n.automaticReviveCap,e.automaticReviveCap);return r<=i?{warning:r,automaticReviveCap:i}:{...e}}function gDn(t,e){return{unattendedParkMs:JF((t!==null&&typeof t=="object"?t:{}).unattendedParkMs,e.unattendedParkMs)}}function ADn(t){if(!Array.isArray(t))return[...E6];let e=t.filter(n=>typeof n=="string"&&n.trim()!=="").map(n=>n.trim());return e.length>0?e:[...E6]}function yDn(t,e){if(t===null||typeof t!="object")return{...e};let n=t.tcp;return{tcp:typeof n=="string"?n:e.tcp}}function wDn(t){!drt&&t.ledger!==void 0&&(drt=!0,ql({level:"warn",event:"config.ledger.ignored",fields:{variables:Object.values(ynt)}}));let e=x6(),n=e.schema_version,r=t.marketplaces===void 0?{}:t.marketplaces,i=t.plugins===void 0?{}:t.plugins,o=t.auto_update,s=o&&typeof o.interval_hours=="number"?o.interval_hours:void 0,a=s!==void 0&&Number.isFinite(s)&&s>=0?s:e.auto_update.interval_hours,c={crtr:lrt(o?.crtr,e.auto_update.crtr),content:lrt(o?.content,e.auto_update.content),interval_hours:a},u=t.max_panes_per_window,l=JF(u,e.max_panes_per_window),d=typeof t.auto_open_child_viewers=="boolean"?t.auto_open_child_viewers:e.auto_open_child_viewers,p=fDn(t.brokerThresholds,e.brokerThresholds),h=gDn(t.lifecycle,e.lifecycle),m=typeof t.completion_bell=="boolean"?t.completion_bell:e.completion_bell,f=t.working_gerunds===void 0?[...e.working_gerunds]:rZe(t.working_gerunds),g=typeof t.whip_mode=="boolean"?t.whip_mode:e.whip_mode,A=n0e(t.page_components),x=typeof t.page_surface=="boolean"?t.page_surface:e.page_surface,b=ADn(t.whip_messages),v=$I.includes(t.whip_message_mode)?t.whip_message_mode:e.whip_message_mode,S=WI.includes(t.mouse_mode_default)?t.mouse_mode_default:e.mouse_mode_default,_=JF(t.live_cycles,e.live_cycles),T=HI.includes(t.condensed_history)?t.condensed_history:e.condensed_history,M=typeof t.bash_tool_purpose=="boolean"?t.bash_tool_purpose:e.bash_tool_purpose,R=Ki.includes(t.verbosity)?t.verbosity:e.verbosity,B=typeof t.detailed_tool_recaps=="boolean"?t.detailed_tool_recaps:e.detailed_tool_recaps,O=Number.isInteger(t.document_port)&&t.document_port>=1&&t.document_port<=65535?t.document_port:e.document_port,W=K1n(t.keybindings),z=gB(t.tmux_passthrough),$=J1n(t.modelLadders),ae=oDn(t.providerOptions,e.providerOptions),X=tDn(eDn(t.modelRoutes)),ye=X.complete,we=nDn(t.modelRouting,void 0),We=pDn(t.kinds),bt=mDn(t.remoteCanvas),Qt=yDn(t.api,e.api),Ne=t.paths;if(Ne?.user_files!==void 0&&(typeof Ne.user_files!="string"||!Ne.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");let Y=t.store,Ue=t.runtime;if(Ue?.person_uids!==void 0&&(!Array.isArray(Ue.person_uids)||!Ue.person_uids.every(on=>Number.isSafeInteger(on)&&on>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");let Ye=iDn(t.spawnEnv,e.spawnEnv?.allow),Gt=cDn(t.bin),It=lDn(t.humanActions);return{bin:Gt,humanActions:It,schema_version:n,marketplaces:r,plugins:i,auto_update:c,max_panes_per_window:l,auto_open_child_viewers:d,brokerThresholds:p,lifecycle:h,completion_bell:m,working_gerunds:f,whip_mode:g,page_components:A,page_surface:x,whip_messages:b,whip_message_mode:v,mouse_mode_default:S,live_cycles:_,condensed_history:T,bash_tool_purpose:M,verbosity:R,detailed_tool_recaps:B,document_port:O,keybindings:W,tmux_passthrough:z,modelLadders:$,providerOptions:ae,...Object.keys(ye).length>0?{modelRoutes:ye}:{},...Object.keys(X.legacy).length>0?{legacyModelRoutes:X.legacy}:{},...we!==void 0?{modelRouting:we}:{},kinds:We,remoteCanvas:bt,api:Qt,...Ne?{paths:Ne}:{},...Y?{store:Y}:{},...Ue?{runtime:Ue}:{},spawnEnv:Ye}}function EDn(t){return frt(t)}function yrt(t){let e=G0(t);return e?EDn(e):null}var q1n,j1n,Y1n,X1n,crt,sDn,urt,drt,Jd=y(()=>{"use strict";du();pu();g6();uh();nv();wnt();$l();rv();pV();dB();Znt();qF();mE();XAe();y6();KF();q1n=globalThis,j1n=Symbol.for("crtr.broker.config-snapshot");Y1n=new Set(Vd.filter(CF).map(t=>t.id));X1n=["ultra","strong","medium","light"];crt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,sDn=new Set(["crtr","crtrd"]);urt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;drt=!1});var j0=Q((dSi,Qrt)=>{"use strict";var Nrt=["nodebuffer","arraybuffer","fragments"],Lrt=typeof Blob<"u";Lrt&&Nrt.push("blob");Qrt.exports={BINARY_TYPES:Nrt,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Lrt,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var oU=Q((pSi,CV)=>{"use strict";var{EMPTY_BUFFER:dMn}=j0(),v0e=Buffer[Symbol.species];function pMn(t,e){if(t.length===0)return dMn;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let i=0;i<t.length;i++){let o=t[i];n.set(o,r),r+=o.length}return r<e?new v0e(n.buffer,n.byteOffset,r):n}function Ort(t,e,n,r,i){for(let o=0;o<i;o++)n[r+o]=t[o]^e[o&3]}function Frt(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function hMn(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function S0e(t){if(S0e.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new v0e(t):ArrayBuffer.isView(t)?e=new v0e(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),S0e.readOnly=!1),e}CV.exports={concat:pMn,mask:Ort,toArrayBuffer:hMn,toBuffer:S0e,unmask:Frt};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=J("bufferutil");CV.exports.mask=function(e,n,r,i,o){o<48?Ort(e,n,r,i,o):t.mask(e,n,r,i,o)},CV.exports.unmask=function(e,n){e.length<32?Frt(e,n):t.unmask(e,n)}}catch{}});var Wrt=Q((hSi,$rt)=>{"use strict";var Urt=Symbol("kDone"),_0e=Symbol("kRun"),k0e=class{constructor(e){this[Urt]=()=>{this.pending--,this[_0e]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[_0e]()}[_0e](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Urt])}}};$rt.exports=k0e});var bB=Q((mSi,jrt)=>{"use strict";var sU=J("zlib"),Hrt=oU(),mMn=Wrt(),{kStatusCode:Grt}=j0(),fMn=Buffer[Symbol.species],gMn=Buffer.from([0,0,255,255]),vV=Symbol("permessage-deflate"),z0=Symbol("total-length"),EB=Symbol("callback"),wE=Symbol("buffers"),xB=Symbol("error"),IV,T0e=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!IV){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;IV=new mMn(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[EB];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(i=>!(n.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>i.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let i=n[r];if(i.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="client_max_window_bits"){if(i!==!0){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=o}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=i})}),e}decompress(e,n,r){IV.add(i=>{this._decompress(e,n,(o,s)=>{i(),r(o,s)})})}compress(e,n,r){IV.add(i=>{this._compress(e,n,(o,s)=>{i(),r(o,s)})})}_decompress(e,n,r){let i=this._isServer?"client":"server";if(!this._inflate){let o=`${i}_max_window_bits`,s=typeof this.params[o]!="number"?sU.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=sU.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[vV]=this,this._inflate[z0]=0,this._inflate[wE]=[],this._inflate.on("error",yMn),this._inflate.on("data",qrt)}this._inflate[EB]=r,this._inflate.write(e),n&&this._inflate.write(gMn),this._inflate.flush(()=>{let o=this._inflate[xB];if(o){this._inflate.close(),this._inflate=null,r(o);return}let s=Hrt.concat(this._inflate[wE],this._inflate[z0]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[z0]=0,this._inflate[wE]=[],n&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,s)})}_compress(e,n,r){let i=this._isServer?"server":"client";if(!this._deflate){let o=`${i}_max_window_bits`,s=typeof this.params[o]!="number"?sU.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=sU.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[z0]=0,this._deflate[wE]=[],this._deflate.on("data",AMn)}this._deflate[EB]=r,this._deflate.write(e),this._deflate.flush(sU.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=Hrt.concat(this._deflate[wE],this._deflate[z0]);n&&(o=new fMn(o.buffer,o.byteOffset,o.length-4)),this._deflate[EB]=null,this._deflate[z0]=0,this._deflate[wE]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,o)})}};jrt.exports=T0e;function AMn(t){this[wE].push(t),this[z0]+=t.length}function qrt(t){if(this[z0]+=t.length,this[vV]._maxPayload<1||this[z0]<=this[vV]._maxPayload){this[wE].push(t);return}this[xB]=new RangeError("Max payload size exceeded"),this[xB].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[xB][Grt]=1009,this.removeListener("data",qrt),this.reset()}function yMn(t){if(this[vV]._inflate=null,this[xB]){this[EB](this[xB]);return}t[Grt]=1007,this[EB](t)}});var CB=Q((fSi,SV)=>{"use strict";var{isUtf8:zrt}=J("buffer"),{hasBlob:wMn}=j0(),EMn=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function xMn(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function R0e(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function bMn(t){return wMn&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}SV.exports={isBlob:bMn,isValidStatusCode:xMn,isValidUTF8:R0e,tokenChars:EMn};if(zrt)SV.exports.isValidUTF8=function(t){return t.length<24?R0e(t):zrt(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=J("utf-8-validate");SV.exports.isValidUTF8=function(e){return e.length<32?R0e(e):t(e)}}catch{}});var N0e=Q((gSi,eit)=>{"use strict";var{Writable:CMn}=J("stream"),Vrt=bB(),{BINARY_TYPES:IMn,EMPTY_BUFFER:Krt,kStatusCode:vMn,kWebSocket:SMn}=j0(),{concat:B0e,toArrayBuffer:_Mn,unmask:kMn}=oU(),{isValidStatusCode:TMn,isValidUTF8:Yrt}=CB(),_V=Buffer[Symbol.species],dh=0,Jrt=1,Xrt=2,Zrt=3,D0e=4,M0e=5,kV=6,P0e=class extends CMn{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||IMn[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[SMn]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=dh}_write(e,n,r){if(this._opcode===8&&this._state==dh)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new _V(r.buffer,r.byteOffset+e,r.length-e),new _V(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],i=n.length-e;e>=r.length?n.set(this._buffers.shift(),i):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),i),this._buffers[0]=new _V(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case dh:this.getInfo(e);break;case Jrt:this.getPayloadLength16(e);break;case Xrt:this.getPayloadLength64(e);break;case Zrt:this.getMask();break;case D0e:this.getData(e);break;case M0e:case kV:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let r=(n[0]&64)===64;if(r&&!this._extensions[Vrt.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=Jrt:this._payloadLength===127?this._state=Xrt:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=Zrt:this._state=D0e}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=D0e}getData(e){let n=Krt;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&kMn(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=M0e,this.decompress(n,e);return}if(n.length){if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}this._messageLength=this._totalPayloadLength,this._fragments.push(n)}this.dataMessage(e)}decompress(e,n){this._extensions[Vrt.extensionName].decompress(e,this._fin,(i,o)=>{if(i)return n(i);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(s);return}if(this._maxFragments>0&&this._fragments.length>=this._maxFragments){let s=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");n(s);return}this._fragments.push(o)}this.dataMessage(n),this._state===dh&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=dh;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=B0e(r,n):this._binaryType==="arraybuffer"?i=_Mn(B0e(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=dh):(this._state=kV,setImmediate(()=>{this.emit("message",i,!0),this._state=dh,this.startLoop(e)}))}else{let i=B0e(r,n);if(!this._skipUTF8Validation&&!Yrt(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===M0e||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=dh):(this._state=kV,setImmediate(()=>{this.emit("message",i,!1),this._state=dh,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Krt),this.end();else{let r=e.readUInt16BE(0);if(!TMn(r)){let o=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(o);return}let i=new _V(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Yrt(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(o);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=dh;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=dh):(this._state=kV,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=dh,this.startLoop(n)}))}createError(e,n,r,i,o){this._loop=!1,this._errored=!0;let s=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(s,this.createError),s.code=o,s[vMn]=i,s}};eit.exports=P0e});var O0e=Q((ySi,rit)=>{"use strict";var{Duplex:ASi}=J("stream"),{randomFillSync:RMn}=J("crypto"),{types:{isUint8Array:BMn}}=J("util"),tit=bB(),{EMPTY_BUFFER:DMn,kWebSocket:MMn,NOOP:PMn}=j0(),{isBlob:IB,isValidStatusCode:NMn}=CB(),{mask:nit,toBuffer:uv}=oU(),ph=Symbol("kByteLength"),LMn=Buffer.alloc(4),TV=8*1024,lv,vB=TV,Zm=0,QMn=1,OMn=2,L0e=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Zm,this.onerror=PMn,this[MMn]=void 0}static frame(e,n){let r,i=!1,o=2,s=!1;n.mask&&(r=n.maskBuffer||LMn,n.generateMask?n.generateMask(r):(vB===TV&&(lv===void 0&&(lv=Buffer.alloc(TV)),RMn(lv,0,TV),vB=0),r[0]=lv[vB++],r[1]=lv[vB++],r[2]=lv[vB++],r[3]=lv[vB++]),s=(r[0]|r[1]|r[2]|r[3])===0,o=6);let a;typeof e=="string"?(!n.mask||s)&&n[ph]!==void 0?a=n[ph]:(e=Buffer.from(e),a=e.length):(a=e.length,i=n.mask&&n.readOnly&&!s);let c=a;a>=65536?(o+=8,c=127):a>125&&(o+=2,c=126);let u=Buffer.allocUnsafe(i?a+o:o);return u[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(u[0]|=64),u[1]=c,c===126?u.writeUInt16BE(a,2):c===127&&(u[2]=u[3]=0,u.writeUIntBE(a,4,6)),n.mask?(u[1]|=128,u[o-4]=r[0],u[o-3]=r[1],u[o-2]=r[2],u[o-1]=r[3],s?[u,e]:i?(nit(e,r,u,o,a),[u]):(nit(e,r,e,0,a),[u,e])):[u,e]}close(e,n,r,i){let o;if(e===void 0)o=DMn;else{if(typeof e!="number"||!NMn(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(o=Buffer.allocUnsafe(2+a),o.writeUInt16BE(e,0),typeof n=="string")o.write(n,2);else if(BMn(n))o.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[ph]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Zm?this.enqueue([this.dispatch,o,!1,s,i]):this.sendFrame(t.frame(o,s),i)}ping(e,n,r){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):IB(e)?(i=e.size,o=!1):(e=uv(e),i=e.length,o=uv.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[ph]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};IB(e)?this._state!==Zm?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==Zm?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}pong(e,n,r){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):IB(e)?(i=e.size,o=!1):(e=uv(e),i=e.length,o=uv.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[ph]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};IB(e)?this._state!==Zm?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==Zm?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}send(e,n,r){let i=this._extensions[tit.extensionName],o=n.binary?2:1,s=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):IB(e)?(a=e.size,c=!1):(e=uv(e),a=e.length,c=uv.readOnly),this._firstFragment?(this._firstFragment=!1,s&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=i._threshold),this._compress=s):(s=!1,o=0),n.fin&&(this._firstFragment=!0);let u={[ph]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:s};IB(e)?this._state!==Zm?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==Zm?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[ph],this._state=OMn,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Q0e,this,a,i);return}this._bufferedBytes-=r[ph];let s=uv(o);n?this.dispatch(s,n,r,i):(this._state=Zm,this.sendFrame(t.frame(s,r),i),this.dequeue())}).catch(o=>{process.nextTick(FMn,this,o,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let o=this._extensions[tit.extensionName];this._bufferedBytes+=r[ph],this._state=QMn,o.compress(e,r.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Q0e(this,c,i);return}this._bufferedBytes-=r[ph],this._state=Zm,r.readOnly=!1,this.sendFrame(t.frame(a,r),i),this.dequeue()})}dequeue(){for(;this._state===Zm&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][ph],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ph],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};rit.exports=L0e;function Q0e(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let i=t._queue[r],o=i[i.length-1];typeof o=="function"&&o(e)}}function FMn(t,e,n){Q0e(t,e,n),t.onerror(e)}});var pit=Q((wSi,dit)=>{"use strict";var{kForOnEventAttribute:aU,kListener:F0e}=j0(),iit=Symbol("kCode"),oit=Symbol("kData"),sit=Symbol("kError"),ait=Symbol("kMessage"),cit=Symbol("kReason"),SB=Symbol("kTarget"),uit=Symbol("kType"),lit=Symbol("kWasClean"),V0=class{constructor(e){this[SB]=null,this[uit]=e}get target(){return this[SB]}get type(){return this[uit]}};Object.defineProperty(V0.prototype,"target",{enumerable:!0});Object.defineProperty(V0.prototype,"type",{enumerable:!0});var dv=class extends V0{constructor(e,n={}){super(e),this[iit]=n.code===void 0?0:n.code,this[cit]=n.reason===void 0?"":n.reason,this[lit]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[iit]}get reason(){return this[cit]}get wasClean(){return this[lit]}};Object.defineProperty(dv.prototype,"code",{enumerable:!0});Object.defineProperty(dv.prototype,"reason",{enumerable:!0});Object.defineProperty(dv.prototype,"wasClean",{enumerable:!0});var _B=class extends V0{constructor(e,n={}){super(e),this[sit]=n.error===void 0?null:n.error,this[ait]=n.message===void 0?"":n.message}get error(){return this[sit]}get message(){return this[ait]}};Object.defineProperty(_B.prototype,"error",{enumerable:!0});Object.defineProperty(_B.prototype,"message",{enumerable:!0});var cU=class extends V0{constructor(e,n={}){super(e),this[oit]=n.data===void 0?null:n.data}get data(){return this[oit]}};Object.defineProperty(cU.prototype,"data",{enumerable:!0});var UMn={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[aU]&&i[F0e]===e&&!i[aU])return;let r;if(t==="message")r=function(o,s){let a=new cU("message",{data:s?o:o.toString()});a[SB]=this,RV(e,this,a)};else if(t==="close")r=function(o,s){let a=new dv("close",{code:o,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[SB]=this,RV(e,this,a)};else if(t==="error")r=function(o){let s=new _B("error",{error:o,message:o.message});s[SB]=this,RV(e,this,s)};else if(t==="open")r=function(){let o=new V0("open");o[SB]=this,RV(e,this,o)};else return;r[aU]=!!n[aU],r[F0e]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[F0e]===e&&!n[aU]){this.removeListener(t,n);break}}};dit.exports={CloseEvent:dv,ErrorEvent:_B,Event:V0,EventTarget:UMn,MessageEvent:cU};function RV(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var BV=Q((ESi,hit)=>{"use strict";var{tokenChars:uU}=CB();function Dg(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function $Mn(t){let e=Object.create(null),n=Object.create(null),r=!1,i=!1,o=!1,s,a,c=-1,u=-1,l=-1,d=0;for(;d<t.length;d++)if(u=t.charCodeAt(d),s===void 0)if(l===-1&&uU[u]===1)c===-1&&(c=d);else if(d!==0&&(u===32||u===9))l===-1&&c!==-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let h=t.slice(c,l);u===44?(Dg(e,h,n),n=Object.create(null)):s=h,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(l===-1&&uU[u]===1)c===-1&&(c=d);else if(u===32||u===9)l===-1&&c!==-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d),Dg(n,t.slice(c,l),!0),u===44&&(Dg(e,s,n),n=Object.create(null),s=void 0),c=l=-1}else if(u===61&&c!==-1&&l===-1)a=t.slice(c,d),c=l=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(i){if(uU[u]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:r||(r=!0),i=!1}else if(o)if(uU[u]===1)c===-1&&(c=d);else if(u===34&&c!==-1)o=!1,l=d;else if(u===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(u===34&&t.charCodeAt(d-1)===61)o=!0;else if(l===-1&&uU[u]===1)c===-1&&(c=d);else if(c!==-1&&(u===32||u===9))l===-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let h=t.slice(c,l);r&&(h=h.replace(/\\/g,""),r=!1),Dg(n,a,h),u===44&&(Dg(e,s,n),n=Object.create(null),s=void 0),a=void 0,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(c===-1||o||u===32||u===9)throw new SyntaxError("Unexpected end of input");l===-1&&(l=d);let p=t.slice(c,l);return s===void 0?Dg(e,p,n):(a===void 0?Dg(n,p,!0):r?Dg(n,a,p.replace(/\\/g,"")):Dg(n,a,p),Dg(e,s,n)),e}function WMn(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(i=>{let o=r[i];return Array.isArray(o)||(o=[o]),o.map(s=>s===!0?i:`${i}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}hit.exports={format:WMn,parse:$Mn}});var NV=Q((CSi,vit)=>{"use strict";var HMn=J("events"),GMn=J("https"),qMn=J("http"),git=J("net"),jMn=J("tls"),{randomBytes:zMn,createHash:VMn}=J("crypto"),{Duplex:xSi,Readable:bSi}=J("stream"),{URL:U0e}=J("url"),EE=bB(),KMn=N0e(),YMn=O0e(),{isBlob:JMn}=CB(),{BINARY_TYPES:mit,CLOSE_TIMEOUT:XMn,EMPTY_BUFFER:DV,GUID:ZMn,kForOnEventAttribute:$0e,kListener:ePn,kStatusCode:tPn,kWebSocket:ac,NOOP:Ait}=j0(),{EventTarget:{addEventListener:nPn,removeEventListener:rPn}}=pit(),{format:iPn,parse:oPn}=BV(),{toBuffer:sPn}=oU(),yit=Symbol("kAborted"),W0e=[8,13],K0=["CONNECTING","OPEN","CLOSING","CLOSED"],aPn=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,qo=class t extends HMn{constructor(e,n,r){super(),this._binaryType=mit[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=DV,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),wit(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){mit.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let i=new KMn({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),o=new YMn(e,this._extensions,r.generateMask);this._receiver=i,this._sender=o,this._socket=e,i[ac]=this,o[ac]=this,e[ac]=this,i.on("conclude",lPn),i.on("drain",dPn),i.on("error",pPn),i.on("message",hPn),i.on("ping",mPn),i.on("pong",fPn),o.onerror=gPn,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",bit),e.on("data",PV),e.on("end",Cit),e.on("error",Iit),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[EE.extensionName]&&this._extensions[EE.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){np(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),xit(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){H0e(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||DV,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){H0e(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||DV,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){H0e(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[EE.extensionName]||(i.compress=!1),this._sender.send(e||DV,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){np(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(qo,"CONNECTING",{enumerable:!0,value:K0.indexOf("CONNECTING")});Object.defineProperty(qo.prototype,"CONNECTING",{enumerable:!0,value:K0.indexOf("CONNECTING")});Object.defineProperty(qo,"OPEN",{enumerable:!0,value:K0.indexOf("OPEN")});Object.defineProperty(qo.prototype,"OPEN",{enumerable:!0,value:K0.indexOf("OPEN")});Object.defineProperty(qo,"CLOSING",{enumerable:!0,value:K0.indexOf("CLOSING")});Object.defineProperty(qo.prototype,"CLOSING",{enumerable:!0,value:K0.indexOf("CLOSING")});Object.defineProperty(qo,"CLOSED",{enumerable:!0,value:K0.indexOf("CLOSED")});Object.defineProperty(qo.prototype,"CLOSED",{enumerable:!0,value:K0.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(qo.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(qo.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[$0e])return e[ePn];return null},set(e){for(let n of this.listeners(t))if(n[$0e]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[$0e]:!0})}})});qo.prototype.addEventListener=nPn;qo.prototype.removeEventListener=rPn;vit.exports=qo;function wit(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:XMn,protocolVersion:W0e[1],maxBufferedChunks:1048576,maxFragments:131072,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!W0e.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${W0e.join(", ")})`);let o;if(e instanceof U0e)o=e;else try{o=new U0e(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),t._url=o.href;let s=o.protocol==="wss:",a=o.protocol==="ws+unix:",c;if(o.protocol!=="ws:"&&!s&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"),c){let f=new SyntaxError(c);if(t._redirects===0)throw f;MV(t,f);return}let u=s?443:80,l=zMn(16).toString("base64"),d=s?GMn.request:qMn.request,p=new Set,h;if(i.createConnection=i.createConnection||(s?uPn:cPn),i.defaultPort=i.defaultPort||u,i.port=o.port||u,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(h=new EE({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=iPn({[EE.extensionName]:h.offer()})),n.length){for(let f of n){if(typeof f!="string"||!aPn.test(f)||p.has(f))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(f)}i.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(o.username||o.password)&&(i.auth=`${o.username}:${o.password}`),a){let f=i.path.split(":");i.socketPath=f[0],i.path=f[1]}let m;if(i.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=s,t._originalHostOrSocketPath=a?i.socketPath:o.host;let f=r&&r.headers;if(r={...r,headers:{}},f)for(let[g,A]of Object.entries(f))r.headers[g.toLowerCase()]=A}else if(t.listenerCount("redirect")===0){let f=a?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!f||t._originalSecure&&!s)&&(delete i.headers.authorization,delete i.headers.cookie,f||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),m=t._req=d(i),t._redirects&&t.emit("redirect",t.url,m)}else m=t._req=d(i);i.timeout&&m.on("timeout",()=>{np(t,m,"Opening handshake has timed out")}),m.on("error",f=>{m===null||m[yit]||(m=t._req=null,MV(t,f))}),m.on("response",f=>{let g=f.headers.location,A=f.statusCode;if(g&&i.followRedirects&&A>=300&&A<400){if(++t._redirects>i.maxRedirects){np(t,m,"Maximum redirects exceeded");return}m.abort();let x;try{x=new U0e(g,e)}catch{let v=new SyntaxError(`Invalid URL: ${g}`);MV(t,v);return}wit(t,x,n,r)}else t.emit("unexpected-response",m,f)||np(t,m,`Unexpected server response: ${f.statusCode}`)}),m.on("upgrade",(f,g,A)=>{if(t.emit("upgrade",f),t.readyState!==qo.CONNECTING)return;m=t._req=null;let x=f.headers.upgrade;if(x===void 0||x.toLowerCase()!=="websocket"){np(t,g,"Invalid Upgrade header");return}let b=VMn("sha1").update(l+ZMn).digest("base64");if(f.headers["sec-websocket-accept"]!==b){np(t,g,"Invalid Sec-WebSocket-Accept header");return}let v=f.headers["sec-websocket-protocol"],S;if(v!==void 0?p.size?p.has(v)||(S="Server sent an invalid subprotocol"):S="Server sent a subprotocol but none was requested":p.size&&(S="Server sent no subprotocol"),S){np(t,g,S);return}v&&(t._protocol=v);let _=f.headers["sec-websocket-extensions"];if(_!==void 0){if(!h){np(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let T;try{T=oPn(_)}catch{np(t,g,"Invalid Sec-WebSocket-Extensions header");return}let M=Object.keys(T);if(M.length!==1||M[0]!==EE.extensionName){np(t,g,"Server indicated an extension that was not requested");return}try{h.accept(T[EE.extensionName])}catch{np(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[EE.extensionName]=h}t.setSocket(g,A,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(m,t):m.end()}function MV(t,e){t._readyState=qo.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function cPn(t){return t.path=t.socketPath,git.connect(t)}function uPn(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=git.isIP(t.host)?"":t.host),jMn.connect(t)}function np(t,e,n){t._readyState=qo.CLOSING;let r=new Error(n);Error.captureStackTrace(r,np),e.setHeader?(e[yit]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(MV,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function H0e(t,e,n){if(e){let r=JMn(e)?e.size:sPn(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${K0[t.readyState]})`);process.nextTick(n,r)}}function lPn(t,e){let n=this[ac];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[ac]!==void 0&&(n._socket.removeListener("data",PV),process.nextTick(Eit,n._socket),t===1005?n.close():n.close(t,e))}function dPn(){let t=this[ac];t.isPaused||t._socket.resume()}function pPn(t){let e=this[ac];e._socket[ac]!==void 0&&(e._socket.removeListener("data",PV),process.nextTick(Eit,e._socket),e.close(t[tPn])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function fit(){this[ac].emitClose()}function hPn(t,e){this[ac].emit("message",t,e)}function mPn(t){let e=this[ac];e._autoPong&&e.pong(t,!this._isServer,Ait),e.emit("ping",t)}function fPn(t){this[ac].emit("pong",t)}function Eit(t){t.resume()}function gPn(t){let e=this[ac];e.readyState!==qo.CLOSED&&(e.readyState===qo.OPEN&&(e._readyState=qo.CLOSING,xit(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function xit(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function bit(){let t=this[ac];if(this.removeListener("close",bit),this.removeListener("data",PV),this.removeListener("end",Cit),t._readyState=qo.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[ac]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",fit),t._receiver.on("finish",fit))}function PV(t){this[ac]._receiver.write(t)||this.pause()}function Cit(){let t=this[ac];t._readyState=qo.CLOSING,t._receiver.end(),this.end()}function Iit(){let t=this[ac];this.removeListener("error",Iit),this.on("error",Ait),t&&(t._readyState=qo.CLOSING,this.destroy())}});var Tit=Q((vSi,kit)=>{"use strict";var ISi=NV(),{Duplex:APn}=J("stream");function Sit(t){t.emit("close")}function yPn(){!this.destroyed&&this._writableState.finished&&this.destroy()}function _it(t){this.removeListener("error",_it),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function wPn(t,e){let n=!0,r=new APn({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,s){let a=!s&&r._readableState.objectMode?o.toString():o;r.push(a)||t.pause()}),t.once("error",function(o){r.destroyed||(n=!1,r.destroy(o))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(i,o){if(t.readyState===t.CLOSED){o(i),process.nextTick(Sit,r);return}let s=!1;t.once("error",function(c){s=!0,o(c)}),t.once("close",function(){s||o(i),process.nextTick(Sit,r)}),n&&t.terminate()},r._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(i,o,s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(i,o,s)});return}t.send(i,s)},r.on("end",yPn),r.on("error",_it),r}kit.exports=wPn});var G0e=Q((SSi,Rit)=>{"use strict";var{tokenChars:EPn}=CB();function xPn(t){let e=new Set,n=-1,r=-1,i=0;for(i;i<t.length;i++){let s=t.charCodeAt(i);if(r===-1&&EPn[s]===1)n===-1&&(n=i);else if(i!==0&&(s===32||s===9))r===-1&&n!==-1&&(r=i);else if(s===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${i}`);r===-1&&(r=i);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let o=t.slice(n,i);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}Rit.exports={parse:xPn}});var Qit=Q((kSi,Lit)=>{"use strict";var bPn=J("events"),LV=J("http"),{Duplex:_Si}=J("stream"),{createHash:CPn}=J("crypto"),Bit=BV(),pv=bB(),IPn=G0e(),vPn=NV(),{CLOSE_TIMEOUT:SPn,GUID:_Pn,kWebSocket:kPn}=j0(),TPn=/^[+/0-9A-Za-z]{22}==$/,Dit=0,Mit=1,Nit=2,q0e=class extends bPn{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:1024*1024,maxFragments:128*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:SPn,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:vPn,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=LV.createServer((r,i)=>{let o=LV.STATUS_CODES[426];i.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),i.end(o)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=RPn(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,o,s)=>{this.handleUpgrade(i,o,s,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Dit}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Nit){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(lU,this);return}if(e&&this.once("close",e),this._state!==Mit)if(this._state=Mit,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(lU,this):process.nextTick(lU,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{lU(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,i){n.on("error",Pit);let o=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){hv(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){hv(this,e,n,400,"Invalid Upgrade header");return}if(o===void 0||!TPn.test(o)){hv(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){hv(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){dU(n,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=IPn.parse(c)}catch{hv(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let l=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&l!==void 0){let p=new pv({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=Bit.parse(l);h[pv.extensionName]&&(p.accept(h[pv.extensionName]),d[pv.extensionName]=p)}catch{hv(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let p={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(p,(h,m,f,g)=>{if(!h)return dU(n,m||401,f,g);this.completeUpgrade(d,o,u,e,n,r,i)});return}if(!this.options.verifyClient(p))return dU(n,401)}this.completeUpgrade(d,o,u,e,n,r,i)}completeUpgrade(e,n,r,i,o,s,a){if(!o.readable||!o.writable)return o.destroy();if(o[kPn])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Dit)return dU(o,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${CPn("sha1").update(n+_Pn).digest("base64")}`],l=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;d&&(u.push(`Sec-WebSocket-Protocol: ${d}`),l._protocol=d)}if(e[pv.extensionName]){let d=e[pv.extensionName].params,p=Bit.format({[pv.extensionName]:[d]});u.push(`Sec-WebSocket-Extensions: ${p}`),l._extensions=e}this.emit("headers",u,i),o.write(u.concat(`\r
101
101
  `).join(`\r
@@ -0,0 +1,8 @@
1
+ -- 020-machine-calls-status-all.sql — `machine_calls.op` accepts `status.all`: every broker running on the machine, from one scan of
2
+ -- its process table, so the node-lifecycle tick checks all of a machine's executions with one call instead of one `status` call per
3
+ -- execution. One transaction; the CHECK only widens: `schema_min_reader` is not touched, so the previous release (version 19) still
4
+ -- opens the result. It never writes a `status.all` row, and a holder on that release forwards one it claims like any other op.
5
+ ALTER TABLE machine_calls DROP CONSTRAINT IF EXISTS machine_calls_op_check;
6
+ ALTER TABLE machine_calls ADD CONSTRAINT machine_calls_op_check
7
+ CHECK (op IN ('start', 'wake', 'stop', 'status', 'status.all', 'delete', 'viewer', 'cron.run', 'cron.cancel',
8
+ 'worktree.create', 'worktree.rollback', 'worktree.close', 'worktree.abandon', 'worktree.finalize'));
@@ -1,7 +1,7 @@
1
1
  /** The canvas schema version this build supports: the number of the highest delta in `schema-pg/` (the baseline
2
2
  * `schema-pg.sql` is version 1). `scripts/install-runtime.mjs` reads this module from a candidate generation to refuse
3
3
  * one below the live database's `schema_min_reader`. */
4
- export declare const CANVAS_SCHEMA_VERSION = 19;
4
+ export declare const CANVAS_SCHEMA_VERSION = 20;
5
5
  /** The Postgres schema holding the canvas tables: `CRTR_DATABASE_SCHEMA` (`crtr` in the cloud deploy). Unset or empty
6
6
  * means the role's own search_path (`public` on a Mac and on a VM). A name that is not a plain identifier is an error:
7
7
  * it is put in a `search_path` connection option. */
@@ -1 +1 @@
1
- var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=19;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
1
+ var m=Object.defineProperty;var r=(n,e)=>m(n,"name",{value:e,configurable:!0});const A=20;function _(n=process.env){const e=n.CRTR_DATABASE_SCHEMA?.trim();if(e){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(e))throw new Error(`CRTR_DATABASE_SCHEMA must be a plain identifier (letters, digits, underscore); got ${JSON.stringify(e)}`);return e}}r(_,"canvasDatabaseSchema");function h(n=process.env){return n.CRTR_SCHEMA_DATABASE_URL?.trim()||void 0}r(h,"canvasSchemaDatabaseUrl");function E(n=process.env){const e=_(n);return e===void 0?void 0:`-c search_path=${e}`}r(E,"canvasSearchPathOptions");async function v(n,e){const t=e===void 0?"canvas_meta":`"${e.replace(/"/g,'""')}".canvas_meta`;if((await n.query(`SELECT to_regclass('${t.replace(/'/g,"''")}') IS NOT NULL AS found`)).rows[0].found!==!0)return;const u=(await n.query(`SELECT key, value FROM ${t} WHERE key IN ('schema_version', 'schema_min_reader')`)).rows,o=r(c=>{const i=u.find(f=>f.key===c);if(i===void 0)return;const d=Number(i.value);if(!Number.isSafeInteger(d))throw new Error(`canvas_meta.${c} is not an integer: ${String(i.value)}`);return d},"value"),s=o("schema_version");return s===void 0?void 0:{version:s,minReader:o("schema_min_reader")??s}}r(v,"readStoredVersions");async function l(n,e,t){const a=await v(n,t);if(a!==void 0&&a.minReader>e)throw new Error(`refusing to select runtime with canvas schema ${e}: the live database requires readers at version ${a.minReader} or above (it is at ${a.version}); install a descendant build instead`)}r(l,"assertCandidateMayOpen");export{A as CANVAS_SCHEMA_VERSION,l as assertCandidateMayOpen,_ as canvasDatabaseSchema,h as canvasSchemaDatabaseUrl,E as canvasSearchPathOptions,v as readStoredVersions};
@@ -65,6 +65,20 @@ export declare function otherLiveGrantOfApp(app: string, sub: string): Promise<b
65
65
  /** Every provider id a scope of an active grant's resolved set names: a
66
66
  * `<id>:<group>` string whose id is not `crtr` (the runtime's own namespace). */
67
67
  export declare function providerIdsFromGrants(grants: readonly GrantRecord[]): string[];
68
+ /** The provider ids an active grant this machine acts on names: `providerIdsFromGrants(localGrants())`, computed in the database. On a cloud
69
+ * role the mirror holds every person's grants and each resolved scope list runs to hundreds of kilobytes, so loading and parsing the
70
+ * whole mirror held up every request behind it; this returns one short row per provider. A row whose computed columns lag its
71
+ * revision names nothing, as `record()` reads it. The `::jsonb` cast cannot fail: `replaceGrants`, the only writer, stores
72
+ * `JSON.stringify` of lists `entries()` accepted, and `entries()` refuses the strings jsonb rejects (`jsonbSafe`). */
73
+ export declare function activeProviderIds(): Promise<string[]>;
74
+ /** Whether this machine acts on any active grant (`localGrants()` holds one), read without loading a row. */
75
+ export declare function anyActiveGrant(): Promise<boolean>;
76
+ /** The `sub` of every mirrored grant, whatever its status: who the grants are for, without reading their scopes. A row whose
77
+ * computed columns lag its revision is left out, as `allGrants()` leaves it out. */
78
+ export declare function grantSubs(): Promise<string[]>;
79
+ /** The active mirrored grants, of `person` alone when given; unparsable rows are dropped. What token discard reads: it looks only at active
80
+ * grants, and on a cloud role removed rows outnumber them several times over. */
81
+ export declare function activeGrants(person?: string): Promise<GrantRecord[]>;
68
82
  /** The provider ids an active grant of `person` names: the directory's provider bundles that person has, and so the only
69
83
  * rows of their plugin list that a provider call installs on its own (`ensureProviderBundle`) rather than from a source. */
70
84
  export declare function grantedProviderIds(person: string): Promise<Set<string>>;
@@ -80,7 +94,8 @@ export declare function isProviderBundleRow(row: {
80
94
  * would hand back every person the fleet serves. */
81
95
  export declare function activeGrantsOfPerson(person: string): Promise<ActiveGrant[]>;
82
96
  /** Every mirrored grant, whatever its status. On a cloud role that is every person's, and their scope lists run to megabytes: a request
83
- * acting for one person reads `grantsOfPerson`. */
97
+ * acting for one person reads `grantsOfPerson`, and a pass over every person reads `activeProviderIds`, `anyActiveGrant`, `grantSubs`
98
+ * or `activeGrants`. */
84
99
  export declare function allGrants(): Promise<GrantRecord[]>;
85
100
  /** `person`'s (`user:<id>`) mirrored grants, whatever their status. */
86
101
  export declare function grantsOfPerson(person: string): Promise<GrantRecord[]>;