@tocca-systems/twp-cli 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.public.md +80 -0
- package/LICENSE +47 -0
- package/README.md +279 -0
- package/dist/THIRD-PARTY-NOTICES.md +1239 -0
- package/dist/ai-dispatch-T6PJ4DUG.js +82 -0
- package/dist/app-S33SNSH5.js +1370 -0
- package/dist/chunk-3WJHTPOZ.js +48 -0
- package/dist/chunk-4QI5NX4C.js +6 -0
- package/dist/chunk-5QCAIKFE.js +9 -0
- package/dist/chunk-63LDNYGW.js +23 -0
- package/dist/chunk-7ZVTACQS.js +8 -0
- package/dist/chunk-DIMZRTLE.js +37 -0
- package/dist/chunk-DXXFUNYN.js +7 -0
- package/dist/chunk-FQDYLZV3.js +6 -0
- package/dist/chunk-GY7KI5E5.js +4 -0
- package/dist/chunk-II5RVJQN.js +3 -0
- package/dist/chunk-IM4H52FC.js +109 -0
- package/dist/chunk-J7QYPKVK.js +18 -0
- package/dist/chunk-KCXVV45F.js +16 -0
- package/dist/chunk-L37NS5L2.js +8 -0
- package/dist/chunk-N2UVRM3Z.js +5 -0
- package/dist/chunk-N3B737KO.js +57 -0
- package/dist/chunk-NERYSBA4.js +9 -0
- package/dist/chunk-NHYMHCAT.js +4 -0
- package/dist/chunk-NNOYO67O.js +7 -0
- package/dist/chunk-PMOUHEJQ.js +5 -0
- package/dist/chunk-Q7YSSWTR.js +33 -0
- package/dist/chunk-RQFG3OUL.js +41 -0
- package/dist/chunk-RZVI6PMW.js +5 -0
- package/dist/chunk-VSJBJXZO.js +3 -0
- package/dist/chunk-VSQXY2VX.js +42 -0
- package/dist/chunk-WVS4W5FY.js +16 -0
- package/dist/chunk-ZZ5EYKCK.js +58 -0
- package/dist/cli.js +132 -0
- package/dist/commands-QKNOQRWT.js +60 -0
- package/dist/commands-T47RY6EH.js +365 -0
- package/dist/devtools-VZW7JDIG.js +131 -0
- package/dist/dist-HZIZTJ4O.js +93 -0
- package/dist/fuzzysort-DFVKV4B4.js +3 -0
- package/dist/oneshot-JD5LINMX.js +18 -0
- package/dist/project-BEY4CNSF.js +13 -0
- package/dist/run-EDV5273K.js +58 -0
- package/dist/schedule-command-LWUBXHBQ.js +13 -0
- package/dist/setup-GY674TII.js +74 -0
- package/dist/task-MQYRE4QC.js +135 -0
- package/dist/update-WDWUECN7.js +21 -0
- package/package.json +73 -0
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
|
+
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
+
import{__commonJS,__require,__toESM}from"./chunk-VSJBJXZO.js";var require_constants=__commonJS({"node_modules/ws/lib/constants.js"(exports,module){"use strict";var BINARY_TYPES=["nodebuffer","arraybuffer","fragments"];var hasBlob=typeof Blob!=="undefined";if(hasBlob)BINARY_TYPES.push("blob");module.exports={BINARY_TYPES,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("webs\
|
|
4
|
+
ocket"),NOOP:()=>{}}}});var require_buffer_util=__commonJS({"node_modules/ws/lib/buffer-util.js"(exports,module){"use strict";var{EMPTY_BUFFER}=require_constants();var FastBuffer=Buffer[Symbol.species];function concat(list,totalLength){if(list.length===0)return EMPTY_BUFFER;if(list.length===1)return list[0];const target=Buffer.allocUnsafe(totalLength);let offset=0;for(let i=0;i<list.length;i++){const buf=list[i];target.set(buf,offset);offset+=buf.length}if(offset<totalLength){return new FastBuffer(target.buffer,target.
|
|
5
|
+
byteOffset,offset)}return target}function _mask(source,mask,output,offset,length){for(let i=0;i<length;i++){output[offset+i]=source[i]^mask[i&3]}}function _unmask(buffer,mask){for(let i=0;i<buffer.length;i++){buffer[i]^=mask[i&3]}}function toArrayBuffer(buf){if(buf.length===buf.buffer.byteLength){return buf.buffer}return buf.buffer.slice(buf.byteOffset,buf.byteOffset+buf.length)}function toBuffer(data){toBuffer.readOnly=true;if(Buffer.isBuffer(data))return data;let buf;if(data instanceof ArrayBuffer){
|
|
6
|
+
buf=new FastBuffer(data)}else if(ArrayBuffer.isView(data)){buf=new FastBuffer(data.buffer,data.byteOffset,data.byteLength)}else{buf=Buffer.from(data);toBuffer.readOnly=false}return buf}module.exports={concat,mask:_mask,toArrayBuffer,toBuffer,unmask:_unmask};if(!process.env.WS_NO_BUFFER_UTIL){try{const bufferUtil=__require("bufferutil");module.exports.mask=function(source,mask,output,offset,length){if(length<48)_mask(source,mask,output,offset,length);else bufferUtil.mask(source,mask,output,offset,
|
|
7
|
+
length)};module.exports.unmask=function(buffer,mask){if(buffer.length<32)_unmask(buffer,mask);else bufferUtil.unmask(buffer,mask)}}catch(e){}}}});var require_limiter=__commonJS({"node_modules/ws/lib/limiter.js"(exports,module){"use strict";var kDone=Symbol("kDone");var kRun=Symbol("kRun");var Limiter=class{constructor(concurrency){this[kDone]=()=>{this.pending--;this[kRun]()};this.concurrency=concurrency||Infinity;this.jobs=[];this.pending=0}add(job){this.jobs.push(job);this[kRun]()}[kRun](){if(this.pending===this.concurrency)return;if(this.jobs.length){const job=this.jobs.shift();this.pending++;job(this[kDone])}}};module.exports=Limiter}});var require_permessage_deflate=__commonJS({"node_modules/ws/lib/permessage-deflate.js"(exports,module){"use strict";var zlib=__require("zlib");var bufferUtil=require_buffer_util();var Limiter=require_limiter();var{kStatusCode}=require_constants();var FastBuffer=Buffer[Symbol.species];var TRAILER=Buffer.from([0,0,255,255]);var kPerMessageDeflate=Symbol("permessage-deflate");var kTotalLength=Symbol("total-length");var kCallback=Symbol("callback");var kBuffers=Symbol("buffers");var kError=Symbol("e\
|
|
8
|
+
rror");var zlibLimiter;var PerMessageDeflate2=class{constructor(options){this._options=options||{};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;if(!zlibLimiter){const concurrency=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zlibLimiter=new Limiter(concurrency)}}static get extensionName(){return"per\
|
|
9
|
+
message-deflate"}offer(){const params={};if(this._options.serverNoContextTakeover){params.server_no_context_takeover=true}if(this._options.clientNoContextTakeover){params.client_no_context_takeover=true}if(this._options.serverMaxWindowBits){params.server_max_window_bits=this._options.serverMaxWindowBits}if(this._options.clientMaxWindowBits){params.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits==null){params.client_max_window_bits=true}return params}accept(configurations){
|
|
10
|
+
configurations=this.normalizeParams(configurations);this.params=this._isServer?this.acceptAsServer(configurations):this.acceptAsClient(configurations);return this.params}cleanup(){if(this._inflate){this._inflate.close();this._inflate=null}if(this._deflate){const callback=this._deflate[kCallback];this._deflate.close();this._deflate=null;if(callback){callback(new Error("The deflate stream was closed while data was being processed"))}}}acceptAsServer(offers){const opts=this._options;const accepted=offers.
|
|
11
|
+
find(params=>{if(opts.serverNoContextTakeover===false&¶ms.server_no_context_takeover||params.server_max_window_bits&&(opts.serverMaxWindowBits===false||typeof opts.serverMaxWindowBits==="number"&&opts.serverMaxWindowBits>params.server_max_window_bits)||typeof opts.clientMaxWindowBits==="number"&&(typeof params.client_max_window_bits==="number"?opts.clientMaxWindowBits>params.client_max_window_bits:!params.client_max_window_bits)){return false}return true});if(!accepted){throw new Error("None\
|
|
12
|
+
of the extension offers can be accepted")}if(opts.serverNoContextTakeover){accepted.server_no_context_takeover=true}if(opts.clientNoContextTakeover){accepted.client_no_context_takeover=true}if(typeof opts.serverMaxWindowBits==="number"){accepted.server_max_window_bits=opts.serverMaxWindowBits}if(typeof opts.clientMaxWindowBits==="number"){accepted.client_max_window_bits=opts.clientMaxWindowBits}else if(accepted.client_max_window_bits===true||opts.clientMaxWindowBits===false){delete accepted.client_max_window_bits}
|
|
13
|
+
return accepted}acceptAsClient(response){const params=response[0];if(this._options.clientNoContextTakeover===false&¶ms.client_no_context_takeover){throw new Error('Unexpected parameter "client_no_context_takeover"')}if(!params.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number"){params.client_max_window_bits=this._options.clientMaxWindowBits}}else if(this._options.clientMaxWindowBits===false||typeof this._options.clientMaxWindowBits==="number"&¶ms.client_max_window_bits>
|
|
14
|
+
this._options.clientMaxWindowBits){throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}return params}normalizeParams(configurations){configurations.forEach(params=>{Object.keys(params).forEach(key=>{let value=params[key];if(value.length>1){throw new Error(`Parameter "${key}" must have only a single value`)}value=value[0];if(key==="client_max_window_bits"){if(value!==true){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for par\
|
|
15
|
+
ameter "${key}": ${value}`)}value=num}else if(!this._isServer){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else if(key==="server_max_window_bits"){const num=+value;if(!Number.isInteger(num)||num<8||num>15){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}value=num}else if(key==="client_no_context_takeover"||key==="server_no_context_takeover"){if(value!==true){throw new TypeError(`Invalid value for parameter "${key}": ${value}`)}}else{throw new Error(
|
|
16
|
+
`Unknown parameter "${key}"`)}params[key]=value})});return configurations}decompress(data,fin,callback){zlibLimiter.add(done=>{this._decompress(data,fin,(err,result)=>{done();callback(err,result)})})}compress(data,fin,callback){zlibLimiter.add(done=>{this._compress(data,fin,(err,result)=>{done();callback(err,result)})})}_decompress(data,fin,callback){const endpoint=this._isServer?"client":"server";if(!this._inflate){const key=`${endpoint}_max_window_bits`;const windowBits=typeof this.params[key]!==
|
|
17
|
+
"number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._inflate=zlib.createInflateRaw({...this._options.zlibInflateOptions,windowBits});this._inflate[kPerMessageDeflate]=this;this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];this._inflate.on("error",inflateOnError);this._inflate.on("data",inflateOnData)}this._inflate[kCallback]=callback;this._inflate.write(data);if(fin)this._inflate.write(TRAILER);this._inflate.flush(()=>{const err=this._inflate[kError];if(err){this._inflate.close();this.
|
|
18
|
+
_inflate=null;callback(err);return}const data2=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);if(this._inflate._readableState.endEmitted){this._inflate.close();this._inflate=null}else{this._inflate[kTotalLength]=0;this._inflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._inflate.reset()}}callback(null,data2)})}_compress(data,fin,callback){const endpoint=this._isServer?"server":"client";if(!this._deflate){const key=`${endpoint}_max_window_bit\
|
|
19
|
+
s`;const windowBits=typeof this.params[key]!=="number"?zlib.Z_DEFAULT_WINDOWBITS:this.params[key];this._deflate=zlib.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits});this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];this._deflate.on("data",deflateOnData)}this._deflate[kCallback]=callback;this._deflate.write(data);this._deflate.flush(zlib.Z_SYNC_FLUSH,()=>{if(!this._deflate){return}let data2=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);if(fin){data2=
|
|
20
|
+
new FastBuffer(data2.buffer,data2.byteOffset,data2.length-4)}this._deflate[kCallback]=null;this._deflate[kTotalLength]=0;this._deflate[kBuffers]=[];if(fin&&this.params[`${endpoint}_no_context_takeover`]){this._deflate.reset()}callback(null,data2)})}};module.exports=PerMessageDeflate2;function deflateOnData(chunk){this[kBuffers].push(chunk);this[kTotalLength]+=chunk.length}function inflateOnData(chunk){this[kTotalLength]+=chunk.length;if(this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=
|
|
21
|
+
this[kPerMessageDeflate]._maxPayload){this[kBuffers].push(chunk);return}this[kError]=new RangeError("Max payload size exceeded");this[kError].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";this[kError][kStatusCode]=1009;this.removeListener("data",inflateOnData);this.reset()}function inflateOnError(err){this[kPerMessageDeflate]._inflate=null;if(this[kError]){this[kCallback](this[kError]);return}err[kStatusCode]=1007;this[kCallback](err)}}});var require_validation=__commonJS({"node_modules/ws/lib/validation.js"(exports,module){"use strict";var{isUtf8}=__require("buffer");var{hasBlob}=require_constants();var tokenChars=[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 isValidStatusCode(code){return code>=1e3&&code<=1014&&
|
|
22
|
+
code!==1004&&code!==1005&&code!==1006||code>=3e3&&code<=4999}function _isValidUTF8(buf){const len=buf.length;let i=0;while(i<len){if((buf[i]&128)===0){i++}else if((buf[i]&224)===192){if(i+1===len||(buf[i+1]&192)!==128||(buf[i]&254)===192){return false}i+=2}else if((buf[i]&240)===224){if(i+2>=len||(buf[i+1]&192)!==128||(buf[i+2]&192)!==128||buf[i]===224&&(buf[i+1]&224)===128||buf[i]===237&&(buf[i+1]&224)===160){return false}i+=3}else if((buf[i]&248)===240){if(i+3>=len||(buf[i+1]&192)!==128||(buf[i+
|
|
23
|
+
2]&192)!==128||(buf[i+3]&192)!==128||buf[i]===240&&(buf[i+1]&240)===128||buf[i]===244&&buf[i+1]>143||buf[i]>244){return false}i+=4}else{return false}}return true}function isBlob(value){return hasBlob&&typeof value==="object"&&typeof value.arrayBuffer==="function"&&typeof value.type==="string"&&typeof value.stream==="function"&&(value[Symbol.toStringTag]==="Blob"||value[Symbol.toStringTag]==="File")}module.exports={isBlob,isValidStatusCode,isValidUTF8:_isValidUTF8,tokenChars};if(isUtf8){module.exports.
|
|
24
|
+
isValidUTF8=function(buf){return buf.length<24?_isValidUTF8(buf):isUtf8(buf)}}else if(!process.env.WS_NO_UTF_8_VALIDATE){try{const isValidUTF8=__require("utf-8-validate");module.exports.isValidUTF8=function(buf){return buf.length<32?_isValidUTF8(buf):isValidUTF8(buf)}}catch(e){}}}});var require_receiver=__commonJS({"node_modules/ws/lib/receiver.js"(exports,module){"use strict";var{Writable}=__require("stream");var PerMessageDeflate2=require_permessage_deflate();var{BINARY_TYPES,EMPTY_BUFFER,kStatusCode,kWebSocket}=require_constants();var{concat,toArrayBuffer,unmask}=require_buffer_util();var{isValidStatusCode,isValidUTF8}=require_validation();var FastBuffer=Buffer[Symbol.species];var GET_INFO=0;var GET_PAYLOAD_LENGTH_16=1;var GET_PAYLOAD_LENGTH_64=2;var GET_MASK=3;var GET_DATA=4;
|
|
25
|
+
var INFLATING=5;var DEFER_EVENT=6;var Receiver2=class extends Writable{constructor(options={}){super();this._allowSynchronousEvents=options.allowSynchronousEvents!==void 0?options.allowSynchronousEvents:true;this._binaryType=options.binaryType||BINARY_TYPES[0];this._extensions=options.extensions||{};this._isServer=!!options.isServer;this._maxBufferedChunks=options.maxBufferedChunks|0;this._maxFragments=options.maxFragments|0;this._maxPayload=options.maxPayload|0;this._skipUTF8Validation=!!options.
|
|
26
|
+
skipUTF8Validation;this[kWebSocket]=void 0;this._bufferedBytes=0;this._buffers=[];this._compressed=false;this._payloadLength=0;this._mask=void 0;this._fragmented=0;this._masked=false;this._fin=false;this._opcode=0;this._totalPayloadLength=0;this._messageLength=0;this._numFragments=0;this._fragments=[];this._errored=false;this._loop=false;this._state=GET_INFO}_write(chunk,encoding,cb){if(this._opcode===8&&this._state==GET_INFO)return cb();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){
|
|
27
|
+
cb(this.createError(RangeError,"Too many buffered chunks",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=chunk.length;this._buffers.push(chunk);this.startLoop(cb)}consume(n){this._bufferedBytes-=n;if(n===this._buffers[0].length)return this._buffers.shift();if(n<this._buffers[0].length){const buf=this._buffers[0];this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n);return new FastBuffer(buf.buffer,buf.byteOffset,n)}const dst=Buffer.allocUnsafe(n);do{
|
|
28
|
+
const buf=this._buffers[0];const offset=dst.length-n;if(n>=buf.length){dst.set(this._buffers.shift(),offset)}else{dst.set(new Uint8Array(buf.buffer,buf.byteOffset,n),offset);this._buffers[0]=new FastBuffer(buf.buffer,buf.byteOffset+n,buf.length-n)}n-=buf.length}while(n>0);return dst}startLoop(cb){this._loop=true;do{switch(this._state){case GET_INFO:this.getInfo(cb);break;case GET_PAYLOAD_LENGTH_16:this.getPayloadLength16(cb);break;case GET_PAYLOAD_LENGTH_64:this.getPayloadLength64(cb);break;case GET_MASK:
|
|
29
|
+
this.getMask();break;case GET_DATA:this.getData(cb);break;case INFLATING:case DEFER_EVENT:this._loop=false;return}}while(this._loop);if(!this._errored)cb()}getInfo(cb){if(this._bufferedBytes<2){this._loop=false;return}const buf=this.consume(2);if((buf[0]&48)!==0){const error=this.createError(RangeError,"RSV2 and RSV3 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_2_3");cb(error);return}const compressed=(buf[0]&64)===64;if(compressed&&!this._extensions[PerMessageDeflate2.extensionName]){const error=this.
|
|
30
|
+
createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}this._fin=(buf[0]&128)===128;this._opcode=buf[0]&15;this._payloadLength=buf[1]&127;if(this._opcode===0){if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(!this._fragmented){const error=this.createError(RangeError,"invalid opcode 0",true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._opcode=this._fragmented}else if(this.
|
|
31
|
+
_opcode===1||this._opcode===2){if(this._fragmented){const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}this._compressed=compressed}else if(this._opcode>7&&this._opcode<11){if(!this._fin){const error=this.createError(RangeError,"FIN must be set",true,1002,"WS_ERR_EXPECTED_FIN");cb(error);return}if(compressed){const error=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");cb(error);return}if(this.
|
|
32
|
+
_payloadLength>125||this._opcode===8&&this._payloadLength===1){const error=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,true,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");cb(error);return}}else{const error=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");cb(error);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;this._masked=(buf[1]&128)===128;if(this._isServer){if(!this._masked){const error=this.createError(
|
|
33
|
+
RangeError,"MASK must be set",true,1002,"WS_ERR_EXPECTED_MASK");cb(error);return}}else if(this._masked){const error=this.createError(RangeError,"MASK must be clear",true,1002,"WS_ERR_UNEXPECTED_MASK");cb(error);return}if(this._payloadLength===126)this._state=GET_PAYLOAD_LENGTH_16;else if(this._payloadLength===127)this._state=GET_PAYLOAD_LENGTH_64;else this.haveLength(cb)}getPayloadLength16(cb){if(this._bufferedBytes<2){this._loop=false;return}this._payloadLength=this.consume(2).readUInt16BE(0);this.
|
|
34
|
+
haveLength(cb)}getPayloadLength64(cb){if(this._bufferedBytes<8){this._loop=false;return}const buf=this.consume(8);const num=buf.readUInt32BE(0);if(num>Math.pow(2,53-32)-1){const error=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",false,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");cb(error);return}this._payloadLength=num*Math.pow(2,32)+buf.readUInt32BE(4);this.haveLength(cb)}haveLength(cb){if(this._payloadLength&&this._opcode<8){this._totalPayloadLength+=this.
|
|
35
|
+
_payloadLength;if(this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}}if(this._masked)this._state=GET_MASK;else this._state=GET_DATA}getMask(){if(this._bufferedBytes<4){this._loop=false;return}this._mask=this.consume(4);this._state=GET_DATA}getData(cb){let data=EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=false;
|
|
36
|
+
return}data=this.consume(this._payloadLength);if(this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0){unmask(data,this._mask)}}if(this._opcode>7){this.controlMessage(data,cb);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){const error=this.createError(RangeError,"Too many message fragments",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");cb(error);return}if(this._compressed){this._state=INFLATING;this.decompress(data,cb);return}if(data.length){this._messageLength=
|
|
37
|
+
this._totalPayloadLength;this._fragments.push(data)}this.dataMessage(cb)}decompress(data,cb){const perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName];perMessageDeflate.decompress(data,this._fin,(err,buf)=>{if(err)return cb(err);if(buf.length){this._messageLength+=buf.length;if(this._messageLength>this._maxPayload&&this._maxPayload>0){const error=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");cb(error);return}this._fragments.
|
|
38
|
+
push(buf)}this.dataMessage(cb);if(this._state===GET_INFO)this.startLoop(cb)})}dataMessage(cb){if(!this._fin){this._state=GET_INFO;return}const messageLength=this._messageLength;const fragments=this._fragments;this._totalPayloadLength=0;this._messageLength=0;this._fragmented=0;this._numFragments=0;this._fragments=[];if(this._opcode===2){let data;if(this._binaryType==="nodebuffer"){data=concat(fragments,messageLength)}else if(this._binaryType==="arraybuffer"){data=toArrayBuffer(concat(fragments,messageLength))}else if(this.
|
|
39
|
+
_binaryType==="blob"){data=new Blob(fragments)}else{data=fragments}if(this._allowSynchronousEvents){this.emit("message",data,true);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",data,true);this._state=GET_INFO;this.startLoop(cb)})}}else{const buf=concat(fragments,messageLength);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}if(this._state===INFLATING||
|
|
40
|
+
this._allowSynchronousEvents){this.emit("message",buf,false);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit("message",buf,false);this._state=GET_INFO;this.startLoop(cb)})}}}controlMessage(data,cb){if(this._opcode===8){if(data.length===0){this._loop=false;this.emit("conclude",1005,EMPTY_BUFFER);this.end()}else{const code=data.readUInt16BE(0);if(!isValidStatusCode(code)){const error=this.createError(RangeError,`invalid status code ${code}`,true,1002,"WS_ERR_INVALID_C\
|
|
41
|
+
LOSE_CODE");cb(error);return}const buf=new FastBuffer(data.buffer,data.byteOffset+2,data.length-2);if(!this._skipUTF8Validation&&!isValidUTF8(buf)){const error=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");cb(error);return}this._loop=false;this.emit("conclude",code,buf);this.end()}this._state=GET_INFO;return}if(this._allowSynchronousEvents){this.emit(this._opcode===9?"ping":"pong",data);this._state=GET_INFO}else{this._state=DEFER_EVENT;setImmediate(()=>{this.emit(
|
|
42
|
+
this._opcode===9?"ping":"pong",data);this._state=GET_INFO;this.startLoop(cb)})}}createError(ErrorCtor,message,prefix,statusCode,errorCode){this._loop=false;this._errored=true;const err=new ErrorCtor(prefix?`Invalid WebSocket frame: ${message}`:message);Error.captureStackTrace(err,this.createError);err.code=errorCode;err[kStatusCode]=statusCode;return err}};module.exports=Receiver2}});var require_sender=__commonJS({"node_modules/ws/lib/sender.js"(exports,module){"use strict";var{Duplex}=__require("stream");var{randomFillSync}=__require("crypto");var{types:{isUint8Array}}=__require("util");var PerMessageDeflate2=require_permessage_deflate();var{EMPTY_BUFFER,kWebSocket,NOOP}=require_constants();var{isBlob,isValidStatusCode}=require_validation();var{mask:applyMask,toBuffer}=require_buffer_util();var kByteLength=Symbol("kByteLength");var maskBuffer=Buffer.alloc(4);var RANDOM_POOL_SIZE=8*
|
|
43
|
+
1024;var randomPool;var randomPoolPointer=RANDOM_POOL_SIZE;var DEFAULT=0;var DEFLATING=1;var GET_BLOB_DATA=2;var Sender2=class _Sender{constructor(socket,extensions,generateMask){this._extensions=extensions||{};if(generateMask){this._generateMask=generateMask;this._maskBuffer=Buffer.alloc(4)}this._socket=socket;this._firstFragment=true;this._compress=false;this._bufferedBytes=0;this._queue=[];this._state=DEFAULT;this.onerror=NOOP;this[kWebSocket]=void 0}static frame(data,options){let mask;let merge=false;
|
|
44
|
+
let offset=2;let skipMasking=false;if(options.mask){mask=options.maskBuffer||maskBuffer;if(options.generateMask){options.generateMask(mask)}else{if(randomPoolPointer===RANDOM_POOL_SIZE){if(randomPool===void 0){randomPool=Buffer.alloc(RANDOM_POOL_SIZE)}randomFillSync(randomPool,0,RANDOM_POOL_SIZE);randomPoolPointer=0}mask[0]=randomPool[randomPoolPointer++];mask[1]=randomPool[randomPoolPointer++];mask[2]=randomPool[randomPoolPointer++];mask[3]=randomPool[randomPoolPointer++]}skipMasking=(mask[0]|mask[1]|
|
|
45
|
+
mask[2]|mask[3])===0;offset=6}let dataLength;if(typeof data==="string"){if((!options.mask||skipMasking)&&options[kByteLength]!==void 0){dataLength=options[kByteLength]}else{data=Buffer.from(data);dataLength=data.length}}else{dataLength=data.length;merge=options.mask&&options.readOnly&&!skipMasking}let payloadLength=dataLength;if(dataLength>=65536){offset+=8;payloadLength=127}else if(dataLength>125){offset+=2;payloadLength=126}const target=Buffer.allocUnsafe(merge?dataLength+offset:offset);target[0]=
|
|
46
|
+
options.fin?options.opcode|128:options.opcode;if(options.rsv1)target[0]|=64;target[1]=payloadLength;if(payloadLength===126){target.writeUInt16BE(dataLength,2)}else if(payloadLength===127){target[2]=target[3]=0;target.writeUIntBE(dataLength,4,6)}if(!options.mask)return[target,data];target[1]|=128;target[offset-4]=mask[0];target[offset-3]=mask[1];target[offset-2]=mask[2];target[offset-1]=mask[3];if(skipMasking)return[target,data];if(merge){applyMask(data,mask,target,offset,dataLength);return[target]}
|
|
47
|
+
applyMask(data,mask,data,0,dataLength);return[target,data]}close(code,data,mask,cb){let buf;if(code===void 0){buf=EMPTY_BUFFER}else if(typeof code!=="number"||!isValidStatusCode(code)){throw new TypeError("First argument must be a valid error code number")}else if(data===void 0||!data.length){buf=Buffer.allocUnsafe(2);buf.writeUInt16BE(code,0)}else{const length=Buffer.byteLength(data);if(length>123){throw new RangeError("The message must not be greater than 123 bytes")}buf=Buffer.allocUnsafe(2+length);
|
|
48
|
+
buf.writeUInt16BE(code,0);if(typeof data==="string"){buf.write(data,2)}else if(isUint8Array(data)){buf.set(data,2)}else{throw new TypeError("Second argument must be a string or a Uint8Array")}}const options={[kByteLength]:buf.length,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:8,readOnly:false,rsv1:false};if(this._state!==DEFAULT){this.enqueue([this.dispatch,buf,false,options,cb])}else{this.sendFrame(_Sender.frame(buf,options),cb)}}ping(data,mask,cb){let byteLength;
|
|
49
|
+
let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:9,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){
|
|
50
|
+
this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(_Sender.frame(data,options),cb)}}pong(data,mask,cb){let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(byteLength>
|
|
51
|
+
125){throw new RangeError("The data size must not be greater than 125 bytes")}const options={[kByteLength]:byteLength,fin:true,generateMask:this._generateMask,mask,maskBuffer:this._maskBuffer,opcode:10,readOnly,rsv1:false};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,false,options,cb])}else{this.getBlobData(data,false,options,cb)}}else if(this._state!==DEFAULT){this.enqueue([this.dispatch,data,false,options,cb])}else{this.sendFrame(_Sender.frame(data,options),cb)}}send(data,options,cb){
|
|
52
|
+
const perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName];let opcode=options.binary?2:1;let rsv1=options.compress;let byteLength;let readOnly;if(typeof data==="string"){byteLength=Buffer.byteLength(data);readOnly=false}else if(isBlob(data)){byteLength=data.size;readOnly=false}else{data=toBuffer(data);byteLength=data.length;readOnly=toBuffer.readOnly}if(this._firstFragment){this._firstFragment=false;if(rsv1&&perMessageDeflate&&perMessageDeflate.params[perMessageDeflate._isServer?
|
|
53
|
+
"server_no_context_takeover":"client_no_context_takeover"]){rsv1=byteLength>=perMessageDeflate._threshold}this._compress=rsv1}else{rsv1=false;opcode=0}if(options.fin)this._firstFragment=true;const opts={[kByteLength]:byteLength,fin:options.fin,generateMask:this._generateMask,mask:options.mask,maskBuffer:this._maskBuffer,opcode,readOnly,rsv1};if(isBlob(data)){if(this._state!==DEFAULT){this.enqueue([this.getBlobData,data,this._compress,opts,cb])}else{this.getBlobData(data,this._compress,opts,cb)}}else if(this.
|
|
54
|
+
_state!==DEFAULT){this.enqueue([this.dispatch,data,this._compress,opts,cb])}else{this.dispatch(data,this._compress,opts,cb)}}getBlobData(blob,compress,options,cb){this._bufferedBytes+=options[kByteLength];this._state=GET_BLOB_DATA;blob.arrayBuffer().then(arrayBuffer=>{if(this._socket.destroyed){const err=new Error("The socket was closed while the blob was being read");process.nextTick(callCallbacks,this,err,cb);return}this._bufferedBytes-=options[kByteLength];const data=toBuffer(arrayBuffer);if(!compress){
|
|
55
|
+
this._state=DEFAULT;this.sendFrame(_Sender.frame(data,options),cb);this.dequeue()}else{this.dispatch(data,compress,options,cb)}}).catch(err=>{process.nextTick(onError,this,err,cb)})}dispatch(data,compress,options,cb){if(!compress){this.sendFrame(_Sender.frame(data,options),cb);return}const perMessageDeflate=this._extensions[PerMessageDeflate2.extensionName];this._bufferedBytes+=options[kByteLength];this._state=DEFLATING;perMessageDeflate.compress(data,options.fin,(_,buf)=>{if(this._socket.destroyed){
|
|
56
|
+
const err=new Error("The socket was closed while data was being compressed");callCallbacks(this,err,cb);return}this._bufferedBytes-=options[kByteLength];this._state=DEFAULT;options.readOnly=false;this.sendFrame(_Sender.frame(buf,options),cb);this.dequeue()})}dequeue(){while(this._state===DEFAULT&&this._queue.length){const params=this._queue.shift();this._bufferedBytes-=params[3][kByteLength];Reflect.apply(params[0],this,params.slice(1))}}enqueue(params){this._bufferedBytes+=params[3][kByteLength];
|
|
57
|
+
this._queue.push(params)}sendFrame(list,cb){if(list.length===2){this._socket.cork();this._socket.write(list[0]);this._socket.write(list[1],cb);this._socket.uncork()}else{this._socket.write(list[0],cb)}}};module.exports=Sender2;function callCallbacks(sender,err,cb){if(typeof cb==="function")cb(err);for(let i=0;i<sender._queue.length;i++){const params=sender._queue[i];const callback=params[params.length-1];if(typeof callback==="function")callback(err)}}function onError(sender,err,cb){callCallbacks(
|
|
58
|
+
sender,err,cb);sender.onerror(err)}}});var require_event_target=__commonJS({"node_modules/ws/lib/event-target.js"(exports,module){"use strict";var{kForOnEventAttribute,kListener}=require_constants();var kCode=Symbol("kCode");var kData=Symbol("kData");var kError=Symbol("kError");var kMessage=Symbol("kMessage");var kReason=Symbol("kReason");var kTarget=Symbol("kTarget");var kType=Symbol("kType");var kWasClean=Symbol("kWasClean");var Event=class{constructor(type){this[kTarget]=null;this[kType]=type}get target(){return this[kTarget]}get type(){
|
|
59
|
+
return this[kType]}};Object.defineProperty(Event.prototype,"target",{enumerable:true});Object.defineProperty(Event.prototype,"type",{enumerable:true});var CloseEvent=class extends Event{constructor(type,options={}){super(type);this[kCode]=options.code===void 0?0:options.code;this[kReason]=options.reason===void 0?"":options.reason;this[kWasClean]=options.wasClean===void 0?false:options.wasClean}get code(){return this[kCode]}get reason(){return this[kReason]}get wasClean(){return this[kWasClean]}};
|
|
60
|
+
Object.defineProperty(CloseEvent.prototype,"code",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"reason",{enumerable:true});Object.defineProperty(CloseEvent.prototype,"wasClean",{enumerable:true});var ErrorEvent=class extends Event{constructor(type,options={}){super(type);this[kError]=options.error===void 0?null:options.error;this[kMessage]=options.message===void 0?"":options.message}get error(){return this[kError]}get message(){return this[kMessage]}};Object.defineProperty(ErrorEvent.
|
|
61
|
+
prototype,"error",{enumerable:true});Object.defineProperty(ErrorEvent.prototype,"message",{enumerable:true});var MessageEvent=class extends Event{constructor(type,options={}){super(type);this[kData]=options.data===void 0?null:options.data}get data(){return this[kData]}};Object.defineProperty(MessageEvent.prototype,"data",{enumerable:true});var EventTarget={addEventListener(type,handler,options={}){for(const listener of this.listeners(type)){if(!options[kForOnEventAttribute]&&listener[kListener]===
|
|
62
|
+
handler&&!listener[kForOnEventAttribute]){return}}let wrapper;if(type==="message"){wrapper=function onMessage(data,isBinary){const event=new MessageEvent("message",{data:isBinary?data:data.toString()});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="close"){wrapper=function onClose(code,message){const event=new CloseEvent("close",{code,reason:message.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});event[kTarget]=this;callListener(handler,this,event)}}else if(type===
|
|
63
|
+
"error"){wrapper=function onError(error){const event=new ErrorEvent("error",{error,message:error.message});event[kTarget]=this;callListener(handler,this,event)}}else if(type==="open"){wrapper=function onOpen(){const event=new Event("open");event[kTarget]=this;callListener(handler,this,event)}}else{return}wrapper[kForOnEventAttribute]=!!options[kForOnEventAttribute];wrapper[kListener]=handler;if(options.once){this.once(type,wrapper)}else{this.on(type,wrapper)}},removeEventListener(type,handler){for(const listener of this.
|
|
64
|
+
listeners(type)){if(listener[kListener]===handler&&!listener[kForOnEventAttribute]){this.removeListener(type,listener);break}}}};module.exports={CloseEvent,ErrorEvent,Event,EventTarget,MessageEvent};function callListener(listener,thisArg,event){if(typeof listener==="object"&&listener.handleEvent){listener.handleEvent.call(listener,event)}else{listener.call(thisArg,event)}}}});var require_extension=__commonJS({"node_modules/ws/lib/extension.js"(exports,module){"use strict";var{tokenChars}=require_validation();function push(dest,name,elem){if(dest[name]===void 0)dest[name]=[elem];else dest[name].push(elem)}function parse(header){const offers=Object.create(null);let params=Object.create(null);let mustUnescape=false;let isEscaping=false;let inQuotes=false;let extensionName;let paramName;let start=-1;let code=-1;let end=-1;let i=0;for(;i<header.length;i++){code=header.charCodeAt(
|
|
65
|
+
i);if(extensionName===void 0){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;const name=header.slice(start,end);if(code===44){push(offers,name,params);params=Object.create(null)}else{extensionName=name}start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(paramName===
|
|
66
|
+
void 0){if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(code===32||code===9){if(end===-1&&start!==-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;push(params,header.slice(start,end),true);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=void 0}start=end=-1}else if(code===61&&start!==-1&&end===-1){paramName=header.slice(start,i);start=end=-1}else{throw new SyntaxError(
|
|
67
|
+
`Unexpected character at index ${i}`)}}else{if(isEscaping){if(tokenChars[code]!==1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(start===-1)start=i;else if(!mustUnescape)mustUnescape=true;isEscaping=false}else if(inQuotes){if(tokenChars[code]===1){if(start===-1)start=i}else if(code===34&&start!==-1){inQuotes=false;end=i}else if(code===92){isEscaping=true}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}else if(code===34&&header.charCodeAt(i-1)===61){inQuotes=true}else if(end===
|
|
68
|
+
-1&&tokenChars[code]===1){if(start===-1)start=i}else if(start!==-1&&(code===32||code===9)){if(end===-1)end=i}else if(code===59||code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===-1)end=i;let value=header.slice(start,end);if(mustUnescape){value=value.replace(/\\/g,"");mustUnescape=false}push(params,paramName,value);if(code===44){push(offers,extensionName,params);params=Object.create(null);extensionName=void 0}paramName=void 0;start=end=-1}else{throw new SyntaxError(
|
|
69
|
+
`Unexpected character at index ${i}`)}}}if(start===-1||inQuotes||code===32||code===9){throw new SyntaxError("Unexpected end of input")}if(end===-1)end=i;const token=header.slice(start,end);if(extensionName===void 0){push(offers,token,params)}else{if(paramName===void 0){push(params,token,true)}else if(mustUnescape){push(params,paramName,token.replace(/\\/g,""))}else{push(params,paramName,token)}push(offers,extensionName,params)}return offers}function format(extensions){return Object.keys(extensions).
|
|
70
|
+
map(extension2=>{let configurations=extensions[extension2];if(!Array.isArray(configurations))configurations=[configurations];return configurations.map(params=>{return[extension2].concat(Object.keys(params).map(k=>{let values=params[k];if(!Array.isArray(values))values=[values];return values.map(v=>v===true?k:`${k}=${v}`).join("; ")})).join("; ")}).join(", ")}).join(", ")}module.exports={format,parse}}});var require_websocket=__commonJS({"node_modules/ws/lib/websocket.js"(exports,module){"use strict";var EventEmitter=__require("events");var https=__require("https");var http=__require("http");var net=__require("net");var tls=__require("tls");var{randomBytes,createHash}=__require("crypto");var{Duplex,Readable}=__require("stream");var{URL}=__require("url");var PerMessageDeflate2=require_permessage_deflate();var Receiver2=require_receiver();var Sender2=require_sender();var{isBlob}=require_validation();
|
|
71
|
+
var{BINARY_TYPES,CLOSE_TIMEOUT,EMPTY_BUFFER,GUID,kForOnEventAttribute,kListener,kStatusCode,kWebSocket,NOOP}=require_constants();var{EventTarget:{addEventListener,removeEventListener}}=require_event_target();var{format,parse}=require_extension();var{toBuffer}=require_buffer_util();var kAborted=Symbol("kAborted");var protocolVersions=[8,13];var readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"];var subprotocolRegex=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var WebSocket2=class _WebSocket extends EventEmitter{constructor(address,protocols,options){
|
|
72
|
+
super();this._binaryType=BINARY_TYPES[0];this._closeCode=1006;this._closeFrameReceived=false;this._closeFrameSent=false;this._closeMessage=EMPTY_BUFFER;this._closeTimer=null;this._errorEmitted=false;this._extensions={};this._paused=false;this._protocol="";this._readyState=_WebSocket.CONNECTING;this._receiver=null;this._sender=null;this._socket=null;if(address!==null){this._bufferedAmount=0;this._isServer=false;this._redirects=0;if(protocols===void 0){protocols=[]}else if(!Array.isArray(protocols)){
|
|
73
|
+
if(typeof protocols==="object"&&protocols!==null){options=protocols;protocols=[]}else{protocols=[protocols]}}initAsClient(this,address,protocols,options)}else{this._autoPong=options.autoPong;this._closeTimeout=options.closeTimeout;this._isServer=true}}get binaryType(){return this._binaryType}set binaryType(type){if(!BINARY_TYPES.includes(type))return;this._binaryType=type;if(this._receiver)this._receiver._binaryType=type}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this.
|
|
74
|
+
_socket._writableState.length+this._sender._bufferedBytes}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(socket,head,options){const receiver=new Receiver2({allowSynchronousEvents:options.allowSynchronousEvents,binaryType:this.binaryType,
|
|
75
|
+
extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:options.maxBufferedChunks,maxFragments:options.maxFragments,maxPayload:options.maxPayload,skipUTF8Validation:options.skipUTF8Validation});const sender=new Sender2(socket,this._extensions,options.generateMask);this._receiver=receiver;this._sender=sender;this._socket=socket;receiver[kWebSocket]=this;sender[kWebSocket]=this;socket[kWebSocket]=this;receiver.on("conclude",receiverOnConclude);receiver.on("drain",receiverOnDrain);receiver.
|
|
76
|
+
on("error",receiverOnError);receiver.on("message",receiverOnMessage);receiver.on("ping",receiverOnPing);receiver.on("pong",receiverOnPong);sender.onerror=senderOnError;if(socket.setTimeout)socket.setTimeout(0);if(socket.setNoDelay)socket.setNoDelay();if(head.length>0)socket.unshift(head);socket.on("close",socketOnClose);socket.on("data",socketOnData);socket.on("end",socketOnEnd);socket.on("error",socketOnError);this._readyState=_WebSocket.OPEN;this.emit("open")}emitClose(){if(!this._socket){this.
|
|
77
|
+
_readyState=_WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[PerMessageDeflate2.extensionName]){this._extensions[PerMessageDeflate2.extensionName].cleanup()}this._receiver.removeAllListeners();this._readyState=_WebSocket.CLOSED;this.emit("close",this._closeCode,this._closeMessage)}close(code,data){if(this.readyState===_WebSocket.CLOSED)return;if(this.readyState===_WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was est\
|
|
78
|
+
ablished";abortHandshake(this,this._req,msg);return}if(this.readyState===_WebSocket.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)){this._socket.end()}return}this._readyState=_WebSocket.CLOSING;this._sender.close(code,data,!this._isServer,err=>{if(err)return;this._closeFrameSent=true;if(this._closeFrameReceived||this._receiver._writableState.errorEmitted){this._socket.end()}});setCloseTimer(this)}pause(){if(this.readyState===_WebSocket.CONNECTING||
|
|
79
|
+
this.readyState===_WebSocket.CLOSED){return}this._paused=true;this._socket.pause()}ping(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=void 0}else if(typeof mask==="function"){cb=mask;mask=void 0}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===void 0)mask=!this._isServer;this._sender.ping(data||
|
|
80
|
+
EMPTY_BUFFER,mask,cb)}pong(data,mask,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof data==="function"){cb=data;data=mask=void 0}else if(typeof mask==="function"){cb=mask;mask=void 0}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}if(mask===void 0)mask=!this._isServer;this._sender.pong(data||EMPTY_BUFFER,mask,cb)}resume(){if(this.readyState===_WebSocket.
|
|
81
|
+
CONNECTING||this.readyState===_WebSocket.CLOSED){return}this._paused=false;if(!this._receiver._writableState.needDrain)this._socket.resume()}send(data,options,cb){if(this.readyState===_WebSocket.CONNECTING){throw new Error("WebSocket is not open: readyState 0 (CONNECTING)")}if(typeof options==="function"){cb=options;options={}}if(typeof data==="number")data=data.toString();if(this.readyState!==_WebSocket.OPEN){sendAfterClose(this,data,cb);return}const opts={binary:typeof data!=="string",mask:!this.
|
|
82
|
+
_isServer,compress:true,fin:true,...options};if(!this._extensions[PerMessageDeflate2.extensionName]){opts.compress=false}this._sender.send(data||EMPTY_BUFFER,opts,cb)}terminate(){if(this.readyState===_WebSocket.CLOSED)return;if(this.readyState===_WebSocket.CONNECTING){const msg="WebSocket was closed before the connection was established";abortHandshake(this,this._req,msg);return}if(this._socket){this._readyState=_WebSocket.CLOSING;this._socket.destroy()}}};Object.defineProperty(WebSocket2,"CONNE\
|
|
83
|
+
CTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket2.prototype,"CONNECTING",{enumerable:true,value:readyStates.indexOf("CONNECTING")});Object.defineProperty(WebSocket2,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket2.prototype,"OPEN",{enumerable:true,value:readyStates.indexOf("OPEN")});Object.defineProperty(WebSocket2,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket2.
|
|
84
|
+
prototype,"CLOSING",{enumerable:true,value:readyStates.indexOf("CLOSING")});Object.defineProperty(WebSocket2,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});Object.defineProperty(WebSocket2.prototype,"CLOSED",{enumerable:true,value:readyStates.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(property=>{Object.defineProperty(WebSocket2.prototype,property,{enumerable:true})});["open","error","close","message"].forEach(
|
|
85
|
+
method=>{Object.defineProperty(WebSocket2.prototype,`on${method}`,{enumerable:true,get(){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute])return listener[kListener]}return null},set(handler){for(const listener of this.listeners(method)){if(listener[kForOnEventAttribute]){this.removeListener(method,listener);break}}if(typeof handler!=="function")return;this.addEventListener(method,handler,{[kForOnEventAttribute]:true})}})});WebSocket2.prototype.addEventListener=addEventListener;
|
|
86
|
+
WebSocket2.prototype.removeEventListener=removeEventListener;module.exports=WebSocket2;function initAsClient(websocket,address,protocols,options){const opts={allowSynchronousEvents:true,autoPong:true,closeTimeout:CLOSE_TIMEOUT,protocolVersion:protocolVersions[1],maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:true,followRedirects:false,maxRedirects:10,...options,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"\
|
|
87
|
+
GET",host:void 0,path:void 0,port:void 0};websocket._autoPong=opts.autoPong;websocket._closeTimeout=opts.closeTimeout;if(!protocolVersions.includes(opts.protocolVersion)){throw new RangeError(`Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`)}let parsedUrl;if(address instanceof URL){parsedUrl=address}else{try{parsedUrl=new URL(address)}catch{throw new SyntaxError(`Invalid URL: ${address}`)}}if(parsedUrl.protocol==="http:"){parsedUrl.protocol=
|
|
88
|
+
"ws:"}else if(parsedUrl.protocol==="https:"){parsedUrl.protocol="wss:"}websocket._url=parsedUrl.href;const isSecure=parsedUrl.protocol==="wss:";const isIpcUrl=parsedUrl.protocol==="ws+unix:";let invalidUrlMessage;if(parsedUrl.protocol!=="ws:"&&!isSecure&&!isIpcUrl){invalidUrlMessage=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`}else if(isIpcUrl&&!parsedUrl.pathname){invalidUrlMessage="The URL's pathname is empty"}else if(parsedUrl.hash){invalidUrlMessage="Th\
|
|
89
|
+
e URL contains a fragment identifier"}if(invalidUrlMessage){const err=new SyntaxError(invalidUrlMessage);if(websocket._redirects===0){throw err}else{emitErrorAndClose(websocket,err);return}}const defaultPort=isSecure?443:80;const key=randomBytes(16).toString("base64");const request=isSecure?https.request:http.request;const protocolSet=new Set;let perMessageDeflate;opts.createConnection=opts.createConnection||(isSecure?tlsConnect:netConnect);opts.defaultPort=opts.defaultPort||defaultPort;opts.port=
|
|
90
|
+
parsedUrl.port||defaultPort;opts.host=parsedUrl.hostname.startsWith("[")?parsedUrl.hostname.slice(1,-1):parsedUrl.hostname;opts.headers={...opts.headers,"Sec-WebSocket-Version":opts.protocolVersion,"Sec-WebSocket-Key":key,Connection:"Upgrade",Upgrade:"websocket"};opts.path=parsedUrl.pathname+parsedUrl.search;opts.timeout=opts.handshakeTimeout;if(opts.perMessageDeflate){perMessageDeflate=new PerMessageDeflate2({...opts.perMessageDeflate,isServer:false,maxPayload:opts.maxPayload});opts.headers["Se\
|
|
91
|
+
c-WebSocket-Extensions"]=format({[PerMessageDeflate2.extensionName]:perMessageDeflate.offer()})}if(protocols.length){for(const protocol of protocols){if(typeof protocol!=="string"||!subprotocolRegex.test(protocol)||protocolSet.has(protocol)){throw new SyntaxError("An invalid or duplicated subprotocol was specified")}protocolSet.add(protocol)}opts.headers["Sec-WebSocket-Protocol"]=protocols.join(",")}if(opts.origin){if(opts.protocolVersion<13){opts.headers["Sec-WebSocket-Origin"]=opts.origin}else{
|
|
92
|
+
opts.headers.Origin=opts.origin}}if(parsedUrl.username||parsedUrl.password){opts.auth=`${parsedUrl.username}:${parsedUrl.password}`}if(isIpcUrl){const parts=opts.path.split(":");opts.socketPath=parts[0];opts.path=parts[1]}let req;if(opts.followRedirects){if(websocket._redirects===0){websocket._originalIpc=isIpcUrl;websocket._originalSecure=isSecure;websocket._originalHostOrSocketPath=isIpcUrl?opts.socketPath:parsedUrl.host;const headers=options&&options.headers;options={...options,headers:{}};if(headers){
|
|
93
|
+
for(const[key2,value]of Object.entries(headers)){options.headers[key2.toLowerCase()]=value}}}else if(websocket.listenerCount("redirect")===0){const isSameHost=isIpcUrl?websocket._originalIpc?opts.socketPath===websocket._originalHostOrSocketPath:false:websocket._originalIpc?false:parsedUrl.host===websocket._originalHostOrSocketPath;if(!isSameHost||websocket._originalSecure&&!isSecure){delete opts.headers.authorization;delete opts.headers.cookie;if(!isSameHost)delete opts.headers.host;opts.auth=void 0}}
|
|
94
|
+
if(opts.auth&&!options.headers.authorization){options.headers.authorization="Basic "+Buffer.from(opts.auth).toString("base64")}req=websocket._req=request(opts);if(websocket._redirects){websocket.emit("redirect",websocket.url,req)}}else{req=websocket._req=request(opts)}if(opts.timeout){req.on("timeout",()=>{abortHandshake(websocket,req,"Opening handshake has timed out")})}req.on("error",err=>{if(req===null||req[kAborted])return;req=websocket._req=null;emitErrorAndClose(websocket,err)});req.on("re\
|
|
95
|
+
sponse",res=>{const location=res.headers.location;const statusCode=res.statusCode;if(location&&opts.followRedirects&&statusCode>=300&&statusCode<400){if(++websocket._redirects>opts.maxRedirects){abortHandshake(websocket,req,"Maximum redirects exceeded");return}req.abort();let addr;try{addr=new URL(location,address)}catch(e){const err=new SyntaxError(`Invalid URL: ${location}`);emitErrorAndClose(websocket,err);return}initAsClient(websocket,addr,protocols,options)}else if(!websocket.emit("unexpect\
|
|
96
|
+
ed-response",req,res)){abortHandshake(websocket,req,`Unexpected server response: ${res.statusCode}`)}});req.on("upgrade",(res,socket,head)=>{websocket.emit("upgrade",res);if(websocket.readyState!==WebSocket2.CONNECTING)return;req=websocket._req=null;const upgrade=res.headers.upgrade;if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){abortHandshake(websocket,socket,"Invalid Upgrade header");return}const digest=createHash("sha1").update(key+GUID).digest("base64");if(res.headers["sec-websock\
|
|
97
|
+
et-accept"]!==digest){abortHandshake(websocket,socket,"Invalid Sec-WebSocket-Accept header");return}const serverProt=res.headers["sec-websocket-protocol"];let protError;if(serverProt!==void 0){if(!protocolSet.size){protError="Server sent a subprotocol but none was requested"}else if(!protocolSet.has(serverProt)){protError="Server sent an invalid subprotocol"}}else if(protocolSet.size){protError="Server sent no subprotocol"}if(protError){abortHandshake(websocket,socket,protError);return}if(serverProt)
|
|
98
|
+
websocket._protocol=serverProt;const secWebSocketExtensions=res.headers["sec-websocket-extensions"];if(secWebSocketExtensions!==void 0){if(!perMessageDeflate){const message="Server sent a Sec-WebSocket-Extensions header but no extension was requested";abortHandshake(websocket,socket,message);return}let extensions;try{extensions=parse(secWebSocketExtensions)}catch(err){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}const extensionNames=Object.
|
|
99
|
+
keys(extensions);if(extensionNames.length!==1||extensionNames[0]!==PerMessageDeflate2.extensionName){const message="Server indicated an extension that was not requested";abortHandshake(websocket,socket,message);return}try{perMessageDeflate.accept(extensions[PerMessageDeflate2.extensionName])}catch(err){const message="Invalid Sec-WebSocket-Extensions header";abortHandshake(websocket,socket,message);return}websocket._extensions[PerMessageDeflate2.extensionName]=perMessageDeflate}websocket.setSocket(
|
|
100
|
+
socket,head,{allowSynchronousEvents:opts.allowSynchronousEvents,generateMask:opts.generateMask,maxBufferedChunks:opts.maxBufferedChunks,maxFragments:opts.maxFragments,maxPayload:opts.maxPayload,skipUTF8Validation:opts.skipUTF8Validation})});if(opts.finishRequest){opts.finishRequest(req,websocket)}else{req.end()}}function emitErrorAndClose(websocket,err){websocket._readyState=WebSocket2.CLOSING;websocket._errorEmitted=true;websocket.emit("error",err);websocket.emitClose()}function netConnect(options){
|
|
101
|
+
options.path=options.socketPath;return net.connect(options)}function tlsConnect(options){options.path=void 0;if(!options.servername&&options.servername!==""){options.servername=net.isIP(options.host)?"":options.host}return tls.connect(options)}function abortHandshake(websocket,stream,message){websocket._readyState=WebSocket2.CLOSING;const err=new Error(message);Error.captureStackTrace(err,abortHandshake);if(stream.setHeader){stream[kAborted]=true;stream.abort();if(stream.socket&&!stream.socket.destroyed){
|
|
102
|
+
stream.socket.destroy()}process.nextTick(emitErrorAndClose,websocket,err)}else{stream.destroy(err);stream.once("error",websocket.emit.bind(websocket,"error"));stream.once("close",websocket.emitClose.bind(websocket))}}function sendAfterClose(websocket,data,cb){if(data){const length=isBlob(data)?data.size:toBuffer(data).length;if(websocket._socket)websocket._sender._bufferedBytes+=length;else websocket._bufferedAmount+=length}if(cb){const err=new Error(`WebSocket is not open: readyState ${websocket.
|
|
103
|
+
readyState} (${readyStates[websocket.readyState]})`);process.nextTick(cb,err)}}function receiverOnConclude(code,reason){const websocket=this[kWebSocket];websocket._closeFrameReceived=true;websocket._closeMessage=reason;websocket._closeCode=code;if(websocket._socket[kWebSocket]===void 0)return;websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);if(code===1005)websocket.close();else websocket.close(code,reason)}function receiverOnDrain(){const websocket=this[kWebSocket];
|
|
104
|
+
if(!websocket.isPaused)websocket._socket.resume()}function receiverOnError(err){const websocket=this[kWebSocket];if(websocket._socket[kWebSocket]!==void 0){websocket._socket.removeListener("data",socketOnData);process.nextTick(resume,websocket._socket);websocket.close(err[kStatusCode])}if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err)}}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(data,isBinary){this[kWebSocket].emit("mess\
|
|
105
|
+
age",data,isBinary)}function receiverOnPing(data){const websocket=this[kWebSocket];if(websocket._autoPong)websocket.pong(data,!this._isServer,NOOP);websocket.emit("ping",data)}function receiverOnPong(data){this[kWebSocket].emit("pong",data)}function resume(stream){stream.resume()}function senderOnError(err){const websocket=this[kWebSocket];if(websocket.readyState===WebSocket2.CLOSED)return;if(websocket.readyState===WebSocket2.OPEN){websocket._readyState=WebSocket2.CLOSING;setCloseTimer(websocket)}
|
|
106
|
+
this._socket.end();if(!websocket._errorEmitted){websocket._errorEmitted=true;websocket.emit("error",err)}}function setCloseTimer(websocket){websocket._closeTimer=setTimeout(websocket._socket.destroy.bind(websocket._socket),websocket._closeTimeout)}function socketOnClose(){const websocket=this[kWebSocket];this.removeListener("close",socketOnClose);this.removeListener("data",socketOnData);this.removeListener("end",socketOnEnd);websocket._readyState=WebSocket2.CLOSING;if(!this._readableState.endEmitted&&
|
|
107
|
+
!websocket._closeFrameReceived&&!websocket._receiver._writableState.errorEmitted&&this._readableState.length!==0){const chunk=this.read(this._readableState.length);websocket._receiver.write(chunk)}websocket._receiver.end();this[kWebSocket]=void 0;clearTimeout(websocket._closeTimer);if(websocket._receiver._writableState.finished||websocket._receiver._writableState.errorEmitted){websocket.emitClose()}else{websocket._receiver.on("error",receiverOnFinish);websocket._receiver.on("finish",receiverOnFinish)}}
|
|
108
|
+
function socketOnData(chunk){if(!this[kWebSocket]._receiver.write(chunk)){this.pause()}}function socketOnEnd(){const websocket=this[kWebSocket];websocket._readyState=WebSocket2.CLOSING;websocket._receiver.end();this.end()}function socketOnError(){const websocket=this[kWebSocket];this.removeListener("error",socketOnError);this.on("error",NOOP);if(websocket){websocket._readyState=WebSocket2.CLOSING;this.destroy()}}}});var require_stream=__commonJS({"node_modules/ws/lib/stream.js"(exports,module){"use strict";var WebSocket2=require_websocket();var{Duplex}=__require("stream");function emitClose(stream){stream.emit("close")}function duplexOnEnd(){if(!this.destroyed&&this._writableState.finished){this.destroy()}}function duplexOnError(err){this.removeListener("error",duplexOnError);this.destroy();if(this.listenerCount("error")===0){this.emit("error",err)}}function createWebSocketStream2(ws,options){let terminateOnDestroy=true;
|
|
109
|
+
const duplex=new Duplex({...options,autoDestroy:false,emitClose:false,objectMode:false,writableObjectMode:false});ws.on("message",function message(msg,isBinary){const data=!isBinary&&duplex._readableState.objectMode?msg.toString():msg;if(!duplex.push(data))ws.pause()});ws.once("error",function error(err){if(duplex.destroyed)return;terminateOnDestroy=false;duplex.destroy(err)});ws.once("close",function close(){if(duplex.destroyed)return;duplex.push(null)});duplex._destroy=function(err,callback){if(ws.
|
|
110
|
+
readyState===ws.CLOSED){callback(err);process.nextTick(emitClose,duplex);return}let called=false;ws.once("error",function error(err2){called=true;callback(err2)});ws.once("close",function close(){if(!called)callback(err);process.nextTick(emitClose,duplex)});if(terminateOnDestroy)ws.terminate()};duplex._final=function(callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._final(callback)});return}if(ws._socket===null)return;if(ws._socket._writableState.finished){callback();
|
|
111
|
+
if(duplex._readableState.endEmitted)duplex.destroy()}else{ws._socket.once("finish",function finish(){callback()});ws.close()}};duplex._read=function(){if(ws.isPaused)ws.resume()};duplex._write=function(chunk,encoding,callback){if(ws.readyState===ws.CONNECTING){ws.once("open",function open(){duplex._write(chunk,encoding,callback)});return}ws.send(chunk,callback)};duplex.on("end",duplexOnEnd);duplex.on("error",duplexOnError);return duplex}module.exports=createWebSocketStream2}});var require_subprotocol=__commonJS({"node_modules/ws/lib/subprotocol.js"(exports,module){"use strict";var{tokenChars}=require_validation();function parse(header){const protocols=new Set;let start=-1;let end=-1;let i=0;for(i;i<header.length;i++){const code=header.charCodeAt(i);if(end===-1&&tokenChars[code]===1){if(start===-1)start=i}else if(i!==0&&(code===32||code===9)){if(end===-1&&start!==-1)end=i}else if(code===44){if(start===-1){throw new SyntaxError(`Unexpected character at index ${i}`)}if(end===
|
|
112
|
+
-1)end=i;const protocol2=header.slice(start,end);if(protocols.has(protocol2)){throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`)}protocols.add(protocol2);start=end=-1}else{throw new SyntaxError(`Unexpected character at index ${i}`)}}if(start===-1||end!==-1){throw new SyntaxError("Unexpected end of input")}const protocol=header.slice(start,i);if(protocols.has(protocol)){throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`)}protocols.add(protocol);return protocols}
|
|
113
|
+
module.exports={parse}}});var require_websocket_server=__commonJS({"node_modules/ws/lib/websocket-server.js"(exports,module){"use strict";var EventEmitter=__require("events");var http=__require("http");var{Duplex}=__require("stream");var{createHash}=__require("crypto");var extension2=require_extension();var PerMessageDeflate2=require_permessage_deflate();var subprotocol2=require_subprotocol();var WebSocket2=require_websocket();var{CLOSE_TIMEOUT,GUID,kWebSocket}=require_constants();var keyRegex=/^[+/0-9A-Za-z]{22}==$/;var RUNNING=0;
|
|
114
|
+
var CLOSING=1;var CLOSED=2;var WebSocketServer2=class extends EventEmitter{constructor(options,callback){super();options={allowSynchronousEvents:true,autoPong:true,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:false,handleProtocols:null,clientTracking:true,closeTimeout:CLOSE_TIMEOUT,verifyClient:null,noServer:false,backlog:null,server:null,host:null,path:null,port:null,WebSocket:WebSocket2,...options};if(options.port==null&&!options.
|
|
115
|
+
server&&!options.noServer||options.port!=null&&(options.server||options.noServer)||options.server&&options.noServer){throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified')}if(options.port!=null){this._server=http.createServer((req,res)=>{const body=http.STATUS_CODES[426];res.writeHead(426,{"Content-Length":body.length,"Content-Type":"text/plain"});res.end(body)});this._server.listen(options.port,options.host,options.backlog,callback)}else if(options.
|
|
116
|
+
server){this._server=options.server}if(this._server){const emitConnection=this.emit.bind(this,"connection");this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(req,socket,head)=>{this.handleUpgrade(req,socket,head,emitConnection)}})}if(options.perMessageDeflate===true)options.perMessageDeflate={};if(options.clientTracking){this.clients=new Set;this._shouldEmitClose=false}this.options=options;this._state=RUNNING}address(){
|
|
117
|
+
if(this.options.noServer){throw new Error('The server is operating in "noServer" mode')}if(!this._server)return null;return this._server.address()}close(cb){if(this._state===CLOSED){if(cb){this.once("close",()=>{cb(new Error("The server is not running"))})}process.nextTick(emitClose,this);return}if(cb)this.once("close",cb);if(this._state===CLOSING)return;this._state=CLOSING;if(this.options.noServer||this.options.server){if(this._server){this._removeListeners();this._removeListeners=this._server=
|
|
118
|
+
null}if(this.clients){if(!this.clients.size){process.nextTick(emitClose,this)}else{this._shouldEmitClose=true}}else{process.nextTick(emitClose,this)}}else{const server=this._server;this._removeListeners();this._removeListeners=this._server=null;server.close(()=>{emitClose(this)})}}shouldHandle(req){if(this.options.path){const index=req.url.indexOf("?");const pathname=index!==-1?req.url.slice(0,index):req.url;if(pathname!==this.options.path)return false}return true}handleUpgrade(req,socket,head,cb){
|
|
119
|
+
socket.on("error",socketOnError);const key=req.headers["sec-websocket-key"];const upgrade=req.headers.upgrade;const version=+req.headers["sec-websocket-version"];if(req.method!=="GET"){const message="Invalid HTTP method";abortHandshakeOrEmitwsClientError(this,req,socket,405,message);return}if(upgrade===void 0||upgrade.toLowerCase()!=="websocket"){const message="Invalid Upgrade header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(key===void 0||!keyRegex.test(key)){const message="\
|
|
120
|
+
Missing or invalid Sec-WebSocket-Key header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}if(version!==13&&version!==8){const message="Missing or invalid Sec-WebSocket-Version header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message,{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(req)){abortHandshake(socket,400);return}const secWebSocketProtocol=req.headers["sec-websocket-protocol"];let protocols=new Set;if(secWebSocketProtocol!==void 0){try{
|
|
121
|
+
protocols=subprotocol2.parse(secWebSocketProtocol)}catch(err){const message="Invalid Sec-WebSocket-Protocol header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}const secWebSocketExtensions=req.headers["sec-websocket-extensions"];const extensions={};if(this.options.perMessageDeflate&&secWebSocketExtensions!==void 0){const perMessageDeflate=new PerMessageDeflate2({...this.options.perMessageDeflate,isServer:true,maxPayload:this.options.maxPayload});try{const offers=extension2.
|
|
122
|
+
parse(secWebSocketExtensions);if(offers[PerMessageDeflate2.extensionName]){perMessageDeflate.accept(offers[PerMessageDeflate2.extensionName]);extensions[PerMessageDeflate2.extensionName]=perMessageDeflate}}catch(err){const message="Invalid or unacceptable Sec-WebSocket-Extensions header";abortHandshakeOrEmitwsClientError(this,req,socket,400,message);return}}if(this.options.verifyClient){const info={origin:req.headers[`${version===8?"sec-websocket-origin":"origin"}`],secure:!!(req.socket.authorized||
|
|
123
|
+
req.socket.encrypted),req};if(this.options.verifyClient.length===2){this.options.verifyClient(info,(verified,code,message,headers)=>{if(!verified){return abortHandshake(socket,code||401,message,headers)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)});return}if(!this.options.verifyClient(info))return abortHandshake(socket,401)}this.completeUpgrade(extensions,key,protocols,req,socket,head,cb)}completeUpgrade(extensions,key,protocols,req,socket,head,cb){if(!socket.readable||!socket.
|
|
124
|
+
writable)return socket.destroy();if(socket[kWebSocket]){throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration")}if(this._state>RUNNING)return abortHandshake(socket,503);const digest=createHash("sha1").update(key+GUID).digest("base64");const headers=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${digest}`];const ws=new this.options.WebSocket(null,void 0,this.options);if(protocols.
|
|
125
|
+
size){const protocol=this.options.handleProtocols?this.options.handleProtocols(protocols,req):protocols.values().next().value;if(protocol){headers.push(`Sec-WebSocket-Protocol: ${protocol}`);ws._protocol=protocol}}if(extensions[PerMessageDeflate2.extensionName]){const params=extensions[PerMessageDeflate2.extensionName].params;const value=extension2.format({[PerMessageDeflate2.extensionName]:[params]});headers.push(`Sec-WebSocket-Extensions: ${value}`);ws._extensions=extensions}this.emit("headers",
|
|
126
|
+
headers,req);socket.write(headers.concat("\r\n").join("\r\n"));socket.removeListener("error",socketOnError);ws.setSocket(socket,head,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation});if(this.clients){this.clients.add(ws);ws.on("close",()=>{this.clients.delete(ws);if(this._shouldEmitClose&&!this.clients.size){process.
|
|
127
|
+
nextTick(emitClose,this)}})}cb(ws,req)}};module.exports=WebSocketServer2;function addListeners(server,map){for(const event of Object.keys(map))server.on(event,map[event]);return function removeListeners(){for(const event of Object.keys(map)){server.removeListener(event,map[event])}}}function emitClose(server){server._state=CLOSED;server.emit("close")}function socketOnError(){this.destroy()}function abortHandshake(socket,code,message,headers){message=message||http.STATUS_CODES[code];headers={Connection:"\
|
|
128
|
+
close","Content-Type":"text/html","Content-Length":Buffer.byteLength(message),...headers};socket.once("finish",socket.destroy);socket.end(`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r
|
|
129
|
+
`+Object.keys(headers).map(h=>`${h}: ${headers[h]}`).join("\r\n")+"\r\n\r\n"+message)}function abortHandshakeOrEmitwsClientError(server,req,socket,code,message,headers){if(server.listenerCount("wsClientError")){const err=new Error(message);Error.captureStackTrace(err,abortHandshakeOrEmitwsClientError);server.emit("wsClientError",err,socket,req)}else{abortHandshake(socket,code,message,headers)}}}});var import_stream=__toESM(require_stream(),1);var import_extension=__toESM(require_extension(),1);var import_permessage_deflate=__toESM(require_permessage_deflate(),1);var import_receiver=__toESM(require_receiver(),1);var import_sender=__toESM(require_sender(),1);var import_subprotocol=__toESM(require_subprotocol(),1);var import_websocket=__toESM(require_websocket(),1);var import_websocket_server=__toESM(require_websocket_server(),1);var wrapper_default=import_websocket.default;var customGlobal=globalThis;customGlobal.WebSocket||=wrapper_default;customGlobal.window||=globalThis;customGlobal.self||=globalThis;customGlobal.window.__REACT_DEVTOOLS_COMPONENT_FILTERS__=[{type:1,value:7,isEnabled:true},{type:2,value:"InternalApp",isEnabled:true,isValid:true},{type:2,value:"InternalAppContext",isEnabled:true,isValid:true},{type:2,value:"InternalStdoutContext",isEnabled:true,isValid:true},{type:2,value:"InternalStderrContext",isEnabled:true,isValid:true},{type:2,value:"Interna\
|
|
130
|
+
lStdinContext",isEnabled:true,isValid:true},{type:2,value:"InternalFocusContext",isEnabled:true,isValid:true}];import devtools from"react-devtools-core";var isDevToolsReachable=async()=>new Promise(resolve=>{const socket=new wrapper_default("ws://localhost:8097");const timeout=setTimeout(()=>{socket.terminate();resolve(false)},2e3);timeout.unref();socket.on("open",()=>{clearTimeout(timeout);socket.terminate();resolve(true)});socket.on("error",()=>{clearTimeout(timeout);socket.terminate();resolve(false)})});if(await isDevToolsReachable()){devtools.initialize();devtools.connectToDevTools()}else{console.warn(
|
|
131
|
+
"DEV is set to true, but the React DevTools server is not running. Start it with:\n\n$ npx react-devtools\n")}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
|
+
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
+
import"./chunk-VSJBJXZO.js";var isObject=obj=>{return obj!==null&&Object.prototype.toString.call(obj)==="[object Object]"};var strictDeepEqual=(first,second)=>{if(first===second){return true}if(typeof first!==typeof second){return false}if(Array.isArray(first)&&Array.isArray(second)){if(first.length!==second.length){return false}for(let i=0;i<first.length;i+=1){if(!strictDeepEqual(first[i],second[i])){return false}}return true}if(isObject(first)&&isObject(second)){const firstEntries=Object.entries(first);const secondKeys=new Set(
|
|
4
|
+
Object.keys(second));if(firstEntries.length!==secondKeys.size){return false}for(const[key,value]of firstEntries){if(!strictDeepEqual(value,second[key])){return false}secondKeys.delete(key)}return secondKeys.size===0}return false};var isFalse=obj=>{if(obj===null||obj===void 0||obj===false){return true}if(typeof obj==="string"){return obj===""}if(typeof obj==="object"){if(Array.isArray(obj)){return obj.length===0}if(obj===null){return true}return Object.keys(obj).length===0}return false};var isAlpha=ch=>{
|
|
5
|
+
return ch>="a"&&ch<="z"||ch>="A"&&ch<="Z"||ch==="_"};var isNum=ch=>{return ch>="0"&&ch<="9"||ch==="-"};var isAlphaNum=ch=>{return ch>="a"&&ch<="z"||ch>="A"&&ch<="Z"||ch>="0"&&ch<="9"||ch==="_"};var ensureInteger=value=>{if(!(typeof value==="number")||Math.floor(value)!==value){throw new Error("invalid-value: expecting an integer.")}return value};var ensurePositiveInteger=value=>{if(!(typeof value==="number")||value<0||Math.floor(value)!==value){throw new Error("invalid-value: expecting a non-neg\
|
|
6
|
+
ative integer.")}return value};var ensureNumbers=(...operands)=>{for(let i=0;i<operands.length;i++){if(operands[i]===null||operands[i]===void 0){throw new Error("not-a-number: undefined")}if(typeof operands[i]!=="number"){throw new Error("not-a-number")}}};var notZero=n=>{n=+n;if(!n){throw new Error("not-a-number: divide by zero")}return n};var add=(left,right)=>{ensureNumbers(left,right);const result=left+right;return result};var sub=(left,right)=>{ensureNumbers(left,right);const result=left-right;
|
|
7
|
+
return result};var mul=(left,right)=>{ensureNumbers(left,right);const result=left*right;return result};var divide=(left,right)=>{ensureNumbers(left,right);const result=left/notZero(right);return result};var div=(left,right)=>{ensureNumbers(left,right);const result=Math.floor(left/notZero(right));return result};var mod=(left,right)=>{ensureNumbers(left,right);const result=left%right;return result};var findFirst=(subject,sub2,start,end)=>{if(!subject||!sub2){return null}start=Math.max(ensureInteger(
|
|
8
|
+
start=start||0),0);end=Math.min(ensureInteger(end=end||subject.length),subject.length);const offset=subject.slice(start,end).indexOf(sub2);return offset===-1?null:offset+start};var findLast=(subject,sub2,start,end)=>{if(!subject||!sub2){return null}start=Math.max(ensureInteger(start=start||0),0);end=Math.min(ensureInteger(end=end||subject.length),subject.length);const offset=subject.slice(start,end).lastIndexOf(sub2);const result=offset===-1?null:offset+start;return result};var lower=subject=>subject.
|
|
9
|
+
toLowerCase();var ensurePadFuncParams=(name,width,padding)=>{padding=padding||" ";if(padding.length>1){throw new Error(`invalid value, ${name} expects its 'pad' parameter to be a valid string with a single codepoint`)}ensurePositiveInteger(width);return padding};var padLeft=(subject,width,padding)=>{padding=ensurePadFuncParams("pad_left",width,padding);return subject&&subject.padStart(width,padding)||""};var padRight=(subject,width,padding)=>{padding=ensurePadFuncParams("pad_right",width,padding);
|
|
10
|
+
return subject&&subject.padEnd(width,padding)||""};var replace=(subject,string,by,count)=>{if(count===0){return subject}if(!count){return subject.split(string).join(by)}ensurePositiveInteger(count);[...Array(count).keys()].map(()=>subject=subject.replace(string,by));return subject};var split=(subject,search2,count)=>{if(subject.length==0&&search2.length===0){return[]}if(count===null||count===void 0){return subject.split(search2)}ensurePositiveInteger(count);if(count===0){return[subject]}const split2=subject.
|
|
11
|
+
split(search2);return[...split2.slice(0,count),split2.slice(count).join(search2)]};var trim=(subject,chars)=>{return trimLeft(trimRight(subject,chars),chars)};var trimLeft=(subject,chars)=>{return trimImpl(subject,list=>new RegExp(`^[${list}]*(.*?)`),chars)};var trimRight=(subject,chars)=>{return trimImpl(subject,list=>new RegExp(`(.*?)[${list}]*$`),chars)};var trimImpl=(subject,regExper,chars)=>{const pattern=chars?chars.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"):"\\s\x85";return subject.replace(regExper(
|
|
12
|
+
pattern),"$1")};var upper=subject=>subject.toUpperCase();var basicTokens={"(":"Lparen",")":"Rparen","*":"Star",",":"Comma",".":"Dot",":":"Colon","@":"Current","]":"Rbracket","{":"Lbrace","}":"Rbrace","+":"Plus","%":"Modulo","?":"Question","\u2212":"Minus","\xD7":"Multiply","\xF7":"Divide"};var operatorStartToken={"!":true,"<":true,"=":true,">":true,"&":true,"|":true,"/":true};var skipChars={" ":true,"\n":true,"\r":true," ":true};var StreamLexer=class{_current=0;_enable_legacy_literals=false;tokenize(stream,options){
|
|
13
|
+
const tokens=[];this._current=0;this._enable_legacy_literals=options?.enable_legacy_literals||false;let start;let identifier;let token;while(this._current<stream.length){if(isAlpha(stream[this._current])){start=this._current;identifier=this.consumeUnquotedIdentifier(stream);tokens.push({start,type:"UnquotedIdentifier",value:identifier})}else if(basicTokens[stream[this._current]]!==void 0){tokens.push({start:this._current,type:basicTokens[stream[this._current]],value:stream[this._current]});this.
|
|
14
|
+
_current+=1}else if(stream[this._current]==="$"){start=this._current;if(this._current+1<stream.length&&isAlpha(stream[this._current+1])){this._current+=1;identifier=this.consumeUnquotedIdentifier(stream);tokens.push({start,type:"Variable",value:identifier})}else{tokens.push({start,type:"Root",value:stream[this._current]});this._current+=1}}else if(stream[this._current]==="-"){if(this._current+1<stream.length&&isNum(stream[this._current+1])){const token2=this.consumeNumber(stream);token2&&tokens.
|
|
15
|
+
push(token2)}else{const token2={start:this._current,type:"Minus",value:"-"};tokens.push(token2);this._current+=1}}else if(isNum(stream[this._current])){token=this.consumeNumber(stream);tokens.push(token)}else if(stream[this._current]==="["){token=this.consumeLBracket(stream);tokens.push(token)}else if(stream[this._current]==='"'){start=this._current;identifier=this.consumeQuotedIdentifier(stream);tokens.push({start,type:"QuotedIdentifier",value:identifier})}else if(stream[this._current]===`'`){start=
|
|
16
|
+
this._current;identifier=this.consumeRawStringLiteral(stream);tokens.push({start,type:"Literal",value:identifier})}else if(stream[this._current]==="`"){start=this._current;const literal=this.consumeLiteral(stream);tokens.push({start,type:"Literal",value:literal})}else if(operatorStartToken[stream[this._current]]!==void 0){token=this.consumeOperator(stream);token&&tokens.push(token)}else if(skipChars[stream[this._current]]!==void 0){this._current+=1}else{const error=new Error(`Syntax error: unkno\
|
|
17
|
+
wn character: ${stream[this._current]}`);error.name="LexerError";throw error}}return tokens}consumeUnquotedIdentifier(stream){const start=this._current;this._current+=1;while(this._current<stream.length&&isAlphaNum(stream[this._current])){this._current+=1}return stream.slice(start,this._current)}consumeQuotedIdentifier(stream){const start=this._current;this._current+=1;const maxLength=stream.length;while(stream[this._current]!=='"'&&this._current<maxLength){let current=this._current;if(stream[current]===
|
|
18
|
+
"\\"&&(stream[current+1]==="\\"||stream[current+1]==='"')){current+=2}else{current+=1}this._current=current}this._current+=1;const[value,ok]=this.parseJSON(stream.slice(start,this._current));if(!ok){const error=new Error(`syntax: unexpected end of JSON input`);error.name="LexerError";throw error}return value}consumeRawStringLiteral(stream){const start=this._current;this._current+=1;const maxLength=stream.length;while(stream[this._current]!==`'`&&this._current<maxLength){let current=this._current;
|
|
19
|
+
if(stream[current]==="\\"&&(stream[current+1]==="\\"||stream[current+1]===`'`)){current+=2}else{current+=1}this._current=current}this._current+=1;const literal=stream.slice(start+1,this._current-1);return replace(replace(literal,`\\\\`,`\\`),`\\'`,`'`)}consumeNumber(stream){const start=this._current;this._current+=1;const maxLength=stream.length;while(isNum(stream[this._current])&&this._current<maxLength){this._current+=1}const value=parseInt(stream.slice(start,this._current),10);return{start,value,
|
|
20
|
+
type:"Number"}}consumeLBracket(stream){const start=this._current;this._current+=1;if(stream[this._current]==="?"){this._current+=1;return{start,type:"Filter",value:"[?"}}if(stream[this._current]==="]"){this._current+=1;return{start,type:"Flatten",value:"[]"}}return{start,type:"Lbracket",value:"["}}consumeOrElse(stream,peek,token,orElse){const start=this._current;this._current+=1;if(this._current<stream.length&&stream[this._current]===peek){this._current+=1;return{start,type:orElse,value:stream.slice(
|
|
21
|
+
start,this._current)}}return{start,type:token,value:stream[start]}}consumeOperator(stream){const start=this._current;const startingChar=stream[start];switch(startingChar){case"!":return this.consumeOrElse(stream,"=","Not","NE");case"<":return this.consumeOrElse(stream,"=","LT","LTE");case">":return this.consumeOrElse(stream,"=","GT","GTE");case"=":return this.consumeOrElse(stream,"=","Assign","EQ");case"&":return this.consumeOrElse(stream,"&","Expref","And");case"|":return this.consumeOrElse(stream,
|
|
22
|
+
"|","Pipe","Or");case"/":return this.consumeOrElse(stream,"/","Divide","Div")}}consumeLiteral(stream){this._current+=1;const start=this._current;const maxLength=stream.length;while(stream[this._current]!=="`"&&this._current<maxLength){let current=this._current;if(stream[current]==="\\"&&(stream[current+1]==="\\"||stream[current+1]==="`")){current+=2}else{current+=1}this._current=current}let literalString=stream.slice(start,this._current).trimStart();literalString=literalString.replace("\\`","`");
|
|
23
|
+
let literal=null;let ok=false;if(this.looksLikeJSON(literalString)){[literal,ok]=this.parseJSON(literalString)}if(!ok&&this._enable_legacy_literals){[literal,ok]=this.parseJSON(`"${literalString}"`)}if(!ok){const error=new Error(`Syntax error: unexpected end of JSON input or invalid format for a JSON literal: ${stream[this._current]}`);error.name="LexerError";throw error}this._current+=1;return literal}looksLikeJSON(literalString){const startingChars='[{"';const jsonLiterals=["true","false","nul\
|
|
24
|
+
l"];const numberLooking="-0123456789";if(literalString===""){return false}if(startingChars.includes(literalString[0])){return true}if(jsonLiterals.includes(literalString)){return true}if(numberLooking.includes(literalString[0])){const[_,ok]=this.parseJSON(literalString);return ok}return false}parseJSON(text){try{const json=JSON.parse(text);return[json,true]}catch{return[null,false]}}};var Lexer=new StreamLexer;var Lexer_default=Lexer;var bindingPower={["EOF"]:0,["Variable"]:0,["UnquotedIdentifie\
|
|
25
|
+
r"]:0,["QuotedIdentifier"]:0,["Rbracket"]:0,["Rparen"]:0,["Comma"]:0,["Rbrace"]:0,["Number"]:0,["Current"]:0,["Expref"]:0,["Root"]:0,["Assign"]:1,["Pipe"]:1,["Question"]:2,["Or"]:3,["And"]:4,["EQ"]:5,["GT"]:5,["LT"]:5,["GTE"]:5,["LTE"]:5,["NE"]:5,["Minus"]:6,["Plus"]:6,["Div"]:7,["Divide"]:7,["Modulo"]:7,["Multiply"]:7,["Flatten"]:9,["Star"]:20,["Filter"]:21,["Dot"]:40,["Not"]:45,["Lbrace"]:50,["Lbracket"]:55,["Lparen"]:60};var TokenParser=class _TokenParser{index=0;tokens=[];parse(expression,options){
|
|
26
|
+
this.loadTokens(expression,options||{enable_legacy_literals:false});this.index=0;const ast=this.expression(0);if(this.lookahead(0)!=="EOF"){const token=this.lookaheadToken(0);this.errorToken(token,`Syntax error: unexpected token type: ${token.type}, value: ${token.value}`)}return ast}loadTokens(expression,options){this.tokens=Lexer_default.tokenize(expression,options);this.tokens.push({type:"EOF",value:"",start:expression.length})}expression(rbp){const leftToken=this.lookaheadToken(0);this.advance();
|
|
27
|
+
let left=this.nud(leftToken);let currentTokenType=this.lookahead(0);while(rbp<bindingPower[currentTokenType]){this.advance();left=this.led(currentTokenType,left);currentTokenType=this.lookahead(0)}return left}lookahead(offset){return this.tokens[this.index+offset].type}lookaheadToken(offset){return this.tokens[this.index+offset]}advance(){this.index+=1}nud(token){switch(token.type){case"Variable":return{type:"Variable",name:token.value};case"Literal":return{type:"Literal",value:token.value};case"\
|
|
28
|
+
UnquotedIdentifier":{if(_TokenParser.isKeyword(token,"let")&&this.lookahead(0)==="Variable"){return this.parseLetExpression()}else{return{type:"Field",name:token.value}}}case"QuotedIdentifier":if(this.lookahead(0)==="Lparen"){throw new Error("Syntax error: quoted identifier not allowed for function names.")}else{return{type:"Field",name:token.value}}case"Not":{const child=this.expression(bindingPower.Not);return{type:"NotExpression",child}}case"Minus":{const child=this.expression(bindingPower.Minus);
|
|
29
|
+
return{type:"Unary",operator:token.type,operand:child}}case"Plus":{const child=this.expression(bindingPower.Plus);return{type:"Unary",operator:token.type,operand:child}}case"Star":{const left={type:"Identity"};return{type:"ValueProjection",left,right:this.parseProjectionRHS(bindingPower.Star)}}case"Filter":return this.led(token.type,{type:"Identity"});case"Lbrace":return this.parseMultiselectHash();case"Flatten":{const left={type:"Flatten",child:{type:"Identity"}};const right=this.parseProjectionRHS(
|
|
30
|
+
bindingPower.Flatten);return{type:"Projection",left,right}}case"Lbracket":{if(this.lookahead(0)==="Number"||this.lookahead(0)==="Colon"){const right=this.parseIndexExpression();return this.projectIfSlice({type:"Identity"},right)}if(this.lookahead(0)==="Star"&&this.lookahead(1)==="Rbracket"){this.advance();this.advance();const right=this.parseProjectionRHS(bindingPower.Star);return{left:{type:"Identity"},right,type:"Projection"}}return this.parseMultiselectList()}case"Current":return{type:"Curren\
|
|
31
|
+
t"};case"Root":return{type:"Root"};case"Expref":{const child=this.expression(bindingPower.Expref);return{type:"ExpressionReference",child}}case"Lparen":{const expression=this.expression(0);this.match("Rparen");return expression}default:this.errorToken(token)}}led(tokenName,left){switch(tokenName){case"Question":{const trueExpr=this.expression(0);this.match("Colon");const falseExpr=this.expression(0);return{type:"Ternary",condition:left,trueExpr,falseExpr}}case"Dot":{const rbp=bindingPower.Dot;if(this.
|
|
32
|
+
lookahead(0)!=="Star"){const right2=this.parseDotRHS(rbp);return{type:"Subexpression",left,right:right2}}this.advance();const right=this.parseProjectionRHS(rbp);return{type:"ValueProjection",left,right}}case"Pipe":{const right=this.expression(bindingPower.Pipe);return{type:"Pipe",left,right}}case"Or":{const right=this.expression(bindingPower.Or);return{type:"OrExpression",left,right}}case"And":{const right=this.expression(bindingPower.And);return{type:"AndExpression",left,right}}case"Lparen":{if(left.
|
|
33
|
+
type!=="Field"){throw new Error("Syntax error: expected a Field node")}const name=left.name;const args=this.parseCommaSeparatedExpressionsUntilToken("Rparen");const node={name,type:"Function",children:args};return node}case"Filter":{const condition=this.expression(0);this.match("Rbracket");const right=this.lookahead(0)==="Flatten"?{type:"Identity"}:this.parseProjectionRHS(bindingPower.Filter);return{type:"FilterProjection",left,right,condition}}case"Flatten":{const leftNode={type:"Flatten",child:left};
|
|
34
|
+
const right=this.parseProjectionRHS(bindingPower.Flatten);return{type:"Projection",left:leftNode,right}}case"Assign":{const leftNode=left;const right=this.expression(0);return{type:"Binding",variable:leftNode.name,reference:right}}case"EQ":case"NE":case"GT":case"GTE":case"LT":case"LTE":return this.parseComparator(left,tokenName);case"Plus":case"Minus":case"Multiply":case"Star":case"Divide":case"Modulo":case"Div":return this.parseArithmetic(left,tokenName);case"Lbracket":{const token=this.lookaheadToken(
|
|
35
|
+
0);if(token.type==="Number"||token.type==="Colon"){const right2=this.parseIndexExpression();return this.projectIfSlice(left,right2)}this.match("Star");this.match("Rbracket");const right=this.parseProjectionRHS(bindingPower.Star);return{type:"Projection",left,right}}default:return this.errorToken(this.lookaheadToken(0))}}static isKeyword(token,keyword){return token.type==="UnquotedIdentifier"&&token.value===keyword}match(tokenType){if(this.lookahead(0)===tokenType){this.advance();return}else{const token=this.
|
|
36
|
+
lookaheadToken(0);this.errorToken(token,`Syntax error: expected ${tokenType}, got: ${token.type}`)}}errorToken(token,message=""){const error=new Error(message||`Syntax error: invalid token (${token.type}): "${token.value}"`);error.name="ParserError";throw error}parseIndexExpression(){if(this.lookahead(0)==="Colon"||this.lookahead(1)==="Colon"){return this.parseSliceExpression()}const value=Number(this.lookaheadToken(0).value);this.advance();this.match("Rbracket");return{type:"Index",value}}projectIfSlice(left,right){
|
|
37
|
+
const indexExpr={type:"IndexExpression",left,right};if(right.type==="Slice"){return{left:indexExpr,right:this.parseProjectionRHS(bindingPower.Star),type:"Projection"}}return indexExpr}parseSliceExpression(){const parts=[null,null,null];let index=0;let current=this.lookaheadToken(0);while(current.type!="Rbracket"&&index<3){if(current.type==="Colon"){index++;if(index===3){this.errorToken(this.lookaheadToken(0),"Syntax error, too many colons in slice expression")}this.advance()}else if(current.type===
|
|
38
|
+
"Number"){const part=this.lookaheadToken(0).value;parts[index]=part;this.advance()}else{const next=this.lookaheadToken(0);this.errorToken(next,`Syntax error, unexpected token: ${next.value}(${next.type})`)}current=this.lookaheadToken(0)}this.match("Rbracket");const[start,stop,step]=parts;return{type:"Slice",start,stop,step}}parseLetExpression(){const separated=this.parseCommaSeparatedExpressionsUntilKeyword("in");const expression=this.expression(0);const bindings=separated.map(binding=>binding);
|
|
39
|
+
return{type:"LetExpression",bindings,expression}}parseCommaSeparatedExpressionsUntilKeyword(keyword){return this.parseCommaSeparatedExpressionsUntil(()=>{return _TokenParser.isKeyword(this.lookaheadToken(0),keyword)},()=>{this.advance()})}parseCommaSeparatedExpressionsUntilToken(token){return this.parseCommaSeparatedExpressionsUntil(()=>{return this.lookahead(0)===token},()=>{return this.match(token)})}parseCommaSeparatedExpressionsUntil(isEndToken,matchEndToken){const args=[];let expression;while(!isEndToken()){
|
|
40
|
+
expression=this.expression(0);if(this.lookahead(0)==="Comma"){this.match("Comma")}args.push(expression)}matchEndToken();return args}parseComparator(left,comparator){const right=this.expression(bindingPower[comparator]);return{type:"Comparator",name:comparator,left,right}}parseArithmetic(left,operator){const right=this.expression(bindingPower[operator]);return{type:"Arithmetic",operator,left,right}}parseDotRHS(rbp){const lookahead=this.lookahead(0);const exprTokens=["UnquotedIdentifier","QuotedId\
|
|
41
|
+
entifier","Star"];if(exprTokens.includes(lookahead)){return this.expression(rbp)}if(lookahead==="Lbracket"){this.match("Lbracket");return this.parseMultiselectList()}if(lookahead==="Lbrace"){this.match("Lbrace");return this.parseMultiselectHash()}const token=this.lookaheadToken(0);this.errorToken(token,`Syntax error, unexpected token: ${token.value}(${token.type})`)}parseProjectionRHS(rbp){if(bindingPower[this.lookahead(0)]<10){return{type:"Identity"}}if(this.lookahead(0)==="Lbracket"){return this.
|
|
42
|
+
expression(rbp)}if(this.lookahead(0)==="Filter"){return this.expression(rbp)}if(this.lookahead(0)==="Dot"){this.match("Dot");return this.parseDotRHS(rbp)}const token=this.lookaheadToken(0);this.errorToken(token,`Syntax error, unexpected token: ${token.value}(${token.type})`)}parseMultiselectList(){const expressions=[];while(this.lookahead(0)!=="Rbracket"){const expression=this.expression(0);expressions.push(expression);if(this.lookahead(0)==="Comma"){this.match("Comma");if(this.lookahead(0)==="R\
|
|
43
|
+
bracket"){throw new Error("Syntax error: unexpected token Rbracket")}}}this.match("Rbracket");return{type:"MultiSelectList",children:expressions}}parseMultiselectHash(){const pairs=[];const identifierTypes=["UnquotedIdentifier","QuotedIdentifier"];let keyToken;let keyName;let value;for(;;){keyToken=this.lookaheadToken(0);if(!identifierTypes.includes(keyToken.type)){throw new Error(`Syntax error: expecting an identifier token, got: ${keyToken.type}`)}keyName=keyToken.value;this.advance();this.match(
|
|
44
|
+
"Colon");value=this.expression(0);pairs.push({value,type:"KeyValuePair",name:keyName});if(this.lookahead(0)==="Comma"){this.match("Comma")}else if(this.lookahead(0)==="Rbrace"){this.match("Rbrace");break}}return{type:"MultiSelectHash",children:pairs}}};var Parser=new TokenParser;var Parser_default=Parser;var Text=class _Text{_text;constructor(text){this._text=text}get string(){return this._text}get length(){return this.codePoints.length}compareTo(other){return _Text.compare(this,new _Text(other))}static get comparer(){
|
|
45
|
+
const stringComparer=(left,right)=>{return new _Text(left).compareTo(right)};return stringComparer}static compare(left,right){const leftCp=left.codePoints;const rightCp=right.codePoints;for(let index=0;index<Math.min(leftCp.length,rightCp.length);index++){if(leftCp[index]===rightCp[index]){continue}return leftCp[index]-rightCp[index]>0?1:-1}return leftCp.length-rightCp.length>0?1:-1}reverse(){return String.fromCodePoint(...this.codePoints.reverse())}get codePoints(){const array=[...this._text].map(
|
|
46
|
+
s=>s.codePointAt(0));return array}};var createMathFunction=mathFn=>([value])=>mathFn(value);var createStringFunction=stringFn=>([subject])=>stringFn(subject);var createObjectFunction=objFn=>([obj])=>objFn(obj);var Runtime=class{_interpreter;_functionTable;_customFunctions=new Set;TYPE_NAME_TABLE=Object.freeze({[0]:"number",[1]:"any",[2]:"string",[3]:"array",[4]:"object",[5]:"boolean",[6]:"expression",[7]:"null",[8]:"Array<number>",[10]:"Array<object>",[9]:"Array<string>",[11]:"Array<Array<any>>"});constructor(interpreter){
|
|
47
|
+
this._interpreter=interpreter;this._functionTable=this.buildFunctionTable()}buildFunctionTable(){return{abs:{_func:createMathFunction(Math.abs),_signature:[{types:[0]}]},ceil:{_func:createMathFunction(Math.ceil),_signature:[{types:[0]}]},floor:{_func:createMathFunction(Math.floor),_signature:[{types:[0]}]},lower:{_func:createStringFunction(lower),_signature:[{types:[2]}]},upper:{_func:createStringFunction(upper),_signature:[{types:[2]}]},keys:{_func:createObjectFunction(Object.keys),_signature:[
|
|
48
|
+
{types:[4]}]},values:{_func:createObjectFunction(Object.values),_signature:[{types:[4]}]},avg:{_func:this.functionAvg,_signature:[{types:[8]}]},contains:{_func:this.functionContains,_signature:[{types:[2,3]},{types:[1]}]},ends_with:{_func:this.functionEndsWith,_signature:[{types:[2]},{types:[2]}]},find_first:{_func:this.functionFindFirst,_signature:[{types:[2]},{types:[2]},{types:[0],optional:true},{types:[0],optional:true}]},find_last:{_func:this.functionFindLast,_signature:[{types:[2]},{types:[
|
|
49
|
+
2]},{types:[0],optional:true},{types:[0],optional:true}]},from_items:{_func:this.functionFromItems,_signature:[{types:[11]}]},group_by:{_func:this.functionGroupBy,_signature:[{types:[3]},{types:[6]}]},items:{_func:this.functionItems,_signature:[{types:[4]}]},join:{_func:this.functionJoin,_signature:[{types:[2]},{types:[9]}]},length:{_func:this.functionLength,_signature:[{types:[2,3,4]}]},map:{_func:this.functionMap,_signature:[{types:[6]},{types:[3]}]},max:{_func:this.functionMax,_signature:[{types:[
|
|
50
|
+
8,9]}]},max_by:{_func:this.functionMaxBy,_signature:[{types:[3]},{types:[6]}]},merge:{_func:this.functionMerge,_signature:[{types:[4],variadic:true}]},min:{_func:this.functionMin,_signature:[{types:[8,9]}]},min_by:{_func:this.functionMinBy,_signature:[{types:[3]},{types:[6]}]},not_null:{_func:this.functionNotNull,_signature:[{types:[1],variadic:true}]},pad_left:{_func:this.functionPadLeft,_signature:[{types:[2]},{types:[0]},{types:[2],optional:true}]},pad_right:{_func:this.functionPadRight,_signature:[
|
|
51
|
+
{types:[2]},{types:[0]},{types:[2],optional:true}]},replace:{_func:this.functionReplace,_signature:[{types:[2]},{types:[2]},{types:[2]},{types:[0],optional:true}]},reverse:{_func:this.functionReverse,_signature:[{types:[2,3]}]},sort:{_func:this.functionSort,_signature:[{types:[9,8]}]},sort_by:{_func:this.functionSortBy,_signature:[{types:[3]},{types:[6]}]},split:{_func:this.functionSplit,_signature:[{types:[2]},{types:[2]},{types:[0],optional:true}]},starts_with:{_func:this.functionStartsWith,_signature:[
|
|
52
|
+
{types:[2]},{types:[2]}]},sum:{_func:this.functionSum,_signature:[{types:[8]}]},to_array:{_func:this.functionToArray,_signature:[{types:[1]}]},to_number:{_func:this.functionToNumber,_signature:[{types:[1]}]},to_string:{_func:this.functionToString,_signature:[{types:[1]}]},trim:{_func:this.functionTrim,_signature:[{types:[2]},{types:[2],optional:true}]},trim_left:{_func:this.functionTrimLeft,_signature:[{types:[2]},{types:[2],optional:true}]},trim_right:{_func:this.functionTrimRight,_signature:[{
|
|
53
|
+
types:[2]},{types:[2],optional:true}]},type:{_func:this.functionType,_signature:[{types:[1]}]},zip:{_func:this.functionZip,_signature:[{types:[3],variadic:true}]}}}registerFunction(name,customFunction,signature,options){const result=this._registerInternal(name,customFunction,signature,options);if(!result.success){throw new Error(result.message)}}_registerInternal(name,customFunction,signature,options={}){if(!name||typeof name!=="string"||name.trim()===""){return{success:false,reason:"invalid-nam\
|
|
54
|
+
e",message:"Function name must be a non-empty string"}}try{this.validateInputSignatures(name,signature)}catch(error){return{success:false,reason:"invalid-signature",message:error instanceof Error?error.message:"Invalid function signature"}}const{override=false,warn=false}=options;const exists=name in this._functionTable;if(exists&&!override){return{success:false,reason:"already-exists",message:`Function already defined: ${name}(). Use { override: true } to replace it.`}}if(exists&&override&&warn){
|
|
55
|
+
console.warn(`Warning: Overriding existing function: ${name}()`)}this._functionTable[name]={_func:customFunction.bind(this),_signature:signature};this._customFunctions.add(name);const message=exists?`Function ${name}() overridden successfully`:`Function ${name}() registered successfully`;return{success:true,message}}register(name,customFunction,signature,options={}){return this._registerInternal(name,customFunction,signature,options)}unregister(name){if(!this._customFunctions.has(name)){return false}
|
|
56
|
+
delete this._functionTable[name];this._customFunctions.delete(name);return true}isRegistered(name){return name in this._functionTable}getRegistered(){return Object.keys(this._functionTable)}getCustomFunctions(){return Array.from(this._customFunctions)}clearCustomFunctions(){for(const name of this._customFunctions){delete this._functionTable[name]}this._customFunctions.clear()}callFunction(name,resolvedArgs){const functionEntry=this._functionTable[name];if(functionEntry===void 0){throw new Error(
|
|
57
|
+
`Unknown function: ${name}()`)}this.validateArgs(name,resolvedArgs,functionEntry._signature);return functionEntry._func.call(this,resolvedArgs)}validateInputSignatures(name,signature){for(let i=0;i<signature.length;i+=1){if("variadic"in signature[i]&&i!==signature.length-1){throw new Error(`Invalid arity: ${name}() 'variadic' argument ${i+1} must occur last`)}}}validateArgs(name,args,signature){this.validateInputSignatures(name,signature);this.validateArity(name,args,signature);this.validateTypes(
|
|
58
|
+
name,args,signature)}validateArity(name,args,signature){const numberOfRequiredArgs=signature.filter(argSignature=>!(argSignature.optional??false)).length;const lastArgIsVariadic=signature[signature.length-1]?.variadic??false;const tooFewArgs=args.length<numberOfRequiredArgs;const tooManyArgs=args.length>signature.length;if(lastArgIsVariadic&&tooFewArgs||!lastArgIsVariadic&&(tooFewArgs||tooManyArgs)){const tooFewModifier=tooFewArgs&&(!lastArgIsVariadic&&numberOfRequiredArgs>1||lastArgIsVariadic)?
|
|
59
|
+
"at least ":"";const pluralized=signature.length>1;throw new Error(`Invalid arity: ${name}() takes ${tooFewModifier}${numberOfRequiredArgs} argument${pluralized&&"s"||""} but received ${args.length}`)}}validateTypes(name,args,signature){for(let i=0;i<signature.length;i+=1){const currentSpec=signature[i].types;const actualType=this.getTypeName(args[i]);if(actualType===void 0){continue}const typeMatched=currentSpec.some(expectedType=>this.typeMatches(actualType,expectedType,args[i]));if(!typeMatched){
|
|
60
|
+
const expected=currentSpec.map(typeId=>this.TYPE_NAME_TABLE[typeId]).join(" | ");throw new Error(`Invalid type: ${name}() expected argument ${i+1} to be type (${expected}) but received type ${this.TYPE_NAME_TABLE[actualType]} instead.`)}}}typeMatches(actual,expected,argValue){if(expected===1){return true}if(expected===9||expected===8||expected===10||expected===11||expected===3){if(expected===3){return actual===3}if(actual===3){let subtype;if(expected===8){subtype=0}else if(expected===10){subtype=
|
|
61
|
+
4}else if(expected===9){subtype=2}else if(expected===11){subtype=3}const array=argValue;for(let i=0;i<array.length;i+=1){const typeName=this.getTypeName(array[i]);if(typeName!==void 0&&subtype!==void 0&&!this.typeMatches(typeName,subtype,array[i])){return false}}return true}}else{return actual===expected}return false}getTypeName(obj){if(obj===null){return 7}if(typeof obj==="string"){return 2}if(typeof obj==="number"){return 0}if(typeof obj==="boolean"){return 5}if(Array.isArray(obj)){return 3}if(typeof obj===
|
|
62
|
+
"object"){if(obj.expref){return 6}return 4}return}createKeyFunction(exprefNode,allowedTypes){const interpreter=this._interpreter;const keyFunc=x=>{const current=interpreter.visit(exprefNode,x);if(!allowedTypes.includes(this.getTypeName(current))){const msg=`Invalid type: expected one of (${allowedTypes.map(t=>this.TYPE_NAME_TABLE[t]).join(" | ")}), received ${this.TYPE_NAME_TABLE[this.getTypeName(current)]}`;throw new Error(msg)}return current};return keyFunc}functionAvg=([inputArray])=>{if(!inputArray||
|
|
63
|
+
inputArray.length==0){return null}let sum=0;for(let i=0;i<inputArray.length;i+=1){sum+=inputArray[i]}return sum/inputArray.length};functionContains=([searchable,searchValue])=>{if(Array.isArray(searchable)){const array=searchable;return array.includes(searchValue)}if(typeof searchable==="string"){const text=searchable;if(typeof searchValue==="string"){return text.includes(searchValue)}}return null};functionEndsWith=resolvedArgs=>{const[searchStr,suffix]=resolvedArgs;return searchStr.includes(suffix,
|
|
64
|
+
searchStr.length-suffix.length)};functionFindFirst=this.createFindFunction(findFirst);functionFindLast=this.createFindFunction(findLast);createFindFunction(findFn){return resolvedArgs=>{const subject=resolvedArgs[0];const search2=resolvedArgs[1];const start=resolvedArgs.length>2?resolvedArgs[2]:void 0;const end=resolvedArgs.length>3?resolvedArgs[3]:void 0;return findFn(subject,search2,start,end)}}functionFromItems=([array])=>{array.map(pair=>{if(pair.length!=2||typeof pair[0]!=="string"){throw new Error(
|
|
65
|
+
"invalid value, each array must contain two elements, a pair of string and value")}});return Object.fromEntries(array)};functionGroupBy=([array,exprefNode])=>{const keyFunction=this.createKeyFunction(exprefNode,[2]);return array.reduce((acc,cur)=>{const k=keyFunction(cur??{});const target=acc[k]=acc[k]||[];target.push(cur);return acc},{})};functionItems=([inputValue])=>{return Object.entries(inputValue)};functionJoin=resolvedArgs=>{const[joinChar,listJoin]=resolvedArgs;return listJoin.join(joinChar)};functionLength=([
|
|
66
|
+
inputValue])=>{if(typeof inputValue==="string"){return new Text(inputValue).length}if(Array.isArray(inputValue)){return inputValue.length}return Object.keys(inputValue).length};functionMap=([exprefNode,elements])=>{if(!this._interpreter){return[]}const mapped=[];const interpreter=this._interpreter;for(let i=0;i<elements.length;i+=1){mapped.push(interpreter.visit(exprefNode,elements[i]))}return mapped};functionMax=([inputValue])=>{if(!inputValue.length){return null}const typeName=this.getTypeName(
|
|
67
|
+
inputValue[0]);if(typeName===0){return Math.max(...inputValue)}const elements=inputValue;let maxElement=elements[0];for(let i=1;i<elements.length;i+=1){if(maxElement.localeCompare(elements[i])<0){maxElement=elements[i]}}return maxElement};functionMaxBy=resolvedArgs=>{const exprefNode=resolvedArgs[1];const resolvedArray=resolvedArgs[0];const keyFunction=this.createKeyFunction(exprefNode,[0,2]);let maxNumber=-Infinity;let maxRecord;let current;for(let i=0;i<resolvedArray.length;i+=1){current=keyFunction&&
|
|
68
|
+
keyFunction(resolvedArray[i]);if(current!==void 0&¤t>maxNumber){maxNumber=current;maxRecord=resolvedArray[i]}}return maxRecord||null};functionMerge=resolvedArgs=>{let merged={};for(let i=0;i<resolvedArgs.length;i+=1){const current=resolvedArgs[i];merged=Object.assign(merged,current)}return merged};functionMin=([inputValue])=>{if(!inputValue.length){return null}const typeName=this.getTypeName(inputValue[0]);if(typeName===0){return Math.min(...inputValue)}const elements=inputValue;let minElement=elements[0];
|
|
69
|
+
for(let i=1;i<elements.length;i+=1){if(elements[i].localeCompare(minElement)<0){minElement=elements[i]}}return minElement};functionMinBy=resolvedArgs=>{const exprefNode=resolvedArgs[1];const resolvedArray=resolvedArgs[0];const keyFunction=this.createKeyFunction(exprefNode,[0,2]);let minNumber=Infinity;let minRecord;let current;for(let i=0;i<resolvedArray.length;i+=1){current=keyFunction&&keyFunction(resolvedArray[i]);if(current!==void 0&¤t<minNumber){minNumber=current;minRecord=resolvedArray[i]}}
|
|
70
|
+
return minRecord||null};functionNotNull=resolvedArgs=>{for(let i=0;i<resolvedArgs.length;i+=1){if(this.getTypeName(resolvedArgs[i])!==7){return resolvedArgs[i]}}return null};functionPadLeft=this.createPadFunction(padLeft);functionPadRight=this.createPadFunction(padRight);createPadFunction(padFn){return resolvedArgs=>{const subject=resolvedArgs[0];const width=resolvedArgs[1];const padding=resolvedArgs.length>2?resolvedArgs[2]:void 0;return padFn(subject,width,padding)}}functionReplace=resolvedArgs=>{
|
|
71
|
+
const subject=resolvedArgs[0];const string=resolvedArgs[1];const by=resolvedArgs[2];return replace(subject,string,by,resolvedArgs.length>3?resolvedArgs[3]:void 0)};functionSplit=resolvedArgs=>{const subject=resolvedArgs[0];const search2=resolvedArgs[1];return split(subject,search2,resolvedArgs.length>2?resolvedArgs[2]:void 0)};functionReverse=([inputValue])=>{const typeName=this.getTypeName(inputValue);if(typeName===2){return new Text(inputValue).reverse()}const reversedArray=inputValue.slice(0);
|
|
72
|
+
reversedArray.reverse();return reversedArray};functionSort=([inputValue])=>{if(inputValue.length==0){return inputValue}if(typeof inputValue[0]==="string"){return[...inputValue].sort(Text.comparer)}return[...inputValue].sort()};functionSortBy=resolvedArgs=>{const sortedArray=resolvedArgs[0].slice(0);if(sortedArray.length===0){return sortedArray}const interpreter=this._interpreter;const exprefNode=resolvedArgs[1];const requiredType=this.getTypeName(interpreter.visit(exprefNode,sortedArray[0]));if(requiredType!==
|
|
73
|
+
void 0&&![0,2].includes(requiredType)){throw new Error(`Invalid type: unexpected type (${this.TYPE_NAME_TABLE[requiredType]})`)}function throwInvalidTypeError(rt,item){throw new Error(`Invalid type: expected (${rt.TYPE_NAME_TABLE[requiredType]}), received ${rt.TYPE_NAME_TABLE[rt.getTypeName(item)]}`)}return sortedArray.sort((a,b)=>{const exprA=interpreter.visit(exprefNode,a);const exprB=interpreter.visit(exprefNode,b);if(this.getTypeName(exprA)!==requiredType){throwInvalidTypeError(this,exprA)}else if(this.
|
|
74
|
+
getTypeName(exprB)!==requiredType){throwInvalidTypeError(this,exprB)}if(requiredType===2){return Text.comparer(exprA,exprB)}return exprA-exprB})};functionStartsWith=([searchable,searchStr])=>{return searchable.startsWith(searchStr)};functionSum=([inputValue])=>{return inputValue.reduce((x,y)=>x+y,0)};functionToArray=([inputValue])=>{if(this.getTypeName(inputValue)===3){return inputValue}return[inputValue]};functionToNumber=([inputValue])=>{const typeName=this.getTypeName(inputValue);let convertedValue;
|
|
75
|
+
if(typeName===0){return inputValue}if(typeName===2){convertedValue=+inputValue;if(!isNaN(convertedValue)){return convertedValue}}return null};functionToString=([inputValue])=>{if(this.getTypeName(inputValue)===2){return inputValue}return JSON.stringify(inputValue)};functionTrim=this.createTrimFunction(trim);functionTrimLeft=this.createTrimFunction(trimLeft);functionTrimRight=this.createTrimFunction(trimRight);createTrimFunction(trimFn){return resolvedArgs=>{const subject=resolvedArgs[0];const chars=resolvedArgs.
|
|
76
|
+
length>1?resolvedArgs[1]:void 0;return trimFn(subject,chars)}}functionType=([inputValue])=>{switch(this.getTypeName(inputValue)){case 0:return"number";case 2:return"string";case 3:return"array";case 4:return"object";case 5:return"boolean";case 7:return"null";default:throw new Error("invalid-type")}};functionZip=array=>{const length=Math.min(...array.map(arr=>arr.length));const result=Array(length).fill(null).map((_,index)=>array.map(arr=>arr[index]));return result}};var ScopeChain=class _ScopeChain{inner=void 0;data={};get currentScopeData(){
|
|
77
|
+
return this.data}withScope(data){const outer=new _ScopeChain;outer.inner=this;outer.data=data;return outer}getValue(identifier){if(Object.prototype.hasOwnProperty.call(this.data,identifier)){return this.data[identifier]}if(this.inner){return this.inner.getValue(identifier)}return null}};var emptyScopeChain=new ScopeChain;var TreeInterpreter=class _TreeInterpreter{runtime;_rootValue=null;_scope;constructor(){this.runtime=new Runtime(this);this._scope=new ScopeChain}withScope(scope){const interpreter=new _TreeInterpreter;
|
|
78
|
+
interpreter.runtime._functionTable=this.runtime._functionTable;interpreter._rootValue=this._rootValue;interpreter._scope=this._scope.withScope(scope);return interpreter}search(node,value){this._rootValue=value;this._scope=emptyScopeChain;return this.visit(node,value)}visit(node,value){switch(node.type){case"Ternary":{const condition=this.visit(node.condition,value);if(!isFalse(condition)){return this.visit(node.trueExpr,value)}return this.visit(node.falseExpr,value)}case"Field":const identifier=node.
|
|
79
|
+
name;if(value===null||typeof value!=="object"||Array.isArray(value)){return null}return value[identifier]??null;case"LetExpression":{const{bindings,expression}=node;let scope={};bindings.forEach(binding=>{const reference=this.visit(binding,value);scope={...scope,...reference}});return this.withScope(scope).visit(expression,value)}case"Binding":{const{variable,reference}=node;const result=this.visit(reference,value);return{[variable]:result}}case"Variable":{const variable=node.name;if(!this._scope.
|
|
80
|
+
getValue(variable)&&!Object.prototype.hasOwnProperty.call(this._scope.currentScopeData,variable)){throw new Error(`Error referencing undefined variable ${variable}`)}return this._scope.getValue(variable)}case"IndexExpression":return this.visit(node.right,this.visit(node.left,value));case"Subexpression":{const result=this.visit(node.left,value);return result!=null?this.visit(node.right,result)??null:null}case"Index":{if(!Array.isArray(value)){return null}const index=node.value<0?value.length+node.
|
|
81
|
+
value:node.value;return value[index]??null}case"Slice":{if(!Array.isArray(value)&&typeof value!=="string"){return null}const{start,stop,step}=this.computeSliceParams(value.length,node);if(typeof value==="string"){const chars=[...value];const sliced=this.slice(chars,start,stop,step);return sliced.join("")}else{return this.slice(value,start,stop,step)}}case"Projection":{const{left,right}=node;let allowString=false;if(left.type==="IndexExpression"&&left.right.type==="Slice"){allowString=true}const base=this.
|
|
82
|
+
visit(left,value);if(allowString&&typeof base==="string"){return this.visit(right,base)}if(!Array.isArray(base)){return null}const collected=[];for(const elem of base){const current=this.visit(right,elem);if(current!==null){collected.push(current)}}return collected}case"ValueProjection":{const{left,right}=node;const base=this.visit(left,value);if(base===null||typeof base!=="object"||Array.isArray(base)){return null}const collected=[];const values=Object.values(base);for(const elem of values){const current=this.
|
|
83
|
+
visit(right,elem);if(current!==null){collected.push(current)}}return collected}case"FilterProjection":{const{left,right,condition}=node;const base=this.visit(left,value);if(!Array.isArray(base)){return null}const results=[];for(const elem of base){const matched=this.visit(condition,elem);if(isFalse(matched)){continue}const result=this.visit(right,elem);if(result!==null){results.push(result)}}return results}case"Arithmetic":{const first=this.visit(node.left,value);const second=this.visit(node.right,
|
|
84
|
+
value);switch(node.operator){case"Plus":return add(first,second);case"Minus":return sub(first,second);case"Multiply":case"Star":return mul(first,second);case"Divide":return divide(first,second);case"Modulo":return mod(first,second);case"Div":return div(first,second);default:throw new Error(`Syntax error: unknown arithmetic operator: ${node.operator}`)}}case"Unary":{const operand=this.visit(node.operand,value);switch(node.operator){case"Plus":ensureNumbers(operand);return operand;case"Minus":ensureNumbers(
|
|
85
|
+
operand);return-operand;default:throw new Error(`Syntax error: unknown arithmetic operator: ${node.operator}`)}}case"Comparator":{const first=this.visit(node.left,value);const second=this.visit(node.right,value);switch(node.name){case"EQ":return strictDeepEqual(first,second);case"NE":return!strictDeepEqual(first,second)}if(typeof first!=="number"||typeof second!=="number"){return null}switch(node.name){case"GT":return first>second;case"GTE":return first>=second;case"LT":return first<second;case"\
|
|
86
|
+
LTE":return first<=second}}case"Flatten":{const original=this.visit(node.child,value);return Array.isArray(original)?original.flat():null}case"Root":return this._rootValue;case"MultiSelectList":{const collected=[];for(const child of node.children){collected.push(this.visit(child,value))}return collected}case"MultiSelectHash":{const collected={};for(const child of node.children){collected[child.name]=this.visit(child.value,value)}return collected}case"OrExpression":{const result=this.visit(node.left,
|
|
87
|
+
value);if(isFalse(result)){return this.visit(node.right,value)}return result}case"AndExpression":{const result=this.visit(node.left,value);if(isFalse(result)){return result}return this.visit(node.right,value)}case"NotExpression":return isFalse(this.visit(node.child,value));case"Literal":return node.value;case"Pipe":return this.visit(node.right,this.visit(node.left,value));case"Function":{const args=[];for(const child of node.children){args.push(this.visit(child,value))}return this.runtime.callFunction(
|
|
88
|
+
node.name,args)}case"ExpressionReference":return{expref:true,...node.child};case"Current":case"Identity":return value}}computeSliceParams(arrayLength,sliceNode){let{start,stop,step}=sliceNode;if(step===null){step=1}else if(step===0){const error=new Error("Invalid value: slice step cannot be 0");error.name="RuntimeError";throw error}start=start===null?step<0?arrayLength-1:0:this.capSliceRange(arrayLength,start,step);stop=stop===null?step<0?-1:arrayLength:this.capSliceRange(arrayLength,stop,step);
|
|
89
|
+
return{start,stop,step}}capSliceRange(arrayLength,actualValue,step){let nextActualValue=actualValue;if(nextActualValue<0){nextActualValue+=arrayLength;if(nextActualValue<0){nextActualValue=step<0?-1:0}}else if(nextActualValue>=arrayLength){nextActualValue=step<0?arrayLength-1:arrayLength}return nextActualValue}slice(collection,start,end,step){const result=[];if(step>0){for(let i=start;i<end;i+=step){result.push(collection[i])}}else{for(let i=start;i>end;i+=step){result.push(collection[i])}}return result}};
|
|
90
|
+
var TreeInterpreterInstance=new TreeInterpreter;var TreeInterpreter_default=TreeInterpreterInstance;var TYPE_ANY=1;var TYPE_ARRAY=3;var TYPE_ARRAY_ARRAY=11;var TYPE_ARRAY_NUMBER=8;var TYPE_ARRAY_OBJECT=10;var TYPE_ARRAY_STRING=9;var TYPE_BOOLEAN=5;var TYPE_EXPREF=6;var TYPE_NULL=7;var TYPE_NUMBER=0;var TYPE_OBJECT=4;var TYPE_STRING=2;function compile(expression,options){const nodeTree=Parser_default.parse(expression,options);return nodeTree}function tokenize(expression,options){return Lexer_default.
|
|
91
|
+
tokenize(expression,options)}var registerFunction=(functionName,customFunction,signature,options)=>{TreeInterpreter_default.runtime.registerFunction(functionName,customFunction,signature,options)};var register=(name,customFunction,signature,options)=>{return TreeInterpreter_default.runtime.register(name,customFunction,signature,options)};var unregisterFunction=name=>{return TreeInterpreter_default.runtime.unregister(name)};var isRegistered=name=>{return TreeInterpreter_default.runtime.isRegistered(
|
|
92
|
+
name)};var getRegisteredFunctions=()=>{return TreeInterpreter_default.runtime.getRegistered()};var getCustomFunctions=()=>{return TreeInterpreter_default.runtime.getCustomFunctions()};var clearCustomFunctions=()=>{TreeInterpreter_default.runtime.clearCustomFunctions()};function search(data,expression,options){const nodeTree=Parser_default.parse(expression,options);return TreeInterpreter_default.search(nodeTree,data)}function Scope(){return new ScopeChain}var TreeInterpreter2=TreeInterpreter_default;
|
|
93
|
+
var jmespath={compile,registerFunction,register,unregisterFunction,isRegistered,getRegisteredFunctions,getCustomFunctions,clearCustomFunctions,search,tokenize,TreeInterpreter:TreeInterpreter2,TYPE_ANY,TYPE_ARRAY_NUMBER,TYPE_ARRAY_STRING,TYPE_ARRAY,TYPE_BOOLEAN,TYPE_EXPREF,TYPE_NULL,TYPE_NUMBER,TYPE_OBJECT,TYPE_STRING};export{Scope,TYPE_ANY,TYPE_ARRAY,TYPE_ARRAY_ARRAY,TYPE_ARRAY_NUMBER,TYPE_ARRAY_OBJECT,TYPE_ARRAY_STRING,TYPE_BOOLEAN,TYPE_EXPREF,TYPE_NULL,TYPE_NUMBER,TYPE_OBJECT,TYPE_STRING,TreeInterpreter2 as TreeInterpreter,clearCustomFunctions,compile,jmespath as default,getCustomFunctions,getRegisteredFunctions,isRegistered,jmespath,register,registerFunction,search,tokenize,unregisterFunction};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
|
+
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
+
import{buildResidentSet,buildSystemPrompt,createAuditLogger,currentBranch,displayCwd,runTurn}from"./chunk-IM4H52FC.js";import{getMode}from"./chunk-NNOYO67O.js";import{RelayError,createRuntime,pickModel}from"./chunk-RQFG3OUL.js";import{checkMinSupportedVersion,enforceMinSupportedVersion,floorNeedsRefresh}from"./chunk-DXXFUNYN.js";import"./chunk-N2UVRM3Z.js";import"./chunk-PMOUHEJQ.js";import"./chunk-63LDNYGW.js";import"./chunk-NERYSBA4.js";import"./chunk-RZVI6PMW.js";
|
|
4
|
+
import"./chunk-J7QYPKVK.js";import{stripTerminalControls}from"./chunk-NHYMHCAT.js";import"./chunk-VSJBJXZO.js";async function runOneShot(opts,deps={}){const out=deps.out??(text=>void process.stdout.write(stripTerminalControls(text)));const err=deps.err??(text=>void process.stderr.write(stripTerminalControls(text)));const prompt=opts.fromStdin?await(deps.readStdin??readStdin)():opts.prompt;if(prompt.trim()===""){err('\u30D7\u30ED\u30F3\u30D7\u30C8\u304C\u7A7A\u3067\u3059\u3002`twp -p "\u8CEA\u554F"`\uFF08`-p -` \u3067\u6A19\u6E96\u5165\u529B\uFF09\n');return 2}const runtime=deps.runtime??createRuntime({...opts.
|
|
5
|
+
profile!==void 0?{profile:opts.profile}:{},...opts.model!==void 0?{model:opts.model}:{},cliVersion:opts.version});const cachedFloor=runtime.loadCachedFloor();if(await checkMinSupportedVersion({current:opts.version,cachedFloor:cachedFloor.minSupportedVersion,refresh:async()=>(await runtime.loadCatalog()).minSupportedVersion,write:err})){return 1}if(!runtime.loggedIn){err("\u30ED\u30B0\u30A4\u30F3\u3057\u3066\u3044\u307E\u305B\u3093\u3002`twp login` \u3092\u5B9F\u884C\u3057\u3066\u304F\u3060\u3055\u3044\u3002\n");
|
|
6
|
+
return 1}let model=runtime.configuredModel??"";let catalog=null;if(model===""){catalog=await runtime.loadCatalog();const picked=pickModel(catalog,void 0);model=picked.model;if(catalog.source!=="server"){err(`\u26A0 \u30E2\u30C7\u30EB\u4E00\u89A7\u3092\u53D6\u5F97\u3067\u304D\u306A\u304B\u3063\u305F\u305F\u3081 ${model} \u3067\u5B9F\u884C\u3057\u307E\u3059\uFF08${catalog.source}\uFF09
|
|
7
|
+
`)}}else if(floorNeedsRefresh(cachedFloor.fetchedAt)){catalog=await runtime.loadCatalog()}if(catalog!==null&&enforceMinSupportedVersion({current:opts.version,floor:catalog.minSupportedVersion,write:err})){return 1}const controller=new AbortController;let interrupted=false;const onSigint=()=>{interrupted=true;controller.abort()};process.on("SIGINT",onSigint);let wroteText=false;try{const mode=getMode(opts.mode);const resident=buildResidentSet(mode,{...opts.permissionMode!==void 0?{permissionMode:opts.
|
|
8
|
+
permissionMode}:{}});const audit=deps.audit??createAuditLogger({mode:mode.id,permissionMode:opts.permissionMode,model,cwd:process.cwd(),cliVersion:opts.version,interactive:false,onOpen:file=>err(`audit: ${file}
|
|
9
|
+
`)});const result=await runTurn(runtime.client,runtime.context,{input:prompt,model,system:buildSystemPrompt({cwd:displayCwd(),branch:currentBranch(),modeLabel:mode.label,cliVersion:opts.version,toolNames:resident.tools.map(t=>t.name)}),signal:controller.signal,onTextDelta:delta=>{wroteText=true;out(stripTerminalControls(delta))},tools:resident.tools,execute:{mode,ctx:{cwd:process.cwd()},sessionAllow:new Set,...opts.permissionMode!==void 0?{permissionMode:opts.permissionMode}:{},audit},onToolUse:()=>{
|
|
10
|
+
if(wroteText){out("\n");wroteText=false}},onToolResult:(call,result2)=>err(`tool: ${call.name} \u2192 ${result2.denied===true?"denied":result2.isError===true?"error":"ok"}
|
|
11
|
+
`)});if(result.text!==""&&!result.text.endsWith("\n"))out("\n");const u=result.usage;err(`usage: model=${model} input=${u.inputTokens} cache_read=${u.cacheReadTokens} cache_write=${u.cacheWriteTokens} output=${u.outputTokens}
|
|
12
|
+
`);if(result.droppedMessages>0){err(`\u26A0 \u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u4E0A\u9650\u306E\u305F\u3081\u53E4\u3044\u3084\u308A\u53D6\u308A ${result.droppedMessages} \u4EF6\u3092\u843D\u3068\u3057\u307E\u3057\u305F
|
|
13
|
+
`)}if(result.maxStepsReached){err("\u26A0 \u30C4\u30FC\u30EB\u5B9F\u884C\u306E\u5F80\u5FA9\u304C\u4E0A\u9650\u306B\u9054\u3057\u305F\u305F\u3081\u6253\u3061\u5207\u308A\u307E\u3057\u305F\uFF08\u7D9A\u304D\u306F\u540C\u3058\u4F1A\u8A71\u3067\u518D\u5EA6\u6307\u793A\u3057\u3066\u304F\u3060\u3055\u3044\uFF09\n");return 1}if(result.upstreamError!==null){err(`\u30E2\u30C7\u30EB\u306E\u5FDC\u7B54\u304C\u9014\u4E2D\u3067\u7D42\u308F\u308A\u307E\u3057\u305F: ${result.upstreamError}
|
|
14
|
+
`);return 1}if(result.aborted||interrupted){err("\u4E2D\u65AD\u3057\u307E\u3057\u305F\uFF08\u3053\u3053\u307E\u3067\u306E\u6D88\u8CBB\u306F\u30C6\u30CA\u30F3\u30C8\u306E\u30AF\u30EC\u30B8\u30C3\u30C8\u306B\u8A08\u4E0A\u3055\u308C\u307E\u3059\uFF09\n");return 130}if(result.emptyResponse){err("\u30E2\u30C7\u30EB\u304B\u3089\u30C6\u30AD\u30B9\u30C8\u5FDC\u7B54\u304C\u3042\u308A\u307E\u305B\u3093\u3067\u3057\u305F\n");return 1}return 0}catch(e){const partial=e.usage;if(partial&&partial.inputTokens+partial.
|
|
15
|
+
outputTokens>0){err(`usage(\u4E2D\u65AD\u307E\u3067): input=${partial.inputTokens} cache_read=${partial.cacheReadTokens} cache_write=${partial.cacheWriteTokens} output=${partial.outputTokens}
|
|
16
|
+
`)}if(e instanceof RelayError){err(`${e.message}
|
|
17
|
+
`);return 1}err(`\u30A8\u30E9\u30FC: ${e.message}
|
|
18
|
+
`);return 1}finally{process.off("SIGINT",onSigint)}}async function readStdin(){const chunks=[];for await(const chunk of process.stdin)chunks.push(Buffer.from(chunk));return Buffer.concat(chunks).toString("utf8")}export{runOneShot};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createRequire as __twpCreateRequire } from 'node:module';
|
|
2
|
+
const require = __twpCreateRequire(import.meta.url);
|
|
3
|
+
import{isRecord,pick,requireResolved,withResolved}from"./chunk-FQDYLZV3.js";import{ApiResponseError,LIST_FLAGS,LIST_PAGING_HELP,UsageError,envelopePaging,nonEmpty,positiveInteger}from"./chunk-KCXVV45F.js";import{collapsesInUrlPath,safeProjectIdPolicy}from"./chunk-5QCAIKFE.js";import"./chunk-VSJBJXZO.js";var LIST_COLUMNS=["id","code","name","status","effective_status"];var GET_COLUMNS=["id","code","name","status","effective_status","display_flg","closed_flg","task_enabled_flg","start_date","end_date","created_at","updated_at"];var MEMBER_COLUMNS=["user_id","user_name","user_email","role","alias","department_name"];function memberItems(body){const list=isRecord(body)?body["list"]:void 0;if(!Array.isArray(list)){throw new ApiResponseError("\u30E1\u30F3\u30D0\u30FC\u4E00\u89A7\u306E\u5FDC\u7B54\u306B list \u914D\u5217\u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002")}
|
|
4
|
+
return list}var listPaging=envelopePaging({label:"\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u4E00\u89A7"});function listItems(body){return listPaging.items(body)}function projectObject(body){const project=isRecord(body)?body["project"]:void 0;if(!isRecord(project)){throw new ApiResponseError("\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u8A73\u7D30\u306E\u5FDC\u7B54\u306B project \u304C\u3042\u308A\u307E\u305B\u3093\u3002\u63A5\u7D9A\u5148\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002")}return project}
|
|
5
|
+
var projectDomain={name:"project",summary:"\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306E\u4E00\u89A7\u30FB\u8A73\u7D30",operations:[{name:"list",summary:"\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u3092\u4E00\u89A7\u3059\u308B",usage:"twp project list [--all] [--limit <\u4EF6\u6570>] [--cursor <\u30AB\u30FC\u30BD\u30EB>] [--keyword <\u8A9E>] [--status <\u72B6\u614B>]",description:"--output json \u306F API \u304C\u8FD4\u3059\u5168\u30D5\u30A3\u30FC\u30EB\u30C9\u3092\u51FA\u3057\u307E\u3059\u3002\n--output table / text / tsv \u306F\u8981\u7D04\u5217\uFF08id / code / name / status / effective_status\uFF09\u3067\u3059\u3002\n\u6B32\u3057\u3044\u5217\u3060\u3051\u3092\
|
|
6
|
+
\u6A5F\u68B0\u51E6\u7406\u3057\u305F\u3044\u3068\u304D\u306F --query \u3067\u9078\u3093\u3067\u304F\u3060\u3055\u3044\uFF08--query \u306F\u751F\u30C7\u30FC\u30BF\u306B\u5BFE\u3057\u3066\u8A55\u4FA1\u3055\u308C\u307E\u3059\uFF09\u3002\n\n"+LIST_PAGING_HELP,flags:[...LIST_FLAGS,{name:"--keyword",summary:"\u30B3\u30FC\u30C9\u30FB\u540D\u79F0\u306E\u90E8\u5206\u4E00\u81F4\u3067\u7D5E\u308A\u8FBC\u3080",takesValue:true,placeholder:"<\u8A9E>"},{name:"--status",summary:"\u30B9\u30C6\u30FC\u30BF\u30B9\u3067\u7D5E\u308A\u8FBC\u3080\uFF08\u4F8B: active\uFF09",
|
|
7
|
+
takesValue:true,placeholder:"<\u72B6\u614B>"}],paging:listPaging,plan(input){if(input.args.length>0){throw new UsageError(`list \u306F\u4F4D\u7F6E\u5F15\u6570\u3092\u53D6\u308A\u307E\u305B\u3093: ${input.args.join(" ")}`,"twp project list help")}return{method:"GET",path:"/api/v2/projects",query:{limit:positiveInteger(input.flags,"--limit"),cursor:nonEmpty(input.flags,"--cursor"),keyword:nonEmpty(input.flags,"--keyword"),status:nonEmpty(input.flags,"--status")}}},summarize:body=>listItems(body).map(
|
|
8
|
+
row=>pick(row,LIST_COLUMNS)),raw:body=>listItems(body)},{name:"get",summary:"\u30D7\u30ED\u30B8\u30A7\u30AF\u30C81\u4EF6\u306E\u8A73\u7D30\u3092\u8868\u793A\u3059\u308B",usage:"twp project get <ID|\u30B3\u30FC\u30C9>",description:'ID\uFF08UUID / ULID\uFF09\u306A\u3089\u305D\u306E\u307E\u307E\u3001\u305D\u308C\u4EE5\u5916\u306F\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u30B3\u30FC\u30C9\u3068\u3057\u3066\u89E3\u6C7A\u3057\u307E\u3059\uFF081\u5F80\u5FA9\uFF09\u3002\n\u30B3\u30FC\u30C9\u304C\u898B\u3064\u304B\u3089\u306A\u3044\u5834\u5408\u3001\u30B5\u30FC\u30D0\u306F\u300C\u5B58\u5728\u3057\u306A\u3044\u300D\u3068\u300C\u95B2\u89A7\u6A29\u9650\u304C\u7121\u3044\u300D\u3092\u610F\u56F3\u7684\u306B\u533A\u5225\u3057\u307E\u305B\u3093\u3002\n\u30B3\u30FC\u30C9\u304C literally "help" \u306E\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u3092\u5F15\u304F\u3068\u304D\u3060\u3051 `twp project get -- help` \u3068\u66F8\u304D\u307E\u3059\n\uFF08\u5148\u982D\u306E help \u306F\u30D8\u30EB\u30D7\u8981\u6C42\u3068\u3057\u3066\u89E3\u91C8\u3055\u308C\u308B\u305F\u3081\uFF09\u3002',
|
|
9
|
+
flags:[],plan(input){const[rawRef,...rest]=input.args;const ref=rawRef?.trim()??"";if(ref===""){throw new UsageError("\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306E UUID \u304B\u30B3\u30FC\u30C9\u3092\u6307\u5B9A\u3057\u3066\u304F\u3060\u3055\u3044","twp project get help")}if(rest.length>0){throw new UsageError(`get \u304C\u53D7\u3051\u53D6\u308C\u308B\u5F15\u6570\u306F1\u3064\u3060\u3051\u3067\u3059: ${rest.join(" ")}`,"twp project get help")}if(collapsesInUrlPath(ref)){throw new UsageError(`\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\
|
|
10
|
+
\u306E UUID \u304B\u30B3\u30FC\u30C9\u3068\u3057\u3066\u4F7F\u3048\u306A\u3044\u5024\u3067\u3059: ${ref}`,"\u30C9\u30C3\u30C8\u3060\u3051\u306E\u5024\u306F URL \u306E\u30D1\u30B9\u8981\u7D20\u3068\u3057\u3066\u6D88\u3048\u3066\u3057\u307E\u3046\u305F\u3081\u53D7\u3051\u4ED8\u3051\u307E\u305B\u3093\u3002")}return safeProjectIdPolicy.isDirectId(ref)?{method:"GET",path:`/api/v2/projects/${encodeURIComponent(ref)}`}:{method:"GET",path:`/api/v2/projects/by-code/${encodeURIComponent(ref)}`}},summarize:body=>pick(
|
|
11
|
+
projectObject(body),GET_COLUMNS),raw:body=>projectObject(body)},{name:"members",summary:"\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\u306E\u30E1\u30F3\u30D0\u30FC\u3092\u4E00\u89A7\u3059\u308B",usage:"twp project members [<ID|\u30B3\u30FC\u30C9>]",description:"\u7701\u7565\u3059\u308B\u3068\u65E2\u5B9A\u30D7\u30ED\u30B8\u30A7\u30AF\u30C8\uFF08TWP_PROJECT / .twp/config.json / ~/.twp/config.json\uFF09\u3092\u4F7F\u3044\u307E\u3059\u3002\n\u3053\u306E API \u306F\u30DA\u30FC\u30B8\u30F3\u30B0\u3092\u6301\u305F\u305A\u3001\u5E38\u306B\u5168\u4EF6\u3092\u8FD4\u3057\u307E\u3059\uFF08--all / --limit \u306F\u3042\u308A\u307E\u305B\u3093\uFF09\u3002\n\u3053\u3053\u306B\u51FA\u308B user_id / user_email \u306F twp task list --assignee \u306B\u305D\u306E\u307E\u307E\u6E21\u305B\u307E\u3059\u3002",
|
|
12
|
+
flags:[],async prepare(input,ctx){const[ref,...rest]=input.args;if(rest.length>0){throw new UsageError(`members \u304C\u53D7\u3051\u53D6\u308C\u308B\u5F15\u6570\u306F1\u3064\u3060\u3051\u3067\u3059: ${rest.join(" ")}`,"twp project members help")}return withResolved(input,{projectId:await ctx.projectId(ref)})},plan(input){const projectId=requireResolved(input,"projectId");return{method:"GET",path:`/api/v2/projects/${encodeURIComponent(projectId)}/members`}},summarize:body=>memberItems(body).map(row=>pick(
|
|
13
|
+
row,MEMBER_COLUMNS)),raw:body=>memberItems(body)}]};export{projectDomain};
|