@north-light/cli 0.3.743 → 0.3.745
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/builtin-memory/crouter-concepts/scopes-and-trust.md +2 -2
- package/dist/builtin-memory/crouter-sdk/README.md +1 -1
- package/dist/builtin-memory/crouter-sdk/client.md +1 -1
- package/dist/builtin-memory/crouter-sdk/getting-started.md +3 -38
- package/dist/clients/attach/viewer.js +1 -1
- package/dist/commands/sys/provider-login.js +2 -2
- package/dist/commands/sys.js +1 -1
- package/dist/core/canvas/daemon-owner.d.ts +1 -1
- package/dist/core/canvas/paths.d.ts +1 -1
- package/dist/core/canvas/person-state.d.ts +3 -0
- package/dist/core/canvas/person-state.js +1 -1
- package/dist/core/canvas/person.d.ts +2 -3
- package/dist/core/canvas/person.js +7 -7
- package/dist/core/canvas/tree.js +4 -4
- package/dist/core/environments.d.ts +0 -10
- package/dist/core/environments.js +1 -1
- package/dist/core/runtime/blaxel-environment.js +1 -1
- package/dist/core/secrets.d.ts +2 -4
- package/dist/core/secrets.js +1 -1
- package/dist/core/spaces/space.js +2 -2
- package/dist/core/user-settings.js +1 -1
- package/dist/daemon/api/environment-of.d.ts +1 -1
- package/dist/daemon/api/environment-of.js +3 -3
- package/dist/daemon/api/handlers/document-access.js +1 -1
- package/dist/daemon/api/router.d.ts +1 -1
- package/dist/daemon/crtrd-cli.js +1 -1
- package/dist/daemon/crtrd.d.ts +4 -2
- package/dist/daemon/crtrd.js +20 -20
- package/dist/daemon/manage.d.ts +0 -8
- package/dist/daemon/manage.js +3 -3
- package/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
- package/dist/daemon/reconcilers/storage-maintenance.d.ts +0 -2
- package/dist/daemon/reconcilers/storage-maintenance.js +1 -1
- package/docs/concepts/scopes-and-trust.md +2 -2
- package/docs/public-api.md +1 -7
- package/docs/sdk/README.md +1 -1
- package/docs/sdk/client.md +1 -1
- package/docs/sdk/getting-started.md +3 -38
- package/package.json +3 -3
- package/packages/crouter-api/dist/commands/sys/provider-login.js +2 -2
- package/packages/crouter-api/dist/commands/sys.js +1 -3
- package/packages/crouter-api/dist/core/canvas/paths.js +1 -1
- package/packages/crouter-api/dist/core/canvas/person-state.js +4 -0
- package/packages/crouter-api/dist/core/canvas/person.js +2 -14
- package/packages/crouter-api/dist/core/canvas/tree.js +3 -1
- package/packages/crouter-api/dist/core/environments.js +2 -38
- package/packages/crouter-api/dist/core/model-auth/daemon-login.js +2 -2
- package/packages/crouter-api/dist/core/runtime/blaxel-environment.js +3 -3
- package/packages/crouter-api/dist/core/secrets.js +1 -11
- package/packages/crouter-api/dist/core/spaces/space.js +2 -2
- package/packages/crouter-api/dist/core/user-settings.js +1 -1
- package/packages/crouter-api/dist/daemon/api/environment-of.js +7 -4
- package/packages/crouter-api/dist/daemon/manage.js +0 -4
- package/packages/crouter-api/dist/daemon/reconcilers/node-lifecycle/remote-wake.js +2 -2
- package/packages/crouter-api/package.json +1 -1
- package/packages/crouter-identity/package.json +1 -1
- package/packages/crouter-plugin/package.json +3 -3
- package/runtime.lock.json +14 -14
- package/dist/commands/sys/connect.d.ts +0 -1
- package/dist/commands/sys/connect.js +0 -3
- package/dist/commands/sys/db.d.ts +0 -1
- package/dist/commands/sys/db.js +0 -1
- package/dist/core/canvas/export-sqlite.d.ts +0 -14
- package/dist/core/canvas/export-sqlite.js +0 -3
- package/dist/daemon/api/document-listener.d.ts +0 -7
- package/dist/daemon/api/document-listener.js +0 -1
- package/dist/daemon/api/document-secret.d.ts +0 -2
- package/dist/daemon/api/document-secret.js +0 -1
- package/dist/daemon/export-sqlite-run.d.ts +0 -1
- package/dist/daemon/export-sqlite-run.js +0 -4
- package/packages/crouter-api/dist/commands/sys/connect.js +0 -185
- package/packages/crouter-api/dist/commands/sys/db.js +0 -69
|
@@ -97,7 +97,7 @@ To prepare for this change:
|
|
|
97
97
|
See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode definitions.`))}Ret.exports=sB;sB.parse=sB;sB.toClientConfig=Tet;sB.parseIntoClientConfig=cTn});var wge=L((Fxi,Pet)=>{"use strict";var uTn=K("dns"),Met=UF(),Det=Bet().parse,su=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||Met[t])},lTn=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 Met.ssl},aB=function(t){return"'"+(""+t).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},Jd=function(t,e,n){let r=e[n];r!=null&&t.push(n+"="+aB(r))},Ege=class{constructor(e){if(e=typeof e=="string"?Det(e):e||{},e.connectionString&&(e=Object.assign({},e,Det(e.connectionString))),this.user=su("user",e),this.database=su("database",e),this.database===void 0&&(this.database=this.user),this.port=parseInt(su("port",e),10),this.host=su("host",e),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:su("password",e)}),this.binary=su("binary",e),this.options=su("options",e),this.ssl=typeof e.ssl>"u"?lTn():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=su("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=su("client_encoding",e),this.replication=su("replication",e),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=su("application_name",e,"PGAPPNAME"),this.fallback_application_name=su("fallback_application_name",e,!1),this.statement_timeout=su("statement_timeout",e,!1),this.lock_timeout=su("lock_timeout",e,!1),this.idle_in_transaction_session_timeout=su("idle_in_transaction_session_timeout",e,!1),this.query_timeout=su("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=[];Jd(n,this,"user"),Jd(n,this,"password"),Jd(n,this,"port"),Jd(n,this,"application_name"),Jd(n,this,"fallback_application_name"),Jd(n,this,"connect_timeout"),Jd(n,this,"options");let r=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if(Jd(n,r,"sslmode"),Jd(n,r,"sslca"),Jd(n,r,"sslkey"),Jd(n,r,"sslcert"),Jd(n,r,"sslrootcert"),Jd(n,this,"sslnegotiation"),this.database&&n.push("dbname="+aB(this.database)),this.replication&&n.push("replication="+aB(this.replication)),this.host&&n.push("host="+aB(this.host)),this.isDomainSocket)return e(null,n.join(" "));this.client_encoding&&n.push("client_encoding="+aB(this.client_encoding)),uTn.lookup(this.host,function(i,o){return i?e(i,null):(n.push("hostaddr="+aB(o)),e(null,n.join(" ")))})}};Pet.exports=Ege});var bge=L((Uxi,Oet)=>{"use strict";var dTn=FF(),Net=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,xge=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=Net.exec(e.text):n=Net.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]=dTn.getTypeParser(i.dataTypeID,i.format||"text")}this._prebuiltEmptyResultObject={...n}}};Oet.exports=xge});var Uet=L(($xi,Fet)=>{"use strict";var{EventEmitter:pTn}=K("events"),Let=bge(),Qet=jI(),Cge=class extends pTn{constructor(e,n,r){super(),e=Qet.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 Let(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 Let(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:Qet.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){}};Fet.exports=Cge});var Qge=L($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 Ige=class extends Error{constructor(e,n,r){super(e),this.length=n,this.name=r}};$n.DatabaseError=Ige;var vge=class{constructor(e,n){this.length=e,this.chunk=n,this.name="copyData"}};$n.CopyDataMessage=vge;var Sge=class{constructor(e,n,r,i){this.length=e,this.name=n,this.binary=r,this.columnTypes=new Array(i)}};$n.CopyResponse=Sge;var _ge=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=_ge;var kge=class{constructor(e,n){this.length=e,this.fieldCount=n,this.name="rowDescription",this.fields=new Array(this.fieldCount)}};$n.RowDescriptionMessage=kge;var Tge=class{constructor(e,n){this.length=e,this.parameterCount=n,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}};$n.ParameterDescriptionMessage=Tge;var Rge=class{constructor(e,n,r){this.length=e,this.parameterName=n,this.parameterValue=r,this.name="parameterStatus"}};$n.ParameterStatusMessage=Rge;var Bge=class{constructor(e,n){this.length=e,this.salt=n,this.name="authenticationMD5Password"}};$n.AuthenticationMD5Password=Bge;var Dge=class{constructor(e,n,r){this.length=e,this.processID=n,this.secretKey=r,this.name="backendKeyData"}};$n.BackendKeyDataMessage=Dge;var Mge=class{constructor(e,n,r,i){this.length=e,this.processId=n,this.channel=r,this.payload=i,this.name="notification"}};$n.NotificationResponseMessage=Mge;var Pge=class{constructor(e,n){this.length=e,this.status=n,this.name="readyForQuery"}};$n.ReadyForQueryMessage=Pge;var Nge=class{constructor(e,n){this.length=e,this.text=n,this.name="commandComplete"}};$n.CommandCompleteMessage=Nge;var Oge=class{constructor(e,n){this.length=e,this.fields=n,this.name="dataRow",this.fieldCount=n.length}};$n.DataRowMessage=Oge;var Lge=class{constructor(e,n){this.length=e,this.message=n,this.name="notice"}};$n.NoticeMessage=Lge});var $et=L($6=>{"use strict";Object.defineProperty($6,"__esModule",{value:!0});$6.Writer=void 0;var Fge=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}};$6.Writer=Fge});var Get=L(H6=>{"use strict";Object.defineProperty(H6,"__esModule",{value:!0});H6.serialize=void 0;var Wet=$et(),Vi=new Wet.Writer,hTn=t=>{Vi.addInt16(3).addInt16(0);for(let r of Object.keys(t))Vi.addCString(r).addCString(t[r]);Vi.addCString("client_encoding").addCString("UTF8");let e=Vi.addCString("").flush(),n=e.length+4;return new Wet.Writer().addInt32(n).add(e).flush()},mTn=()=>{let t=Buffer.allocUnsafe(8);return t.writeInt32BE(8,0),t.writeInt32BE(80877103,4),t},fTn=t=>Vi.addCString(t).flush(112),gTn=function(t,e){return Vi.addCString(t).addInt32PrefixedString(e),Vi.flush(112)},ATn=function(t){return Vi.addString(t).flush(112)},yTn=t=>Vi.addCString(t).flush(81),Het=[],ETn=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||Het,r=n.length,i=Vi.addCString(e).addCString(t.text).addInt16(r);for(let o=0;o<r;o++)i.addInt32(n[o]);return Vi.flush(80)},wTn=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?Vi.addInt32(-1):o instanceof Buffer?(s=1,Vi.addInt32(o.length),Vi.add(o)):Vi.addInt32PrefixedString(o);let a=Vi.buffer;a[n++]=0,a[n++]=s}},xTn=(t={})=>{let e=t.portal||"",n=t.statement||"",r=t.binary||!1,i=t.values||Het,o=i.length;Vi.addCString(e).addCString(n),Vi.addInt16(o);let s=Vi.reserveUnsafe(o*2);Vi.addInt16(o);try{wTn(i,t.valueMapper,s)}catch(a){throw Vi.clear(),a}return Vi.addInt16(1),Vi.addInt16(r?1:0),Vi.flush(66)},bTn=Buffer.from([69,0,0,0,9,0,0,0,0,0]),CTn=t=>{if(!t||!t.portal&&!t.rows)return bTn;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},ITn=(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},Uge=(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=Vi.addCString("P").flush(68),STn=Vi.addCString("S").flush(68),_Tn=t=>t.name?Uge(68,`${t.type}${t.name||""}`):t.type==="P"?vTn:STn,kTn=t=>{let e=`${t.type}${t.name||""}`;return Uge(67,e)},TTn=t=>Vi.add(t).flush(100),RTn=t=>Uge(102,t),W6=t=>Buffer.from([t,0,0,0,4]),BTn=W6(72),DTn=W6(83),MTn=W6(88),PTn=W6(99),NTn={startup:hTn,password:fTn,requestSsl:mTn,sendSASLInitialResponseMessage:gTn,sendSCRAMClientFinalMessage:ATn,query:yTn,parse:ETn,bind:xTn,execute:CTn,describe:_Tn,close:kTn,flush:()=>BTn,sync:()=>DTn,end:()=>MTn,copyData:TTn,copyDone:()=>PTn,copyFail:RTn,cancel:ITn};H6.serialize=NTn});var qet=L(G6=>{"use strict";Object.defineProperty(G6,"__esModule",{value:!0});G6.BufferReader=void 0;var $ge=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}};G6.BufferReader=$ge});var Ket=L(q6=>{"use strict";Object.defineProperty(q6,"__esModule",{value:!0});q6.Parser=void 0;var as=Qge(),OTn=qet(),Hge=1,LTn=4,jet=Hge+LTn,Xd=-1,Wge=Buffer.allocUnsafe(0),Gge=class{constructor(e){if(this.buffer=Wge,this.bufferLength=0,this.bufferOffset=0,this.reader=new OTn.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+jet<=r;){let o=this.buffer[i],s=this.buffer.readUInt32BE(i+Hge),a=Hge+s;if(a+i<=r){let c=this.handlePacket(i+jet,o,s,this.buffer);n(c),i+=a}else break}i===r?(this.buffer=Wge,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=as.bindComplete;break;case 49:s=as.parseComplete;break;case 51:s=as.closeComplete;break;case 110:s=as.noData;break;case 115:s=as.portalSuspended;break;case 99:s=as.copyDone;break;case 87:s=as.replicationStart;break;case 73:s=as.emptyQuery;break;case 68:s=zTn(o);break;case 67:s=FTn(o);break;case 90:s=QTn(o);break;case 65:s=HTn(o);break;case 82:s=YTn(o,r);break;case 83:s=VTn(o);break;case 75:s=KTn(o);break;case 69:s=zet(o,"error");break;case 78:s=zet(o,"notice");break;case 84:s=GTn(o);break;case 116:s=jTn(o);break;case 71:s=$Tn(o);break;case 72:s=WTn(o);break;case 100:s=UTn(o,r);break;default:return new as.DatabaseError("received invalid response: "+n.toString(16),r,"error")}return o.setBuffer(0,Wge),s.length=r,s}};q6.Parser=Gge;var QTn=t=>{let e=t.string(1);return new as.ReadyForQueryMessage(Xd,e)},FTn=t=>{let e=t.cstring();return new as.CommandCompleteMessage(Xd,e)},UTn=(t,e)=>{let n=t.bytes(e-4);return new as.CopyDataMessage(Xd,n)},$Tn=t=>Vet(t,"copyInResponse"),WTn=t=>Vet(t,"copyOutResponse"),Vet=(t,e)=>{let n=t.byte()!==0,r=t.int16(),i=new as.CopyResponse(Xd,e,n,r);for(let o=0;o<r;o++)i.columnTypes[o]=t.int16();return i},HTn=t=>{let e=t.int32(),n=t.cstring(),r=t.cstring();return new as.NotificationResponseMessage(Xd,e,n,r)},GTn=t=>{let e=t.int16(),n=new as.RowDescriptionMessage(Xd,e);for(let r=0;r<e;r++)n.fields[r]=qTn(t);return n},qTn=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 as.Field(e,n,r,i,o,s,a)},jTn=t=>{let e=t.int16(),n=new as.ParameterDescriptionMessage(Xd,e);for(let r=0;r<e;r++)n.dataTypeIDs[r]=t.uint32();return n},zTn=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 as.DataRowMessage(Xd,n)},VTn=t=>{let e=t.cstring(),n=t.cstring();return new as.ParameterStatusMessage(Xd,e,n)},KTn=t=>{let e=t.int32(),n=t.int32();return new as.BackendKeyDataMessage(Xd,e,n)},YTn=(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 as.AuthenticationMD5Password(Xd,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},zet=(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 as.NoticeMessage(Xd,i):new as.DatabaseError(i,Xd,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 qge=L(KI=>{"use strict";Object.defineProperty(KI,"__esModule",{value:!0});KI.DatabaseError=KI.serialize=void 0;KI.parse=eRn;var JTn=Qge();Object.defineProperty(KI,"DatabaseError",{enumerable:!0,get:function(){return JTn.DatabaseError}});var XTn=Get();Object.defineProperty(KI,"serialize",{enumerable:!0,get:function(){return XTn.serialize}});var ZTn=Ket();function eRn(t,e){let n=new ZTn.Parser;return t.on("data",r=>n.parse(r,e)),new Promise(r=>t.on("end",()=>r()))}});var Yet=L(jge=>{"use strict";Object.defineProperty(jge,"__esModule",{value:!0});jge.default={}});var Xet=L((Kxi,Jet)=>{var{getStream:tRn,getSecureStream:nRn}=sRn();Jet.exports={getStream:tRn,getSecureStream:nRn};function rRn(){function t(n){let r=K("net");return new r.Socket}function e(n){return K("tls").connect(n)}return{getStream:t,getSecureStream:e}}function iRn(){function t(n){let{CloudflareSocket:r}=Yet();return new r(n)}function e(n){return n.socket.startTls(n),n.socket}return{getStream:t,getSecureStream:e}}function oRn(){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 sRn(){return oRn()?iRn():rRn()}});var Vge=L((Yxi,ett)=>{"use strict";var aRn=K("events").EventEmitter,{parse:cRn,serialize:Ja}=qge(),Zet=Xet(),{getStream:uRn}=Zet,lRn=Ja.flush(),dRn=Ja.sync(),pRn=Ja.end(),zge=class extends aRn{constructor(e){super(),e=e||{},this.stream=e.stream||uRn(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=K("net");o.isIP&&o.isIP(e)===0&&(i.servername=e);try{r.stream=Zet.getSecureStream(i)}catch(s){return r.emit("error",s)}r.attachListeners(r.stream),r.stream.on("error",n),r.emit("sslconnect")}attachListeners(e){cRn(e,n=>{let r=n.name==="error"?"errorMessage":n.name;this._emitMessage&&this.emit("message",n),this.emit(r,n)})}requestSsl(){this.stream.write(Ja.requestSsl())}startup(e){this.stream.write(Ja.startup(e))}cancel(e,n){this._send(Ja.cancel(e,n))}password(e){this._send(Ja.password(e))}sendSASLInitialResponseMessage(e,n){this._send(Ja.sendSASLInitialResponseMessage(e,n))}sendSCRAMClientFinalMessage(e){this._send(Ja.sendSCRAMClientFinalMessage(e))}_send(e){return this.stream.writable?this.stream.write(e):!1}query(e){this._send(Ja.query(e))}parse(e){this._send(Ja.parse(e))}bind(e){this._send(Ja.bind(e))}execute(e){this._send(Ja.execute(e))}flush(){this.stream.writable&&this.stream.write(lRn)}sync(){this._send(dRn)}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(pRn,()=>{this.stream.end()})}close(e){this._send(Ja.close(e))}describe(e){this._send(Ja.describe(e))}sendCopyFromChunk(e){this._send(Ja.copyData(e))}endCopyFrom(){this._send(Ja.copyDone())}sendCopyFail(e){this._send(Ja.copyFail(e))}};ett.exports=zge});var itt=L((Jxi,rtt)=>{"use strict";var{Transform:hRn}=K("stream"),{StringDecoder:mRn}=K("string_decoder"),Ew=Symbol("last"),j6=Symbol("decoder");function fRn(t,e,n){let r;if(this.overflow){if(r=this[j6].write(t).split(this.matcher),r.length===1)return n();r.shift(),this.overflow=!1}else this[Ew]+=this[j6].write(t),r=this[Ew].split(this.matcher);this[Ew]=r.pop();for(let i=0;i<r.length;i++)try{ntt(this,this.mapper(r[i]))}catch(o){return n(o)}if(this.overflow=this[Ew].length>this.maxLength,this.overflow&&!this.skipOverflow){n(new Error("maximum buffer reached"));return}n()}function gRn(t){if(this[Ew]+=this[j6].end(),this[Ew])try{ntt(this,this.mapper(this[Ew]))}catch(e){return t(e)}t()}function ntt(t,e){e!==void 0&&t.push(e)}function ttt(t){return t}function ARn(t,e,n){switch(t=t||/\r?\n/,e=e||ttt,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=ttt)}n=Object.assign({},n),n.autoDestroy=!0,n.transform=fRn,n.flush=gRn,n.readableObjectMode=!0;let r=new hRn(n);return r[Ew]="",r[j6]=new mRn("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}rtt.exports=ARn});var att=L((Xxi,j0)=>{"use strict";var ott=K("path"),yRn=K("stream").Stream,ERn=itt(),stt=K("util"),wRn=5432,z6=process.platform==="win32",WF=process.stderr,xRn=56,bRn=7,CRn=61440,IRn=32768;function vRn(t){return(t&CRn)==IRn}var cB=["host","port","database","user","password"],Kge=cB.length,SRn=cB[Kge-1];function Yge(){var t=WF instanceof yRn&&WF.writable===!0;if(t){var e=Array.prototype.slice.call(arguments).concat(`
|
|
98
98
|
`);WF.write(stt.format.apply(stt,e))}}Object.defineProperty(j0.exports,"isWin",{get:function(){return z6},set:function(t){z6=t}});j0.exports.warnTo=function(t){var e=WF;return WF=t,e};j0.exports.getFileName=function(t){var e=t||process.env,n=e.PGPASSFILE||(z6?ott.join(e.APPDATA||"./","postgresql","pgpass.conf"):ott.join(e.HOME||"./",".pgpass"));return n};j0.exports.usePgPass=function(t,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:z6?!0:(e=e||"<unkn>",vRn(t.mode)?t.mode&(xRn|bRn)?(Yge('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(Yge('WARNING: password file "%s" is not a plain file',e),!1))};var _Rn=j0.exports.match=function(t,e){return cB.slice(0,-1).reduce(function(n,r,i){return i==1&&Number(t[r]||wRn)===Number(e[r])?n&&!0:n&&(e[r]==="*"||e[r]===t[r])},!0)};j0.exports.getPassword=function(t,e,n){var r,i=e.pipe(ERn());function o(c){var u=kRn(c);u&&TRn(u)&&_Rn(t,u)&&(r=u[SRn],i.end())}var s=function(){e.destroy(),n(r)},a=function(c){e.destroy(),Yge("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 kRn=j0.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[cB[l]]=h},u=0;u<t.length-1;u+=1){if(e=t.charAt(u+1),n=t.charAt(u),a=r==Kge-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===Kge?s:null,s},TRn=j0.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<cB.length;n+=1){var r=e[n],i=t[cB[n]]||"",o=r(i);if(!o)return!1}return!0}});var utt=L((ebi,Jge)=>{"use strict";var Zxi=K("path"),ctt=K("fs"),V6=att();Jge.exports=function(t,e){var n=V6.getFileName();ctt.stat(n,function(r,i){if(r||!V6.usePgPass(i,n))return e(void 0);var o=ctt.createReadStream(n);V6.getPassword(t,o,e)})};Jge.exports.warnTo=V6.warnTo});var htt=L((tbi,ptt)=>{var RRn=K("events").EventEmitter,ltt=jI(),HF=K("util"),K6=_et(),BRn=U6(),DRn=wge(),Xge=Uet(),MRn=UF(),PRn=Vge(),NRn=fge(),dtt=HF.deprecate(()=>{},"Client.activeQuery is deprecated and will be removed in pg@9.0"),ORn=HF.deprecate(()=>{},"Client.queryQueue is deprecated and will be removed in pg@9.0."),LRn=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."),QRn=HF.deprecate(()=>{},"Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0."),FRn=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 URn(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 Y6=class extends RRn{constructor(e){super(),this.connectionParameters=new DRn(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&&QRn(),this._Promise=n.Promise||global.Promise,this._types=new BRn(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=URn(n.scramMaxIterations,K6.DEFAULT_MAX_SCRAM_ITERATIONS),this.connection=n.connection||new PRn({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||MRn.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 dtt(),this._activeQuery}set activeQuery(e){dtt(),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{utt()(this.connectionParameters,i=>{i!==void 0&&(LRn(),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 NRn.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(n)}catch(n){this.emit("error",n)}})}_handleAuthSASL(e){this._getPassword(()=>{try{this.saslSession=K6.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 K6.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{K6.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 ltt.escapeIdentifier(e)}escapeLiteral(e){return ltt.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 Xge(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 Xge)?"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&&FRn(),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 ORn(),this._queryQueue}};Y6.Query=Xge;ptt.exports=Y6});var gtt=L((nbi,ftt)=>{"use strict";var $Rn=K("events").EventEmitter,Zge=function(){},mtt=(t,e)=>{let n=t.findIndex(e);return n===-1?void 0:t.splice(n,1)[0]},eAe=class{constructor(e,n,r){this.client=e,this.idleListener=n,this.timeoutId=r}},uB=class{constructor(e){this.callback=e}};function WRn(){throw new Error("Release called on client which has already been released to the pool.")}function J6(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 HRn(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 tAe=class extends $Rn{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=mtt(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=J6(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 uB(n.callback)),r;let i=(a,c,u)=>{clearTimeout(s),n.callback(a,c,u)},o=new uB(i),s=setTimeout(()=>{mtt(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 uB(n.callback)),r}newClient(e){let n=new this.Client(this.options);this._clients.push(n);let r=HRn(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,Zge);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,Zge)})});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 uB((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,Zge);n.callback(void 0,e,e.release)}):n.callback(void 0,e,e.release)}_releaseOnce(e,n){let r=!1;return i=>{r&&WRn(),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 eAe(e,n,o)),this._pulseQueue()}query(e,n,r){if(typeof e=="function"){let o=J6(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=J6(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=J6(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}};ftt.exports=tAe});var Ett=L((rbi,ytt)=>{"use strict";var Att=K("events").EventEmitter,GRn=K("util"),rAe=jI(),lB=ytt.exports=function(t,e,n){Att.call(this),t=rAe.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))};GRn.inherits(lB,Att);var qRn={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"};lB.prototype.handleError=function(t){let e=this.native&&this.native.pq.resultErrorFields();if(e)for(let n in e){let r=qRn[n]||n;t[r]=e[n]}this.callback?this.callback(t):this.emit("error",t),this.state="error"};lB.prototype.then=function(t,e){return this._getPromise().then(t,e)};lB.prototype.catch=function(t){return this._getPromise().catch(t)};lB.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)};lB.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(rAe.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(rAe.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 Itt=L((ibi,Ctt)=>{var jRn=K("util"),wtt;try{wtt=K("pg-native")}catch(t){throw t}var zRn=U6(),xtt=K("events").EventEmitter,VRn=K("util"),KRn=wge(),btt=Ett(),YRn=jRn.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."),Dc=Ctt.exports=function(t){xtt.call(this),t=t||{},this._Promise=t.Promise||global.Promise,this._types=new zRn(t.types),this.native=new wtt({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 KRn(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={}};Dc.Query=btt;VRn.inherits(Dc,xtt);Dc.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};Dc.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)})})};Dc.prototype.connect=function(t){if(t){this._connect(t);return}return new this._Promise((e,n)=>{this._connect(r=>{r?n(r):e(this)})})};Dc.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 btt(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&&YRn(),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)};Dc.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};Dc.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};Dc.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()})};Dc.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=jI();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()})};Dc.prototype.cancel=function(t){this._activeQuery===t?this.native.cancel(function(){}):this._queryQueue.indexOf(t)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(t),1)};Dc.prototype.ref=function(){};Dc.prototype.unref=function(){};Dc.prototype.setTypeParser=function(t,e,n){return this._types.setTypeParser(t,e,n)};Dc.prototype.getTypeParser=function(t,e){return this._types.getTypeParser(t,e)};Dc.prototype.isConnected=function(){return this._connected};Dc.prototype.getTransactionStatus=function(){return this.native.getTransactionStatus()}});var iAe=L((obi,vtt)=>{"use strict";vtt.exports=Itt()});var nAe=L((abi,X6)=>{"use strict";var JRn=htt(),XRn=UF(),ZRn=Vge(),eBn=bge(),tBn=jI(),nBn=gtt(),rBn=U6(),{DatabaseError:iBn}=qge(),{escapeIdentifier:oBn,escapeLiteral:sBn}=jI(),aBn=t=>class extends nBn{constructor(n){super(n,t)}},Stt=function(t){this.defaults=XRn,this.Client=t,this.Query=this.Client.Query,this.Pool=aBn(this.Client),this._pools=[],this.Connection=ZRn,this.types=FF(),this.DatabaseError=iBn,this.TypeOverrides=rBn,this.escapeIdentifier=oBn,this.escapeLiteral=sBn,this.Result=eBn,this.utils=tBn},_tt=JRn,ktt=!1;try{ktt=!!process.env.NODE_PG_FORCE_NATIVE}catch{}ktt&&(_tt=iAe());X6.exports=new Stt(_tt);Object.defineProperty(X6.exports,"native",{configurable:!0,enumerable:!1,get(){let t=null;try{t=new Stt(iAe())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(X6.exports,"native",{value:t}),t}})});var Zd,cbi,ubi,lbi,dbi,pbi,hbi,mbi,fbi,gbi,Abi,ybi,Ttt,Rtt=A(()=>{Zd=cn(nAe(),1),cbi=Zd.default.Client,ubi=Zd.default.Pool,lbi=Zd.default.Connection,dbi=Zd.default.types,pbi=Zd.default.Query,hbi=Zd.default.DatabaseError,mbi=Zd.default.escapeIdentifier,fbi=Zd.default.escapeLiteral,gbi=Zd.default.Result,Abi=Zd.default.TypeOverrides,ybi=Zd.default.defaults,Ttt=Zd.default});var cBn,uBn,oAe,xbi,Btt=A(()=>{"use strict";Rtt();cBn=["mail","node","grant","run_event","report","structured_request","queue","spend_limits","environment_image","fault_retry","settings","machine","machine_call","document","review","execution_exit"],uBn=new Set(cBn),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 Ttt.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);uBn.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(()=>{}))}},xbi=new oAe});var Dtt=A(()=>{"use strict";MF()});function mBn(t){switch(t){case pBn:return"context-nudge";case lBn:return"bearings";case hBn:return"review-boundary";case dBn:return"situational";default:return}}function aAe(t){return t.replace(/&(?:amp|lt|gt|quot|apos);/g,e=>({"&":"&","<":"<",">":">",""":'"',"'":"'"})[e])}function sAe(t){let e={};Z6.lastIndex=0;let n=0;for(;n<t.length&&!/^\s*$/.test(t.slice(n));){Z6.lastIndex=n;let r=Z6.exec(t);if(r===null)return null;let[,i,o,s]=r;if(i===void 0||Object.hasOwn(e,i))return null;e[i]=aAe(o??s??""),n=Z6.lastIndex}return e}function cAe(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 fBn(t){let e=[],n=/<from\b([^>]*)>([\s\S]*?)<\/from>/g;for(let r of t.matchAll(n)){let i=sAe(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=sAe(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:aAe(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 gBn(t,e,n,r){return{kind:t,facts:e,body:n,senders:r}}function Ltt(t){let e=/^<runtime\b([^>]*)>/.exec(t);if(e===null||!t.endsWith("</runtime>"))return null;let n=sAe(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(":")?aAe(r):r;return gBn(i,s,a,i==="inbox"?fBn(a):[])}function dB(t){let e=cAe(t),n=Ltt(e);if(n!==null)return n;if(t.role!=="custom")return null;let r=mBn(t.customType);return r===void 0?null:{kind:r,facts:Object.freeze({}),body:e,senders:[]}}function YI(t){return t.disposition==="human-answer"&&Ltt(t.body.trim())===null}var lBn,dBn,pBn,hBn,Mtt,Ptt,Ntt,Ott,Z6,JI=A(()=>{"use strict";lBn="crtr-context",dBn="crtr-situational-context",pBn="crtr-context-nudge",hBn="crtr-review-boundary",Mtt="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.",Ptt="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.",Ntt="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.",Ott="Your previous turn stopped on a provider fault. Continue from where you left off and retry the work that failed.";Z6=/\s+([A-Za-z_:][A-Za-z0-9_:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/gy});var Qtt=A(()=>{"use strict";JI()});function ABn(){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=ABn();if(t===void 0)return Aw({autostart:!1});let e=MZe();if(e===void 0)throw new Error("broker has no node token for CRTR_API_URL");return new Tg({baseUrl:t,headers:{authorization:`Bearer ${e}`}})}function Ftt(t,e){return DF().appendNodeLog(t,{record:e,expected_execution_id:yBn()})}function yBn(){let t=ZYe();if(t===void 0||t==="")throw new Error("broker launch is missing CRTR_EXECUTION_ID");return t}async function Utt(t,e){return DF().recordNodeFault(t,e)}async function $tt(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=A(()=>{"use strict";B6();PZe();D6();fw();N6();Bc();OZe();XI();Btt();Dtt();Qtt()});function wBn(t,e){Wtt=Wtt.then(async()=>{try{let{appended:n}=await Ftt(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
|
-
`)}})}function Gl(t){let e=_6();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=VXe({...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=YXe(n);return e.component==="broker"&&e.node_id!==void 0&&(EBn??=MI())?(wBn(e.node_id,r),!0):e.component==="daemon"?$Xe(e.path,r):g6(e.path,r)}var EBn,Wtt,XI=A(()=>{"use strict";vfe();KXe();JXe();jfe();Bc();MF();Wtt=Promise.resolve()});var Htt,Gtt=A(()=>{"use strict";XI();Htt={sandboxUsdPerGbHour:"CRTR_LEDGER_SANDBOX_USD_PER_GB_HOUR",sandboxStandbyS:"CRTR_LEDGER_SANDBOX_STANDBY_S",storageUsdPerGbMonth:"CRTR_LEDGER_STORAGE_USD_PER_GB_MONTH",infraFreeUsdPerMonth:"CRTR_LEDGER_INFRA_FREE_USD_PER_MONTH",takePct:"CRTR_LEDGER_TAKE_PCT",r2Move:"CRTR_LEDGER_R2_MOVE"}});function eV(t){return t.flatMap(e=>e.path===void 0?[]:[e.path])}var GF=A(()=>{"use strict"});var qtt=A(()=>{"use strict"});import{createHash as xBn}from"node:crypto";function Vtt(t){return t===void 0?"absent":xBn("sha256").update(JSON.stringify(t)).digest("hex")}function Ktt(t,e){ztt.set(t,e)}function z0(){let t;try{t=x6()}catch(n){if(n instanceof SF)return jtt();if(n instanceof vF)return uAe??jtt();throw n}let e=ztt.get(t);if(e!==void 0)return e;if(uAe!==void 0)return uAe;throw new lAe(t)}function Ytt(t){bBn=t}function Jtt(t){CBn=t}function jF(t){let e=z0().settings[t];return{settings:e===void 0?null:structuredClone(e),revision:Vtt(e)}}function Xtt(t){let e=z0().state[t];return e===void 0?{marketplaces:{},plugins:{},activeCanvas:null}:structuredClone(e)}function Ztt(){return structuredClone(z0().profiles)}function ent(t){let e=z0().profiles.find(n=>n.profileId===t);return e===void 0?null:structuredClone(e)}var qF,lAe,ztt,jtt,uAe,bBn,CBn,pB=A(()=>{"use strict";eB();qF=class extends Error{constructor(){super("settings changed since the supplied revision"),this.name="SettingsRevisionConflictError"}},lAe=class extends Error{constructor(e){super(`settings for ${e} are not loaded in this process`),this.name="PersonSettingsNotLoadedError"}},ztt=new Map;jtt=()=>({profiles:[],defaults:{},settings:{},state:{},apps:{}});bBn=async()=>{throw new Error("no settings transport installed in this process")}});var tnt=A(()=>{"use strict"});var nnt=A(()=>{"use strict";Bc()});var rnt=A(()=>{"use strict"});var int=A(()=>{"use strict"});var ont=A(()=>{"use strict"});var snt=A(()=>{"use strict"});var ant=A(()=>{"use strict"});var cnt=A(()=>{"use strict"});var unt=A(()=>{"use strict"});var lnt=A(()=>{"use strict"});var dnt=A(()=>{"use strict"});var pnt,dAe=A(()=>{"use strict";pnt=["trial_ended","card_required","card_limit","nothing_left","app_limit","team_limit","app_unpaid"]});var hnt=A(()=>{"use strict"});var mnt=A(()=>{"use strict"});var fnt=A(()=>{"use strict"});var gnt=A(()=>{"use strict"});var Ant=A(()=>{"use strict"});var ynt=A(()=>{"use strict"});var Ent=A(()=>{"use strict"});var wnt=A(()=>{"use strict"});var xnt=A(()=>{"use strict"});var bnt=A(()=>{"use strict"});var Cnt=A(()=>{"use strict"});var Int=A(()=>{"use strict"});var vnt=A(()=>{"use strict"});var Snt=A(()=>{"use strict"});var _nt=A(()=>{"use strict"});var knt=A(()=>{"use strict"});var Tnt=A(()=>{"use strict"});var Rnt=A(()=>{"use strict"});var Bnt=A(()=>{"use strict"});var Dnt=A(()=>{"use strict"});var Mnt=A(()=>{"use strict"});var Pnt=A(()=>{"use strict"});var Nnt=A(()=>{"use strict"});var Ont=A(()=>{"use strict"});var Lnt=A(()=>{"use strict"});var Qnt=A(()=>{"use strict"});var Fnt=A(()=>{"use strict"});var Unt=A(()=>{"use strict"});var $nt=A(()=>{"use strict"});var Wnt=A(()=>{"use strict"});var Hnt=A(()=>{"use strict"});var Gnt=A(()=>{"use strict"});var qnt=A(()=>{"use strict"});var jnt=A(()=>{"use strict"});var znt=A(()=>{"use strict"});var ZI=A(()=>{"use strict";B6();fw();int();Vfe();ont();snt();ant();JI();Yfe();cnt();unt();lnt();dnt();dAe();hnt();mnt();fnt();gnt();Ant();ynt();Ent();Jfe();wnt();xnt();bnt();Cnt();Int();vnt();Xfe();Snt();_nt();knt();GF();Tnt();Rnt();Bnt();Dnt();Mnt();Pnt();Nnt();Ont();Lnt();Qnt();Fnt();Unt();$nt();Wnt();Hnt();Gnt();qnt();jnt();znt()});function IBn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function zF(t,e,n={}){if(t.code==="daemon_restarting")return new os("daemon_restarting",t.message,ji.NETWORK,{next:"crtrd is now on the new generation \u2014 retry the command."});if(t.code==="layout_migration_required")return new os("layout_migration_required",t.message,ji.NETWORK,{next:"Run `crtr sys migrate` while the runtime is offline, then restart it."});if(t.code==="daemon_unavailable")return new os("daemon_unavailable",t.message,ji.NETWORK,{next:"Start it with `crtr sys daemon start`, then retry."});if(t.code==="northlight_unreachable"){let a=t.details?.next;return new os("northlight_unreachable",t.message,ji.NETWORK,{next:typeof a=="string"&&a!==""?a:"Check this computer's internet connection, then retry."})}if(t.code==="model_sign_in_required"){let a=t.details?.url;return new ep({error:t.code,message:t.message,next:typeof a=="string"?`Ask the person to sign in at ${a}, then retry.`:"Ask the person to sign in to an AI subscription on their Northlight account, then retry.",...typeof a=="string"?{details:{url:a}}:{}},ji.USAGE)}let r=t.details,i=SBn(t,r,n.providerCall===!0);if(t.status===503||n.providerCall===!0&&t.status===504&&i.code!==void 0){let a=i.code??t.code,c={next:i.next??e??"Retry the command; if it persists, inspect the unavailable service named in the error."};return i.details!==void 0&&(c.details=i.details),i.code!==void 0&&(i.field!==void 0&&(c.field=i.field),i.received!==void 0&&(c.received=i.received),i.retryAfterS!==void 0&&(c.retry_after_s=i.retryAfterS)),new os(a,t.message,ji.NETWORK,c)}let o=Array.isArray(r?.violations)?r.violations.map(a=>`${String(a.field)} ${String(a.problem)}${a.received!==void 0?` (received ${JSON.stringify(a.received)})`:""}`):[],s=r&&typeof r.error=="string"&&typeof r.message=="string"&&typeof r.next=="string"?r:{error:i.code??vBn[t.status]??t.code,...i.field!==void 0?{field:i.field}:{},...i.received!==void 0?{received:i.received}:{},...i.retryAfterS!==void 0?{retry_after_s:i.retryAfterS}:{},...i.details!==void 0?{details:i.details}:{},message:o.length>0?`${t.message}: ${o.join("; ")}`:t.message.trim()!==""?t.message:`request refused (HTTP ${t.status}, ${t.code}) with no message`,next:i.next??(r?.outcome==="unknown"?"The change may already be applied: check the current state before repeating it, and do not report it failed.":void 0)??e??(i.retryAfterS!==void 0?`Wait ${i.retryAfterS}s, then retry; do not retry sooner.`:t.status>=500?"This is a crtr bug, not a bad call. Retry; if it persists, report it (the daemon log holds the full cause).":t.status===404&&i.code===void 0?"List nodes with `crtr node inspect list`.":"Inspect the error and adjust the call. See -h for the schema.")};return new ep(s,_Bn(s.error,t.status))}function SBn(t,e,n){let r=o=>typeof o=="string"&&/^[a-z][a-z0-9_]*$/.test(o);if(n&&t.origin!==void 0&&t.origin!=="provider"&&r(t.code)){let o={code:t.code};return(t.status===503||t.status===504)&&(o.next=t.retryable===!0?"Retry the command; if it persists, the machine or service named in the error is unavailable.":"Read the error before retrying: the action may already have run."),IBn(t.details)&&(o.details=t.details),t.param!==void 0&&(o.field=t.param),typeof t.retryAfterS=="number"&&(o.retryAfterS=t.retryAfterS),o}if(t.origin!=="provider"||e===void 0||e===null||typeof e!="object")return{};let i={};return typeof e.status=="number"&&r(e.code)&&(i.code=e.code),typeof e.next=="string"&&e.next.trim()!==""&&(i.next=e.next),typeof e.field=="string"&&e.field!==""?i.field=e.field:t.param!==void 0&&(i.field=t.param),e.received!==void 0&&e.received!==null&&(i.received=e.received),typeof t.retryAfterS=="number"&&(i.retryAfterS=t.retryAfterS),i}function _Bn(t,e){return t==="not_found"||e===404?ji.NOT_FOUND:t==="ambiguous"?ji.AMBIGUOUS:ji.USAGE}var $Ii,ep,vBn,ev=A(()=>{"use strict";$l();ru();nnt();rnt();ZI();$Ii=256*1024,ep=class extends os{payload;constructor(e,n=ji.USAGE){super(e.error,e.message,n,{...e}),this.name="InputError",this.payload=e}};vBn={400:"invalid_request",404:"not_found",409:"conflict",422:"unprocessable"}});var pAe=A(()=>{"use strict"});var hAe=A(()=>{"use strict";Hu()});import{DatabaseSync as zIi}from"node:sqlite";var mAe=A(()=>{"use strict"});import{DatabaseSync as JIi}from"node:sqlite";var Vnt=A(()=>{"use strict";pAe();Hu();fAe();mAe()});import{DatabaseSync as Evi}from"node:sqlite";var fAe=A(()=>{"use strict";pAe();Hu();ev();iu();hAe();Vnt();mAe();hAe()});var tV=A(()=>{"use strict"});import{loadLinuxNative as BBn}from"../../native/linux.js";var Mvi,gAe=A(()=>{"use strict";tV();Mvi=BBn()});var Ynt=A(()=>{"use strict";gAe();tV()});import{join as PBn}from"node:path";function Jnt(){return PBn(Zm(),"runtime-client.json")}function NBn(){let t=q0(Jnt());if(t?.token_sha256===void 0)return null;let{owner:e}=t;if(typeof e!="string"||!/^user:.+/.test(e))throw new Error(`${Jnt()} was written by join but has a missing or invalid owner`);return t}function Xnt(){return NBn()?.issuer??null}var Znt=A(()=>{"use strict";ev();$l();Hu();Wl();fAe();iu();Ynt();N6();ww()});import{chmodSync as Xvi,existsSync as yAe,mkdirSync as Zvi,readFileSync as ert,rmSync as eSi,writeFileSync as tSi}from"node:fs";import{dirname as rSi,join as EAe}from"node:path";function V0(){let t=OBn();if(!yAe(t))return;let e=JSON.parse(ert(t,"utf8"));if(typeof e.apiUrl!="string"||typeof e.environmentId!="string"||e.runId!==void 0&&typeof e.runId!="string"||typeof e.directoryUrl!="string")throw new Error(`${t} must hold {apiUrl, environmentId, directoryUrl}`);let n=e.account!==void 0&&typeof e.account?.id=="string"&&typeof e.account.display=="string"?{id:e.account.id,display:e.account.display}:void 0;return{apiUrl:e.apiUrl,environmentId:e.environmentId,...e.runId===void 0?{}:{runId:e.runId},directoryUrl:e.directoryUrl,...n===void 0?{}:{account:n}}}function QBn(){let t=LBn();if(!yAe(t))return;let e=JSON.parse(ert(t,"utf8"));if(typeof e.runId!="string"||typeof e.apiUrl!="string"||typeof e.directoryUrl!="string"||e.state!=="running"&&e.state!=="committed"&&e.state!=="activated"||typeof e.account?.id!="string"||typeof e.account.display!="string")throw new Error(`${t} is not a move record`);return{runId:e.runId,apiUrl:e.apiUrl,directoryUrl:e.directoryUrl,account:{id:e.account.id,display:e.account.display},notify:typeof e.notify=="string"?e.notify:null,state:e.state,notified:e.notified===!0,pid:typeof e.pid=="number"?e.pid:0}}var OBn,LBn,trt,nrt,FBn,rrt,VF=A(()=>{"use strict";Hu();Znt();$l();iu();ru();OBn=()=>EAe(Wu(),"machine.json");LBn=()=>EAe(Wu(),"import","move.json");trt=()=>QBn()?.state==="committed",nrt=t=>new os("move_unfinished",`crtr's records are already in your Northlight account, but this computer has not switched over${t===void 0?".":`: ${t}`}`,ji.USAGE,{next:"Run `crtr sys signin` to finish."}),FBn=()=>["pg","canvas.db","canvas.db.imported"].some(t=>yAe(EAe(Wu(),t))),rrt=()=>V0()===void 0&&!FBn()&&Xnt()===null});function $Bn(t){return t.grantee??"app:terminal"}function WBn(t){if(!irt.test(t))throw hw(`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 nV(t){WBn(t);let e=ent(t);if(e===null)throw m6(`profile not found: ${t}`,{received:t});return Ofe($Bn(e.manifest),t).dir}function HBn(){return{entries:Ztt(),unreadableIds:[]}}function rV(){return HBn().entries}function GBn(t){let e=rV(),n=qBn(e,t,ort);return n?{kind:"resolved",entry:n}:{kind:"absent"}}function qBn(t,e,n){if(irt.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 MXe(`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 jBn(t,e,n){let r=t.map(i=>`${n(i).profileId} (${n(i).name})`);return m6(`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 Rg(t){let e=GBn(t);if(e.kind==="resolved")return e.entry;throw jBn(rV(),t,ort)}var irt,ort,tv=A(()=>{"use strict";ru();Hu();GF();iu();pB();$l();tnt();eB();VF();irt=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/;ort=t=>({profileId:t.profileId,name:t.manifest.name})});import{homedir as srt}from"node:os";import{existsSync as zBn,statSync as VBn}from"node:fs";import{join as iV,resolve as art,dirname as KBn,sep as wAe}from"node:path";function tp(){return iV(Wu(),"scope")}function YBn(t,e){if(!zBn(t)||Xm(t)===Xm(iV(srt(),LI))||Xm(t).startsWith(`${Xm(Nfe())}${wAe}`)&&t.endsWith(`${wAe}home${wAe}${LI}`)||!MI()&&(Xm(t)===Xm(e)||Xm(t)===Xm(_F())))return!1;try{return VBn(t).isDirectory()}catch{return!1}}function JBn(t=process.cwd()){return crt(t)[0]??null}function XBn(t,e){let n=[],r=Xm(srt()),i=art(t);for(;;){let o=iV(i,LI);if(YBn(o,e)&&n.push(o),Xm(i)===r)return n;let s=KBn(i);if(s===i)return n;i=s}}function crt(t=process.cwd(),e=Gme()||null){return ZBn(t,e)}function ZBn(t,e){let n=art(t),r=tp(),i=[n];if(!MI()&&e!==null&&e!=="")try{let{manifest:a}=Rg(e);i.push(...eV(a.projects))}catch{}let o=new Set,s=[];for(let a of i)for(let c of XBn(a,r))o.has(c)||(o.add(c),s.push(c));return s}function urt(t){return JBn(t)}function K0(t){return t==="builtin"?null:t==="user"?tp():urt()}function AAe(t){let e=t==="user"?Wu():K0(t);return e?iV(e,"plugins"):null}var ww=A(()=>{"use strict";Bc();GF();ru();qtt();$l();tv();iu();Hu()});import{join as eDn}from"node:path";function tDn(t){return eDn(t,RXe,BXe)}function nDn(t){let e;try{e=q0(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 rDn(t){return nDn(tDn(t))}function lrt(t){let e=rDn(t);return e.status==="ok"?e.manifest:null}var xAe=A(()=>{"use strict";ru();iu()});import{existsSync as iDn,mkdirSync as oDn,readdirSync as prt,rmSync as hrt,rmdirSync as sDn,statSync as aDn,unlinkSync as cDn,writeFileSync as uDn}from"node:fs";import{randomUUID as lDn}from"node:crypto";function frt(t){return Math.min(t*2,dDn)}function grt(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function CAe(t,e){return`${t}/${bAe}${e}`}function IAe(t){try{return prt(t).find(e=>e.startsWith(bAe))?.slice(bAe.length)??null}catch{return null}}function Art(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 mDn(t){try{return prt(t).length===0}catch{return!1}}function fDn(t){try{return Date.now()-aDn(t).mtimeMs}catch{return 0}}function gDn(t,e){let n=IAe(t);if(n!==null){if(Art(n))return;try{cDn(CAe(t,n))}catch(r){if(r.code==="ENOENT")return;throw r}}else{if(fDn(t)<=e)return;if(!mDn(t)){hrt(t,{recursive:!0,force:!0});return}}try{sDn(t)}catch(r){let i=r.code;if(i!=="ENOENT"&&i!=="ENOTEMPTY"&&i!=="EEXIST")throw r}}function oV(t){let e=IAe(t);if(e===null)return null;let n=Number(e.split(".",1)[0]);return Number.isSafeInteger(n)&&n>0?n:null}function yrt(t,e){let n=Date.now()+e,r=mrt;for(;;){let i=IAe(t);if(i===null||Number(i.split(".",1)[0])===process.pid||!Art(i))return;let o=n-Date.now();if(o<=0)return;grt(Math.min(r,o)),r=frt(r)}}function drt(t,e){let n=`${process.pid}.${lDn()}`;try{return oDn(t,{mode:448}),uDn(CAe(t,n),"",{flag:"wx",mode:384}),{path:t,token:n}}catch(r){if(r.code!=="EEXIST")throw r;return gDn(t,e),null}}function nv(t,e,n={}){let r=n.staleMs??pDn,i=Date.now()+(n.timeoutMs??hDn),o=mrt,s=drt(t,r);for(;s===null;){if(Date.now()>=i)throw n.timeoutError?.()??new Error(`timed out waiting for the exclusive lock: ${t}`);grt(Math.min(o,Math.max(0,i-Date.now()))),o=frt(o),s=drt(t,r)}try{return e()}finally{iDn(CAe(s.path,s.token))&&hrt(s.path,{recursive:!0,force:!0})}}var bAe,mrt,dDn,pDn,hDn,rv=A(()=>{"use strict";bAe="owner.",mrt=10,dDn=250,pDn=3e4,hDn=5e3});import{join as ADn}from"node:path";function Ert(t,e){return ADn(t,"tmp",`${e}.swap.lock`)}function wrt(t,e){let n=oV(Ert(t,e));return n!==null&&n!==process.pid}function xrt(t,e){yrt(Ert(t,e),yDn)}var yDn,brt=A(()=>{"use strict";rv();yDn=2e3});function sV(t,e){let n=t.apps[EDn];return n===void 0&&e===null?null:{...e??{},plugins:structuredClone(n?.plugins??{}),marketplaces:structuredClone(n?.marketplaces??{})}}var EDn,vAe=A(()=>{"use strict";Bc();pB();EDn="app:terminal"});import{join as SAe}from"node:path";function wDn(t,e){let n=t==="user"?mF()?sV(z0(),jF("user").settings):jF("user").settings:q0(SAe(e,d6));return n&&n.plugins&&typeof n.plugins=="object"?n.plugins:{}}function xDn(t,e,n){let r=Object.keys(e);return r.every(i=>n.has(i))?[]:r.filter(i=>!n.has(i)&&wrt(t,i))}function aV(t,e){if(t==="user"&&w6())return[];let n=t!=="user"?SAe(e,"plugins"):AAe("user");if(n===void 0||!Mfe(n))return[];let r=wDn(t,e),i=Crt(t,n,r),o=xDn(e,r,new Set(i.map(s=>s.name)));if(o.length===0)return i;for(let s of o)xrt(e,s);return Crt(t,n,r)}function Crt(t,e,n){let r=[];for(let i of Pfe(e)){let o=SAe(e,i),s=lrt(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 cV=A(()=>{"use strict";ru();iu();xAe();brt();eB();pB();vAe();ww()});import{existsSync as bDn,realpathSync as CDn}from"node:fs";import{basename as IDn,dirname as vDn,join as h_i,resolve as Irt}from"node:path";function hB(t){let e=Irt(t),n=e,r=[];for(;!bDn(n);){let i=vDn(n);if(i===n)return e;r.unshift(IDn(n)),n=i}return Irt(CDn(n),...r)}var vrt=A(()=>{"use strict"});function SDn(t){let e=zi.indexOf(t);return`less ${zi.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 ${lV[t]}`}function uV(t,e,n){let r=t.indexOf(e),i=r>=0?r:0;return t[(i+n+t.length)%t.length]}function Srt(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 iv(t,e){return t==="true"?!0:t==="false"?!1:`${e} must be true or false`}function Trt(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 _Dn(t,e){let n=Trt(t,e);return typeof n=="string"||n<1?`${e} must be an integer >= 1`:n}function krt(t,e){let n=t.providerOptions[e];if(n!==void 0)return n;let r={};return t.providerOptions[e]=r,r}function BDn(){let t=[];for(let e of Object.values(Rrt))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 lV,_rt,kDn,TDn,KF,Rrt,RDn,g_i,_Ae=A(()=>{"use strict";ru();lV={replies:"Replies only",summaries:"Messages + summaries",tools:"Tool calls",previews:"Previews",full:"Full"};_rt=[!1,"notify","apply"],kDn=[0,1,6,12,24,48,72,168],TDn=[1,2,3,4,5,6,8,10,12],KF="openai-codex";Rrt={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=uV(_rt,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=uV(_rt,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=Srt(kDn,t.auto_update.interval_hours,e)},setFromString:(t,e)=>{let n=Trt(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=Srt(TDn,t.max_panes_per_window,e)},setFromString:(t,e)=>{let n=_Dn(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=iv(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=iv(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=iv(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=iv(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:QI.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=uV(QI,t.whip_message_mode,e)},setFromString:(t,e)=>QI.includes(e)?(t.whip_message_mode=e,null):`whip_message_mode must be one of: ${QI.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:FI.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=uV(FI,t.mouse_mode_default,e)},setFromString:(t,e)=>FI.includes(e)?(t.mouse_mode_default=e,null):`mouse_mode_default must be one of: ${FI.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=iv(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:zi.join("|"),applies:"Applies on the next attach.",group:"display",order:30,format:t=>t.verbosity,display:t=>SDn(t.verbosity),cycle:(t,e)=>{let n=zi.indexOf(t.verbosity)+e;t.verbosity=zi[Math.max(0,Math.min(zi.length-1,n))]},setFromString:(t,e)=>zi.includes(e)?(t.verbosity=e,null):`verbosity must be one of: ${zi.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=iv(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.${KF}.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[KF]?.fastMode?"on":"off",cycle:t=>{let e=krt(t,KF);e.fastMode=!e.fastMode},setFromString:(t,e)=>{let n=iv(e,`providerOptions.${KF}.fastMode`);return typeof n=="string"?n:(krt(t,KF).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"}},RDn=Object.keys(Rrt);g_i=BDn()});function YF(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 BAe(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(!MDn.test(a))throw new Error(`${e}[${o}] has invalid page kind ${fB(a)}; expected /^[a-z][a-z0-9-]{0,63}$/`);if(PDn.has(a)||DDn.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=YF(a);if(dV.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 Drt(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=YF(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 Mrt(t,e){return e.find(n=>n.kind===t)}var kAe,DDn,MDn,PDn,Brt,TAe,dV,RAe,JF=A(()=>{"use strict";kAe=["options","text","table","cards","chart"],DDn=["page","step"],MDn=/^[a-z][a-z0-9-]{0,63}$/,PDn=new Set(kAe),Brt=[{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}];TAe=Object.fromEntries(Brt.filter(t=>!t.structural).map(t=>[t.tag,t.kind])),dV=new Set(Brt.map(t=>t.tag)),RAe=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 Qrt,join as Frt}from"node:path";import{existsSync as ODn,mkdirSync as I_i,statSync as v_i}from"node:fs";function LDn(t){return Frt(t,d6)}function QDn(t){return Frt(t,DXe)}function Urt(t){let e=hB(t),n=hB(tp());if(e===n)return{key:"user",kind:"user",root:n};if(Qrt(e)===".crouter")return{key:"project",kind:"project",root:e};for(let r of rV()){let i=hB(nV(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 $rt(t){if(Qrt(t)===".crouter"){let r;try{r=hB(t)}catch(i){if(i.code==="ENOENT")return null;throw i}if(r!==hB(tp()))return q0(LDn(t))}let e=Urt(t).key,n=jF(e).settings;return e==="user"&&mF()?sV(z0(),n):n}function ph(t){let e=FDn[UDn];if(e){if(t!=="user")throw new Error(`broker config snapshot has no ${t} scope`);return e.user}let n=K0(t);return n?$Dn(n):h6()}function $Dn(t){let e=$rt(t);return e?m1n(e):h6()}function WDn(t){let e=q0(QDn(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 Wrt(t){let e=K0(t);return e?t==="project"?ODn(e)?WDn(e):Ife():Xtt(Urt(e).key):Ife()}function HDn(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 t===void 0?[...qDn]:Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string"&&OI.has(e)&&GDn.has(e)))]:[]}function jDn(t,e=Cfe()){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 Hrt(t){return t==="ultra"||t==="strong"||t==="medium"||t==="light"}function DAe(){return Object.create(null)}function pV(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function VDn(t){let e=DAe();for(let[n,r]of Object.entries(t??{}))pV(e,n,r);return e}function XF(t,e){Gl({level:"warn",event:"config.model_routes.invalid",fields:{route_id:t,rule:e}})}function KDn(t,e={}){let n=VDn(e);if(t===null||typeof t!="object"||Array.isArray(t))return n;for(let[r,i]of Object.entries(t)){if(r.trim()===""){XF(r,"route id must be a non-empty string");continue}if(i===null||typeof i!="object"||Array.isArray(i)){XF(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(!Hrt(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){XF(r,c);continue}pV(n,r,a)}return n}function YDn(t){let e=DAe(),n=DAe();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){XF(r,"route must include family, credentialSource, providerId, and models");continue}let o=zDn.filter(s=>i.models[s]===void 0);if(o.length>0){XF(r,`incomplete route; missing strengths: ${o.join(", ")}`),pV(n,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models});continue}pV(e,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models})}return{complete:e,legacy:n}}function JDn(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=>Hrt(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 XDn(t){return t!==""&&t.replace(/\*/g,"")===""}function ZDn(t,e=[]){let n=t,r=Array.isArray(n?.allow)?n.allow.filter(i=>typeof i=="string"):[];for(let i of r)if(XDn(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 e1n(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 n1n(t,e){if(e==="bin"&&t1n.has(t))return`${e}.${t} is reserved by crouter \u2014 pick another bare command name`;if(!Prt.test(t))return`${e}.${t} is not a safe bare command name (expected ${Prt.source})`}function r1n(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))n1n(n,"bin")===void 0&&(typeof r!="string"||r.trim()===""||(e[n]=r));return e}function i1n(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(Nrt.test(n)||i.push(`action name must match ${Nrt.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 o1n(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e=new Set(i1n(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 s1n(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 a1n(t,e=bfe()){let n={...e};if(t!==null&&typeof t=="object")for(let[r,i]of Object.entries(t)){let o=s1n(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 mV(){let t=[{origin:"config.json",components:ph("user").page_components}],e=K0("user");if(e!==null){let n=aV("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:BAe(r.manifest.page_components,i)})}}return Drt(t)}function c1n(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 u1n(t,e=xfe()){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=c1n(o);s!==null&&(n[i]=s)}}return{targets:n}}function Ort(t,e){return t===!0?"notify":t===!1?!1:t==="notify"||t==="apply"?t:e}function hV(t,e){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=1?t:e}function l1n(t,e){let n=t!==null&&typeof t=="object"?t:{},r=hV(n.warning,e.warning),i=hV(n.automaticReviveCap,e.automaticReviveCap);return r<=i?{warning:r,automaticReviveCap:i}:{...e}}function d1n(t,e){return{unattendedParkMs:hV((t!==null&&typeof t=="object"?t:{}).unattendedParkMs,e.unattendedParkMs)}}function p1n(t){if(!Array.isArray(t))return[...p6];let e=t.filter(n=>typeof n=="string"&&n.trim()!=="").map(n=>n.trim());return e.length>0?e:[...p6]}function h1n(t,e){if(t===null||typeof t!="object")return{...e};let n=t.tcp;return{tcp:typeof n=="string"?n:e.tcp}}function m1n(t){!Lrt&&t.ledger!==void 0&&(Lrt=!0,Gl({level:"warn",event:"config.ledger.ignored",fields:{variables:Object.values(Htt)}}));let e=h6(),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:Ort(o?.crtr,e.auto_update.crtr),content:Ort(o?.content,e.auto_update.content),interval_hours:a},u=t.max_panes_per_window,l=hV(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=l1n(t.brokerThresholds,e.brokerThresholds),h=d1n(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]:kXe(t.working_gerunds),g=typeof t.whip_mode=="boolean"?t.whip_mode:e.whip_mode,y=BAe(t.page_components),x=typeof t.page_surface=="boolean"?t.page_surface:e.page_surface,b=p1n(t.whip_messages),v=QI.includes(t.whip_message_mode)?t.whip_message_mode:e.whip_message_mode,S=FI.includes(t.mouse_mode_default)?t.mouse_mode_default:e.mouse_mode_default,_=typeof t.bash_tool_purpose=="boolean"?t.bash_tool_purpose:e.bash_tool_purpose,T=zi.includes(t.verbosity)?t.verbosity:e.verbosity,B=typeof t.detailed_tool_recaps=="boolean"?t.detailed_tool_recaps:e.detailed_tool_recaps,R=Number.isInteger(t.document_port)&&t.document_port>=1&&t.document_port<=65535?t.document_port:e.document_port,P=HDn(t.keybindings),Q=gB(t.tmux_passthrough),$=jDn(t.modelLadders),j=e1n(t.providerOptions,e.providerOptions),H=YDn(KDn(t.modelRoutes)),le=H.complete,ee=JDn(t.modelRouting,void 0),ge=a1n(t.kinds),Ie=u1n(t.remoteCanvas),$e=h1n(t.api,e.api),wt=t.paths;if(wt?.user_files!==void 0&&(typeof wt.user_files!="string"||!wt.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");let Ze=t.store,xt=t.runtime;if(xt?.person_uids!==void 0&&(!Array.isArray(xt.person_uids)||!xt.person_uids.every(et=>Number.isSafeInteger(et)&&et>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");let re=ZDn(t.spawnEnv,e.spawnEnv?.allow),ot=r1n(t.bin),ke=o1n(t.humanActions);return{bin:ot,humanActions:ke,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:y,page_surface:x,whip_messages:b,whip_message_mode:v,mouse_mode_default:S,bash_tool_purpose:_,verbosity:T,detailed_tool_recaps:B,document_port:R,keybindings:P,tmux_passthrough:Q,modelLadders:$,providerOptions:j,...Object.keys(le).length>0?{modelRoutes:le}:{},...Object.keys(H.legacy).length>0?{legacyModelRoutes:H.legacy}:{},...ee!==void 0?{modelRouting:ee}:{},kinds:ge,remoteCanvas:Ie,api:$e,...wt?{paths:wt}:{},...Ze?{store:Ze}:{},...xt?{runtime:xt}:{},spawnEnv:re}}function f1n(t){return $rt(t)}function Grt(t){let e=K0(t);return e?f1n(e):null}var FDn,UDn,GDn,qDn,zDn,Prt,t1n,Nrt,Lrt,Yd=A(()=>{"use strict";Bc();ru();c6();$l();XI();Gtt();iu();ww();cV();tv();vrt();pB();vAe();rv();_Ae();l6();JF();FDn=globalThis,UDn=Symbol.for("crtr.broker.config-snapshot");GDn=new Set(zd.filter(bF).map(t=>t.id)),qDn=Object.freeze(["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live"]);zDn=["ultra","strong","medium","light"];Prt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,t1n=new Set(["crtr","crtrd"]);Nrt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;Lrt=!1});var X0=L((Wki,lit)=>{"use strict";var cit=["nodebuffer","arraybuffer","fragments"],uit=typeof Blob<"u";uit&&cit.push("blob");lit.exports={BINARY_TYPES:cit,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:uit,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var oU=L((Hki,yV)=>{"use strict";var{EMPTY_BUFFER:cMn}=X0(),i0e=Buffer[Symbol.species];function uMn(t,e){if(t.length===0)return cMn;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 i0e(n.buffer,n.byteOffset,r):n}function dit(t,e,n,r,i){for(let o=0;o<i;o++)n[r+o]=t[o]^e[o&3]}function pit(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function lMn(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function o0e(t){if(o0e.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new i0e(t):ArrayBuffer.isView(t)?e=new i0e(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),o0e.readOnly=!1),e}yV.exports={concat:uMn,mask:dit,toArrayBuffer:lMn,toBuffer:o0e,unmask:pit};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=K("bufferutil");yV.exports.mask=function(e,n,r,i,o){o<48?dit(e,n,r,i,o):t.mask(e,n,r,i,o)},yV.exports.unmask=function(e,n){e.length<32?pit(e,n):t.unmask(e,n)}}catch{}});var fit=L((Gki,mit)=>{"use strict";var hit=Symbol("kDone"),s0e=Symbol("kRun"),a0e=class{constructor(e){this[hit]=()=>{this.pending--,this[s0e]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[s0e]()}[s0e](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[hit])}}};mit.exports=a0e});var IB=L((qki,Eit)=>{"use strict";var sU=K("zlib"),git=oU(),dMn=fit(),{kStatusCode:Ait}=X0(),pMn=Buffer[Symbol.species],hMn=Buffer.from([0,0,255,255]),wV=Symbol("permessage-deflate"),Z0=Symbol("total-length"),bB=Symbol("callback"),Cw=Symbol("buffers"),CB=Symbol("error"),EV,c0e=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,!EV){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;EV=new dMn(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[bB];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){EV.add(i=>{this._decompress(e,n,(o,s)=>{i(),r(o,s)})})}compress(e,n,r){EV.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[wV]=this,this._inflate[Z0]=0,this._inflate[Cw]=[],this._inflate.on("error",fMn),this._inflate.on("data",yit)}this._inflate[bB]=r,this._inflate.write(e),n&&this._inflate.write(hMn),this._inflate.flush(()=>{let o=this._inflate[CB];if(o){this._inflate.close(),this._inflate=null,r(o);return}let s=git.concat(this._inflate[Cw],this._inflate[Z0]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Z0]=0,this._inflate[Cw]=[],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[Cw]=[],this._deflate.on("data",mMn)}this._deflate[bB]=r,this._deflate.write(e),this._deflate.flush(sU.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=git.concat(this._deflate[Cw],this._deflate[Z0]);n&&(o=new pMn(o.buffer,o.byteOffset,o.length-4)),this._deflate[bB]=null,this._deflate[Z0]=0,this._deflate[Cw]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,o)})}};Eit.exports=c0e;function mMn(t){this[Cw].push(t),this[Z0]+=t.length}function yit(t){if(this[Z0]+=t.length,this[wV]._maxPayload<1||this[Z0]<=this[wV]._maxPayload){this[Cw].push(t);return}this[CB]=new RangeError("Max payload size exceeded"),this[CB].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[CB][Ait]=1009,this.removeListener("data",yit),this.reset()}function fMn(t){if(this[wV]._inflate=null,this[CB]){this[bB](this[CB]);return}t[Ait]=1007,this[bB](t)}});var vB=L((jki,xV)=>{"use strict";var{isUtf8:wit}=K("buffer"),{hasBlob:gMn}=X0(),AMn=[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 yMn(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function u0e(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 EMn(t){return gMn&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}xV.exports={isBlob:EMn,isValidStatusCode:yMn,isValidUTF8:u0e,tokenChars:AMn};if(wit)xV.exports.isValidUTF8=function(t){return t.length<24?u0e(t):wit(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=K("utf-8-validate");xV.exports.isValidUTF8=function(e){return e.length<32?u0e(e):t(e)}}catch{}});var m0e=L((zki,_it)=>{"use strict";var{Writable:wMn}=K("stream"),xit=IB(),{BINARY_TYPES:xMn,EMPTY_BUFFER:bit,kStatusCode:bMn,kWebSocket:CMn}=X0(),{concat:l0e,toArrayBuffer:IMn,unmask:vMn}=oU(),{isValidStatusCode:SMn,isValidUTF8:Cit}=vB(),bV=Buffer[Symbol.species],mh=0,Iit=1,vit=2,Sit=3,d0e=4,p0e=5,CV=6,h0e=class extends wMn{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||xMn[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[CMn]=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=mh}_write(e,n,r){if(this._opcode===8&&this._state==mh)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 bV(r.buffer,r.byteOffset+e,r.length-e),new bV(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 bV(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 mh:this.getInfo(e);break;case Iit:this.getPayloadLength16(e);break;case vit:this.getPayloadLength64(e);break;case Sit:this.getMask();break;case d0e:this.getData(e);break;case p0e:case CV: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[xit.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=Iit:this._payloadLength===127?this._state=vit: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=Sit:this._state=d0e}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=d0e}getData(e){let n=bit;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&&vMn(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=p0e,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[xit.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===mh&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=mh;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=l0e(r,n):this._binaryType==="arraybuffer"?i=IMn(l0e(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=mh):(this._state=CV,setImmediate(()=>{this.emit("message",i,!0),this._state=mh,this.startLoop(e)}))}else{let i=l0e(r,n);if(!this._skipUTF8Validation&&!Cit(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===p0e||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=mh):(this._state=CV,setImmediate(()=>{this.emit("message",i,!1),this._state=mh,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,bit),this.end();else{let r=e.readUInt16BE(0);if(!SMn(r)){let o=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(o);return}let i=new bV(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Cit(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=mh;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=mh):(this._state=CV,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=mh,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[bMn]=i,s}};_it.exports=h0e});var A0e=L((Kki,Rit)=>{"use strict";var{Duplex:Vki}=K("stream"),{randomFillSync:_Mn}=K("crypto"),{types:{isUint8Array:kMn}}=K("util"),kit=IB(),{EMPTY_BUFFER:TMn,kWebSocket:RMn,NOOP:BMn}=X0(),{isBlob:SB,isValidStatusCode:DMn}=vB(),{mask:Tit,toBuffer:cv}=oU(),fh=Symbol("kByteLength"),MMn=Buffer.alloc(4),IV=8*1024,uv,_B=IV,ef=0,PMn=1,NMn=2,f0e=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=ef,this.onerror=BMn,this[RMn]=void 0}static frame(e,n){let r,i=!1,o=2,s=!1;n.mask&&(r=n.maskBuffer||MMn,n.generateMask?n.generateMask(r):(_B===IV&&(uv===void 0&&(uv=Buffer.alloc(IV)),_Mn(uv,0,IV),_B=0),r[0]=uv[_B++],r[1]=uv[_B++],r[2]=uv[_B++],r[3]=uv[_B++]),s=(r[0]|r[1]|r[2]|r[3])===0,o=6);let a;typeof e=="string"?(!n.mask||s)&&n[fh]!==void 0?a=n[fh]:(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?(Tit(e,r,u,o,a),[u]):(Tit(e,r,e,0,a),[u,e])):[u,e]}close(e,n,r,i){let o;if(e===void 0)o=TMn;else{if(typeof e!="number"||!DMn(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(kMn(n))o.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[fh]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ef?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):SB(e)?(i=e.size,o=!1):(e=cv(e),i=e.length,o=cv.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[fh]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};SB(e)?this._state!==ef?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==ef?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):SB(e)?(i=e.size,o=!1):(e=cv(e),i=e.length,o=cv.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[fh]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};SB(e)?this._state!==ef?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==ef?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}send(e,n,r){let i=this._extensions[kit.extensionName],o=n.binary?2:1,s=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):SB(e)?(a=e.size,c=!1):(e=cv(e),a=e.length,c=cv.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={[fh]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:s};SB(e)?this._state!==ef?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==ef?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[fh],this._state=NMn,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(g0e,this,a,i);return}this._bufferedBytes-=r[fh];let s=cv(o);n?this.dispatch(s,n,r,i):(this._state=ef,this.sendFrame(t.frame(s,r),i),this.dequeue())}).catch(o=>{process.nextTick(OMn,this,o,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let o=this._extensions[kit.extensionName];this._bufferedBytes+=r[fh],this._state=PMn,o.compress(e,r.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");g0e(this,c,i);return}this._bufferedBytes-=r[fh],this._state=ef,r.readOnly=!1,this.sendFrame(t.frame(a,r),i),this.dequeue()})}dequeue(){for(;this._state===ef&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][fh],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][fh],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=f0e;function g0e(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 OMn(t,e,n){g0e(t,e,n),t.onerror(e)}});var Fit=L((Yki,Qit)=>{"use strict";var{kForOnEventAttribute:aU,kListener:y0e}=X0(),Bit=Symbol("kCode"),Dit=Symbol("kData"),Mit=Symbol("kError"),Pit=Symbol("kMessage"),Nit=Symbol("kReason"),kB=Symbol("kTarget"),Oit=Symbol("kType"),Lit=Symbol("kWasClean"),ey=class{constructor(e){this[kB]=null,this[Oit]=e}get target(){return this[kB]}get type(){return this[Oit]}};Object.defineProperty(ey.prototype,"target",{enumerable:!0});Object.defineProperty(ey.prototype,"type",{enumerable:!0});var lv=class extends ey{constructor(e,n={}){super(e),this[Bit]=n.code===void 0?0:n.code,this[Nit]=n.reason===void 0?"":n.reason,this[Lit]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Bit]}get reason(){return this[Nit]}get wasClean(){return this[Lit]}};Object.defineProperty(lv.prototype,"code",{enumerable:!0});Object.defineProperty(lv.prototype,"reason",{enumerable:!0});Object.defineProperty(lv.prototype,"wasClean",{enumerable:!0});var TB=class extends ey{constructor(e,n={}){super(e),this[Mit]=n.error===void 0?null:n.error,this[Pit]=n.message===void 0?"":n.message}get error(){return this[Mit]}get message(){return this[Pit]}};Object.defineProperty(TB.prototype,"error",{enumerable:!0});Object.defineProperty(TB.prototype,"message",{enumerable:!0});var cU=class extends ey{constructor(e,n={}){super(e),this[Dit]=n.data===void 0?null:n.data}get data(){return this[Dit]}};Object.defineProperty(cU.prototype,"data",{enumerable:!0});var LMn={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[aU]&&i[y0e]===e&&!i[aU])return;let r;if(t==="message")r=function(o,s){let a=new cU("message",{data:s?o:o.toString()});a[kB]=this,vV(e,this,a)};else if(t==="close")r=function(o,s){let a=new lv("close",{code:o,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[kB]=this,vV(e,this,a)};else if(t==="error")r=function(o){let s=new TB("error",{error:o,message:o.message});s[kB]=this,vV(e,this,s)};else if(t==="open")r=function(){let o=new ey("open");o[kB]=this,vV(e,this,o)};else return;r[aU]=!!n[aU],r[y0e]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[y0e]===e&&!n[aU]){this.removeListener(t,n);break}}};Qit.exports={CloseEvent:lv,ErrorEvent:TB,Event:ey,EventTarget:LMn,MessageEvent:cU};function vV(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var SV=L((Jki,Uit)=>{"use strict";var{tokenChars:uU}=vB();function Mg(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function QMn(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?(Mg(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),Mg(n,t.slice(c,l),!0),u===44&&(Mg(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),Mg(n,a,h),u===44&&(Mg(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?Mg(e,p,n):(a===void 0?Mg(n,p,!0):r?Mg(n,a,p.replace(/\\/g,"")):Mg(n,a,p),Mg(e,s,n)),e}function FMn(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(", ")}Uit.exports={format:FMn,parse:QMn}});var RV=L((eTi,Xit)=>{"use strict";var UMn=K("events"),$Mn=K("https"),WMn=K("http"),Hit=K("net"),HMn=K("tls"),{randomBytes:GMn,createHash:qMn}=K("crypto"),{Duplex:Xki,Readable:Zki}=K("stream"),{URL:E0e}=K("url"),Iw=IB(),jMn=m0e(),zMn=A0e(),{isBlob:VMn}=vB(),{BINARY_TYPES:$it,CLOSE_TIMEOUT:KMn,EMPTY_BUFFER:_V,GUID:YMn,kForOnEventAttribute:w0e,kListener:JMn,kStatusCode:XMn,kWebSocket:Za,NOOP:Git}=X0(),{EventTarget:{addEventListener:ZMn,removeEventListener:ePn}}=Fit(),{format:tPn,parse:nPn}=SV(),{toBuffer:rPn}=oU(),qit=Symbol("kAborted"),x0e=[8,13],ty=["CONNECTING","OPEN","CLOSING","CLOSED"],iPn=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Go=class t extends UMn{constructor(e,n,r){super(),this._binaryType=$it[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=_V,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]),jit(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){$it.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 jMn({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 zMn(e,this._extensions,r.generateMask);this._receiver=i,this._sender=o,this._socket=e,i[Za]=this,o[Za]=this,e[Za]=this,i.on("conclude",aPn),i.on("drain",cPn),i.on("error",uPn),i.on("message",lPn),i.on("ping",dPn),i.on("pong",pPn),o.onerror=hPn,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Kit),e.on("data",TV),e.on("end",Yit),e.on("error",Jit),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[Iw.extensionName]&&this._extensions[Iw.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())}),Vit(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){b0e(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||_V,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){b0e(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||_V,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){b0e(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Iw.extensionName]||(i.compress=!1),this._sender.send(e||_V,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(Go,"CONNECTING",{enumerable:!0,value:ty.indexOf("CONNECTING")});Object.defineProperty(Go.prototype,"CONNECTING",{enumerable:!0,value:ty.indexOf("CONNECTING")});Object.defineProperty(Go,"OPEN",{enumerable:!0,value:ty.indexOf("OPEN")});Object.defineProperty(Go.prototype,"OPEN",{enumerable:!0,value:ty.indexOf("OPEN")});Object.defineProperty(Go,"CLOSING",{enumerable:!0,value:ty.indexOf("CLOSING")});Object.defineProperty(Go.prototype,"CLOSING",{enumerable:!0,value:ty.indexOf("CLOSING")});Object.defineProperty(Go,"CLOSED",{enumerable:!0,value:ty.indexOf("CLOSED")});Object.defineProperty(Go.prototype,"CLOSED",{enumerable:!0,value:ty.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Go.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Go.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[w0e])return e[JMn];return null},set(e){for(let n of this.listeners(t))if(n[w0e]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[w0e]:!0})}})});Go.prototype.addEventListener=ZMn;Go.prototype.removeEventListener=ePn;Xit.exports=Go;function jit(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:KMn,protocolVersion:x0e[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,!x0e.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${x0e.join(", ")})`);let o;if(e instanceof E0e)o=e;else try{o=new E0e(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;kV(t,f);return}let u=s?443:80,l=GMn(16).toString("base64"),d=s?$Mn.request:WMn.request,p=new Set,h;if(i.createConnection=i.createConnection||(s?sPn:oPn),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 Iw({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=tPn({[Iw.extensionName]:h.offer()})),n.length){for(let f of n){if(typeof f!="string"||!iPn.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,y]of Object.entries(f))r.headers[g.toLowerCase()]=y}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[qit]||(m=t._req=null,kV(t,f))}),m.on("response",f=>{let g=f.headers.location,y=f.statusCode;if(g&&i.followRedirects&&y>=300&&y<400){if(++t._redirects>i.maxRedirects){np(t,m,"Maximum redirects exceeded");return}m.abort();let x;try{x=new E0e(g,e)}catch{let v=new SyntaxError(`Invalid URL: ${g}`);kV(t,v);return}jit(t,x,n,r)}else t.emit("unexpected-response",m,f)||np(t,m,`Unexpected server response: ${f.statusCode}`)}),m.on("upgrade",(f,g,y)=>{if(t.emit("upgrade",f),t.readyState!==Go.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=qMn("sha1").update(l+YMn).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=nPn(_)}catch{np(t,g,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(T);if(B.length!==1||B[0]!==Iw.extensionName){np(t,g,"Server indicated an extension that was not requested");return}try{h.accept(T[Iw.extensionName])}catch{np(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Iw.extensionName]=h}t.setSocket(g,y,{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 kV(t,e){t._readyState=Go.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function oPn(t){return t.path=t.socketPath,Hit.connect(t)}function sPn(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Hit.isIP(t.host)?"":t.host),HMn.connect(t)}function np(t,e,n){t._readyState=Go.CLOSING;let r=new Error(n);Error.captureStackTrace(r,np),e.setHeader?(e[qit]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(kV,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function b0e(t,e,n){if(e){let r=VMn(e)?e.size:rPn(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${ty[t.readyState]})`);process.nextTick(n,r)}}function aPn(t,e){let n=this[Za];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Za]!==void 0&&(n._socket.removeListener("data",TV),process.nextTick(zit,n._socket),t===1005?n.close():n.close(t,e))}function cPn(){let t=this[Za];t.isPaused||t._socket.resume()}function uPn(t){let e=this[Za];e._socket[Za]!==void 0&&(e._socket.removeListener("data",TV),process.nextTick(zit,e._socket),e.close(t[XMn])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Wit(){this[Za].emitClose()}function lPn(t,e){this[Za].emit("message",t,e)}function dPn(t){let e=this[Za];e._autoPong&&e.pong(t,!this._isServer,Git),e.emit("ping",t)}function pPn(t){this[Za].emit("pong",t)}function zit(t){t.resume()}function hPn(t){let e=this[Za];e.readyState!==Go.CLOSED&&(e.readyState===Go.OPEN&&(e._readyState=Go.CLOSING,Vit(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Vit(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Kit(){let t=this[Za];if(this.removeListener("close",Kit),this.removeListener("data",TV),this.removeListener("end",Yit),t._readyState=Go.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[Za]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Wit),t._receiver.on("finish",Wit))}function TV(t){this[Za]._receiver.write(t)||this.pause()}function Yit(){let t=this[Za];t._readyState=Go.CLOSING,t._receiver.end(),this.end()}function Jit(){let t=this[Za];this.removeListener("error",Jit),this.on("error",Git),t&&(t._readyState=Go.CLOSING,this.destroy())}});var not=L((nTi,tot)=>{"use strict";var tTi=RV(),{Duplex:mPn}=K("stream");function Zit(t){t.emit("close")}function fPn(){!this.destroyed&&this._writableState.finished&&this.destroy()}function eot(t){this.removeListener("error",eot),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function gPn(t,e){let n=!0,r=new mPn({...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(Zit,r);return}let s=!1;t.once("error",function(c){s=!0,o(c)}),t.once("close",function(){s||o(i),process.nextTick(Zit,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",fPn),r.on("error",eot),r}tot.exports=gPn});var C0e=L((rTi,rot)=>{"use strict";var{tokenChars:APn}=vB();function yPn(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&&APn[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}rot.exports={parse:yPn}});var lot=L((oTi,uot)=>{"use strict";var EPn=K("events"),BV=K("http"),{Duplex:iTi}=K("stream"),{createHash:wPn}=K("crypto"),iot=SV(),dv=IB(),xPn=C0e(),bPn=RV(),{CLOSE_TIMEOUT:CPn,GUID:IPn,kWebSocket:vPn}=X0(),SPn=/^[+/0-9A-Za-z]{22}==$/,oot=0,sot=1,cot=2,I0e=class extends EPn{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:CPn,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:bPn,...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=BV.createServer((r,i)=>{let o=BV.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=_Pn(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=oot}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===cot){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!==sot)if(this._state=sot,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",aot);let o=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){pv(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){pv(this,e,n,400,"Invalid Upgrade header");return}if(o===void 0||!SPn.test(o)){pv(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){pv(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=xPn.parse(c)}catch{pv(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 dv({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=iot.parse(l);h[dv.extensionName]&&(p.accept(h[dv.extensionName]),d[dv.extensionName]=p)}catch{pv(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[vPn])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>oot)return dU(o,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${wPn("sha1").update(n+IPn).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[dv.extensionName]){let d=e[dv.extensionName].params,p=iot.format({[dv.extensionName]:[d]});u.push(`Sec-WebSocket-Extensions: ${p}`),l._extensions=e}this.emit("headers",u,i),o.write(u.concat(`\r
|
|
100
|
+
`)}})}function Gl(t){let e=_6();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=VXe({...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=YXe(n);return e.component==="broker"&&e.node_id!==void 0&&(EBn??=MI())?(wBn(e.node_id,r),!0):e.component==="daemon"?$Xe(e.path,r):g6(e.path,r)}var EBn,Wtt,XI=A(()=>{"use strict";vfe();KXe();JXe();jfe();Bc();MF();Wtt=Promise.resolve()});var Htt,Gtt=A(()=>{"use strict";XI();Htt={sandboxUsdPerGbHour:"CRTR_LEDGER_SANDBOX_USD_PER_GB_HOUR",sandboxStandbyS:"CRTR_LEDGER_SANDBOX_STANDBY_S",storageUsdPerGbMonth:"CRTR_LEDGER_STORAGE_USD_PER_GB_MONTH",infraFreeUsdPerMonth:"CRTR_LEDGER_INFRA_FREE_USD_PER_MONTH",takePct:"CRTR_LEDGER_TAKE_PCT",r2Move:"CRTR_LEDGER_R2_MOVE"}});function eV(t){return t.flatMap(e=>e.path===void 0?[]:[e.path])}var GF=A(()=>{"use strict"});var qtt=A(()=>{"use strict"});import{createHash as xBn}from"node:crypto";function Vtt(t){return t===void 0?"absent":xBn("sha256").update(JSON.stringify(t)).digest("hex")}function Ktt(t,e){ztt.set(t,e)}function z0(){let t;try{t=x6()}catch(n){if(n instanceof SF)return jtt();if(n instanceof vF)return uAe??jtt();throw n}let e=ztt.get(t);if(e!==void 0)return e;if(uAe!==void 0)return uAe;throw new lAe(t)}function Ytt(t){bBn=t}function Jtt(t){CBn=t}function jF(t){let e=z0().settings[t];return{settings:e===void 0?null:structuredClone(e),revision:Vtt(e)}}function Xtt(t){let e=z0().state[t];return e===void 0?{marketplaces:{},plugins:{},activeCanvas:null}:structuredClone(e)}function Ztt(){return structuredClone(z0().profiles)}function ent(t){let e=z0().profiles.find(n=>n.profileId===t);return e===void 0?null:structuredClone(e)}var qF,lAe,ztt,jtt,uAe,bBn,CBn,pB=A(()=>{"use strict";eB();qF=class extends Error{constructor(){super("settings changed since the supplied revision"),this.name="SettingsRevisionConflictError"}},lAe=class extends Error{constructor(e){super(`settings for ${e} are not loaded in this process`),this.name="PersonSettingsNotLoadedError"}},ztt=new Map;jtt=()=>({profiles:[],defaults:{},settings:{},state:{},apps:{}});bBn=async()=>{throw new Error("no settings transport installed in this process")}});var tnt=A(()=>{"use strict"});var nnt=A(()=>{"use strict";Bc()});var rnt=A(()=>{"use strict"});var int=A(()=>{"use strict"});var ont=A(()=>{"use strict"});var snt=A(()=>{"use strict"});var ant=A(()=>{"use strict"});var cnt=A(()=>{"use strict"});var unt=A(()=>{"use strict"});var lnt=A(()=>{"use strict"});var dnt=A(()=>{"use strict"});var pnt,dAe=A(()=>{"use strict";pnt=["trial_ended","card_required","card_limit","nothing_left","app_limit","team_limit","app_unpaid"]});var hnt=A(()=>{"use strict"});var mnt=A(()=>{"use strict"});var fnt=A(()=>{"use strict"});var gnt=A(()=>{"use strict"});var Ant=A(()=>{"use strict"});var ynt=A(()=>{"use strict"});var Ent=A(()=>{"use strict"});var wnt=A(()=>{"use strict"});var xnt=A(()=>{"use strict"});var bnt=A(()=>{"use strict"});var Cnt=A(()=>{"use strict"});var Int=A(()=>{"use strict"});var vnt=A(()=>{"use strict"});var Snt=A(()=>{"use strict"});var _nt=A(()=>{"use strict"});var knt=A(()=>{"use strict"});var Tnt=A(()=>{"use strict"});var Rnt=A(()=>{"use strict"});var Bnt=A(()=>{"use strict"});var Dnt=A(()=>{"use strict"});var Mnt=A(()=>{"use strict"});var Pnt=A(()=>{"use strict"});var Nnt=A(()=>{"use strict"});var Ont=A(()=>{"use strict"});var Lnt=A(()=>{"use strict"});var Qnt=A(()=>{"use strict"});var Fnt=A(()=>{"use strict"});var Unt=A(()=>{"use strict"});var $nt=A(()=>{"use strict"});var Wnt=A(()=>{"use strict"});var Hnt=A(()=>{"use strict"});var Gnt=A(()=>{"use strict"});var qnt=A(()=>{"use strict"});var jnt=A(()=>{"use strict"});var znt=A(()=>{"use strict"});var ZI=A(()=>{"use strict";B6();fw();int();Vfe();ont();snt();ant();JI();Yfe();cnt();unt();lnt();dnt();dAe();hnt();mnt();fnt();gnt();Ant();ynt();Ent();Jfe();wnt();xnt();bnt();Cnt();Int();vnt();Xfe();Snt();_nt();knt();GF();Tnt();Rnt();Bnt();Dnt();Mnt();Pnt();Nnt();Ont();Lnt();Qnt();Fnt();Unt();$nt();Wnt();Hnt();Gnt();qnt();jnt();znt()});function IBn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function zF(t,e,n={}){if(t.code==="daemon_restarting")return new os("daemon_restarting",t.message,ji.NETWORK,{next:"crtrd is now on the new generation \u2014 retry the command."});if(t.code==="layout_migration_required")return new os("layout_migration_required",t.message,ji.NETWORK,{next:"Run `crtr sys migrate` while the runtime is offline, then restart it."});if(t.code==="daemon_unavailable")return new os("daemon_unavailable",t.message,ji.NETWORK,{next:"Start it with `crtr sys daemon start`, then retry."});if(t.code==="northlight_unreachable"){let a=t.details?.next;return new os("northlight_unreachable",t.message,ji.NETWORK,{next:typeof a=="string"&&a!==""?a:"Check this computer's internet connection, then retry."})}if(t.code==="model_sign_in_required"){let a=t.details?.url;return new ep({error:t.code,message:t.message,next:typeof a=="string"?`Ask the person to sign in at ${a}, then retry.`:"Ask the person to sign in to an AI subscription on their Northlight account, then retry.",...typeof a=="string"?{details:{url:a}}:{}},ji.USAGE)}let r=t.details,i=SBn(t,r,n.providerCall===!0);if(t.status===503||n.providerCall===!0&&t.status===504&&i.code!==void 0){let a=i.code??t.code,c={next:i.next??e??"Retry the command; if it persists, inspect the unavailable service named in the error."};return i.details!==void 0&&(c.details=i.details),i.code!==void 0&&(i.field!==void 0&&(c.field=i.field),i.received!==void 0&&(c.received=i.received),i.retryAfterS!==void 0&&(c.retry_after_s=i.retryAfterS)),new os(a,t.message,ji.NETWORK,c)}let o=Array.isArray(r?.violations)?r.violations.map(a=>`${String(a.field)} ${String(a.problem)}${a.received!==void 0?` (received ${JSON.stringify(a.received)})`:""}`):[],s=r&&typeof r.error=="string"&&typeof r.message=="string"&&typeof r.next=="string"?r:{error:i.code??vBn[t.status]??t.code,...i.field!==void 0?{field:i.field}:{},...i.received!==void 0?{received:i.received}:{},...i.retryAfterS!==void 0?{retry_after_s:i.retryAfterS}:{},...i.details!==void 0?{details:i.details}:{},message:o.length>0?`${t.message}: ${o.join("; ")}`:t.message.trim()!==""?t.message:`request refused (HTTP ${t.status}, ${t.code}) with no message`,next:i.next??(r?.outcome==="unknown"?"The change may already be applied: check the current state before repeating it, and do not report it failed.":void 0)??e??(i.retryAfterS!==void 0?`Wait ${i.retryAfterS}s, then retry; do not retry sooner.`:t.status>=500?"This is a crtr bug, not a bad call. Retry; if it persists, report it (the daemon log holds the full cause).":t.status===404&&i.code===void 0?"List nodes with `crtr node inspect list`.":"Inspect the error and adjust the call. See -h for the schema.")};return new ep(s,_Bn(s.error,t.status))}function SBn(t,e,n){let r=o=>typeof o=="string"&&/^[a-z][a-z0-9_]*$/.test(o);if(n&&t.origin!==void 0&&t.origin!=="provider"&&r(t.code)){let o={code:t.code};return(t.status===503||t.status===504)&&(o.next=t.retryable===!0?"Retry the command; if it persists, the machine or service named in the error is unavailable.":"Read the error before retrying: the action may already have run."),IBn(t.details)&&(o.details=t.details),t.param!==void 0&&(o.field=t.param),typeof t.retryAfterS=="number"&&(o.retryAfterS=t.retryAfterS),o}if(t.origin!=="provider"||e===void 0||e===null||typeof e!="object")return{};let i={};return typeof e.status=="number"&&r(e.code)&&(i.code=e.code),typeof e.next=="string"&&e.next.trim()!==""&&(i.next=e.next),typeof e.field=="string"&&e.field!==""?i.field=e.field:t.param!==void 0&&(i.field=t.param),e.received!==void 0&&e.received!==null&&(i.received=e.received),typeof t.retryAfterS=="number"&&(i.retryAfterS=t.retryAfterS),i}function _Bn(t,e){return t==="not_found"||e===404?ji.NOT_FOUND:t==="ambiguous"?ji.AMBIGUOUS:ji.USAGE}var $Ii,ep,vBn,ev=A(()=>{"use strict";$l();ru();nnt();rnt();ZI();$Ii=256*1024,ep=class extends os{payload;constructor(e,n=ji.USAGE){super(e.error,e.message,n,{...e}),this.name="InputError",this.payload=e}};vBn={400:"invalid_request",404:"not_found",409:"conflict",422:"unprocessable"}});var pAe=A(()=>{"use strict"});var hAe=A(()=>{"use strict";Hu()});import{DatabaseSync as zIi}from"node:sqlite";var mAe=A(()=>{"use strict"});import{DatabaseSync as JIi}from"node:sqlite";var Vnt=A(()=>{"use strict";pAe();Hu();fAe();mAe()});import{DatabaseSync as Evi}from"node:sqlite";var fAe=A(()=>{"use strict";pAe();Hu();ev();iu();hAe();Vnt();mAe();hAe()});var tV=A(()=>{"use strict"});import{loadLinuxNative as BBn}from"../../native/linux.js";var Mvi,gAe=A(()=>{"use strict";tV();Mvi=BBn()});var Ynt=A(()=>{"use strict";gAe();tV()});import{join as PBn}from"node:path";function Jnt(){return PBn(Zm(),"runtime-client.json")}function NBn(){let t=q0(Jnt());if(t?.token_sha256===void 0)return null;let{owner:e}=t;if(typeof e!="string"||!/^user:.+/.test(e))throw new Error(`${Jnt()} was written by join but has a missing or invalid owner`);return t}function Xnt(){return NBn()?.issuer??null}var Znt=A(()=>{"use strict";ev();$l();Hu();Wl();fAe();iu();Ynt();N6();ww()});import{chmodSync as Xvi,existsSync as yAe,mkdirSync as Zvi,readFileSync as ert,rmSync as eSi,writeFileSync as tSi}from"node:fs";import{dirname as rSi,join as EAe}from"node:path";function V0(){let t=OBn();if(!yAe(t))return;let e=JSON.parse(ert(t,"utf8"));if(typeof e.apiUrl!="string"||typeof e.environmentId!="string"||e.runId!==void 0&&typeof e.runId!="string"||typeof e.directoryUrl!="string")throw new Error(`${t} must hold {apiUrl, environmentId, directoryUrl}`);let n=e.account!==void 0&&typeof e.account?.id=="string"&&typeof e.account.display=="string"?{id:e.account.id,display:e.account.display}:void 0;return{apiUrl:e.apiUrl,environmentId:e.environmentId,...e.runId===void 0?{}:{runId:e.runId},directoryUrl:e.directoryUrl,...n===void 0?{}:{account:n}}}function QBn(){let t=LBn();if(!yAe(t))return;let e=JSON.parse(ert(t,"utf8"));if(typeof e.runId!="string"||typeof e.apiUrl!="string"||typeof e.directoryUrl!="string"||e.state!=="running"&&e.state!=="committed"&&e.state!=="activated"||typeof e.account?.id!="string"||typeof e.account.display!="string")throw new Error(`${t} is not a move record`);return{runId:e.runId,apiUrl:e.apiUrl,directoryUrl:e.directoryUrl,account:{id:e.account.id,display:e.account.display},notify:typeof e.notify=="string"?e.notify:null,state:e.state,notified:e.notified===!0,pid:typeof e.pid=="number"?e.pid:0}}var OBn,LBn,trt,nrt,FBn,rrt,VF=A(()=>{"use strict";Hu();Znt();$l();iu();ru();OBn=()=>EAe(Wu(),"machine.json");LBn=()=>EAe(Wu(),"import","move.json");trt=()=>QBn()?.state==="committed",nrt=t=>new os("move_unfinished",`crtr's records are already in your Northlight account, but this computer has not switched over${t===void 0?".":`: ${t}`}`,ji.USAGE,{next:"Run `crtr sys signin` to finish."}),FBn=()=>["pg","canvas.db","canvas.db.imported"].some(t=>yAe(EAe(Wu(),t))),rrt=()=>V0()===void 0&&!FBn()&&Xnt()===null});function $Bn(t){return t.grantee??"app:terminal"}function WBn(t){if(!irt.test(t))throw hw(`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 nV(t){WBn(t);let e=ent(t);if(e===null)throw m6(`profile not found: ${t}`,{received:t});return Ofe($Bn(e.manifest),t).dir}function HBn(){return{entries:Ztt(),unreadableIds:[]}}function rV(){return HBn().entries}function GBn(t){let e=rV(),n=qBn(e,t,ort);return n?{kind:"resolved",entry:n}:{kind:"absent"}}function qBn(t,e,n){if(irt.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 MXe(`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 jBn(t,e,n){let r=t.map(i=>`${n(i).profileId} (${n(i).name})`);return m6(`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 Rg(t){let e=GBn(t);if(e.kind==="resolved")return e.entry;throw jBn(rV(),t,ort)}var irt,ort,tv=A(()=>{"use strict";ru();Hu();GF();iu();pB();$l();tnt();eB();VF();irt=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/;ort=t=>({profileId:t.profileId,name:t.manifest.name})});import{homedir as srt}from"node:os";import{existsSync as zBn,statSync as VBn}from"node:fs";import{join as iV,resolve as art,dirname as KBn,sep as wAe}from"node:path";function tp(){return iV(Wu(),"scope")}function YBn(t,e){if(!zBn(t)||Xm(t)===Xm(iV(srt(),LI))||Xm(t).startsWith(`${Xm(Nfe())}${wAe}`)&&t.endsWith(`${wAe}home${wAe}${LI}`)||!MI()&&(Xm(t)===Xm(e)||Xm(t)===Xm(_F())))return!1;try{return VBn(t).isDirectory()}catch{return!1}}function JBn(t=process.cwd()){return crt(t)[0]??null}function XBn(t,e){let n=[],r=Xm(srt()),i=art(t);for(;;){let o=iV(i,LI);if(YBn(o,e)&&n.push(o),Xm(i)===r)return n;let s=KBn(i);if(s===i)return n;i=s}}function crt(t=process.cwd(),e=Gme()||null){return ZBn(t,e)}function ZBn(t,e){let n=art(t),r=tp(),i=[n];if(!MI()&&e!==null&&e!=="")try{let{manifest:a}=Rg(e);i.push(...eV(a.projects))}catch{}let o=new Set,s=[];for(let a of i)for(let c of XBn(a,r))o.has(c)||(o.add(c),s.push(c));return s}function urt(t){return JBn(t)}function K0(t){return t==="builtin"?null:t==="user"?tp():urt()}function AAe(t){let e=t==="user"?Wu():K0(t);return e?iV(e,"plugins"):null}var ww=A(()=>{"use strict";Bc();GF();ru();qtt();$l();tv();iu();Hu()});import{join as eDn}from"node:path";function tDn(t){return eDn(t,RXe,BXe)}function nDn(t){let e;try{e=q0(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 rDn(t){return nDn(tDn(t))}function lrt(t){let e=rDn(t);return e.status==="ok"?e.manifest:null}var xAe=A(()=>{"use strict";ru();iu()});import{existsSync as iDn,mkdirSync as oDn,readdirSync as prt,rmSync as hrt,rmdirSync as sDn,statSync as aDn,unlinkSync as cDn,writeFileSync as uDn}from"node:fs";import{randomUUID as lDn}from"node:crypto";function frt(t){return Math.min(t*2,dDn)}function grt(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function CAe(t,e){return`${t}/${bAe}${e}`}function IAe(t){try{return prt(t).find(e=>e.startsWith(bAe))?.slice(bAe.length)??null}catch{return null}}function Art(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 mDn(t){try{return prt(t).length===0}catch{return!1}}function fDn(t){try{return Date.now()-aDn(t).mtimeMs}catch{return 0}}function gDn(t,e){let n=IAe(t);if(n!==null){if(Art(n))return;try{cDn(CAe(t,n))}catch(r){if(r.code==="ENOENT")return;throw r}}else{if(fDn(t)<=e)return;if(!mDn(t)){hrt(t,{recursive:!0,force:!0});return}}try{sDn(t)}catch(r){let i=r.code;if(i!=="ENOENT"&&i!=="ENOTEMPTY"&&i!=="EEXIST")throw r}}function oV(t){let e=IAe(t);if(e===null)return null;let n=Number(e.split(".",1)[0]);return Number.isSafeInteger(n)&&n>0?n:null}function yrt(t,e){let n=Date.now()+e,r=mrt;for(;;){let i=IAe(t);if(i===null||Number(i.split(".",1)[0])===process.pid||!Art(i))return;let o=n-Date.now();if(o<=0)return;grt(Math.min(r,o)),r=frt(r)}}function drt(t,e){let n=`${process.pid}.${lDn()}`;try{return oDn(t,{mode:448}),uDn(CAe(t,n),"",{flag:"wx",mode:384}),{path:t,token:n}}catch(r){if(r.code!=="EEXIST")throw r;return gDn(t,e),null}}function nv(t,e,n={}){let r=n.staleMs??pDn,i=Date.now()+(n.timeoutMs??hDn),o=mrt,s=drt(t,r);for(;s===null;){if(Date.now()>=i)throw n.timeoutError?.()??new Error(`timed out waiting for the exclusive lock: ${t}`);grt(Math.min(o,Math.max(0,i-Date.now()))),o=frt(o),s=drt(t,r)}try{return e()}finally{iDn(CAe(s.path,s.token))&&hrt(s.path,{recursive:!0,force:!0})}}var bAe,mrt,dDn,pDn,hDn,rv=A(()=>{"use strict";bAe="owner.",mrt=10,dDn=250,pDn=3e4,hDn=5e3});import{join as ADn}from"node:path";function Ert(t,e){return ADn(t,"tmp",`${e}.swap.lock`)}function wrt(t,e){let n=oV(Ert(t,e));return n!==null&&n!==process.pid}function xrt(t,e){yrt(Ert(t,e),yDn)}var yDn,brt=A(()=>{"use strict";rv();yDn=2e3});function sV(t,e){let n=t.apps[EDn];return n===void 0&&e===null?null:{...e??{},plugins:structuredClone(n?.plugins??{}),marketplaces:structuredClone(n?.marketplaces??{})}}var EDn,vAe=A(()=>{"use strict";Bc();pB();EDn="app:terminal"});import{join as SAe}from"node:path";function wDn(t,e){let n=t==="user"?mF()?sV(z0(),jF("user").settings):jF("user").settings:q0(SAe(e,d6));return n&&n.plugins&&typeof n.plugins=="object"?n.plugins:{}}function xDn(t,e,n){let r=Object.keys(e);return r.every(i=>n.has(i))?[]:r.filter(i=>!n.has(i)&&wrt(t,i))}function aV(t,e){if(t==="user"&&w6())return[];let n=t!=="user"?SAe(e,"plugins"):AAe("user");if(n===void 0||!Mfe(n))return[];let r=wDn(t,e),i=Crt(t,n,r),o=xDn(e,r,new Set(i.map(s=>s.name)));if(o.length===0)return i;for(let s of o)xrt(e,s);return Crt(t,n,r)}function Crt(t,e,n){let r=[];for(let i of Pfe(e)){let o=SAe(e,i),s=lrt(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 cV=A(()=>{"use strict";ru();iu();xAe();brt();eB();pB();vAe();ww()});import{existsSync as bDn,realpathSync as CDn}from"node:fs";import{basename as IDn,dirname as vDn,join as h_i,resolve as Irt}from"node:path";function hB(t){let e=Irt(t),n=e,r=[];for(;!bDn(n);){let i=vDn(n);if(i===n)return e;r.unshift(IDn(n)),n=i}return Irt(CDn(n),...r)}var vrt=A(()=>{"use strict"});function SDn(t){let e=zi.indexOf(t);return`less ${zi.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 ${lV[t]}`}function uV(t,e,n){let r=t.indexOf(e),i=r>=0?r:0;return t[(i+n+t.length)%t.length]}function Srt(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 iv(t,e){return t==="true"?!0:t==="false"?!1:`${e} must be true or false`}function Trt(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 _Dn(t,e){let n=Trt(t,e);return typeof n=="string"||n<1?`${e} must be an integer >= 1`:n}function krt(t,e){let n=t.providerOptions[e];if(n!==void 0)return n;let r={};return t.providerOptions[e]=r,r}function BDn(){let t=[];for(let e of Object.values(Rrt))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 lV,_rt,kDn,TDn,KF,Rrt,RDn,g_i,_Ae=A(()=>{"use strict";ru();lV={replies:"Replies only",summaries:"Messages + summaries",tools:"Tool calls",previews:"Previews",full:"Full"};_rt=[!1,"notify","apply"],kDn=[0,1,6,12,24,48,72,168],TDn=[1,2,3,4,5,6,8,10,12],KF="openai-codex";Rrt={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=uV(_rt,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=uV(_rt,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=Srt(kDn,t.auto_update.interval_hours,e)},setFromString:(t,e)=>{let n=Trt(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=Srt(TDn,t.max_panes_per_window,e)},setFromString:(t,e)=>{let n=_Dn(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=iv(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=iv(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=iv(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=iv(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:QI.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=uV(QI,t.whip_message_mode,e)},setFromString:(t,e)=>QI.includes(e)?(t.whip_message_mode=e,null):`whip_message_mode must be one of: ${QI.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:FI.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=uV(FI,t.mouse_mode_default,e)},setFromString:(t,e)=>FI.includes(e)?(t.mouse_mode_default=e,null):`mouse_mode_default must be one of: ${FI.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=iv(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:zi.join("|"),applies:"Applies on the next attach.",group:"display",order:30,format:t=>t.verbosity,display:t=>SDn(t.verbosity),cycle:(t,e)=>{let n=zi.indexOf(t.verbosity)+e;t.verbosity=zi[Math.max(0,Math.min(zi.length-1,n))]},setFromString:(t,e)=>zi.includes(e)?(t.verbosity=e,null):`verbosity must be one of: ${zi.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=iv(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.${KF}.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[KF]?.fastMode?"on":"off",cycle:t=>{let e=krt(t,KF);e.fastMode=!e.fastMode},setFromString:(t,e)=>{let n=iv(e,`providerOptions.${KF}.fastMode`);return typeof n=="string"?n:(krt(t,KF).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:"daemon API listener"},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"}},RDn=Object.keys(Rrt);g_i=BDn()});function YF(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 BAe(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(!MDn.test(a))throw new Error(`${e}[${o}] has invalid page kind ${fB(a)}; expected /^[a-z][a-z0-9-]{0,63}$/`);if(PDn.has(a)||DDn.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=YF(a);if(dV.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 Drt(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=YF(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 Mrt(t,e){return e.find(n=>n.kind===t)}var kAe,DDn,MDn,PDn,Brt,TAe,dV,RAe,JF=A(()=>{"use strict";kAe=["options","text","table","cards","chart"],DDn=["page","step"],MDn=/^[a-z][a-z0-9-]{0,63}$/,PDn=new Set(kAe),Brt=[{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}];TAe=Object.fromEntries(Brt.filter(t=>!t.structural).map(t=>[t.tag,t.kind])),dV=new Set(Brt.map(t=>t.tag)),RAe=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 Qrt,join as Frt}from"node:path";import{existsSync as ODn,mkdirSync as I_i,statSync as v_i}from"node:fs";function LDn(t){return Frt(t,d6)}function QDn(t){return Frt(t,DXe)}function Urt(t){let e=hB(t),n=hB(tp());if(e===n)return{key:"user",kind:"user",root:n};if(Qrt(e)===".crouter")return{key:"project",kind:"project",root:e};for(let r of rV()){let i=hB(nV(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 $rt(t){if(Qrt(t)===".crouter"){let r;try{r=hB(t)}catch(i){if(i.code==="ENOENT")return null;throw i}if(r!==hB(tp()))return q0(LDn(t))}let e=Urt(t).key,n=jF(e).settings;return e==="user"&&mF()?sV(z0(),n):n}function ph(t){let e=FDn[UDn];if(e){if(t!=="user")throw new Error(`broker config snapshot has no ${t} scope`);return e.user}let n=K0(t);return n?$Dn(n):h6()}function $Dn(t){let e=$rt(t);return e?m1n(e):h6()}function WDn(t){let e=q0(QDn(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 Wrt(t){let e=K0(t);return e?t==="project"?ODn(e)?WDn(e):Ife():Xtt(Urt(e).key):Ife()}function HDn(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 t===void 0?[...qDn]:Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string"&&OI.has(e)&&GDn.has(e)))]:[]}function jDn(t,e=Cfe()){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 Hrt(t){return t==="ultra"||t==="strong"||t==="medium"||t==="light"}function DAe(){return Object.create(null)}function pV(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function VDn(t){let e=DAe();for(let[n,r]of Object.entries(t??{}))pV(e,n,r);return e}function XF(t,e){Gl({level:"warn",event:"config.model_routes.invalid",fields:{route_id:t,rule:e}})}function KDn(t,e={}){let n=VDn(e);if(t===null||typeof t!="object"||Array.isArray(t))return n;for(let[r,i]of Object.entries(t)){if(r.trim()===""){XF(r,"route id must be a non-empty string");continue}if(i===null||typeof i!="object"||Array.isArray(i)){XF(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(!Hrt(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){XF(r,c);continue}pV(n,r,a)}return n}function YDn(t){let e=DAe(),n=DAe();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){XF(r,"route must include family, credentialSource, providerId, and models");continue}let o=zDn.filter(s=>i.models[s]===void 0);if(o.length>0){XF(r,`incomplete route; missing strengths: ${o.join(", ")}`),pV(n,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models});continue}pV(e,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models})}return{complete:e,legacy:n}}function JDn(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=>Hrt(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 XDn(t){return t!==""&&t.replace(/\*/g,"")===""}function ZDn(t,e=[]){let n=t,r=Array.isArray(n?.allow)?n.allow.filter(i=>typeof i=="string"):[];for(let i of r)if(XDn(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 e1n(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 n1n(t,e){if(e==="bin"&&t1n.has(t))return`${e}.${t} is reserved by crouter \u2014 pick another bare command name`;if(!Prt.test(t))return`${e}.${t} is not a safe bare command name (expected ${Prt.source})`}function r1n(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))n1n(n,"bin")===void 0&&(typeof r!="string"||r.trim()===""||(e[n]=r));return e}function i1n(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(Nrt.test(n)||i.push(`action name must match ${Nrt.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 o1n(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e=new Set(i1n(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 s1n(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 a1n(t,e=bfe()){let n={...e};if(t!==null&&typeof t=="object")for(let[r,i]of Object.entries(t)){let o=s1n(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 mV(){let t=[{origin:"config.json",components:ph("user").page_components}],e=K0("user");if(e!==null){let n=aV("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:BAe(r.manifest.page_components,i)})}}return Drt(t)}function c1n(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 u1n(t,e=xfe()){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=c1n(o);s!==null&&(n[i]=s)}}return{targets:n}}function Ort(t,e){return t===!0?"notify":t===!1?!1:t==="notify"||t==="apply"?t:e}function hV(t,e){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=1?t:e}function l1n(t,e){let n=t!==null&&typeof t=="object"?t:{},r=hV(n.warning,e.warning),i=hV(n.automaticReviveCap,e.automaticReviveCap);return r<=i?{warning:r,automaticReviveCap:i}:{...e}}function d1n(t,e){return{unattendedParkMs:hV((t!==null&&typeof t=="object"?t:{}).unattendedParkMs,e.unattendedParkMs)}}function p1n(t){if(!Array.isArray(t))return[...p6];let e=t.filter(n=>typeof n=="string"&&n.trim()!=="").map(n=>n.trim());return e.length>0?e:[...p6]}function h1n(t,e){if(t===null||typeof t!="object")return{...e};let n=t.tcp;return{tcp:typeof n=="string"?n:e.tcp}}function m1n(t){!Lrt&&t.ledger!==void 0&&(Lrt=!0,Gl({level:"warn",event:"config.ledger.ignored",fields:{variables:Object.values(Htt)}}));let e=h6(),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:Ort(o?.crtr,e.auto_update.crtr),content:Ort(o?.content,e.auto_update.content),interval_hours:a},u=t.max_panes_per_window,l=hV(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=l1n(t.brokerThresholds,e.brokerThresholds),h=d1n(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]:kXe(t.working_gerunds),g=typeof t.whip_mode=="boolean"?t.whip_mode:e.whip_mode,y=BAe(t.page_components),x=typeof t.page_surface=="boolean"?t.page_surface:e.page_surface,b=p1n(t.whip_messages),v=QI.includes(t.whip_message_mode)?t.whip_message_mode:e.whip_message_mode,S=FI.includes(t.mouse_mode_default)?t.mouse_mode_default:e.mouse_mode_default,_=typeof t.bash_tool_purpose=="boolean"?t.bash_tool_purpose:e.bash_tool_purpose,T=zi.includes(t.verbosity)?t.verbosity:e.verbosity,B=typeof t.detailed_tool_recaps=="boolean"?t.detailed_tool_recaps:e.detailed_tool_recaps,R=Number.isInteger(t.document_port)&&t.document_port>=1&&t.document_port<=65535?t.document_port:e.document_port,P=HDn(t.keybindings),Q=gB(t.tmux_passthrough),$=jDn(t.modelLadders),j=e1n(t.providerOptions,e.providerOptions),H=YDn(KDn(t.modelRoutes)),le=H.complete,ee=JDn(t.modelRouting,void 0),ge=a1n(t.kinds),Ie=u1n(t.remoteCanvas),$e=h1n(t.api,e.api),wt=t.paths;if(wt?.user_files!==void 0&&(typeof wt.user_files!="string"||!wt.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");let Ze=t.store,xt=t.runtime;if(xt?.person_uids!==void 0&&(!Array.isArray(xt.person_uids)||!xt.person_uids.every(et=>Number.isSafeInteger(et)&&et>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");let re=ZDn(t.spawnEnv,e.spawnEnv?.allow),ot=r1n(t.bin),ke=o1n(t.humanActions);return{bin:ot,humanActions:ke,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:y,page_surface:x,whip_messages:b,whip_message_mode:v,mouse_mode_default:S,bash_tool_purpose:_,verbosity:T,detailed_tool_recaps:B,document_port:R,keybindings:P,tmux_passthrough:Q,modelLadders:$,providerOptions:j,...Object.keys(le).length>0?{modelRoutes:le}:{},...Object.keys(H.legacy).length>0?{legacyModelRoutes:H.legacy}:{},...ee!==void 0?{modelRouting:ee}:{},kinds:ge,remoteCanvas:Ie,api:$e,...wt?{paths:wt}:{},...Ze?{store:Ze}:{},...xt?{runtime:xt}:{},spawnEnv:re}}function f1n(t){return $rt(t)}function Grt(t){let e=K0(t);return e?f1n(e):null}var FDn,UDn,GDn,qDn,zDn,Prt,t1n,Nrt,Lrt,Yd=A(()=>{"use strict";Bc();ru();c6();$l();XI();Gtt();iu();ww();cV();tv();vrt();pB();vAe();rv();_Ae();l6();JF();FDn=globalThis,UDn=Symbol.for("crtr.broker.config-snapshot");GDn=new Set(zd.filter(bF).map(t=>t.id)),qDn=Object.freeze(["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live"]);zDn=["ultra","strong","medium","light"];Prt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,t1n=new Set(["crtr","crtrd"]);Nrt=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;Lrt=!1});var X0=L((Wki,lit)=>{"use strict";var cit=["nodebuffer","arraybuffer","fragments"],uit=typeof Blob<"u";uit&&cit.push("blob");lit.exports={BINARY_TYPES:cit,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:uit,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var oU=L((Hki,yV)=>{"use strict";var{EMPTY_BUFFER:cMn}=X0(),i0e=Buffer[Symbol.species];function uMn(t,e){if(t.length===0)return cMn;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 i0e(n.buffer,n.byteOffset,r):n}function dit(t,e,n,r,i){for(let o=0;o<i;o++)n[r+o]=t[o]^e[o&3]}function pit(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function lMn(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function o0e(t){if(o0e.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new i0e(t):ArrayBuffer.isView(t)?e=new i0e(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),o0e.readOnly=!1),e}yV.exports={concat:uMn,mask:dit,toArrayBuffer:lMn,toBuffer:o0e,unmask:pit};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=K("bufferutil");yV.exports.mask=function(e,n,r,i,o){o<48?dit(e,n,r,i,o):t.mask(e,n,r,i,o)},yV.exports.unmask=function(e,n){e.length<32?pit(e,n):t.unmask(e,n)}}catch{}});var fit=L((Gki,mit)=>{"use strict";var hit=Symbol("kDone"),s0e=Symbol("kRun"),a0e=class{constructor(e){this[hit]=()=>{this.pending--,this[s0e]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[s0e]()}[s0e](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[hit])}}};mit.exports=a0e});var IB=L((qki,Eit)=>{"use strict";var sU=K("zlib"),git=oU(),dMn=fit(),{kStatusCode:Ait}=X0(),pMn=Buffer[Symbol.species],hMn=Buffer.from([0,0,255,255]),wV=Symbol("permessage-deflate"),Z0=Symbol("total-length"),bB=Symbol("callback"),Cw=Symbol("buffers"),CB=Symbol("error"),EV,c0e=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,!EV){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;EV=new dMn(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[bB];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){EV.add(i=>{this._decompress(e,n,(o,s)=>{i(),r(o,s)})})}compress(e,n,r){EV.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[wV]=this,this._inflate[Z0]=0,this._inflate[Cw]=[],this._inflate.on("error",fMn),this._inflate.on("data",yit)}this._inflate[bB]=r,this._inflate.write(e),n&&this._inflate.write(hMn),this._inflate.flush(()=>{let o=this._inflate[CB];if(o){this._inflate.close(),this._inflate=null,r(o);return}let s=git.concat(this._inflate[Cw],this._inflate[Z0]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Z0]=0,this._inflate[Cw]=[],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[Cw]=[],this._deflate.on("data",mMn)}this._deflate[bB]=r,this._deflate.write(e),this._deflate.flush(sU.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=git.concat(this._deflate[Cw],this._deflate[Z0]);n&&(o=new pMn(o.buffer,o.byteOffset,o.length-4)),this._deflate[bB]=null,this._deflate[Z0]=0,this._deflate[Cw]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,o)})}};Eit.exports=c0e;function mMn(t){this[Cw].push(t),this[Z0]+=t.length}function yit(t){if(this[Z0]+=t.length,this[wV]._maxPayload<1||this[Z0]<=this[wV]._maxPayload){this[Cw].push(t);return}this[CB]=new RangeError("Max payload size exceeded"),this[CB].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[CB][Ait]=1009,this.removeListener("data",yit),this.reset()}function fMn(t){if(this[wV]._inflate=null,this[CB]){this[bB](this[CB]);return}t[Ait]=1007,this[bB](t)}});var vB=L((jki,xV)=>{"use strict";var{isUtf8:wit}=K("buffer"),{hasBlob:gMn}=X0(),AMn=[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 yMn(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function u0e(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 EMn(t){return gMn&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}xV.exports={isBlob:EMn,isValidStatusCode:yMn,isValidUTF8:u0e,tokenChars:AMn};if(wit)xV.exports.isValidUTF8=function(t){return t.length<24?u0e(t):wit(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=K("utf-8-validate");xV.exports.isValidUTF8=function(e){return e.length<32?u0e(e):t(e)}}catch{}});var m0e=L((zki,_it)=>{"use strict";var{Writable:wMn}=K("stream"),xit=IB(),{BINARY_TYPES:xMn,EMPTY_BUFFER:bit,kStatusCode:bMn,kWebSocket:CMn}=X0(),{concat:l0e,toArrayBuffer:IMn,unmask:vMn}=oU(),{isValidStatusCode:SMn,isValidUTF8:Cit}=vB(),bV=Buffer[Symbol.species],mh=0,Iit=1,vit=2,Sit=3,d0e=4,p0e=5,CV=6,h0e=class extends wMn{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||xMn[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[CMn]=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=mh}_write(e,n,r){if(this._opcode===8&&this._state==mh)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 bV(r.buffer,r.byteOffset+e,r.length-e),new bV(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 bV(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 mh:this.getInfo(e);break;case Iit:this.getPayloadLength16(e);break;case vit:this.getPayloadLength64(e);break;case Sit:this.getMask();break;case d0e:this.getData(e);break;case p0e:case CV: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[xit.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=Iit:this._payloadLength===127?this._state=vit: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=Sit:this._state=d0e}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=d0e}getData(e){let n=bit;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&&vMn(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=p0e,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[xit.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===mh&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=mh;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=l0e(r,n):this._binaryType==="arraybuffer"?i=IMn(l0e(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=mh):(this._state=CV,setImmediate(()=>{this.emit("message",i,!0),this._state=mh,this.startLoop(e)}))}else{let i=l0e(r,n);if(!this._skipUTF8Validation&&!Cit(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===p0e||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=mh):(this._state=CV,setImmediate(()=>{this.emit("message",i,!1),this._state=mh,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,bit),this.end();else{let r=e.readUInt16BE(0);if(!SMn(r)){let o=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(o);return}let i=new bV(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Cit(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=mh;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=mh):(this._state=CV,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=mh,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[bMn]=i,s}};_it.exports=h0e});var A0e=L((Kki,Rit)=>{"use strict";var{Duplex:Vki}=K("stream"),{randomFillSync:_Mn}=K("crypto"),{types:{isUint8Array:kMn}}=K("util"),kit=IB(),{EMPTY_BUFFER:TMn,kWebSocket:RMn,NOOP:BMn}=X0(),{isBlob:SB,isValidStatusCode:DMn}=vB(),{mask:Tit,toBuffer:cv}=oU(),fh=Symbol("kByteLength"),MMn=Buffer.alloc(4),IV=8*1024,uv,_B=IV,ef=0,PMn=1,NMn=2,f0e=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=ef,this.onerror=BMn,this[RMn]=void 0}static frame(e,n){let r,i=!1,o=2,s=!1;n.mask&&(r=n.maskBuffer||MMn,n.generateMask?n.generateMask(r):(_B===IV&&(uv===void 0&&(uv=Buffer.alloc(IV)),_Mn(uv,0,IV),_B=0),r[0]=uv[_B++],r[1]=uv[_B++],r[2]=uv[_B++],r[3]=uv[_B++]),s=(r[0]|r[1]|r[2]|r[3])===0,o=6);let a;typeof e=="string"?(!n.mask||s)&&n[fh]!==void 0?a=n[fh]:(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?(Tit(e,r,u,o,a),[u]):(Tit(e,r,e,0,a),[u,e])):[u,e]}close(e,n,r,i){let o;if(e===void 0)o=TMn;else{if(typeof e!="number"||!DMn(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(kMn(n))o.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[fh]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ef?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):SB(e)?(i=e.size,o=!1):(e=cv(e),i=e.length,o=cv.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[fh]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};SB(e)?this._state!==ef?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==ef?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):SB(e)?(i=e.size,o=!1):(e=cv(e),i=e.length,o=cv.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[fh]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};SB(e)?this._state!==ef?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==ef?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}send(e,n,r){let i=this._extensions[kit.extensionName],o=n.binary?2:1,s=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):SB(e)?(a=e.size,c=!1):(e=cv(e),a=e.length,c=cv.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={[fh]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:s};SB(e)?this._state!==ef?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==ef?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[fh],this._state=NMn,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(g0e,this,a,i);return}this._bufferedBytes-=r[fh];let s=cv(o);n?this.dispatch(s,n,r,i):(this._state=ef,this.sendFrame(t.frame(s,r),i),this.dequeue())}).catch(o=>{process.nextTick(OMn,this,o,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let o=this._extensions[kit.extensionName];this._bufferedBytes+=r[fh],this._state=PMn,o.compress(e,r.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");g0e(this,c,i);return}this._bufferedBytes-=r[fh],this._state=ef,r.readOnly=!1,this.sendFrame(t.frame(a,r),i),this.dequeue()})}dequeue(){for(;this._state===ef&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][fh],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][fh],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=f0e;function g0e(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 OMn(t,e,n){g0e(t,e,n),t.onerror(e)}});var Fit=L((Yki,Qit)=>{"use strict";var{kForOnEventAttribute:aU,kListener:y0e}=X0(),Bit=Symbol("kCode"),Dit=Symbol("kData"),Mit=Symbol("kError"),Pit=Symbol("kMessage"),Nit=Symbol("kReason"),kB=Symbol("kTarget"),Oit=Symbol("kType"),Lit=Symbol("kWasClean"),ey=class{constructor(e){this[kB]=null,this[Oit]=e}get target(){return this[kB]}get type(){return this[Oit]}};Object.defineProperty(ey.prototype,"target",{enumerable:!0});Object.defineProperty(ey.prototype,"type",{enumerable:!0});var lv=class extends ey{constructor(e,n={}){super(e),this[Bit]=n.code===void 0?0:n.code,this[Nit]=n.reason===void 0?"":n.reason,this[Lit]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Bit]}get reason(){return this[Nit]}get wasClean(){return this[Lit]}};Object.defineProperty(lv.prototype,"code",{enumerable:!0});Object.defineProperty(lv.prototype,"reason",{enumerable:!0});Object.defineProperty(lv.prototype,"wasClean",{enumerable:!0});var TB=class extends ey{constructor(e,n={}){super(e),this[Mit]=n.error===void 0?null:n.error,this[Pit]=n.message===void 0?"":n.message}get error(){return this[Mit]}get message(){return this[Pit]}};Object.defineProperty(TB.prototype,"error",{enumerable:!0});Object.defineProperty(TB.prototype,"message",{enumerable:!0});var cU=class extends ey{constructor(e,n={}){super(e),this[Dit]=n.data===void 0?null:n.data}get data(){return this[Dit]}};Object.defineProperty(cU.prototype,"data",{enumerable:!0});var LMn={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[aU]&&i[y0e]===e&&!i[aU])return;let r;if(t==="message")r=function(o,s){let a=new cU("message",{data:s?o:o.toString()});a[kB]=this,vV(e,this,a)};else if(t==="close")r=function(o,s){let a=new lv("close",{code:o,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[kB]=this,vV(e,this,a)};else if(t==="error")r=function(o){let s=new TB("error",{error:o,message:o.message});s[kB]=this,vV(e,this,s)};else if(t==="open")r=function(){let o=new ey("open");o[kB]=this,vV(e,this,o)};else return;r[aU]=!!n[aU],r[y0e]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[y0e]===e&&!n[aU]){this.removeListener(t,n);break}}};Qit.exports={CloseEvent:lv,ErrorEvent:TB,Event:ey,EventTarget:LMn,MessageEvent:cU};function vV(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var SV=L((Jki,Uit)=>{"use strict";var{tokenChars:uU}=vB();function Mg(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function QMn(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?(Mg(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),Mg(n,t.slice(c,l),!0),u===44&&(Mg(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),Mg(n,a,h),u===44&&(Mg(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?Mg(e,p,n):(a===void 0?Mg(n,p,!0):r?Mg(n,a,p.replace(/\\/g,"")):Mg(n,a,p),Mg(e,s,n)),e}function FMn(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(", ")}Uit.exports={format:FMn,parse:QMn}});var RV=L((eTi,Xit)=>{"use strict";var UMn=K("events"),$Mn=K("https"),WMn=K("http"),Hit=K("net"),HMn=K("tls"),{randomBytes:GMn,createHash:qMn}=K("crypto"),{Duplex:Xki,Readable:Zki}=K("stream"),{URL:E0e}=K("url"),Iw=IB(),jMn=m0e(),zMn=A0e(),{isBlob:VMn}=vB(),{BINARY_TYPES:$it,CLOSE_TIMEOUT:KMn,EMPTY_BUFFER:_V,GUID:YMn,kForOnEventAttribute:w0e,kListener:JMn,kStatusCode:XMn,kWebSocket:Za,NOOP:Git}=X0(),{EventTarget:{addEventListener:ZMn,removeEventListener:ePn}}=Fit(),{format:tPn,parse:nPn}=SV(),{toBuffer:rPn}=oU(),qit=Symbol("kAborted"),x0e=[8,13],ty=["CONNECTING","OPEN","CLOSING","CLOSED"],iPn=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Go=class t extends UMn{constructor(e,n,r){super(),this._binaryType=$it[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=_V,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]),jit(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){$it.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 jMn({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 zMn(e,this._extensions,r.generateMask);this._receiver=i,this._sender=o,this._socket=e,i[Za]=this,o[Za]=this,e[Za]=this,i.on("conclude",aPn),i.on("drain",cPn),i.on("error",uPn),i.on("message",lPn),i.on("ping",dPn),i.on("pong",pPn),o.onerror=hPn,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Kit),e.on("data",TV),e.on("end",Yit),e.on("error",Jit),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[Iw.extensionName]&&this._extensions[Iw.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())}),Vit(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){b0e(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||_V,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){b0e(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||_V,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){b0e(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Iw.extensionName]||(i.compress=!1),this._sender.send(e||_V,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(Go,"CONNECTING",{enumerable:!0,value:ty.indexOf("CONNECTING")});Object.defineProperty(Go.prototype,"CONNECTING",{enumerable:!0,value:ty.indexOf("CONNECTING")});Object.defineProperty(Go,"OPEN",{enumerable:!0,value:ty.indexOf("OPEN")});Object.defineProperty(Go.prototype,"OPEN",{enumerable:!0,value:ty.indexOf("OPEN")});Object.defineProperty(Go,"CLOSING",{enumerable:!0,value:ty.indexOf("CLOSING")});Object.defineProperty(Go.prototype,"CLOSING",{enumerable:!0,value:ty.indexOf("CLOSING")});Object.defineProperty(Go,"CLOSED",{enumerable:!0,value:ty.indexOf("CLOSED")});Object.defineProperty(Go.prototype,"CLOSED",{enumerable:!0,value:ty.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Go.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Go.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[w0e])return e[JMn];return null},set(e){for(let n of this.listeners(t))if(n[w0e]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[w0e]:!0})}})});Go.prototype.addEventListener=ZMn;Go.prototype.removeEventListener=ePn;Xit.exports=Go;function jit(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:KMn,protocolVersion:x0e[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,!x0e.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${x0e.join(", ")})`);let o;if(e instanceof E0e)o=e;else try{o=new E0e(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;kV(t,f);return}let u=s?443:80,l=GMn(16).toString("base64"),d=s?$Mn.request:WMn.request,p=new Set,h;if(i.createConnection=i.createConnection||(s?sPn:oPn),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 Iw({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=tPn({[Iw.extensionName]:h.offer()})),n.length){for(let f of n){if(typeof f!="string"||!iPn.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,y]of Object.entries(f))r.headers[g.toLowerCase()]=y}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[qit]||(m=t._req=null,kV(t,f))}),m.on("response",f=>{let g=f.headers.location,y=f.statusCode;if(g&&i.followRedirects&&y>=300&&y<400){if(++t._redirects>i.maxRedirects){np(t,m,"Maximum redirects exceeded");return}m.abort();let x;try{x=new E0e(g,e)}catch{let v=new SyntaxError(`Invalid URL: ${g}`);kV(t,v);return}jit(t,x,n,r)}else t.emit("unexpected-response",m,f)||np(t,m,`Unexpected server response: ${f.statusCode}`)}),m.on("upgrade",(f,g,y)=>{if(t.emit("upgrade",f),t.readyState!==Go.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=qMn("sha1").update(l+YMn).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=nPn(_)}catch{np(t,g,"Invalid Sec-WebSocket-Extensions header");return}let B=Object.keys(T);if(B.length!==1||B[0]!==Iw.extensionName){np(t,g,"Server indicated an extension that was not requested");return}try{h.accept(T[Iw.extensionName])}catch{np(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Iw.extensionName]=h}t.setSocket(g,y,{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 kV(t,e){t._readyState=Go.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function oPn(t){return t.path=t.socketPath,Hit.connect(t)}function sPn(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Hit.isIP(t.host)?"":t.host),HMn.connect(t)}function np(t,e,n){t._readyState=Go.CLOSING;let r=new Error(n);Error.captureStackTrace(r,np),e.setHeader?(e[qit]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(kV,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function b0e(t,e,n){if(e){let r=VMn(e)?e.size:rPn(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${ty[t.readyState]})`);process.nextTick(n,r)}}function aPn(t,e){let n=this[Za];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Za]!==void 0&&(n._socket.removeListener("data",TV),process.nextTick(zit,n._socket),t===1005?n.close():n.close(t,e))}function cPn(){let t=this[Za];t.isPaused||t._socket.resume()}function uPn(t){let e=this[Za];e._socket[Za]!==void 0&&(e._socket.removeListener("data",TV),process.nextTick(zit,e._socket),e.close(t[XMn])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Wit(){this[Za].emitClose()}function lPn(t,e){this[Za].emit("message",t,e)}function dPn(t){let e=this[Za];e._autoPong&&e.pong(t,!this._isServer,Git),e.emit("ping",t)}function pPn(t){this[Za].emit("pong",t)}function zit(t){t.resume()}function hPn(t){let e=this[Za];e.readyState!==Go.CLOSED&&(e.readyState===Go.OPEN&&(e._readyState=Go.CLOSING,Vit(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Vit(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Kit(){let t=this[Za];if(this.removeListener("close",Kit),this.removeListener("data",TV),this.removeListener("end",Yit),t._readyState=Go.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[Za]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Wit),t._receiver.on("finish",Wit))}function TV(t){this[Za]._receiver.write(t)||this.pause()}function Yit(){let t=this[Za];t._readyState=Go.CLOSING,t._receiver.end(),this.end()}function Jit(){let t=this[Za];this.removeListener("error",Jit),this.on("error",Git),t&&(t._readyState=Go.CLOSING,this.destroy())}});var not=L((nTi,tot)=>{"use strict";var tTi=RV(),{Duplex:mPn}=K("stream");function Zit(t){t.emit("close")}function fPn(){!this.destroyed&&this._writableState.finished&&this.destroy()}function eot(t){this.removeListener("error",eot),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function gPn(t,e){let n=!0,r=new mPn({...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(Zit,r);return}let s=!1;t.once("error",function(c){s=!0,o(c)}),t.once("close",function(){s||o(i),process.nextTick(Zit,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",fPn),r.on("error",eot),r}tot.exports=gPn});var C0e=L((rTi,rot)=>{"use strict";var{tokenChars:APn}=vB();function yPn(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&&APn[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}rot.exports={parse:yPn}});var lot=L((oTi,uot)=>{"use strict";var EPn=K("events"),BV=K("http"),{Duplex:iTi}=K("stream"),{createHash:wPn}=K("crypto"),iot=SV(),dv=IB(),xPn=C0e(),bPn=RV(),{CLOSE_TIMEOUT:CPn,GUID:IPn,kWebSocket:vPn}=X0(),SPn=/^[+/0-9A-Za-z]{22}==$/,oot=0,sot=1,cot=2,I0e=class extends EPn{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:CPn,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:bPn,...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=BV.createServer((r,i)=>{let o=BV.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=_Pn(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=oot}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===cot){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!==sot)if(this._state=sot,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",aot);let o=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){pv(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){pv(this,e,n,400,"Invalid Upgrade header");return}if(o===void 0||!SPn.test(o)){pv(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){pv(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=xPn.parse(c)}catch{pv(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 dv({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=iot.parse(l);h[dv.extensionName]&&(p.accept(h[dv.extensionName]),d[dv.extensionName]=p)}catch{pv(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[vPn])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>oot)return dU(o,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${wPn("sha1").update(n+IPn).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[dv.extensionName]){let d=e[dv.extensionName].params,p=iot.format({[dv.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
|
|
102
102
|
`)),o.removeListener("error",aot),l.setSocket(o,s,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(l),l.on("close",()=>{this.clients.delete(l),this._shouldEmitClose&&!this.clients.size&&process.nextTick(lU,this)})),a(l,i)}};uot.exports=I0e;function _Pn(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function lU(t){t._state=cot,t.emit("close")}function aot(){this.destroy()}function dU(t,e,n,r){n=n||BV.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${BV.STATUS_CODES[e]}\r
|
|
103
103
|
`+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r
|