mqtt-plus 1.1.3 → 1.1.4

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.md CHANGED
@@ -2,6 +2,11 @@
2
2
  ChangeLog
3
3
  =========
4
4
 
5
+ 1.1.4 (2026-02-02)
6
+ ------------------
7
+
8
+ - CLEANUP: various cleanups
9
+
5
10
  1.1.3 (2026-02-02)
6
11
  ------------------
7
12
 
package/README.md CHANGED
@@ -974,7 +974,7 @@ pattern read example/client/+/sink-push-request/%c
974
974
  pattern write example/client/+/sink-push-response/%c
975
975
  pattern read example/client/+/sink-push-chunk/%c
976
976
 
977
- # ==== server/autenticated ACL ====
977
+ # ==== server/authenticated ACL ====
978
978
 
979
979
  user example
980
980
 
@@ -213,12 +213,12 @@ export class SourceTrait extends ServiceTrait {
213
213
  const responseTopic = this.options.topicMake(source, "source-fetch-response", sender);
214
214
  const chunkTopic = this.options.topicMake(source, "source-fetch-chunk", sender);
215
215
  /* callback for sending the ack/nak response */
216
- const sendResponse = (error) => {
216
+ const sendResponse = async (error) => {
217
217
  const auth = this.authenticate();
218
218
  const metaStore = this.metaStore(info.meta);
219
219
  const response = this.msg.makeSourceFetchResponse(requestId, source, error, this.options.id, sender, auth, metaStore);
220
220
  const message = this.codec.encode(response);
221
- this._publishToTopic(responseTopic, message, { qos: 2 }).catch(() => { });
221
+ await this._publishToTopic(responseTopic, message, { qos: 2 }).catch(() => { });
222
222
  };
223
223
  /* callback for creating and sending a chunk message */
224
224
  const sendChunk = (chunk, error, final) => {
@@ -236,10 +236,10 @@ export class SourceTrait extends ServiceTrait {
236
236
  if (!(info.stream instanceof Readable) && !(info.buffer instanceof Promise))
237
237
  throw new Error("handler did not provide data via info.stream or info.buffer fields");
238
238
  /* send ack response */
239
- sendResponse();
239
+ await sendResponse();
240
240
  /* handle Readable stream result */
241
241
  if (info.stream instanceof Readable)
242
- sendStreamAsChunks(info.stream, this.options.chunkSize, sendChunk, () => { }, (err) => sendChunk(undefined, err.message, true));
242
+ sendStreamAsChunks(info.stream, this.options.chunkSize, sendChunk, () => { }, () => { });
243
243
  /* handle Buffer result */
244
244
  else if (info.buffer instanceof Promise)
245
245
  sendBufferAsChunks(await info.buffer, this.options.chunkSize, sendChunk);
@@ -1188,12 +1188,12 @@ class SourceTrait extends ServiceTrait {
1188
1188
  info.authenticated = await this.authenticated(parsed.sender, parsed.auth, handler.auth);
1189
1189
  const responseTopic = this.options.topicMake(source, "source-fetch-response", sender);
1190
1190
  const chunkTopic = this.options.topicMake(source, "source-fetch-chunk", sender);
1191
- const sendResponse = (error) => {
1191
+ const sendResponse = async (error) => {
1192
1192
  const auth = this.authenticate();
1193
1193
  const metaStore = this.metaStore(info.meta);
1194
1194
  const response = this.msg.makeSourceFetchResponse(requestId, source, error, this.options.id, sender, auth, metaStore);
1195
1195
  const message = this.codec.encode(response);
1196
- this._publishToTopic(responseTopic, message, { qos: 2 }).catch(() => {
1196
+ await this._publishToTopic(responseTopic, message, { qos: 2 }).catch(() => {
1197
1197
  });
1198
1198
  };
1199
1199
  const sendChunk = (chunk, error, final) => {
@@ -1209,10 +1209,11 @@ class SourceTrait extends ServiceTrait {
1209
1209
  }).then(async () => {
1210
1210
  if (!(info.stream instanceof node_stream.Readable) && !(info.buffer instanceof Promise))
1211
1211
  throw new Error("handler did not provide data via info.stream or info.buffer fields");
1212
- sendResponse();
1212
+ await sendResponse();
1213
1213
  if (info.stream instanceof node_stream.Readable)
1214
1214
  sendStreamAsChunks(info.stream, this.options.chunkSize, sendChunk, () => {
1215
- }, (err) => sendChunk(void 0, err.message, true));
1215
+ }, () => {
1216
+ });
1216
1217
  else if (info.buffer instanceof Promise)
1217
1218
  sendBufferAsChunks(await info.buffer, this.options.chunkSize, sendChunk);
1218
1219
  }).catch((err) => {
@@ -1170,12 +1170,12 @@ class SourceTrait extends ServiceTrait {
1170
1170
  info.authenticated = await this.authenticated(parsed.sender, parsed.auth, handler.auth);
1171
1171
  const responseTopic = this.options.topicMake(source, "source-fetch-response", sender);
1172
1172
  const chunkTopic = this.options.topicMake(source, "source-fetch-chunk", sender);
1173
- const sendResponse = (error) => {
1173
+ const sendResponse = async (error) => {
1174
1174
  const auth = this.authenticate();
1175
1175
  const metaStore = this.metaStore(info.meta);
1176
1176
  const response = this.msg.makeSourceFetchResponse(requestId, source, error, this.options.id, sender, auth, metaStore);
1177
1177
  const message = this.codec.encode(response);
1178
- this._publishToTopic(responseTopic, message, { qos: 2 }).catch(() => {
1178
+ await this._publishToTopic(responseTopic, message, { qos: 2 }).catch(() => {
1179
1179
  });
1180
1180
  };
1181
1181
  const sendChunk = (chunk, error, final) => {
@@ -1191,10 +1191,11 @@ class SourceTrait extends ServiceTrait {
1191
1191
  }).then(async () => {
1192
1192
  if (!(info.stream instanceof Readable) && !(info.buffer instanceof Promise))
1193
1193
  throw new Error("handler did not provide data via info.stream or info.buffer fields");
1194
- sendResponse();
1194
+ await sendResponse();
1195
1195
  if (info.stream instanceof Readable)
1196
1196
  sendStreamAsChunks(info.stream, this.options.chunkSize, sendChunk, () => {
1197
- }, (err) => sendChunk(void 0, err.message, true));
1197
+ }, () => {
1198
+ });
1198
1199
  else if (info.buffer instanceof Promise)
1199
1200
  sendBufferAsChunks(await info.buffer, this.options.chunkSize, sendChunk);
1200
1201
  }).catch((err) => {
@@ -10,4 +10,4 @@ ${Jr.repeat(s.depth)}}`:s.close="}";break}case J.TAG:f+=String(h),f+=ot(J.POS_IN
10
10
  `;let y=0;for(const E of t.children){if(gi(E)){let h=String(y);t.mt===J.MAP?h=y%2?`val ${(y-1)/2}`:`key ${y/2}`:t.mt===J.TAG&&(h=""),n+=mi(E,e,h)}y++}}return n}const ys={...Ue.defaultDecodeOptions,initialDepth:0,noPrefixHex:!1,minCol:0};function Ei(t,e){const r={...ys,...e,ParentType:Vr,saveOriginal:!0},n=new ar(t,r);let a,s;for(const l of n){if(s=Ue.create(l,a,r,n),l[2]===Ie.BREAK)if(a?.isStreaming)a.left=1;else throw new Error("Unexpected BREAK");if(!gi(s)){const h=new Vr(l,0,a,r);h.leaf=!0,h.children.push(s),Mt(h,n.toHere(l[3])),s=h}let y=(s.depth+1)*2;const E=s.numBytes();for(E&&(y+=1,y+=E*2),r.minCol=Math.max(r.minCol,y),a&&a.push(s,n,l[3]),a=s;a?.done;)s=a,s.leaf||Mt(s,n.toHere(s.offset)),{parent:a}=a}e&&(e.minCol=r.minCol);let f=r.noPrefixHex?"":`0x${Fe(n.toHere(0))}
11
11
  `;return f+=mi(s,r),f}const bi=!Fo();function ur(t){if(typeof t=="object"&&t){if(t.constructor!==Number)throw new Error(`Expected number: ${t}`)}else if(typeof t!="number")throw new Error(`Expected number: ${t}`)}function st(t){if(typeof t=="object"&&t){if(t.constructor!==String)throw new Error(`Expected string: ${t}`)}else if(typeof t!="string")throw new Error(`Expected string: ${t}`)}function rt(t){if(!(t instanceof Uint8Array))throw new Error(`Expected Uint8Array: ${t}`)}function Si(t){if(!Array.isArray(t))throw new Error(`Expected Array: ${t}`)}ge(Map,(t,e,r)=>{const n=[...t.entries()].map(a=>[a[0],a[1],At(a[0],r)]);if(r.rejectDuplicateKeys){const a=new Set;for(const[s,f,l]of n){const y=Fe(l);if(a.has(y))throw new Error(`Duplicate map key: 0x${y}`);a.add(y)}}r.sortKeys&&n.sort(r.sortKeys),jr(t,t.size,J.MAP,e,r);for(const[a,s,f]of n)e.write(f),pt(s,e,r)});function zr(t){return st(t.contents),new Date(t.contents)}zr.comment=t=>{st(t.contents);const e=new Date(t.contents);return`(String ${t.tag===ie.DATE_FULL?"Full ":""}Date) ${e.toISOString()}`},Z.registerDecoder(ie.DATE_STRING,zr),Z.registerDecoder(ie.DATE_FULL,zr);function _i(t){return ur(t.contents),new Date(t.contents*1e3)}_i.comment=t=>(ur(t.contents),`(Epoch Date) ${new Date(t.contents*1e3).toISOString()}`),Z.registerDecoder(ie.DATE_EPOCH,_i);const Yr=1e3*60*60*24;function Ti(t){return ur(t.contents),new Date(t.contents*Yr)}Ti.comment=t=>(ur(t.contents),`(Epoch Date) ${new Date(t.contents*Yr).toISOString()}`),Z.registerDecoder(ie.DATE_EPOCH_DAYS,Ti),ge(Date,(t,e,r)=>{switch(r.dateTag){case ie.DATE_EPOCH:return[r.dateTag,t.valueOf()/1e3];case ie.DATE_STRING:return[r.dateTag,t.toISOString().replace(/\.000Z$/,"Z")];case ie.DATE_EPOCH_DAYS:return[r.dateTag,Math.floor(t.valueOf()/Yr)];case ie.DATE_FULL:return[r.dateTag,t.toISOString().split("T")[0]];default:throw new Error(`Unsupported date tag: ${r.dateTag}`)}});function fr(t,e,r){if(rt(e.contents),r.rejectBigInts)throw new Error(`Decoding unwanted big integer: ${e}(h'${Fe(e.contents)}')`);if(r.requirePreferred&&e.contents[0]===0)throw new Error(`Decoding overly-large bigint: ${e.tag}(h'${Fe(e.contents)})`);let n=e.contents.reduce((s,f)=>s<<8n|BigInt(f),0n);t&&(n=-1n-n);const a=n>=Number.MIN_SAFE_INTEGER&&n<=Number.MAX_SAFE_INTEGER;if(r.requirePreferred&&a)throw new Error(`Decoding bigint that could have been int: ${n}n`);return r.collapseBigInts&&a&&(n=Number(n)),r.boxed?Lt(n,e.contents):n}const vi=fr.bind(null,!1),Ai=fr.bind(null,!0);vi.comment=(t,e)=>`(Positive BigInt) ${fr(!1,t,e)}n`,Ai.comment=(t,e)=>`(Negative BigInt) ${fr(!0,t,e)}n`,Z.registerDecoder(ie.POS_BIGINT,vi),Z.registerDecoder(ie.NEG_BIGINT,Ai);function Xr(t,e){return rt(t.contents),t}Xr.comment=(t,e,r)=>{rt(t.contents);const n={...e,initialDepth:r+2,noPrefixHex:!0},a=Qt(t);let s=2**((a[0]&31)-24)+1;const f=a[s]&31;let l=Fe(a.subarray(s,++s));f>=24&&(l+=" ",l+=Fe(a.subarray(s,s+2**(f-24)))),n.minCol=Math.max(n.minCol,(r+1)*2+l.length);const y=Ei(t.contents,n);let E=`Embedded CBOR
12
12
  `;return E+=`${"".padStart((r+1)*2," ")}${l}`.padEnd(n.minCol+1," "),E+=`-- Bytes (Length: ${t.contents.length})
13
- `,E+=y,E},Xr.noChildren=!0,Z.registerDecoder(ie.CBOR,Xr),Z.registerDecoder(ie.URI,t=>(st(t.contents),new URL(t.contents)),"URI"),ge(URL,t=>[ie.URI,t.toString()]),Z.registerDecoder(ie.BASE64URL,t=>(st(t.contents),No(t.contents)),"Base64url-encoded"),Z.registerDecoder(ie.BASE64,t=>(st(t.contents),Wr(t.contents)),"Base64-encoded"),Z.registerDecoder(35,t=>(st(t.contents),new RegExp(t.contents)),"RegExp"),Z.registerDecoder(21065,t=>{st(t.contents);const e=`^(?:${t.contents})$`;return new RegExp(e,"u")},"I-RegExp"),Z.registerDecoder(ie.REGEXP,t=>{if(Si(t.contents),t.contents.length<1||t.contents.length>2)throw new Error(`Invalid RegExp Array: ${t.contents}`);return new RegExp(t.contents[0],t.contents[1])},"RegExp"),ge(RegExp,t=>[ie.REGEXP,[t.source,t.flags]]),Z.registerDecoder(64,t=>(rt(t.contents),t.contents),"uint8 Typed Array");function Be(t,e,r){rt(t.contents);let n=t.contents.length;if(n%e.BYTES_PER_ELEMENT!==0)throw new Error(`Number of bytes must be divisible by ${e.BYTES_PER_ELEMENT}, got: ${n}`);n/=e.BYTES_PER_ELEMENT;const a=new e(n),s=new DataView(t.contents.buffer,t.contents.byteOffset,t.contents.byteLength),f=s[`get${e.name.replace(/Array/,"")}`].bind(s);for(let l=0;l<n;l++)a[l]=f(l*e.BYTES_PER_ELEMENT,r);return a}function at(t,e,r,n,a){const s=a.forceEndian??bi;if(Ct(s?e:r,t,a),Le(n.byteLength,t,J.BYTE_STRING),bi===s)t.write(new Uint8Array(n.buffer,n.byteOffset,n.byteLength));else{const f=`write${n.constructor.name.replace(/Array/,"")}`,l=t[f].bind(t);for(const y of n)l(y,s)}}Z.registerDecoder(65,t=>Be(t,Uint16Array,!1),"uint16, big endian, Typed Array"),Z.registerDecoder(66,t=>Be(t,Uint32Array,!1),"uint32, big endian, Typed Array"),Z.registerDecoder(67,t=>Be(t,BigUint64Array,!1),"uint64, big endian, Typed Array"),Z.registerDecoder(68,t=>(rt(t.contents),new Uint8ClampedArray(t.contents)),"uint8 Typed Array, clamped arithmetic"),ge(Uint8ClampedArray,t=>[68,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)]),Z.registerDecoder(69,t=>Be(t,Uint16Array,!0),"uint16, little endian, Typed Array"),ge(Uint16Array,(t,e,r)=>at(e,69,65,t,r)),Z.registerDecoder(70,t=>Be(t,Uint32Array,!0),"uint32, little endian, Typed Array"),ge(Uint32Array,(t,e,r)=>at(e,70,66,t,r)),Z.registerDecoder(71,t=>Be(t,BigUint64Array,!0),"uint64, little endian, Typed Array"),ge(BigUint64Array,(t,e,r)=>at(e,71,67,t,r)),Z.registerDecoder(72,t=>(rt(t.contents),new Int8Array(t.contents)),"sint8 Typed Array"),ge(Int8Array,t=>[72,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)]),Z.registerDecoder(73,t=>Be(t,Int16Array,!1),"sint16, big endian, Typed Array"),Z.registerDecoder(74,t=>Be(t,Int32Array,!1),"sint32, big endian, Typed Array"),Z.registerDecoder(75,t=>Be(t,BigInt64Array,!1),"sint64, big endian, Typed Array"),Z.registerDecoder(77,t=>Be(t,Int16Array,!0),"sint16, little endian, Typed Array"),ge(Int16Array,(t,e,r)=>at(e,77,73,t,r)),Z.registerDecoder(78,t=>Be(t,Int32Array,!0),"sint32, little endian, Typed Array"),ge(Int32Array,(t,e,r)=>at(e,78,74,t,r)),Z.registerDecoder(79,t=>Be(t,BigInt64Array,!0),"sint64, little endian, Typed Array"),ge(BigInt64Array,(t,e,r)=>at(e,79,75,t,r)),Z.registerDecoder(81,t=>Be(t,Float32Array,!1),"IEEE 754 binary32, big endian, Typed Array"),Z.registerDecoder(82,t=>Be(t,Float64Array,!1),"IEEE 754 binary64, big endian, Typed Array"),Z.registerDecoder(85,t=>Be(t,Float32Array,!0),"IEEE 754 binary32, little endian, Typed Array"),ge(Float32Array,(t,e,r)=>at(e,85,81,t,r)),Z.registerDecoder(86,t=>Be(t,Float64Array,!0),"IEEE 754 binary64, big endian, Typed Array"),ge(Float64Array,(t,e,r)=>at(e,86,82,t,r)),Z.registerDecoder(ie.SET,(t,e)=>{if(Si(t.contents),e.sortKeys){const r=Ue.decodeToEncodeOpts(e);let n=null;for(const a of t.contents){const s=[a,void 0,At(a,r)];if(n&&e.sortKeys(n,s)>=0)throw new Error(`Set items out of order in tag #${ie.SET}`);n=s}}return new Set(t.contents)},"Set"),ge(Set,(t,e,r)=>{let n=[...t];if(r.sortKeys){const a=n.map(s=>[s,void 0,At(s,r)]);a.sort(r.sortKeys),n=a.map(([s])=>s)}return[ie.SET,n]}),Z.registerDecoder(ie.JSON,t=>(st(t.contents),JSON.parse(t.contents)),"JSON-encoded");function xi(t){return rt(t.contents),new ir().decode(t.contents)}xi.comment=t=>{rt(t.contents);const e=new ir;return`(WTF8 string): ${JSON.stringify(e.decode(t.contents))}`},Z.registerDecoder(ie.WTF8,xi),Z.registerDecoder(ie.SELF_DESCRIBED,t=>t.contents,"Self-Described"),Z.registerDecoder(ie.INVALID_16,()=>{throw new Error(`Tag always invalid: ${ie.INVALID_16}`)},"Invalid"),Z.registerDecoder(ie.INVALID_32,()=>{throw new Error(`Tag always invalid: ${ie.INVALID_32}`)},"Invalid"),Z.registerDecoder(ie.INVALID_64,()=>{throw new Error(`Tag always invalid: ${ie.INVALID_64}`)},"Invalid");function Zr(t){throw new Error(`Encoding ${t.constructor.name} intentionally unimplmented. It is not concrete enough to interoperate. Convert to Uint8Array first.`)}ge(ArrayBuffer,Zr),ge(DataView,Zr),typeof SharedArrayBuffer<"u"&&ge(SharedArrayBuffer,Zr);function lr(t){return[NaN,t.valueOf()]}ge(Boolean,lr),ge(Number,lr),ge(String,lr),ge(BigInt,lr);function ws(t){const e={...Ue.defaultDecodeOptions};if(t.dcbor?Object.assign(e,Ue.dcborDecodeOptions):t.cde&&Object.assign(e,Ue.cdeDecodeOptions),Object.assign(e,t),Object.hasOwn(e,"rejectLongNumbers"))throw new TypeError("rejectLongNumbers has changed to requirePreferred");return e.boxed&&(e.saveOriginal=!0),e}let gs=class{parent=void 0;ret=void 0;step(e,r,n){if(this.ret=Ue.create(e,this.parent,r,n),e[2]===Ie.BREAK)if(this.parent?.isStreaming)this.parent.left=0;else throw new Error("Unexpected BREAK");else this.parent&&this.parent.push(this.ret,n,e[3]);for(this.ret instanceof Ue&&(this.parent=this.ret);this.parent?.done;){this.ret=this.parent.convert(n);const a=this.parent.parent;a?.replaceLast(this.ret,this.parent,n),this.parent=a}}};function ms(t,e={}){const r=ws(e),n=new ar(t,r),a=new gs;for(const s of n)a.step(s,r,n);return a.ret}const{cdeDecodeOptions:wa,dcborDecodeOptions:ga,defaultDecodeOptions:ma}=Ue;class Es{constructor(e={}){this.options={id:kt(),codec:"cbor",timeout:10*1e3,chunkSize:16*1024,topicMake:(r,n,a)=>`${r}/${n}/${a??"any"}`,topicMatch:r=>{const n=r.match(/^(.+)\/([^/]+)\/([^/]+)$/);return n?{name:n[1],operation:n[2],peerId:n[3]==="any"?void 0:n[3]}:null},...e}}}class Qr{static uint8ArrayToBase64(e){return btoa(String.fromCharCode(...e))}static base64ToUint8Array(e){const r=atob(e),n=new Uint8Array(r.length);for(let a=0;a<r.length;a++)n[a]=r.charCodeAt(a);return n}static stringify(e){return JSON.stringify(e,(r,n)=>n instanceof Uint8Array?{__Uint8Array:this.uint8ArrayToBase64(n)}:n)}static parse(e){return JSON.parse(e,(r,n)=>typeof n?.__Uint8Array=="string"?this.base64ToUint8Array(n.__Uint8Array):n)}}class bs{constructor(e){this.type=e,this.types=new zn,this.tags=new Map;const r=64e3;this.types.registerEncoder(Tt,n=>[r,new Uint8Array(n.buffer,n.byteOffset,n.byteLength)]),this.tags.set(r,n=>Tt.from(n.contents))}encode(e){let r;if(this.type==="cbor")try{r=At(e,{types:this.types})}catch{throw new Error("failed to encode CBOR format")}else if(this.type==="json")try{r=Qr.stringify(e)}catch{throw new Error("failed to encode JSON format")}else throw new Error("invalid format");return r}decode(e){let r;if(this.type==="cbor"&&e instanceof Uint8Array)try{r=ms(e,{tags:this.tags})}catch{throw new Error("failed to decode CBOR format")}else if(this.type==="json"&&typeof e=="string")try{r=Qr.parse(e)}catch{throw new Error("failed to decode JSON format")}else throw new Error("invalid format or wrong data type");return r}}class Ss extends Es{constructor(e={}){super(e),this.codec=new bs(this.options.codec)}}class _s extends Ss{str2buf(e){return new TextEncoder().encode(e)}buf2str(e){return new TextDecoder().decode(e)}arr2buf(e){let r;return e instanceof Uint8Array?r=e:r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r}buf2arr(e,r){let n;if(r===Tt)n=Tt.from(e.buffer,e.byteOffset,e.byteLength);else if(r===Uint8Array)n=e;else if(r===Int8Array)n=new Int8Array(e.buffer,e.byteOffset,e.byteLength);else throw new Error("invalid data type");return n}}class nt{constructor(e,r,n,a){this.type=e,this.id=r,this.sender=n,this.receiver=a}}class Ri extends nt{constructor(e,r,n,a,s,f,l){super("event-emission",e,a,s),this.name=r,this.params=n,this.auth=f,this.meta=l}}class Ii extends nt{constructor(e,r,n,a,s,f,l){super("service-call-request",e,a,s),this.name=r,this.params=n,this.auth=f,this.meta=l}}class Bi extends nt{constructor(e,r,n,a,s){super("service-call-response",e,a,s),this.result=r,this.error=n}}class Ni extends nt{constructor(e,r,n,a,s,f,l){super("sink-push-request",e,a,s),this.name=r,this.params=n,this.auth=f,this.meta=l}}class Fi extends nt{constructor(e,r,n,a,s,f,l){super("sink-push-response",e,a,s),this.name=r,this.error=n,this.auth=f,this.meta=l}}class Ui extends nt{constructor(e,r,n,a,s,f,l){super("sink-push-chunk",e,f,l),this.name=r,this.chunk=n,this.error=a,this.final=s}}class ki extends nt{constructor(e,r,n,a,s,f,l){super("source-fetch-request",e,a,s),this.name=r,this.params=n,this.auth=f,this.meta=l}}class Mi extends nt{constructor(e,r,n,a,s,f,l){super("source-fetch-response",e,a,s),this.name=r,this.error=n,this.auth=f,this.meta=l}}class Li extends nt{constructor(e,r,n,a,s,f,l){super("source-fetch-chunk",e,f,l),this.name=r,this.chunk=n,this.error=a,this.final=s}}class Ts{makeEventEmission(e,r,n,a,s,f,l){return new Ri(e,r,n,a,s,f,l)}makeServiceCallRequest(e,r,n,a,s,f,l){return new Ii(e,r,n,a,s,f,l)}makeServiceCallResponse(e,r,n,a,s){return new Bi(e,r,n,a,s)}makeSinkPushRequest(e,r,n,a,s,f,l){return new Ni(e,r,n,a,s,f,l)}makeSinkPushResponse(e,r,n,a,s,f,l){return new Fi(e,r,n,a,s,f,l)}makeSinkPushChunk(e,r,n,a,s,f,l){return new Ui(e,r,n,a,s,f,l)}makeSourceFetchRequest(e,r,n,a,s,f,l){return new ki(e,r,n,a,s,f,l)}makeSourceFetchResponse(e,r,n,a,s,f,l){return new Mi(e,r,n,a,s,f,l)}makeSourceFetchChunk(e,r,n,a,s,f,l){return new Li(e,r,n,a,s,f,l)}parse(e){if(typeof e!="object"||e===null)throw new Error("invalid argument: not an object");if(!("type"in e)||typeof e.type!="string")throw new Error('invalid object: missing or invalid "type" field');if(!("id"in e)||typeof e.id!="string")throw new Error('invalid object: missing or invalid "id" field');if("sender"in e&&e.sender!==void 0&&typeof e.sender!="string")throw new Error('invalid object: invalid "sender" field');if("receiver"in e&&e.receiver!==void 0&&typeof e.receiver!="string")throw new Error('invalid object: invalid "receiver" field');const r=(a,s)=>Object.keys(a).some(f=>!s.includes(f)),n=a=>a.params===void 0||typeof a.params=="object"&&Array.isArray(a.params);if(e.type==="event-emission"){if(typeof e.name!="string")throw new Error('invalid EventEmission object: "name" field must be a string');if(r(e,["type","id","name","params","sender","receiver","auth","meta"]))throw new Error("invalid EventEmission object: contains unknown fields");if(!n(e))throw new Error('invalid EventEmission object: "params" field must be an array');return this.makeEventEmission(e.id,e.name,e.params,e.sender,e.receiver,e.auth,e.meta)}else if(e.type==="service-call-request"){if(typeof e.name!="string")throw new Error('invalid ServiceCallRequest object: "name" field must be a string');if(r(e,["type","id","name","params","sender","receiver","auth","meta"]))throw new Error("invalid ServiceCallRequest object: contains unknown fields");if(!n(e))throw new Error('invalid ServiceCallRequest object: "params" field must be an array');return this.makeServiceCallRequest(e.id,e.name,e.params,e.sender,e.receiver,e.auth,e.meta)}else if(e.type==="service-call-response"){if(r(e,["type","id","result","error","sender","receiver"]))throw new Error("invalid ServiceCallResponse object: contains unknown fields");return this.makeServiceCallResponse(e.id,e.result,e.error,e.sender,e.receiver)}else if(e.type==="sink-push-request"){if(typeof e.name!="string")throw new Error('invalid SinkPushRequest object: "name" field must be a string');if(r(e,["type","id","name","params","sender","receiver","auth","meta"]))throw new Error("invalid SinkPushRequest object: contains unknown fields");if(!n(e))throw new Error('invalid SinkPushRequest object: "params" field must be an array');return this.makeSinkPushRequest(e.id,e.name,e.params,e.sender,e.receiver,e.auth,e.meta)}else if(e.type==="sink-push-response"){if(typeof e.name!="string")throw new Error('invalid SinkPushResponse object: "name" field must be a string');if(e.error!==void 0&&typeof e.error!="string")throw new Error('invalid SinkPushResponse object: "error" field must be a string');if(r(e,["type","id","name","error","sender","receiver","auth","meta"]))throw new Error("invalid SinkPushResponse object: contains unknown fields");return this.makeSinkPushResponse(e.id,e.name,e.error,e.sender,e.receiver,e.auth,e.meta)}else if(e.type==="sink-push-chunk"){if(typeof e.name!="string")throw new Error('invalid SinkPushChunk object: "name" field must be a string');if(e.chunk!==void 0&&(e.chunk===null||typeof e.chunk!="object"))throw new Error('invalid SinkPushChunk object: "chunk" field must be an object');if(e.error!==void 0&&typeof e.error!="string")throw new Error('invalid SinkPushChunk object: "error" field must be a string');if(e.final!==void 0&&typeof e.final!="boolean")throw new Error('invalid SinkPushChunk object: "final" field must be a boolean');if(r(e,["type","id","name","chunk","error","final","sender","receiver"]))throw new Error("invalid SinkPushChunk object: contains unknown fields");return this.makeSinkPushChunk(e.id,e.name,e.chunk,e.error,e.final,e.sender,e.receiver)}else if(e.type==="source-fetch-request"){if(typeof e.name!="string")throw new Error('invalid SourceFetchRequest object: "name" field must be a string');if(r(e,["type","id","name","params","sender","receiver","auth","meta"]))throw new Error("invalid SourceFetchRequest object: contains unknown fields");if(!n(e))throw new Error('invalid SourceFetchRequest object: "params" field must be an array');return this.makeSourceFetchRequest(e.id,e.name,e.params,e.sender,e.receiver,e.auth,e.meta)}else if(e.type==="source-fetch-response"){if(typeof e.name!="string")throw new Error('invalid SourceFetchResponse object: "name" field must be a string');if(e.error!==void 0&&typeof e.error!="string")throw new Error('invalid SourceFetchResponse object: "error" field must be a string');if(r(e,["type","id","name","error","sender","receiver","auth","meta"]))throw new Error("invalid SourceFetchResponse object: contains unknown fields");return this.makeSourceFetchResponse(e.id,e.name,e.error,e.sender,e.receiver,e.auth,e.meta)}else if(e.type==="source-fetch-chunk"){if(typeof e.name!="string")throw new Error('invalid SourceFetchChunk object: "name" field must be a string');if(e.chunk!==void 0&&(e.chunk===null||typeof e.chunk!="object"))throw new Error('invalid SourceFetchChunk object: "chunk" field must be an object');if(e.error!==void 0&&typeof e.error!="string")throw new Error('invalid SourceFetchChunk object: "error" field must be a string');if(e.final!==void 0&&typeof e.final!="boolean")throw new Error('invalid SourceFetchChunk object: "final" field must be a boolean');if(r(e,["type","id","name","chunk","error","final","sender","receiver"]))throw new Error("invalid SourceFetchChunk object: contains unknown fields");return this.makeSourceFetchChunk(e.id,e.name,e.chunk,e.error,e.final,e.sender,e.receiver)}else throw new Error("invalid object: not of any known type")}}class vs extends _s{constructor(){super(...arguments),this.msg=new Ts}}const hr=new TextEncoder,qt=new TextDecoder;function Pi(...t){const e=t.reduce((a,{length:s})=>a+s,0),r=new Uint8Array(e);let n=0;for(const a of t)r.set(a,n),n+=a.length;return r}function xt(t){const e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){const n=t.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=n}return e}function As(t){if(Uint8Array.prototype.toBase64)return t.toBase64();const e=32768,r=[];for(let n=0;n<t.length;n+=e)r.push(String.fromCharCode.apply(null,t.subarray(n,n+e)));return btoa(r.join(""))}function xs(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t);const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function dr(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:qt.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=qt.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return xs(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function en(t){let e=t;return typeof e=="string"&&(e=hr.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):As(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}class Rt extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class je extends Rt{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,r,n="unspecified",a="unspecified"){super(e,{cause:{claim:n,reason:a,payload:r}}),this.claim=n,this.reason=a,this.payload=r}}class Di extends Rt{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,r,n="unspecified",a="unspecified"){super(e,{cause:{claim:n,reason:a,payload:r}}),this.claim=n,this.reason=a,this.payload=r}}class yt extends Rt{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class me extends Rt{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class tn extends Rt{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class Rs extends Rt{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}}function Oi(t,e){const r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(t.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:t};default:throw new yt(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}function Ci(t,e){if(t.startsWith("RS")||t.startsWith("PS")){const{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}}const Je=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),It=(t,e)=>t.name===e;function rn(t){return parseInt(t.name.slice(4),10)}function Is(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Bs(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function Ns(t,e,r){switch(e){case"HS256":case"HS384":case"HS512":{if(!It(t.algorithm,"HMAC"))throw Je("HMAC");const n=parseInt(e.slice(2),10);if(rn(t.algorithm.hash)!==n)throw Je(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!It(t.algorithm,"RSASSA-PKCS1-v1_5"))throw Je("RSASSA-PKCS1-v1_5");const n=parseInt(e.slice(2),10);if(rn(t.algorithm.hash)!==n)throw Je(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!It(t.algorithm,"RSA-PSS"))throw Je("RSA-PSS");const n=parseInt(e.slice(2),10);if(rn(t.algorithm.hash)!==n)throw Je(`SHA-${n}`,"algorithm.hash");break}case"Ed25519":case"EdDSA":{if(!It(t.algorithm,"Ed25519"))throw Je("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!It(t.algorithm,e))throw Je(e);break}case"ES256":case"ES384":case"ES512":{if(!It(t.algorithm,"ECDSA"))throw Je("ECDSA");const n=Is(e);if(t.algorithm.namedCurve!==n)throw Je(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Bs(t,r)}function $i(t,e,...r){if(r=r.filter(Boolean),r.length>2){const n=r.pop();t+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}const Fs=(t,...e)=>$i("Key must be ",t,...e),qi=(t,e,...r)=>$i(`Key for the ${t} algorithm must be `,e,...r);async function Wi(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(Fs(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}return Ns(e,t,r),e}async function Us(t,e,r){const n=await Wi(t,e,"sign");Ci(t,n);const a=await crypto.subtle.sign(Oi(t,n.algorithm),n,r);return new Uint8Array(a)}function Ki(...t){const e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(const n of e){const a=Object.keys(n);if(!r||r.size===0){r=new Set(a);continue}for(const s of a){if(r.has(s))return!1;r.add(s)}}return!0}const Hi=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},Gi=t=>t?.[Symbol.toStringTag]==="KeyObject",ji=t=>Hi(t)||Gi(t),ks=t=>typeof t=="object"&&t!==null;function Wt(t){if(!ks(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}const nn=t=>Wt(t)&&typeof t.kty=="string",Ms=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),Ls=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,Ps=t=>t.kty==="oct"&&typeof t.k=="string",Bt=t=>t?.[Symbol.toStringTag],on=(t,e,r)=>{if(e.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, its "alg" must be "${t}" when present`);if(Array.isArray(e.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case t==="dir":case t.includes("CBC-HS"):n=r;break;case t.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(t):!t.includes("GCM")&&t.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&t.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=t.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&e.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},Ds=(t,e,r)=>{if(!(e instanceof Uint8Array)){if(nn(e)){if(Ps(e)&&on(t,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ji(e))throw new TypeError(qi(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${Bt(e)} instances for symmetric algorithms must be of type "secret"`)}},Os=(t,e,r)=>{if(nn(e))switch(r){case"decrypt":case"sign":if(Ms(e)&&on(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(Ls(e)&&on(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!ji(e))throw new TypeError(qi(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${Bt(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(r){case"sign":throw new TypeError(`${Bt(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${Bt(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(r){case"verify":throw new TypeError(`${Bt(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${Bt(e)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Ji(t,e,r){switch(t.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Ds(t,e,r);break;default:Os(t,e,r)}}function Vi(t,e,r,n,a){if(a.crit!==void 0&&n?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(f=>typeof f!="string"||f.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...e.entries()]):s=e;for(const f of n.crit){if(!s.has(f))throw new yt(`Extension Header Parameter "${f}" is not recognized`);if(a[f]===void 0)throw new t(`Extension Header Parameter "${f}" is missing`);if(s.get(f)&&n[f]===void 0)throw new t(`Extension Header Parameter "${f}" MUST be integrity protected`)}return new Set(n.crit)}function Cs(t){let e,r;switch(t.kty){case"AKP":{switch(t.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":e={name:t.alg},r=t.priv?["sign"]:["verify"];break;default:throw new yt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new yt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(t.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=t.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=t.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new yt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(t.alg){case"Ed25519":case"EdDSA":e={name:"Ed25519"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new yt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new yt('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}async function $s(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:r}=Cs(t),n={...t};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,e,t.ext??!(t.d||t.priv),t.key_ops??r)}let Nt;const zi=async(t,e,r,n=!1)=>{Nt||=new WeakMap;let a=Nt.get(t);if(a?.[r])return a[r];const s=await $s({...e,alg:r});return n&&Object.freeze(t),a?a[r]=s:Nt.set(t,{[r]:s}),s},qs=(t,e)=>{Nt||=new WeakMap;let r=Nt.get(t);if(r?.[e])return r[e];const n=t.type==="public",a=!!n;let s;if(t.asymmetricKeyType==="x25519"){switch(e){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}s=t.toCryptoKey(t.asymmetricKeyType,a,n?[]:["deriveBits"])}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError("given KeyObject instance cannot be used for this algorithm");s=t.toCryptoKey(t.asymmetricKeyType,a,[n?"verify":"sign"])}switch(t.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(e!==t.asymmetricKeyType.toUpperCase())throw new TypeError("given KeyObject instance cannot be used for this algorithm");s=t.toCryptoKey(t.asymmetricKeyType,a,[n?"verify":"sign"])}}if(t.asymmetricKeyType==="rsa"){let f;switch(e){case"RSA-OAEP":f="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":f="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":f="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":f="SHA-512";break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}if(e.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:f},a,n?["encrypt"]:["decrypt"]);s=t.toCryptoKey({name:e.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:f},a,[n?"verify":"sign"])}if(t.asymmetricKeyType==="ec"){const l=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(t.asymmetricKeyDetails?.namedCurve);if(!l)throw new TypeError("given KeyObject instance cannot be used for this algorithm");e==="ES256"&&l==="P-256"&&(s=t.toCryptoKey({name:"ECDSA",namedCurve:l},a,[n?"verify":"sign"])),e==="ES384"&&l==="P-384"&&(s=t.toCryptoKey({name:"ECDSA",namedCurve:l},a,[n?"verify":"sign"])),e==="ES512"&&l==="P-521"&&(s=t.toCryptoKey({name:"ECDSA",namedCurve:l},a,[n?"verify":"sign"])),e.startsWith("ECDH-ES")&&(s=t.toCryptoKey({name:"ECDH",namedCurve:l},a,n?[]:["deriveBits"]))}if(!s)throw new TypeError("given KeyObject instance cannot be used for this algorithm");return r?r[e]=s:Nt.set(t,{[e]:s}),s};async function Yi(t,e){if(t instanceof Uint8Array||Hi(t))return t;if(Gi(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return qs(t,e)}catch(n){if(n instanceof TypeError)throw n}let r=t.export({format:"jwk"});return zi(t,r,e)}if(nn(t))return t.k?dr(t.k):zi(t,t,e,!0);throw new Error("unreachable")}class Ws{#e;#t;#r;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=e}setProtectedHeader(e){if(this.#t)throw new TypeError("setProtectedHeader can only be called once");return this.#t=e,this}setUnprotectedHeader(e){if(this.#r)throw new TypeError("setUnprotectedHeader can only be called once");return this.#r=e,this}async sign(e,r){if(!this.#t&&!this.#r)throw new me("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Ki(this.#t,this.#r))throw new me("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...this.#t,...this.#r},a=Vi(me,new Map([["b64",!0]]),r?.crit,this.#t,n);let s=!0;if(a.has("b64")&&(s=this.#t.b64,typeof s!="boolean"))throw new me('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:f}=n;if(typeof f!="string"||!f)throw new me('JWS "alg" (Algorithm) Header Parameter missing or invalid');Ji(f,e,"sign");let l,y;s?(l=en(this.#e),y=xt(l)):(y=this.#e,l="");let E,h;this.#t?(E=en(JSON.stringify(this.#t)),h=xt(E)):(E="",h=new Uint8Array);const v=Pi(h,xt("."),y),B=await Yi(e,f),q=await Us(f,B,v),O={signature:en(q),payload:l};return this.#r&&(O.header=this.#r),this.#t&&(O.protected=E),O}}class Ks{#e;constructor(e){this.#e=new Ws(e)}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}async sign(e,r){const n=await this.#e.sign(e,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}}const ct=t=>Math.floor(t.getTime()/1e3),Xi=60,Zi=Xi*60,sn=Zi*24,Hs=sn*7,Gs=sn*365.25,js=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Kt(t){const e=js.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const r=parseFloat(e[2]),n=e[3].toLowerCase();let a;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":a=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":a=Math.round(r*Xi);break;case"hour":case"hours":case"hr":case"hrs":case"h":a=Math.round(r*Zi);break;case"day":case"days":case"d":a=Math.round(r*sn);break;case"week":case"weeks":case"w":a=Math.round(r*Hs);break;default:a=Math.round(r*Gs);break}return e[1]==="-"||e[4]==="ago"?-a:a}function wt(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}const Qi=t=>t.includes("/")?t.toLowerCase():`application/${t.toLowerCase()}`,Js=(t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):!1;function Vs(t,e,r={}){let n;try{n=JSON.parse(qt.decode(e))}catch{}if(!Wt(n))throw new tn("JWT Claims Set must be a top-level JSON object");const{typ:a}=r;if(a&&(typeof t.typ!="string"||Qi(t.typ)!==Qi(a)))throw new je('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:s=[],issuer:f,subject:l,audience:y,maxTokenAge:E}=r,h=[...s];E!==void 0&&h.push("iat"),y!==void 0&&h.push("aud"),l!==void 0&&h.push("sub"),f!==void 0&&h.push("iss");for(const O of new Set(h.reverse()))if(!(O in n))throw new je(`missing required "${O}" claim`,n,O,"missing");if(f&&!(Array.isArray(f)?f:[f]).includes(n.iss))throw new je('unexpected "iss" claim value',n,"iss","check_failed");if(l&&n.sub!==l)throw new je('unexpected "sub" claim value',n,"sub","check_failed");if(y&&!Js(n.aud,typeof y=="string"?[y]:y))throw new je('unexpected "aud" claim value',n,"aud","check_failed");let v;switch(typeof r.clockTolerance){case"string":v=Kt(r.clockTolerance);break;case"number":v=r.clockTolerance;break;case"undefined":v=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:B}=r,q=ct(B||new Date);if((n.iat!==void 0||E)&&typeof n.iat!="number")throw new je('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new je('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>q+v)throw new je('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new je('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=q-v)throw new Di('"exp" claim timestamp check failed',n,"exp","check_failed")}if(E){const O=q-n.iat,K=typeof E=="number"?E:Kt(E);if(O-v>K)throw new Di('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(O<0-v)throw new je('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}class zs{#e;constructor(e){if(!Wt(e))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(e)}data(){return hr.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){typeof e=="number"?this.#e.nbf=wt("setNotBefore",e):e instanceof Date?this.#e.nbf=wt("setNotBefore",ct(e)):this.#e.nbf=ct(new Date)+Kt(e)}set exp(e){typeof e=="number"?this.#e.exp=wt("setExpirationTime",e):e instanceof Date?this.#e.exp=wt("setExpirationTime",ct(e)):this.#e.exp=ct(new Date)+Kt(e)}set iat(e){e===void 0?this.#e.iat=ct(new Date):e instanceof Date?this.#e.iat=wt("setIssuedAt",ct(e)):typeof e=="string"?this.#e.iat=wt("setIssuedAt",ct(new Date)+Kt(e)):this.#e.iat=wt("setIssuedAt",e)}}class Ys{#e;#t;constructor(e={}){this.#t=new zs(e)}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,r){const n=new Ks(this.#t.data());if(n.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new tn("JWTs MUST NOT use unencoded payload");return n.sign(e,r)}}async function Xs(t,e,r,n){const a=await Wi(t,e,"verify");Ci(t,a);const s=Oi(t,a.algorithm);try{return await crypto.subtle.verify(s,a,r,n)}catch{return!1}}async function Zs(t,e,r){if(!Wt(t))throw new me("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new me('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new me("JWS Protected Header incorrect type");if(t.payload===void 0)throw new me("JWS Payload missing");if(typeof t.signature!="string")throw new me("JWS Signature missing or incorrect type");if(t.header!==void 0&&!Wt(t.header))throw new me("JWS Unprotected Header incorrect type");let n={};if(t.protected)try{const K=dr(t.protected);n=JSON.parse(qt.decode(K))}catch{throw new me("JWS Protected Header is invalid")}if(!Ki(n,t.header))throw new me("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const a={...n,...t.header},s=Vi(me,new Map([["b64",!0]]),r?.crit,n,a);let f=!0;if(s.has("b64")&&(f=n.b64,typeof f!="boolean"))throw new me('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:l}=a;if(typeof l!="string"||!l)throw new me('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(f){if(typeof t.payload!="string")throw new me("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new me("JWS Payload must be a string or an Uint8Array instance");let y=!1;typeof e=="function"&&(e=await e(n,t),y=!0),Ji(l,e,"verify");const E=Pi(t.protected!==void 0?xt(t.protected):new Uint8Array,xt("."),typeof t.payload=="string"?f?xt(t.payload):hr.encode(t.payload):t.payload);let h;try{h=dr(t.signature)}catch{throw new me("Failed to base64url decode the signature")}const v=await Yi(e,l);if(!await Xs(l,v,h,E))throw new Rs;let q;if(f)try{q=dr(t.payload)}catch{throw new me("Failed to base64url decode the payload")}else typeof t.payload=="string"?q=hr.encode(t.payload):q=t.payload;const O={payload:q};return t.protected!==void 0&&(O.protectedHeader=n),t.header!==void 0&&(O.unprotectedHeader=t.header),y?{...O,key:v}:O}async function Qs(t,e,r){if(t instanceof Uint8Array&&(t=qt.decode(t)),typeof t!="string")throw new me("Compact JWS must be a string or Uint8Array");const{0:n,1:a,2:s,length:f}=t.split(".");if(f!==3)throw new me("Invalid Compact JWS");const l=await Zs({payload:a,protected:n,signature:s},e,r),y={payload:l.payload,protectedHeader:l.protectedHeader};return typeof e=="function"?{...y,key:l.key}:y}async function ea(t,e,r){const n=await Qs(t,e,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new tn("JWTs MUST NOT use unencoded payload");const s={payload:Vs(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof e=="function"?{...s,key:n.key}:s}var ta=jt();class ra{constructor(e,r,n,a){this.timestamp=e,this.level=r,this.msg=n,this.data=a}async resolve(){if(this.msg instanceof Promise&&(this.msg=await this.msg.catch(()=>"<resolve-failed>")),this.data)for(const e of Object.keys(this.data))this.data[e]instanceof Promise&&(this.data[e]=await this.data[e].catch(()=>"<resolve-failed>"))}toString(){const e=new Date(this.timestamp),r=e.getFullYear(),n=(e.getMonth()+1).toString().padStart(2,"0"),a=e.getDate().toString().padStart(2,"0"),s=e.getHours().toString().padStart(2,"0"),f=e.getMinutes().toString().padStart(2,"0"),l=e.getSeconds().toString().padStart(2,"0"),y=e.getMilliseconds().toString().padStart(3,"0"),E=`${r}-${n}-${a} ${s}:${f}:${l}.${y}`,h=this.msg instanceof Promise?"<unresolved>":this.msg;let v="";return this.data!==void 0&&(v=` (${Object.keys(this.data).map(q=>{const O=this.data[q]instanceof Promise?"<unresolved>":this.data[q];return`${q}: ${Qr.stringify(O)}`}).join(", ")})`),`[${E}] ${this.level}: ${h}${v}`}}class na extends vs{constructor(){super(...arguments),this._events=new ta.EventEmitter}on(...e){return this._events.on(...e)}off(...e){return this._events.off(...e)}emitEvent(...e){try{return this._events.emit(...e)}catch{return!1}}log(e,r,n){const a=new ra(Date.now(),e,r,n);this.emitEvent("log",a)}error(e,r){let n=e;r!==void 0&&(n=new Error(`${r}: ${e.message}`,{cause:e})),this.emitEvent("error",n),this.log("error",n.message)}}class ia extends na{constructor(e,r={}){super(r),e===null&&(this.log("info","establishing proxy MQTT client"),e=new Proxy({},{get(n,a,s){return a==="isFakeProxy"?!0:()=>{}}})),this.mqtt=e,this.log("info","hooking into MQTT client"),this._messageHandler=(n,a,s)=>{let f;if(this.options.codec==="json")f=a.toString();else if(this.options.codec==="cbor")f=Tt.isBuffer(a)?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):a;else throw new Error("invalid codec configured");this._onMessage(n,f,s)},this.mqtt.on("message",this._messageHandler)}destroy(){this.log("info","un-hooking from MQTT client"),this.mqtt.off("message",this._messageHandler)}async _subscribeTopic(e,r={}){return this.log("info",`subscribing to MQTT topic "${e}"`),new Promise((n,a)=>{this.mqtt.subscribe(e,{qos:2,...r},(s,f)=>{s?(this.error(s,`subscribing to MQTT topic "${e}" failed`),a(s)):n()})})}async _unsubscribeTopic(e){return this.log("info",`unsubscribing from MQTT topic "${e}"`),new Promise((r,n)=>{this.mqtt.unsubscribe(e,(a,s)=>{a?(this.error(a,`unsubscribing from MQTT topic "${e}" failed`),n(a)):r()})})}async _publishToTopic(e,r,n={}){typeof r=="string"?this.log("info",`publishing to MQTT topic "${e}" (type: string, length: ${r.length} chars)`):this.log("info",`publishing to MQTT topic "${e}" (type: buffer, length: ${r.byteLength} bytes)`);const a=new vt((s,f)=>{let l;try{const y=this.codec.decode(r);l=this.msg.parse(y)}catch(y){return f(y)}s(l)});return this.log("debug",`publishing to MQTT topic "${e}"`,{message:a}),new Promise((s,f)=>{const l=typeof r=="string"?r:Tt.from(r.buffer,r.byteOffset,r.byteLength);this.mqtt.publish(e,l,n,y=>{y?(this.error(y,`publishing to MQTT topic "${e}" failed`),f(y)):s()})})}_onMessage(e,r,n){typeof r=="string"?this.log("info",`received from MQTT topic "${e}" (type: string, length: ${r.length} chars)`):this.log("info",`received from MQTT topic "${e}" (type: buffer, length: ${r.byteLength} bytes)`);let a;try{const s=this.codec.decode(r);a=this.msg.parse(s)}catch(s){const f=s instanceof Error?new Error(`failed to parse message: ${s.message}`,{cause:s}):new Error("failed to parse message");this.error(f);return}this.log("debug",`received from MQTT topic "${e}"`,{message:a}),this._dispatchMessage(e,a).catch(()=>{})}async _dispatchMessage(e,r){}}class oa extends ia{constructor(){super(...arguments),this._meta=new Map}meta(e,r){if(e===void 0)return Object.fromEntries(this._meta);r==null?this._meta.delete(e):this._meta.set(e,r)}metaStore(e){const r=e===void 0||Object.keys(e).length===0;if(!(this._meta.size===0&&r))return this._meta.size>0&&r?Object.fromEntries(this._meta):this._meta.size===0&&!r?e:{...Object.fromEntries(this._meta),...e}}}class sa extends oa{constructor(){super(...arguments),this._credential=null,this._tokens=new Set}credential(e){this._credential=e}async issue(e){if(this._credential===null)throw new Error("credential has to be provided before issuing tokens");const r=new Ys(e);r.setProtectedHeader({alg:"HS256",typ:"JWT"});const n=new TextEncoder().encode(this._credential);return await r.sign(n)}authenticate(e,r){if(e===void 0)return this._tokens.size>0?Array.from(this._tokens):void 0;r===!0?this._tokens.delete(e):this._tokens.add(e)}async validateToken(e){if(this._credential===null)throw new Error("credential has to be provided before validating tokens");const r=new TextEncoder().encode(this._credential);return(await ea(e,r).catch(()=>null))?.payload??null}async authenticated(e,r,n){let a=!1,s,f;if(typeof n=="string"?(s="require",f=[n]):(s=n.mode,f=n.roles),r!==void 0)for(const l of r){const y=await this.validateToken(l);if(y!==null&&!(y.id&&y.id!==e)){for(const E of f)if(y.roles.includes(E)){a=!0;break}if(a)break}}return!a&&s==="optional"&&(a=!0),a}}class aa extends sa{constructor(){super(...arguments),this.events=new Map}async event(e,...r){let n,a,s={},f;if(typeof e=="object"&&e!==null?(n=e.name,a=e.callback,s=e.options??{},f=e.auth):(n=e,a=r[0]),this.events.has(n))throw new Error(`event: event "${n}" already registered`);const l=n,y=this.options.topicMake(l,"event-emission"),E=this.options.topicMake(l,"event-emission",this.options.id);await Promise.all([this._subscribeTopic(y,{qos:0,...s}),this._subscribeTopic(E,{qos:0,...s})]).catch(B=>{throw this._unsubscribeTopic(y).catch(()=>{}),this._unsubscribeTopic(E).catch(()=>{}),B}),this.events.set(n,{callback:a,auth:f});const h=this;return{async destroy(){if(!h.events.has(n))throw new Error(`destroy: event "${n}" not registered`);return h.events.delete(n),Promise.all([h._unsubscribeTopic(y),h._unsubscribeTopic(E)]).then(()=>{})}}}emit(e,...r){let n,a,s,f={},l={},y;typeof e=="object"&&e!==null?(n=e.event,a=e.params,s=e.receiver,f=e.options??{},l=e.meta??{},y=e.dry):(n=e,a=r);const E=kt(),h=this.authenticate(),v=this.metaStore(l),B=this.msg.makeEventEmission(E,n,a,this.options.id,s,h,v),q=this.codec.encode(B),O=this.options.topicMake(n,"event-emission",s);if(y)return{topic:O,payload:q,options:{qos:0,...f}};this._publishToTopic(O,q,{qos:0,...f}).catch(()=>{})}async _dispatchMessage(e,r){super._dispatchMessage(e,r);const n=this.options.topicMatch(e);if(n!==null&&n.operation==="event-emission"&&r instanceof Ri){const a=r.name,s=this.events.get(a),f=r.params??[],l={sender:r.sender??""};r.receiver&&(l.receiver=r.receiver),r.meta&&(l.meta=r.meta),s?.auth&&(l.authenticated=await this.authenticated(r.sender,r.auth,s.auth)),l.authenticated!==void 0&&!l.authenticated?this.error(new Error(`authentication on event "${a}" failed`)):Promise.resolve().then(()=>s?.callback?.(...f,l)).catch(y=>{this.error(y)})}}}class ca extends aa{constructor(){super(...arguments),this.services=new Map,this.responseCallback=new Map,this.responseSubscriptions=new Map}async service(e,...r){let n,a,s={},f="default",l;if(typeof e=="object"&&e!==null?(n=e.name,a=e.callback,s=e.options??{},f=e.share??"default",l=e.auth):(n=e,a=r[0]),this.services.has(n))throw new Error(`register: service "${n}" already registered`);const y=`$share/${f}/${n}`,E=this.options.topicMake(y,"service-call-request"),h=this.options.topicMake(y,"service-call-request",this.options.id);await Promise.all([this._subscribeTopic(E,{qos:2,...s}),this._subscribeTopic(h,{qos:2,...s})]).catch(q=>{throw this._unsubscribeTopic(E).catch(()=>{}),this._unsubscribeTopic(h).catch(()=>{}),q}),this.services.set(n,{callback:a,auth:l});const v=this;return{async destroy(){if(!v.services.has(n))throw new Error(`unregister: service "${n}" not registered`);return v.services.delete(n),Promise.all([v._unsubscribeTopic(E),v._unsubscribeTopic(h)]).then(()=>{})}}}call(e,...r){let n,a,s,f={},l={};typeof e=="object"&&e!==null?(n=e.name,a=e.params,s=e.receiver,f=e.options??{},l=e.meta??{}):(n=e,a=r);const y=kt();this._responseSubscribe(n,{qos:f.qos??2});const E=new Promise((K,C)=>{let S=setTimeout(()=>{this.responseCallback.delete(y),this._responseUnsubscribe(n),S=null,C(new Error("communication timeout"))},this.options.timeout);this.responseCallback.set(y,{name:n,callback:(R,I)=>{S!==null&&(clearTimeout(S),S=null),R?C(R):K(I)}})}),h=this.authenticate(),v=this.metaStore(l),B=this.msg.makeServiceCallRequest(y,n,a,this.options.id,s,h,v),q=this.codec.encode(B),O=this.options.topicMake(n,"service-call-request",s);return this._publishToTopic(O,q,{qos:2,...f}).catch(K=>{const C=this.responseCallback.get(y);C!==void 0&&(this.responseCallback.delete(y),this._responseUnsubscribe(n),C.callback(K,void 0))}),E}_responseSubscribe(e,r={qos:2}){const n=this.options.topicMake(e,"service-call-response",this.options.id),a=this.responseSubscriptions.get(n)??0;this.responseSubscriptions.set(n,a+1),a===0&&this._subscribeTopic(n,r).catch(s=>{const f=this.responseSubscriptions.get(n)??0;f>1?this.responseSubscriptions.set(n,f-1):this.responseSubscriptions.delete(n),this.error(s)})}_responseUnsubscribe(e){const r=this.options.topicMake(e,"service-call-response",this.options.id);if(!this.responseSubscriptions.has(r))return;const n=this.responseSubscriptions.get(r)??0;n>1?this.responseSubscriptions.set(r,n-1):(this.responseSubscriptions.delete(r),this._unsubscribeTopic(r).catch(a=>{this.error(a)}))}async _dispatchMessage(e,r){super._dispatchMessage(e,r);const n=this.options.topicMatch(e);if(n!==null&&n.operation==="service-call-request"&&r instanceof Ii){const a=r.id,s=r.name,f=this.services.get(s),l=r.params??[],y={sender:r.sender??""};r.receiver&&(y.receiver=r.receiver),r.meta&&(y.meta=r.meta),f?.auth&&(y.authenticated=await this.authenticated(r.sender,r.auth,f.auth)),Promise.resolve().then(()=>{if(f===void 0)throw new Error(`service "${s}" not found`);if(y.authenticated!==void 0&&!y.authenticated)throw new Error(`service "${s}" failed authentication`);return f.callback(...l,y)}).then(E=>this.msg.makeServiceCallResponse(a,E,void 0,this.options.id,r.sender),E=>{let h;return E==null?h="undefined error":typeof E=="string"?h=E:E instanceof Error?h=E.message:h=String(E),this.error(new Error(h)),this.msg.makeServiceCallResponse(a,void 0,h,this.options.id,r.sender)}).then(E=>{const h=r.sender;if(h===void 0)throw new Error("invalid request: missing sender");const v=this.codec.encode(E),B=this.options.topicMake(s,"service-call-response",h);return this._publishToTopic(B,v,{qos:2})}).catch(E=>{this.error(E)})}else if(n!==null&&n.operation==="service-call-response"&&n.peerId===this.options.id&&r instanceof Bi){const a=r.id,s=this.responseCallback.get(a);s!==void 0&&(r.error!==void 0?s.callback(new Error(r.error),void 0):s.callback(void 0,r.result),this.responseCallback.delete(a),this._responseUnsubscribe(s.name))}}}class ua extends ca{constructor(){super(...arguments),this.sources=new Map,this.callbacks=new Map}async source(e,...r){let n,a,s={},f="default",l;if(typeof e=="object"&&e!==null?(n=e.name,a=e.callback,s=e.options??{},f=e.share??"default",l=e.auth):(n=e,a=r[0]),this.sources.has(n))throw new Error(`source: source "${n}" already established`);const y=`$share/${f}/${n}`,E=this.options.topicMake(y,"source-fetch-request"),h=this.options.topicMake(y,"source-fetch-request",this.options.id);await Promise.all([this._subscribeTopic(E,{qos:2,...s}),this._subscribeTopic(h,{qos:2,...s})]).catch(q=>{throw this._unsubscribeTopic(E).catch(()=>{}),this._unsubscribeTopic(h).catch(()=>{}),q}),this.sources.set(n,{callback:a,auth:l});const v=this;return{async destroy(){if(!v.sources.has(n))throw new Error(`destroy: source "${n}" not established`);return v.sources.delete(n),Promise.all([v._unsubscribeTopic(E),v._unsubscribeTopic(h)]).then(()=>{})}}}async fetch(e,...r){let n,a,s={},f,l;typeof e=="object"&&e!==null?(n=e.name,l=e.params,a=e.receiver,s=e.options??{},f=e.meta):(n=e,l=r);const y=kt(),E=this.options.topicMake(n,"source-fetch-response",this.options.id),h=this.options.topicMake(n,"source-fetch-chunk",this.options.id);await Promise.all([this._subscribeTopic(E,{qos:2}),this._subscribeTopic(h,{qos:2})]);const v=new Ut.Readable({read(P){}}),B=Wn(v);let q;const O=new Promise(P=>{q=P});let K=null;const C=(P=!1)=>{K!==null&&(clearTimeout(K),K=null),this._unsubscribeTopic(E).catch(()=>{}),this._unsubscribeTopic(h).catch(()=>{}),this.callbacks.delete(y),P&&q?.(void 0)};K=setTimeout(()=>{C(!0),v.destroy(new Error("communication timeout"))},this.options.timeout);let S=!0;this.callbacks.set(y,{name:n,callback:(P,D,G,V)=>{const te=S;S&&(S=!1,q?.(G)),P!==void 0?(C(!te),v.destroy(P)):(D!==void 0&&v.push(D),V&&(C(),v.push(null)))}});const R=this.authenticate(),I=this.metaStore(f),_=this.msg.makeSourceFetchRequest(y,n,l,this.options.id,a,R,I),x=this.codec.encode(_),F=this.options.topicMake(n,"source-fetch-request",a);return this._publishToTopic(F,x,{qos:2,...s}).catch(()=>{}),{stream:v,buffer:B,meta:O}}async _dispatchMessage(e,r){super._dispatchMessage(e,r);const n=this.options.topicMatch(e);if(n!==null&&n.operation==="source-fetch-request"&&r instanceof ki){const a=r.name,s=this.sources.get(a);if(s!==void 0){const f=r.id,l=r.name,y=r.params??[],E=r.sender??"",h=r.receiver,v={sender:E};h&&(v.receiver=h),r.meta&&(v.meta=r.meta),s?.auth&&(v.authenticated=await this.authenticated(r.sender,r.auth,s.auth));const B=this.options.topicMake(l,"source-fetch-response",E),q=this.options.topicMake(l,"source-fetch-chunk",E),O=C=>{const S=this.authenticate(),R=this.metaStore(v.meta),I=this.msg.makeSourceFetchResponse(f,l,C,this.options.id,E,S,R),_=this.codec.encode(I);this._publishToTopic(B,_,{qos:2}).catch(()=>{})},K=(C,S,R)=>{const I=this.msg.makeSourceFetchChunk(f,l,C,S,R,this.options.id,E),_=this.codec.encode(I);this._publishToTopic(q,_,{qos:2}).catch(()=>{})};Promise.resolve().then(()=>{if(v.authenticated!==void 0&&!v.authenticated)throw new Error(`source "${a}" failed authentication`);return s.callback(...y,v)}).then(async()=>{if(!(v.stream instanceof Ut.Readable)&&!(v.buffer instanceof Promise))throw new Error("handler did not provide data via info.stream or info.buffer fields");O(),v.stream instanceof Ut.Readable?Gn(v.stream,this.options.chunkSize,K,()=>{},C=>K(void 0,C.message,!0)):v.buffer instanceof Promise&&Hn(await v.buffer,this.options.chunkSize,K)}).catch(C=>{this.error(C),O(C.message)})}}else if(n!==null&&n.operation==="source-fetch-response"&&r instanceof Mi){const a=r.id,s=r.error,f=r.meta,l=this.callbacks.get(a);l!==void 0&&(s?l.callback(new Error(s),void 0,f,!0):l.callback(void 0,void 0,f,!1))}else if(n!==null&&n.operation==="source-fetch-chunk"&&r instanceof Li){const a=r.id,s=r.error,f=r.final,l=r.chunk!==void 0&&!(r.chunk instanceof Uint8Array)?Uint8Array.from(r.chunk):r.chunk,y=this.callbacks.get(a);y!==void 0&&y.callback(s?new Error(s):void 0,l,void 0,f)}}}class fa extends ua{constructor(){super(...arguments),this.sinks=new Map,this.pushStreams=new Map,this.pushTimers=new Map,this.pushCallbacks=new Map}async sink(e,...r){let n,a,s={},f="default",l;if(typeof e=="object"&&e!==null?(n=e.name,a=e.callback,s=e.options??{},f=e.share??"default",l=e.auth):(n=e,a=r[0]),this.sinks.has(n))throw new Error(`sink: sink "${n}" already established`);const y=`$share/${f}/${n}`,E=this.options.topicMake(y,"sink-push-request"),h=this.options.topicMake(y,"sink-push-request",this.options.id),v=this.options.topicMake(y,"sink-push-chunk",this.options.id);await Promise.all([this._subscribeTopic(E,{qos:2,...s}),this._subscribeTopic(h,{qos:2,...s}),this._subscribeTopic(v,{qos:2,...s})]).catch(O=>{throw this._unsubscribeTopic(E).catch(()=>{}),this._unsubscribeTopic(h).catch(()=>{}),this._unsubscribeTopic(v).catch(()=>{}),O}),this.sinks.set(n,{callback:a,auth:l});const B=this;return{async destroy(){if(!B.sinks.has(n))throw new Error(`destroy: sink "${n}" not established`);return B.sinks.delete(n),Promise.all([B._unsubscribeTopic(E),B._unsubscribeTopic(h),B._unsubscribeTopic(v)]).then(()=>{})}}}async push(e,...r){let n,a,s,f,l={},y;typeof e=="object"&&e!==null?(n=e.name,a=e.data,s=e.params,f=e.receiver,l=e.options??{},y=e.meta):(n=e,a=r[0],s=r.slice(1));const E=kt(),h=this.options.topicMake(n,"sink-push-response",this.options.id);await this._subscribeTopic(h,{qos:2});let v=null;const B=()=>{v!==null&&(clearTimeout(v),v=null),this._unsubscribeTopic(h).catch(()=>{}),this.pushCallbacks.delete(E)};await new Promise((K,C)=>{v=setTimeout(()=>{B(),C(new Error("communication timeout"))},this.options.timeout),this.pushCallbacks.set(E,{name:n,callback:F=>{const P=F.error;P?C(new Error(P)):(F.sender&&(f=F.sender),K())}});const S=this.authenticate(),R=this.metaStore(y),I=this.msg.makeSinkPushRequest(E,n,s,this.options.id,f,S,R),_=this.codec.encode(I),x=this.options.topicMake(n,"sink-push-request",f);this._publishToTopic(x,_,{qos:2,...l}).catch(F=>{C(F)})}).finally(()=>{B()});const q=this.options.topicMake(n,"sink-push-chunk",f),O=(K,C,S)=>{const R=this.msg.makeSinkPushChunk(E,n,K,C,S,this.options.id,f),I=this.codec.encode(R);this._publishToTopic(q,I,{qos:2,...l}).catch(()=>{})};return new Promise((K,C)=>{a instanceof Ut.Readable?Gn(a,this.options.chunkSize,O,()=>K(),S=>C(S)):a instanceof Uint8Array&&(Hn(a,this.options.chunkSize,O),K())})}async _dispatchMessage(e,r){super._dispatchMessage(e,r);const n=this.options.topicMatch(e);if(n!==null&&n.operation==="sink-push-request"&&r instanceof Ni){const a=r.name,s=this.sinks.get(a);if(s!==void 0){const f=r.id,l=r.params??[],y=r.sender??"",E=r.receiver,h={sender:y};E&&(h.receiver=E),r.meta&&(h.meta=r.meta),s?.auth&&(h.authenticated=await this.authenticated(r.sender,r.auth,s.auth));const v=this.options.topicMake(a,"sink-push-response",y),B=K=>{const C=this.authenticate(),S=this.metaStore(h.meta),R=this.msg.makeSinkPushResponse(f,a,K,this.options.id,y,C,S),I=this.codec.encode(R);this._publishToTopic(v,I,{qos:2}).catch(()=>{})},q=()=>{const K=this.pushTimers.get(f);K!==void 0&&(clearTimeout(K),this.pushTimers.delete(f));const C=this.pushStreams.get(f);C!==void 0&&(C.destroy(),this.pushStreams.delete(f))};let O=!1;Promise.resolve().then(()=>{if(h.authenticated!==void 0&&!h.authenticated)throw new Error(`sink "${a}" failed authentication`);const K=new Ut.Readable({read(R){}});this.pushStreams.set(f,K);const C=setTimeout(()=>{const R=this.pushStreams.get(f);R!==void 0&&(R.destroy(new Error("push stream timeout")),this.pushStreams.delete(f),this.pushTimers.delete(f))},this.options.timeout);this.pushTimers.set(f,C);const S=Wn(K);return h.stream=K,h.buffer=S,B(),O=!0,s.callback(...l,h)}).catch(K=>{q(),this.error(K),O||B(K.message)})}}else if(n!==null&&n.operation==="sink-push-response"&&r instanceof Fi){const a=r.id,s=this.pushCallbacks.get(a);s!==void 0&&s.callback(r)}else if(n!==null&&n.operation==="sink-push-chunk"&&r instanceof Ui){const a=r.id,s=r.error,f=r.final,l=r.chunk!==void 0&&!(r.chunk instanceof Uint8Array)?Uint8Array.from(r.chunk):r.chunk,y=this.pushStreams.get(a);if(y!==void 0){const E=()=>{const h=this.pushTimers.get(a);h!==void 0&&(clearTimeout(h),this.pushTimers.delete(a))};s!==void 0?(E(),y.destroy(new Error(s)),this.pushStreams.delete(a)):(l!==void 0&&y.push(l),f&&(E(),y.push(null),this.pushStreams.delete(a)))}}}}class la extends fa{}return la}));
13
+ `,E+=y,E},Xr.noChildren=!0,Z.registerDecoder(ie.CBOR,Xr),Z.registerDecoder(ie.URI,t=>(st(t.contents),new URL(t.contents)),"URI"),ge(URL,t=>[ie.URI,t.toString()]),Z.registerDecoder(ie.BASE64URL,t=>(st(t.contents),No(t.contents)),"Base64url-encoded"),Z.registerDecoder(ie.BASE64,t=>(st(t.contents),Wr(t.contents)),"Base64-encoded"),Z.registerDecoder(35,t=>(st(t.contents),new RegExp(t.contents)),"RegExp"),Z.registerDecoder(21065,t=>{st(t.contents);const e=`^(?:${t.contents})$`;return new RegExp(e,"u")},"I-RegExp"),Z.registerDecoder(ie.REGEXP,t=>{if(Si(t.contents),t.contents.length<1||t.contents.length>2)throw new Error(`Invalid RegExp Array: ${t.contents}`);return new RegExp(t.contents[0],t.contents[1])},"RegExp"),ge(RegExp,t=>[ie.REGEXP,[t.source,t.flags]]),Z.registerDecoder(64,t=>(rt(t.contents),t.contents),"uint8 Typed Array");function Be(t,e,r){rt(t.contents);let n=t.contents.length;if(n%e.BYTES_PER_ELEMENT!==0)throw new Error(`Number of bytes must be divisible by ${e.BYTES_PER_ELEMENT}, got: ${n}`);n/=e.BYTES_PER_ELEMENT;const a=new e(n),s=new DataView(t.contents.buffer,t.contents.byteOffset,t.contents.byteLength),f=s[`get${e.name.replace(/Array/,"")}`].bind(s);for(let l=0;l<n;l++)a[l]=f(l*e.BYTES_PER_ELEMENT,r);return a}function at(t,e,r,n,a){const s=a.forceEndian??bi;if(Ct(s?e:r,t,a),Le(n.byteLength,t,J.BYTE_STRING),bi===s)t.write(new Uint8Array(n.buffer,n.byteOffset,n.byteLength));else{const f=`write${n.constructor.name.replace(/Array/,"")}`,l=t[f].bind(t);for(const y of n)l(y,s)}}Z.registerDecoder(65,t=>Be(t,Uint16Array,!1),"uint16, big endian, Typed Array"),Z.registerDecoder(66,t=>Be(t,Uint32Array,!1),"uint32, big endian, Typed Array"),Z.registerDecoder(67,t=>Be(t,BigUint64Array,!1),"uint64, big endian, Typed Array"),Z.registerDecoder(68,t=>(rt(t.contents),new Uint8ClampedArray(t.contents)),"uint8 Typed Array, clamped arithmetic"),ge(Uint8ClampedArray,t=>[68,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)]),Z.registerDecoder(69,t=>Be(t,Uint16Array,!0),"uint16, little endian, Typed Array"),ge(Uint16Array,(t,e,r)=>at(e,69,65,t,r)),Z.registerDecoder(70,t=>Be(t,Uint32Array,!0),"uint32, little endian, Typed Array"),ge(Uint32Array,(t,e,r)=>at(e,70,66,t,r)),Z.registerDecoder(71,t=>Be(t,BigUint64Array,!0),"uint64, little endian, Typed Array"),ge(BigUint64Array,(t,e,r)=>at(e,71,67,t,r)),Z.registerDecoder(72,t=>(rt(t.contents),new Int8Array(t.contents)),"sint8 Typed Array"),ge(Int8Array,t=>[72,new Uint8Array(t.buffer,t.byteOffset,t.byteLength)]),Z.registerDecoder(73,t=>Be(t,Int16Array,!1),"sint16, big endian, Typed Array"),Z.registerDecoder(74,t=>Be(t,Int32Array,!1),"sint32, big endian, Typed Array"),Z.registerDecoder(75,t=>Be(t,BigInt64Array,!1),"sint64, big endian, Typed Array"),Z.registerDecoder(77,t=>Be(t,Int16Array,!0),"sint16, little endian, Typed Array"),ge(Int16Array,(t,e,r)=>at(e,77,73,t,r)),Z.registerDecoder(78,t=>Be(t,Int32Array,!0),"sint32, little endian, Typed Array"),ge(Int32Array,(t,e,r)=>at(e,78,74,t,r)),Z.registerDecoder(79,t=>Be(t,BigInt64Array,!0),"sint64, little endian, Typed Array"),ge(BigInt64Array,(t,e,r)=>at(e,79,75,t,r)),Z.registerDecoder(81,t=>Be(t,Float32Array,!1),"IEEE 754 binary32, big endian, Typed Array"),Z.registerDecoder(82,t=>Be(t,Float64Array,!1),"IEEE 754 binary64, big endian, Typed Array"),Z.registerDecoder(85,t=>Be(t,Float32Array,!0),"IEEE 754 binary32, little endian, Typed Array"),ge(Float32Array,(t,e,r)=>at(e,85,81,t,r)),Z.registerDecoder(86,t=>Be(t,Float64Array,!0),"IEEE 754 binary64, big endian, Typed Array"),ge(Float64Array,(t,e,r)=>at(e,86,82,t,r)),Z.registerDecoder(ie.SET,(t,e)=>{if(Si(t.contents),e.sortKeys){const r=Ue.decodeToEncodeOpts(e);let n=null;for(const a of t.contents){const s=[a,void 0,At(a,r)];if(n&&e.sortKeys(n,s)>=0)throw new Error(`Set items out of order in tag #${ie.SET}`);n=s}}return new Set(t.contents)},"Set"),ge(Set,(t,e,r)=>{let n=[...t];if(r.sortKeys){const a=n.map(s=>[s,void 0,At(s,r)]);a.sort(r.sortKeys),n=a.map(([s])=>s)}return[ie.SET,n]}),Z.registerDecoder(ie.JSON,t=>(st(t.contents),JSON.parse(t.contents)),"JSON-encoded");function xi(t){return rt(t.contents),new ir().decode(t.contents)}xi.comment=t=>{rt(t.contents);const e=new ir;return`(WTF8 string): ${JSON.stringify(e.decode(t.contents))}`},Z.registerDecoder(ie.WTF8,xi),Z.registerDecoder(ie.SELF_DESCRIBED,t=>t.contents,"Self-Described"),Z.registerDecoder(ie.INVALID_16,()=>{throw new Error(`Tag always invalid: ${ie.INVALID_16}`)},"Invalid"),Z.registerDecoder(ie.INVALID_32,()=>{throw new Error(`Tag always invalid: ${ie.INVALID_32}`)},"Invalid"),Z.registerDecoder(ie.INVALID_64,()=>{throw new Error(`Tag always invalid: ${ie.INVALID_64}`)},"Invalid");function Zr(t){throw new Error(`Encoding ${t.constructor.name} intentionally unimplmented. It is not concrete enough to interoperate. Convert to Uint8Array first.`)}ge(ArrayBuffer,Zr),ge(DataView,Zr),typeof SharedArrayBuffer<"u"&&ge(SharedArrayBuffer,Zr);function lr(t){return[NaN,t.valueOf()]}ge(Boolean,lr),ge(Number,lr),ge(String,lr),ge(BigInt,lr);function ws(t){const e={...Ue.defaultDecodeOptions};if(t.dcbor?Object.assign(e,Ue.dcborDecodeOptions):t.cde&&Object.assign(e,Ue.cdeDecodeOptions),Object.assign(e,t),Object.hasOwn(e,"rejectLongNumbers"))throw new TypeError("rejectLongNumbers has changed to requirePreferred");return e.boxed&&(e.saveOriginal=!0),e}let gs=class{parent=void 0;ret=void 0;step(e,r,n){if(this.ret=Ue.create(e,this.parent,r,n),e[2]===Ie.BREAK)if(this.parent?.isStreaming)this.parent.left=0;else throw new Error("Unexpected BREAK");else this.parent&&this.parent.push(this.ret,n,e[3]);for(this.ret instanceof Ue&&(this.parent=this.ret);this.parent?.done;){this.ret=this.parent.convert(n);const a=this.parent.parent;a?.replaceLast(this.ret,this.parent,n),this.parent=a}}};function ms(t,e={}){const r=ws(e),n=new ar(t,r),a=new gs;for(const s of n)a.step(s,r,n);return a.ret}const{cdeDecodeOptions:wa,dcborDecodeOptions:ga,defaultDecodeOptions:ma}=Ue;class Es{constructor(e={}){this.options={id:kt(),codec:"cbor",timeout:10*1e3,chunkSize:16*1024,topicMake:(r,n,a)=>`${r}/${n}/${a??"any"}`,topicMatch:r=>{const n=r.match(/^(.+)\/([^/]+)\/([^/]+)$/);return n?{name:n[1],operation:n[2],peerId:n[3]==="any"?void 0:n[3]}:null},...e}}}class Qr{static uint8ArrayToBase64(e){return btoa(String.fromCharCode(...e))}static base64ToUint8Array(e){const r=atob(e),n=new Uint8Array(r.length);for(let a=0;a<r.length;a++)n[a]=r.charCodeAt(a);return n}static stringify(e){return JSON.stringify(e,(r,n)=>n instanceof Uint8Array?{__Uint8Array:this.uint8ArrayToBase64(n)}:n)}static parse(e){return JSON.parse(e,(r,n)=>typeof n?.__Uint8Array=="string"?this.base64ToUint8Array(n.__Uint8Array):n)}}class bs{constructor(e){this.type=e,this.types=new zn,this.tags=new Map;const r=64e3;this.types.registerEncoder(Tt,n=>[r,new Uint8Array(n.buffer,n.byteOffset,n.byteLength)]),this.tags.set(r,n=>Tt.from(n.contents))}encode(e){let r;if(this.type==="cbor")try{r=At(e,{types:this.types})}catch{throw new Error("failed to encode CBOR format")}else if(this.type==="json")try{r=Qr.stringify(e)}catch{throw new Error("failed to encode JSON format")}else throw new Error("invalid format");return r}decode(e){let r;if(this.type==="cbor"&&e instanceof Uint8Array)try{r=ms(e,{tags:this.tags})}catch{throw new Error("failed to decode CBOR format")}else if(this.type==="json"&&typeof e=="string")try{r=Qr.parse(e)}catch{throw new Error("failed to decode JSON format")}else throw new Error("invalid format or wrong data type");return r}}class Ss extends Es{constructor(e={}){super(e),this.codec=new bs(this.options.codec)}}class _s extends Ss{str2buf(e){return new TextEncoder().encode(e)}buf2str(e){return new TextDecoder().decode(e)}arr2buf(e){let r;return e instanceof Uint8Array?r=e:r=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r}buf2arr(e,r){let n;if(r===Tt)n=Tt.from(e.buffer,e.byteOffset,e.byteLength);else if(r===Uint8Array)n=e;else if(r===Int8Array)n=new Int8Array(e.buffer,e.byteOffset,e.byteLength);else throw new Error("invalid data type");return n}}class nt{constructor(e,r,n,a){this.type=e,this.id=r,this.sender=n,this.receiver=a}}class Ri extends nt{constructor(e,r,n,a,s,f,l){super("event-emission",e,a,s),this.name=r,this.params=n,this.auth=f,this.meta=l}}class Ii extends nt{constructor(e,r,n,a,s,f,l){super("service-call-request",e,a,s),this.name=r,this.params=n,this.auth=f,this.meta=l}}class Bi extends nt{constructor(e,r,n,a,s){super("service-call-response",e,a,s),this.result=r,this.error=n}}class Ni extends nt{constructor(e,r,n,a,s,f,l){super("sink-push-request",e,a,s),this.name=r,this.params=n,this.auth=f,this.meta=l}}class Fi extends nt{constructor(e,r,n,a,s,f,l){super("sink-push-response",e,a,s),this.name=r,this.error=n,this.auth=f,this.meta=l}}class Ui extends nt{constructor(e,r,n,a,s,f,l){super("sink-push-chunk",e,f,l),this.name=r,this.chunk=n,this.error=a,this.final=s}}class ki extends nt{constructor(e,r,n,a,s,f,l){super("source-fetch-request",e,a,s),this.name=r,this.params=n,this.auth=f,this.meta=l}}class Mi extends nt{constructor(e,r,n,a,s,f,l){super("source-fetch-response",e,a,s),this.name=r,this.error=n,this.auth=f,this.meta=l}}class Li extends nt{constructor(e,r,n,a,s,f,l){super("source-fetch-chunk",e,f,l),this.name=r,this.chunk=n,this.error=a,this.final=s}}class Ts{makeEventEmission(e,r,n,a,s,f,l){return new Ri(e,r,n,a,s,f,l)}makeServiceCallRequest(e,r,n,a,s,f,l){return new Ii(e,r,n,a,s,f,l)}makeServiceCallResponse(e,r,n,a,s){return new Bi(e,r,n,a,s)}makeSinkPushRequest(e,r,n,a,s,f,l){return new Ni(e,r,n,a,s,f,l)}makeSinkPushResponse(e,r,n,a,s,f,l){return new Fi(e,r,n,a,s,f,l)}makeSinkPushChunk(e,r,n,a,s,f,l){return new Ui(e,r,n,a,s,f,l)}makeSourceFetchRequest(e,r,n,a,s,f,l){return new ki(e,r,n,a,s,f,l)}makeSourceFetchResponse(e,r,n,a,s,f,l){return new Mi(e,r,n,a,s,f,l)}makeSourceFetchChunk(e,r,n,a,s,f,l){return new Li(e,r,n,a,s,f,l)}parse(e){if(typeof e!="object"||e===null)throw new Error("invalid argument: not an object");if(!("type"in e)||typeof e.type!="string")throw new Error('invalid object: missing or invalid "type" field');if(!("id"in e)||typeof e.id!="string")throw new Error('invalid object: missing or invalid "id" field');if("sender"in e&&e.sender!==void 0&&typeof e.sender!="string")throw new Error('invalid object: invalid "sender" field');if("receiver"in e&&e.receiver!==void 0&&typeof e.receiver!="string")throw new Error('invalid object: invalid "receiver" field');const r=(a,s)=>Object.keys(a).some(f=>!s.includes(f)),n=a=>a.params===void 0||typeof a.params=="object"&&Array.isArray(a.params);if(e.type==="event-emission"){if(typeof e.name!="string")throw new Error('invalid EventEmission object: "name" field must be a string');if(r(e,["type","id","name","params","sender","receiver","auth","meta"]))throw new Error("invalid EventEmission object: contains unknown fields");if(!n(e))throw new Error('invalid EventEmission object: "params" field must be an array');return this.makeEventEmission(e.id,e.name,e.params,e.sender,e.receiver,e.auth,e.meta)}else if(e.type==="service-call-request"){if(typeof e.name!="string")throw new Error('invalid ServiceCallRequest object: "name" field must be a string');if(r(e,["type","id","name","params","sender","receiver","auth","meta"]))throw new Error("invalid ServiceCallRequest object: contains unknown fields");if(!n(e))throw new Error('invalid ServiceCallRequest object: "params" field must be an array');return this.makeServiceCallRequest(e.id,e.name,e.params,e.sender,e.receiver,e.auth,e.meta)}else if(e.type==="service-call-response"){if(r(e,["type","id","result","error","sender","receiver"]))throw new Error("invalid ServiceCallResponse object: contains unknown fields");return this.makeServiceCallResponse(e.id,e.result,e.error,e.sender,e.receiver)}else if(e.type==="sink-push-request"){if(typeof e.name!="string")throw new Error('invalid SinkPushRequest object: "name" field must be a string');if(r(e,["type","id","name","params","sender","receiver","auth","meta"]))throw new Error("invalid SinkPushRequest object: contains unknown fields");if(!n(e))throw new Error('invalid SinkPushRequest object: "params" field must be an array');return this.makeSinkPushRequest(e.id,e.name,e.params,e.sender,e.receiver,e.auth,e.meta)}else if(e.type==="sink-push-response"){if(typeof e.name!="string")throw new Error('invalid SinkPushResponse object: "name" field must be a string');if(e.error!==void 0&&typeof e.error!="string")throw new Error('invalid SinkPushResponse object: "error" field must be a string');if(r(e,["type","id","name","error","sender","receiver","auth","meta"]))throw new Error("invalid SinkPushResponse object: contains unknown fields");return this.makeSinkPushResponse(e.id,e.name,e.error,e.sender,e.receiver,e.auth,e.meta)}else if(e.type==="sink-push-chunk"){if(typeof e.name!="string")throw new Error('invalid SinkPushChunk object: "name" field must be a string');if(e.chunk!==void 0&&(e.chunk===null||typeof e.chunk!="object"))throw new Error('invalid SinkPushChunk object: "chunk" field must be an object');if(e.error!==void 0&&typeof e.error!="string")throw new Error('invalid SinkPushChunk object: "error" field must be a string');if(e.final!==void 0&&typeof e.final!="boolean")throw new Error('invalid SinkPushChunk object: "final" field must be a boolean');if(r(e,["type","id","name","chunk","error","final","sender","receiver"]))throw new Error("invalid SinkPushChunk object: contains unknown fields");return this.makeSinkPushChunk(e.id,e.name,e.chunk,e.error,e.final,e.sender,e.receiver)}else if(e.type==="source-fetch-request"){if(typeof e.name!="string")throw new Error('invalid SourceFetchRequest object: "name" field must be a string');if(r(e,["type","id","name","params","sender","receiver","auth","meta"]))throw new Error("invalid SourceFetchRequest object: contains unknown fields");if(!n(e))throw new Error('invalid SourceFetchRequest object: "params" field must be an array');return this.makeSourceFetchRequest(e.id,e.name,e.params,e.sender,e.receiver,e.auth,e.meta)}else if(e.type==="source-fetch-response"){if(typeof e.name!="string")throw new Error('invalid SourceFetchResponse object: "name" field must be a string');if(e.error!==void 0&&typeof e.error!="string")throw new Error('invalid SourceFetchResponse object: "error" field must be a string');if(r(e,["type","id","name","error","sender","receiver","auth","meta"]))throw new Error("invalid SourceFetchResponse object: contains unknown fields");return this.makeSourceFetchResponse(e.id,e.name,e.error,e.sender,e.receiver,e.auth,e.meta)}else if(e.type==="source-fetch-chunk"){if(typeof e.name!="string")throw new Error('invalid SourceFetchChunk object: "name" field must be a string');if(e.chunk!==void 0&&(e.chunk===null||typeof e.chunk!="object"))throw new Error('invalid SourceFetchChunk object: "chunk" field must be an object');if(e.error!==void 0&&typeof e.error!="string")throw new Error('invalid SourceFetchChunk object: "error" field must be a string');if(e.final!==void 0&&typeof e.final!="boolean")throw new Error('invalid SourceFetchChunk object: "final" field must be a boolean');if(r(e,["type","id","name","chunk","error","final","sender","receiver"]))throw new Error("invalid SourceFetchChunk object: contains unknown fields");return this.makeSourceFetchChunk(e.id,e.name,e.chunk,e.error,e.final,e.sender,e.receiver)}else throw new Error("invalid object: not of any known type")}}class vs extends _s{constructor(){super(...arguments),this.msg=new Ts}}const hr=new TextEncoder,qt=new TextDecoder;function Pi(...t){const e=t.reduce((a,{length:s})=>a+s,0),r=new Uint8Array(e);let n=0;for(const a of t)r.set(a,n),n+=a.length;return r}function xt(t){const e=new Uint8Array(t.length);for(let r=0;r<t.length;r++){const n=t.charCodeAt(r);if(n>127)throw new TypeError("non-ASCII string encountered in encode()");e[r]=n}return e}function As(t){if(Uint8Array.prototype.toBase64)return t.toBase64();const e=32768,r=[];for(let n=0;n<t.length;n+=e)r.push(String.fromCharCode.apply(null,t.subarray(n,n+e)));return btoa(r.join(""))}function xs(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(t);const e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}function dr(t){if(Uint8Array.fromBase64)return Uint8Array.fromBase64(typeof t=="string"?t:qt.decode(t),{alphabet:"base64url"});let e=t;e instanceof Uint8Array&&(e=qt.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/");try{return xs(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}}function en(t){let e=t;return typeof e=="string"&&(e=hr.encode(e)),Uint8Array.prototype.toBase64?e.toBase64({alphabet:"base64url",omitPadding:!0}):As(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}class Rt extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(e,r){super(e,r),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}class je extends Rt{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(e,r,n="unspecified",a="unspecified"){super(e,{cause:{claim:n,reason:a,payload:r}}),this.claim=n,this.reason=a,this.payload=r}}class Di extends Rt{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(e,r,n="unspecified",a="unspecified"){super(e,{cause:{claim:n,reason:a,payload:r}}),this.claim=n,this.reason=a,this.payload=r}}class yt extends Rt{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"}class me extends Rt{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"}class tn extends Rt{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"}class Rs extends Rt{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(e="signature verification failed",r){super(e,r)}}function Oi(t,e){const r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:parseInt(t.slice(-3),10)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":case"EdDSA":return{name:"Ed25519"};case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":return{name:t};default:throw new yt(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}function Ci(t,e){if(t.startsWith("RS")||t.startsWith("PS")){const{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}}const Je=(t,e="algorithm.name")=>new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`),It=(t,e)=>t.name===e;function rn(t){return parseInt(t.name.slice(4),10)}function Is(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Bs(t,e){if(e&&!t.usages.includes(e))throw new TypeError(`CryptoKey does not support this operation, its usages must include ${e}.`)}function Ns(t,e,r){switch(e){case"HS256":case"HS384":case"HS512":{if(!It(t.algorithm,"HMAC"))throw Je("HMAC");const n=parseInt(e.slice(2),10);if(rn(t.algorithm.hash)!==n)throw Je(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!It(t.algorithm,"RSASSA-PKCS1-v1_5"))throw Je("RSASSA-PKCS1-v1_5");const n=parseInt(e.slice(2),10);if(rn(t.algorithm.hash)!==n)throw Je(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!It(t.algorithm,"RSA-PSS"))throw Je("RSA-PSS");const n=parseInt(e.slice(2),10);if(rn(t.algorithm.hash)!==n)throw Je(`SHA-${n}`,"algorithm.hash");break}case"Ed25519":case"EdDSA":{if(!It(t.algorithm,"Ed25519"))throw Je("Ed25519");break}case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":{if(!It(t.algorithm,e))throw Je(e);break}case"ES256":case"ES384":case"ES512":{if(!It(t.algorithm,"ECDSA"))throw Je("ECDSA");const n=Is(e);if(t.algorithm.namedCurve!==n)throw Je(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Bs(t,r)}function $i(t,e,...r){if(r=r.filter(Boolean),r.length>2){const n=r.pop();t+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&e.constructor?.name&&(t+=` Received an instance of ${e.constructor.name}`),t}const Fs=(t,...e)=>$i("Key must be ",t,...e),qi=(t,e,...r)=>$i(`Key for the ${t} algorithm must be `,e,...r);async function Wi(t,e,r){if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(Fs(e,"CryptoKey","KeyObject","JSON Web Key"));return crypto.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}return Ns(e,t,r),e}async function Us(t,e,r){const n=await Wi(t,e,"sign");Ci(t,n);const a=await crypto.subtle.sign(Oi(t,n.algorithm),n,r);return new Uint8Array(a)}function Ki(...t){const e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(const n of e){const a=Object.keys(n);if(!r||r.size===0){r=new Set(a);continue}for(const s of a){if(r.has(s))return!1;r.add(s)}}return!0}const Hi=t=>{if(t?.[Symbol.toStringTag]==="CryptoKey")return!0;try{return t instanceof CryptoKey}catch{return!1}},Gi=t=>t?.[Symbol.toStringTag]==="KeyObject",ji=t=>Hi(t)||Gi(t),ks=t=>typeof t=="object"&&t!==null;function Wt(t){if(!ks(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}const nn=t=>Wt(t)&&typeof t.kty=="string",Ms=t=>t.kty!=="oct"&&(t.kty==="AKP"&&typeof t.priv=="string"||typeof t.d=="string"),Ls=t=>t.kty!=="oct"&&t.d===void 0&&t.priv===void 0,Ps=t=>t.kty==="oct"&&typeof t.k=="string",Bt=t=>t?.[Symbol.toStringTag],on=(t,e,r)=>{if(e.use!==void 0){let n;switch(r){case"sign":case"verify":n="sig";break;case"encrypt":case"decrypt":n="enc";break}if(e.use!==n)throw new TypeError(`Invalid key for this operation, its "use" must be "${n}" when present`)}if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, its "alg" must be "${t}" when present`);if(Array.isArray(e.key_ops)){let n;switch(!0){case(r==="sign"||r==="verify"):case t==="dir":case t.includes("CBC-HS"):n=r;break;case t.startsWith("PBES2"):n="deriveBits";break;case/^A\d{3}(?:GCM)?(?:KW)?$/.test(t):!t.includes("GCM")&&t.endsWith("KW")?n=r==="encrypt"?"wrapKey":"unwrapKey":n=r;break;case(r==="encrypt"&&t.startsWith("RSA")):n="wrapKey";break;case r==="decrypt":n=t.startsWith("RSA")?"unwrapKey":"deriveBits";break}if(n&&e.key_ops?.includes?.(n)===!1)throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${n}" when present`)}return!0},Ds=(t,e,r)=>{if(!(e instanceof Uint8Array)){if(nn(e)){if(Ps(e)&&on(t,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ji(e))throw new TypeError(qi(t,e,"CryptoKey","KeyObject","JSON Web Key","Uint8Array"));if(e.type!=="secret")throw new TypeError(`${Bt(e)} instances for symmetric algorithms must be of type "secret"`)}},Os=(t,e,r)=>{if(nn(e))switch(r){case"decrypt":case"sign":if(Ms(e)&&on(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a private JWK");case"encrypt":case"verify":if(Ls(e)&&on(t,e,r))return;throw new TypeError("JSON Web Key for this operation must be a public JWK")}if(!ji(e))throw new TypeError(qi(t,e,"CryptoKey","KeyObject","JSON Web Key"));if(e.type==="secret")throw new TypeError(`${Bt(e)} instances for asymmetric algorithms must not be of type "secret"`);if(e.type==="public")switch(r){case"sign":throw new TypeError(`${Bt(e)} instances for asymmetric algorithm signing must be of type "private"`);case"decrypt":throw new TypeError(`${Bt(e)} instances for asymmetric algorithm decryption must be of type "private"`)}if(e.type==="private")switch(r){case"verify":throw new TypeError(`${Bt(e)} instances for asymmetric algorithm verifying must be of type "public"`);case"encrypt":throw new TypeError(`${Bt(e)} instances for asymmetric algorithm encryption must be of type "public"`)}};function Ji(t,e,r){switch(t.substring(0,2)){case"A1":case"A2":case"di":case"HS":case"PB":Ds(t,e,r);break;default:Os(t,e,r)}}function Vi(t,e,r,n,a){if(a.crit!==void 0&&n?.crit===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(f=>typeof f!="string"||f.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...e.entries()]):s=e;for(const f of n.crit){if(!s.has(f))throw new yt(`Extension Header Parameter "${f}" is not recognized`);if(a[f]===void 0)throw new t(`Extension Header Parameter "${f}" is missing`);if(s.get(f)&&n[f]===void 0)throw new t(`Extension Header Parameter "${f}" MUST be integrity protected`)}return new Set(n.crit)}function Cs(t){let e,r;switch(t.kty){case"AKP":{switch(t.alg){case"ML-DSA-44":case"ML-DSA-65":case"ML-DSA-87":e={name:t.alg},r=t.priv?["sign"]:["verify"];break;default:throw new yt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new yt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(t.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=t.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=t.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new yt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(t.alg){case"Ed25519":case"EdDSA":e={name:"Ed25519"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new yt('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new yt('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}async function $s(t){if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:r}=Cs(t),n={...t};return n.kty!=="AKP"&&delete n.alg,delete n.use,crypto.subtle.importKey("jwk",n,e,t.ext??!(t.d||t.priv),t.key_ops??r)}let Nt;const zi=async(t,e,r,n=!1)=>{Nt||=new WeakMap;let a=Nt.get(t);if(a?.[r])return a[r];const s=await $s({...e,alg:r});return n&&Object.freeze(t),a?a[r]=s:Nt.set(t,{[r]:s}),s},qs=(t,e)=>{Nt||=new WeakMap;let r=Nt.get(t);if(r?.[e])return r[e];const n=t.type==="public",a=!!n;let s;if(t.asymmetricKeyType==="x25519"){switch(e){case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}s=t.toCryptoKey(t.asymmetricKeyType,a,n?[]:["deriveBits"])}if(t.asymmetricKeyType==="ed25519"){if(e!=="EdDSA"&&e!=="Ed25519")throw new TypeError("given KeyObject instance cannot be used for this algorithm");s=t.toCryptoKey(t.asymmetricKeyType,a,[n?"verify":"sign"])}switch(t.asymmetricKeyType){case"ml-dsa-44":case"ml-dsa-65":case"ml-dsa-87":{if(e!==t.asymmetricKeyType.toUpperCase())throw new TypeError("given KeyObject instance cannot be used for this algorithm");s=t.toCryptoKey(t.asymmetricKeyType,a,[n?"verify":"sign"])}}if(t.asymmetricKeyType==="rsa"){let f;switch(e){case"RSA-OAEP":f="SHA-1";break;case"RS256":case"PS256":case"RSA-OAEP-256":f="SHA-256";break;case"RS384":case"PS384":case"RSA-OAEP-384":f="SHA-384";break;case"RS512":case"PS512":case"RSA-OAEP-512":f="SHA-512";break;default:throw new TypeError("given KeyObject instance cannot be used for this algorithm")}if(e.startsWith("RSA-OAEP"))return t.toCryptoKey({name:"RSA-OAEP",hash:f},a,n?["encrypt"]:["decrypt"]);s=t.toCryptoKey({name:e.startsWith("PS")?"RSA-PSS":"RSASSA-PKCS1-v1_5",hash:f},a,[n?"verify":"sign"])}if(t.asymmetricKeyType==="ec"){const l=new Map([["prime256v1","P-256"],["secp384r1","P-384"],["secp521r1","P-521"]]).get(t.asymmetricKeyDetails?.namedCurve);if(!l)throw new TypeError("given KeyObject instance cannot be used for this algorithm");e==="ES256"&&l==="P-256"&&(s=t.toCryptoKey({name:"ECDSA",namedCurve:l},a,[n?"verify":"sign"])),e==="ES384"&&l==="P-384"&&(s=t.toCryptoKey({name:"ECDSA",namedCurve:l},a,[n?"verify":"sign"])),e==="ES512"&&l==="P-521"&&(s=t.toCryptoKey({name:"ECDSA",namedCurve:l},a,[n?"verify":"sign"])),e.startsWith("ECDH-ES")&&(s=t.toCryptoKey({name:"ECDH",namedCurve:l},a,n?[]:["deriveBits"]))}if(!s)throw new TypeError("given KeyObject instance cannot be used for this algorithm");return r?r[e]=s:Nt.set(t,{[e]:s}),s};async function Yi(t,e){if(t instanceof Uint8Array||Hi(t))return t;if(Gi(t)){if(t.type==="secret")return t.export();if("toCryptoKey"in t&&typeof t.toCryptoKey=="function")try{return qs(t,e)}catch(n){if(n instanceof TypeError)throw n}let r=t.export({format:"jwk"});return zi(t,r,e)}if(nn(t))return t.k?dr(t.k):zi(t,t,e,!0);throw new Error("unreachable")}class Ws{#e;#t;#r;constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this.#e=e}setProtectedHeader(e){if(this.#t)throw new TypeError("setProtectedHeader can only be called once");return this.#t=e,this}setUnprotectedHeader(e){if(this.#r)throw new TypeError("setUnprotectedHeader can only be called once");return this.#r=e,this}async sign(e,r){if(!this.#t&&!this.#r)throw new me("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!Ki(this.#t,this.#r))throw new me("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...this.#t,...this.#r},a=Vi(me,new Map([["b64",!0]]),r?.crit,this.#t,n);let s=!0;if(a.has("b64")&&(s=this.#t.b64,typeof s!="boolean"))throw new me('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:f}=n;if(typeof f!="string"||!f)throw new me('JWS "alg" (Algorithm) Header Parameter missing or invalid');Ji(f,e,"sign");let l,y;s?(l=en(this.#e),y=xt(l)):(y=this.#e,l="");let E,h;this.#t?(E=en(JSON.stringify(this.#t)),h=xt(E)):(E="",h=new Uint8Array);const v=Pi(h,xt("."),y),B=await Yi(e,f),q=await Us(f,B,v),O={signature:en(q),payload:l};return this.#r&&(O.header=this.#r),this.#t&&(O.protected=E),O}}class Ks{#e;constructor(e){this.#e=new Ws(e)}setProtectedHeader(e){return this.#e.setProtectedHeader(e),this}async sign(e,r){const n=await this.#e.sign(e,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}}const ct=t=>Math.floor(t.getTime()/1e3),Xi=60,Zi=Xi*60,sn=Zi*24,Hs=sn*7,Gs=sn*365.25,js=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;function Kt(t){const e=js.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const r=parseFloat(e[2]),n=e[3].toLowerCase();let a;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":a=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":a=Math.round(r*Xi);break;case"hour":case"hours":case"hr":case"hrs":case"h":a=Math.round(r*Zi);break;case"day":case"days":case"d":a=Math.round(r*sn);break;case"week":case"weeks":case"w":a=Math.round(r*Hs);break;default:a=Math.round(r*Gs);break}return e[1]==="-"||e[4]==="ago"?-a:a}function wt(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}const Qi=t=>t.includes("/")?t.toLowerCase():`application/${t.toLowerCase()}`,Js=(t,e)=>typeof t=="string"?e.includes(t):Array.isArray(t)?e.some(Set.prototype.has.bind(new Set(t))):!1;function Vs(t,e,r={}){let n;try{n=JSON.parse(qt.decode(e))}catch{}if(!Wt(n))throw new tn("JWT Claims Set must be a top-level JSON object");const{typ:a}=r;if(a&&(typeof t.typ!="string"||Qi(t.typ)!==Qi(a)))throw new je('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:s=[],issuer:f,subject:l,audience:y,maxTokenAge:E}=r,h=[...s];E!==void 0&&h.push("iat"),y!==void 0&&h.push("aud"),l!==void 0&&h.push("sub"),f!==void 0&&h.push("iss");for(const O of new Set(h.reverse()))if(!(O in n))throw new je(`missing required "${O}" claim`,n,O,"missing");if(f&&!(Array.isArray(f)?f:[f]).includes(n.iss))throw new je('unexpected "iss" claim value',n,"iss","check_failed");if(l&&n.sub!==l)throw new je('unexpected "sub" claim value',n,"sub","check_failed");if(y&&!Js(n.aud,typeof y=="string"?[y]:y))throw new je('unexpected "aud" claim value',n,"aud","check_failed");let v;switch(typeof r.clockTolerance){case"string":v=Kt(r.clockTolerance);break;case"number":v=r.clockTolerance;break;case"undefined":v=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:B}=r,q=ct(B||new Date);if((n.iat!==void 0||E)&&typeof n.iat!="number")throw new je('"iat" claim must be a number',n,"iat","invalid");if(n.nbf!==void 0){if(typeof n.nbf!="number")throw new je('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>q+v)throw new je('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(n.exp!==void 0){if(typeof n.exp!="number")throw new je('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=q-v)throw new Di('"exp" claim timestamp check failed',n,"exp","check_failed")}if(E){const O=q-n.iat,K=typeof E=="number"?E:Kt(E);if(O-v>K)throw new Di('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(O<0-v)throw new je('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n}class zs{#e;constructor(e){if(!Wt(e))throw new TypeError("JWT Claims Set MUST be an object");this.#e=structuredClone(e)}data(){return hr.encode(JSON.stringify(this.#e))}get iss(){return this.#e.iss}set iss(e){this.#e.iss=e}get sub(){return this.#e.sub}set sub(e){this.#e.sub=e}get aud(){return this.#e.aud}set aud(e){this.#e.aud=e}set jti(e){this.#e.jti=e}set nbf(e){typeof e=="number"?this.#e.nbf=wt("setNotBefore",e):e instanceof Date?this.#e.nbf=wt("setNotBefore",ct(e)):this.#e.nbf=ct(new Date)+Kt(e)}set exp(e){typeof e=="number"?this.#e.exp=wt("setExpirationTime",e):e instanceof Date?this.#e.exp=wt("setExpirationTime",ct(e)):this.#e.exp=ct(new Date)+Kt(e)}set iat(e){e===void 0?this.#e.iat=ct(new Date):e instanceof Date?this.#e.iat=wt("setIssuedAt",ct(e)):typeof e=="string"?this.#e.iat=wt("setIssuedAt",ct(new Date)+Kt(e)):this.#e.iat=wt("setIssuedAt",e)}}class Ys{#e;#t;constructor(e={}){this.#t=new zs(e)}setIssuer(e){return this.#t.iss=e,this}setSubject(e){return this.#t.sub=e,this}setAudience(e){return this.#t.aud=e,this}setJti(e){return this.#t.jti=e,this}setNotBefore(e){return this.#t.nbf=e,this}setExpirationTime(e){return this.#t.exp=e,this}setIssuedAt(e){return this.#t.iat=e,this}setProtectedHeader(e){return this.#e=e,this}async sign(e,r){const n=new Ks(this.#t.data());if(n.setProtectedHeader(this.#e),Array.isArray(this.#e?.crit)&&this.#e.crit.includes("b64")&&this.#e.b64===!1)throw new tn("JWTs MUST NOT use unencoded payload");return n.sign(e,r)}}async function Xs(t,e,r,n){const a=await Wi(t,e,"verify");Ci(t,a);const s=Oi(t,a.algorithm);try{return await crypto.subtle.verify(s,a,r,n)}catch{return!1}}async function Zs(t,e,r){if(!Wt(t))throw new me("Flattened JWS must be an object");if(t.protected===void 0&&t.header===void 0)throw new me('Flattened JWS must have either of the "protected" or "header" members');if(t.protected!==void 0&&typeof t.protected!="string")throw new me("JWS Protected Header incorrect type");if(t.payload===void 0)throw new me("JWS Payload missing");if(typeof t.signature!="string")throw new me("JWS Signature missing or incorrect type");if(t.header!==void 0&&!Wt(t.header))throw new me("JWS Unprotected Header incorrect type");let n={};if(t.protected)try{const K=dr(t.protected);n=JSON.parse(qt.decode(K))}catch{throw new me("JWS Protected Header is invalid")}if(!Ki(n,t.header))throw new me("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const a={...n,...t.header},s=Vi(me,new Map([["b64",!0]]),r?.crit,n,a);let f=!0;if(s.has("b64")&&(f=n.b64,typeof f!="boolean"))throw new me('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:l}=a;if(typeof l!="string"||!l)throw new me('JWS "alg" (Algorithm) Header Parameter missing or invalid');if(f){if(typeof t.payload!="string")throw new me("JWS Payload must be a string")}else if(typeof t.payload!="string"&&!(t.payload instanceof Uint8Array))throw new me("JWS Payload must be a string or an Uint8Array instance");let y=!1;typeof e=="function"&&(e=await e(n,t),y=!0),Ji(l,e,"verify");const E=Pi(t.protected!==void 0?xt(t.protected):new Uint8Array,xt("."),typeof t.payload=="string"?f?xt(t.payload):hr.encode(t.payload):t.payload);let h;try{h=dr(t.signature)}catch{throw new me("Failed to base64url decode the signature")}const v=await Yi(e,l);if(!await Xs(l,v,h,E))throw new Rs;let q;if(f)try{q=dr(t.payload)}catch{throw new me("Failed to base64url decode the payload")}else typeof t.payload=="string"?q=hr.encode(t.payload):q=t.payload;const O={payload:q};return t.protected!==void 0&&(O.protectedHeader=n),t.header!==void 0&&(O.unprotectedHeader=t.header),y?{...O,key:v}:O}async function Qs(t,e,r){if(t instanceof Uint8Array&&(t=qt.decode(t)),typeof t!="string")throw new me("Compact JWS must be a string or Uint8Array");const{0:n,1:a,2:s,length:f}=t.split(".");if(f!==3)throw new me("Invalid Compact JWS");const l=await Zs({payload:a,protected:n,signature:s},e,r),y={payload:l.payload,protectedHeader:l.protectedHeader};return typeof e=="function"?{...y,key:l.key}:y}async function ea(t,e,r){const n=await Qs(t,e,r);if(n.protectedHeader.crit?.includes("b64")&&n.protectedHeader.b64===!1)throw new tn("JWTs MUST NOT use unencoded payload");const s={payload:Vs(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return typeof e=="function"?{...s,key:n.key}:s}var ta=jt();class ra{constructor(e,r,n,a){this.timestamp=e,this.level=r,this.msg=n,this.data=a}async resolve(){if(this.msg instanceof Promise&&(this.msg=await this.msg.catch(()=>"<resolve-failed>")),this.data)for(const e of Object.keys(this.data))this.data[e]instanceof Promise&&(this.data[e]=await this.data[e].catch(()=>"<resolve-failed>"))}toString(){const e=new Date(this.timestamp),r=e.getFullYear(),n=(e.getMonth()+1).toString().padStart(2,"0"),a=e.getDate().toString().padStart(2,"0"),s=e.getHours().toString().padStart(2,"0"),f=e.getMinutes().toString().padStart(2,"0"),l=e.getSeconds().toString().padStart(2,"0"),y=e.getMilliseconds().toString().padStart(3,"0"),E=`${r}-${n}-${a} ${s}:${f}:${l}.${y}`,h=this.msg instanceof Promise?"<unresolved>":this.msg;let v="";return this.data!==void 0&&(v=` (${Object.keys(this.data).map(q=>{const O=this.data[q]instanceof Promise?"<unresolved>":this.data[q];return`${q}: ${Qr.stringify(O)}`}).join(", ")})`),`[${E}] ${this.level}: ${h}${v}`}}class na extends vs{constructor(){super(...arguments),this._events=new ta.EventEmitter}on(...e){return this._events.on(...e)}off(...e){return this._events.off(...e)}emitEvent(...e){try{return this._events.emit(...e)}catch{return!1}}log(e,r,n){const a=new ra(Date.now(),e,r,n);this.emitEvent("log",a)}error(e,r){let n=e;r!==void 0&&(n=new Error(`${r}: ${e.message}`,{cause:e})),this.emitEvent("error",n),this.log("error",n.message)}}class ia extends na{constructor(e,r={}){super(r),e===null&&(this.log("info","establishing proxy MQTT client"),e=new Proxy({},{get(n,a,s){return a==="isFakeProxy"?!0:()=>{}}})),this.mqtt=e,this.log("info","hooking into MQTT client"),this._messageHandler=(n,a,s)=>{let f;if(this.options.codec==="json")f=a.toString();else if(this.options.codec==="cbor")f=Tt.isBuffer(a)?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):a;else throw new Error("invalid codec configured");this._onMessage(n,f,s)},this.mqtt.on("message",this._messageHandler)}destroy(){this.log("info","un-hooking from MQTT client"),this.mqtt.off("message",this._messageHandler)}async _subscribeTopic(e,r={}){return this.log("info",`subscribing to MQTT topic "${e}"`),new Promise((n,a)=>{this.mqtt.subscribe(e,{qos:2,...r},(s,f)=>{s?(this.error(s,`subscribing to MQTT topic "${e}" failed`),a(s)):n()})})}async _unsubscribeTopic(e){return this.log("info",`unsubscribing from MQTT topic "${e}"`),new Promise((r,n)=>{this.mqtt.unsubscribe(e,(a,s)=>{a?(this.error(a,`unsubscribing from MQTT topic "${e}" failed`),n(a)):r()})})}async _publishToTopic(e,r,n={}){typeof r=="string"?this.log("info",`publishing to MQTT topic "${e}" (type: string, length: ${r.length} chars)`):this.log("info",`publishing to MQTT topic "${e}" (type: buffer, length: ${r.byteLength} bytes)`);const a=new vt((s,f)=>{let l;try{const y=this.codec.decode(r);l=this.msg.parse(y)}catch(y){return f(y)}s(l)});return this.log("debug",`publishing to MQTT topic "${e}"`,{message:a}),new Promise((s,f)=>{const l=typeof r=="string"?r:Tt.from(r.buffer,r.byteOffset,r.byteLength);this.mqtt.publish(e,l,n,y=>{y?(this.error(y,`publishing to MQTT topic "${e}" failed`),f(y)):s()})})}_onMessage(e,r,n){typeof r=="string"?this.log("info",`received from MQTT topic "${e}" (type: string, length: ${r.length} chars)`):this.log("info",`received from MQTT topic "${e}" (type: buffer, length: ${r.byteLength} bytes)`);let a;try{const s=this.codec.decode(r);a=this.msg.parse(s)}catch(s){const f=s instanceof Error?new Error(`failed to parse message: ${s.message}`,{cause:s}):new Error("failed to parse message");this.error(f);return}this.log("debug",`received from MQTT topic "${e}"`,{message:a}),this._dispatchMessage(e,a).catch(()=>{})}async _dispatchMessage(e,r){}}class oa extends ia{constructor(){super(...arguments),this._meta=new Map}meta(e,r){if(e===void 0)return Object.fromEntries(this._meta);r==null?this._meta.delete(e):this._meta.set(e,r)}metaStore(e){const r=e===void 0||Object.keys(e).length===0;if(!(this._meta.size===0&&r))return this._meta.size>0&&r?Object.fromEntries(this._meta):this._meta.size===0&&!r?e:{...Object.fromEntries(this._meta),...e}}}class sa extends oa{constructor(){super(...arguments),this._credential=null,this._tokens=new Set}credential(e){this._credential=e}async issue(e){if(this._credential===null)throw new Error("credential has to be provided before issuing tokens");const r=new Ys(e);r.setProtectedHeader({alg:"HS256",typ:"JWT"});const n=new TextEncoder().encode(this._credential);return await r.sign(n)}authenticate(e,r){if(e===void 0)return this._tokens.size>0?Array.from(this._tokens):void 0;r===!0?this._tokens.delete(e):this._tokens.add(e)}async validateToken(e){if(this._credential===null)throw new Error("credential has to be provided before validating tokens");const r=new TextEncoder().encode(this._credential);return(await ea(e,r).catch(()=>null))?.payload??null}async authenticated(e,r,n){let a=!1,s,f;if(typeof n=="string"?(s="require",f=[n]):(s=n.mode,f=n.roles),r!==void 0)for(const l of r){const y=await this.validateToken(l);if(y!==null&&!(y.id&&y.id!==e)){for(const E of f)if(y.roles.includes(E)){a=!0;break}if(a)break}}return!a&&s==="optional"&&(a=!0),a}}class aa extends sa{constructor(){super(...arguments),this.events=new Map}async event(e,...r){let n,a,s={},f;if(typeof e=="object"&&e!==null?(n=e.name,a=e.callback,s=e.options??{},f=e.auth):(n=e,a=r[0]),this.events.has(n))throw new Error(`event: event "${n}" already registered`);const l=n,y=this.options.topicMake(l,"event-emission"),E=this.options.topicMake(l,"event-emission",this.options.id);await Promise.all([this._subscribeTopic(y,{qos:0,...s}),this._subscribeTopic(E,{qos:0,...s})]).catch(B=>{throw this._unsubscribeTopic(y).catch(()=>{}),this._unsubscribeTopic(E).catch(()=>{}),B}),this.events.set(n,{callback:a,auth:f});const h=this;return{async destroy(){if(!h.events.has(n))throw new Error(`destroy: event "${n}" not registered`);return h.events.delete(n),Promise.all([h._unsubscribeTopic(y),h._unsubscribeTopic(E)]).then(()=>{})}}}emit(e,...r){let n,a,s,f={},l={},y;typeof e=="object"&&e!==null?(n=e.event,a=e.params,s=e.receiver,f=e.options??{},l=e.meta??{},y=e.dry):(n=e,a=r);const E=kt(),h=this.authenticate(),v=this.metaStore(l),B=this.msg.makeEventEmission(E,n,a,this.options.id,s,h,v),q=this.codec.encode(B),O=this.options.topicMake(n,"event-emission",s);if(y)return{topic:O,payload:q,options:{qos:0,...f}};this._publishToTopic(O,q,{qos:0,...f}).catch(()=>{})}async _dispatchMessage(e,r){super._dispatchMessage(e,r);const n=this.options.topicMatch(e);if(n!==null&&n.operation==="event-emission"&&r instanceof Ri){const a=r.name,s=this.events.get(a),f=r.params??[],l={sender:r.sender??""};r.receiver&&(l.receiver=r.receiver),r.meta&&(l.meta=r.meta),s?.auth&&(l.authenticated=await this.authenticated(r.sender,r.auth,s.auth)),l.authenticated!==void 0&&!l.authenticated?this.error(new Error(`authentication on event "${a}" failed`)):Promise.resolve().then(()=>s?.callback?.(...f,l)).catch(y=>{this.error(y)})}}}class ca extends aa{constructor(){super(...arguments),this.services=new Map,this.responseCallback=new Map,this.responseSubscriptions=new Map}async service(e,...r){let n,a,s={},f="default",l;if(typeof e=="object"&&e!==null?(n=e.name,a=e.callback,s=e.options??{},f=e.share??"default",l=e.auth):(n=e,a=r[0]),this.services.has(n))throw new Error(`register: service "${n}" already registered`);const y=`$share/${f}/${n}`,E=this.options.topicMake(y,"service-call-request"),h=this.options.topicMake(y,"service-call-request",this.options.id);await Promise.all([this._subscribeTopic(E,{qos:2,...s}),this._subscribeTopic(h,{qos:2,...s})]).catch(q=>{throw this._unsubscribeTopic(E).catch(()=>{}),this._unsubscribeTopic(h).catch(()=>{}),q}),this.services.set(n,{callback:a,auth:l});const v=this;return{async destroy(){if(!v.services.has(n))throw new Error(`unregister: service "${n}" not registered`);return v.services.delete(n),Promise.all([v._unsubscribeTopic(E),v._unsubscribeTopic(h)]).then(()=>{})}}}call(e,...r){let n,a,s,f={},l={};typeof e=="object"&&e!==null?(n=e.name,a=e.params,s=e.receiver,f=e.options??{},l=e.meta??{}):(n=e,a=r);const y=kt();this._responseSubscribe(n,{qos:f.qos??2});const E=new Promise((K,C)=>{let S=setTimeout(()=>{this.responseCallback.delete(y),this._responseUnsubscribe(n),S=null,C(new Error("communication timeout"))},this.options.timeout);this.responseCallback.set(y,{name:n,callback:(R,I)=>{S!==null&&(clearTimeout(S),S=null),R?C(R):K(I)}})}),h=this.authenticate(),v=this.metaStore(l),B=this.msg.makeServiceCallRequest(y,n,a,this.options.id,s,h,v),q=this.codec.encode(B),O=this.options.topicMake(n,"service-call-request",s);return this._publishToTopic(O,q,{qos:2,...f}).catch(K=>{const C=this.responseCallback.get(y);C!==void 0&&(this.responseCallback.delete(y),this._responseUnsubscribe(n),C.callback(K,void 0))}),E}_responseSubscribe(e,r={qos:2}){const n=this.options.topicMake(e,"service-call-response",this.options.id),a=this.responseSubscriptions.get(n)??0;this.responseSubscriptions.set(n,a+1),a===0&&this._subscribeTopic(n,r).catch(s=>{const f=this.responseSubscriptions.get(n)??0;f>1?this.responseSubscriptions.set(n,f-1):this.responseSubscriptions.delete(n),this.error(s)})}_responseUnsubscribe(e){const r=this.options.topicMake(e,"service-call-response",this.options.id);if(!this.responseSubscriptions.has(r))return;const n=this.responseSubscriptions.get(r)??0;n>1?this.responseSubscriptions.set(r,n-1):(this.responseSubscriptions.delete(r),this._unsubscribeTopic(r).catch(a=>{this.error(a)}))}async _dispatchMessage(e,r){super._dispatchMessage(e,r);const n=this.options.topicMatch(e);if(n!==null&&n.operation==="service-call-request"&&r instanceof Ii){const a=r.id,s=r.name,f=this.services.get(s),l=r.params??[],y={sender:r.sender??""};r.receiver&&(y.receiver=r.receiver),r.meta&&(y.meta=r.meta),f?.auth&&(y.authenticated=await this.authenticated(r.sender,r.auth,f.auth)),Promise.resolve().then(()=>{if(f===void 0)throw new Error(`service "${s}" not found`);if(y.authenticated!==void 0&&!y.authenticated)throw new Error(`service "${s}" failed authentication`);return f.callback(...l,y)}).then(E=>this.msg.makeServiceCallResponse(a,E,void 0,this.options.id,r.sender),E=>{let h;return E==null?h="undefined error":typeof E=="string"?h=E:E instanceof Error?h=E.message:h=String(E),this.error(new Error(h)),this.msg.makeServiceCallResponse(a,void 0,h,this.options.id,r.sender)}).then(E=>{const h=r.sender;if(h===void 0)throw new Error("invalid request: missing sender");const v=this.codec.encode(E),B=this.options.topicMake(s,"service-call-response",h);return this._publishToTopic(B,v,{qos:2})}).catch(E=>{this.error(E)})}else if(n!==null&&n.operation==="service-call-response"&&n.peerId===this.options.id&&r instanceof Bi){const a=r.id,s=this.responseCallback.get(a);s!==void 0&&(r.error!==void 0?s.callback(new Error(r.error),void 0):s.callback(void 0,r.result),this.responseCallback.delete(a),this._responseUnsubscribe(s.name))}}}class ua extends ca{constructor(){super(...arguments),this.sources=new Map,this.callbacks=new Map}async source(e,...r){let n,a,s={},f="default",l;if(typeof e=="object"&&e!==null?(n=e.name,a=e.callback,s=e.options??{},f=e.share??"default",l=e.auth):(n=e,a=r[0]),this.sources.has(n))throw new Error(`source: source "${n}" already established`);const y=`$share/${f}/${n}`,E=this.options.topicMake(y,"source-fetch-request"),h=this.options.topicMake(y,"source-fetch-request",this.options.id);await Promise.all([this._subscribeTopic(E,{qos:2,...s}),this._subscribeTopic(h,{qos:2,...s})]).catch(q=>{throw this._unsubscribeTopic(E).catch(()=>{}),this._unsubscribeTopic(h).catch(()=>{}),q}),this.sources.set(n,{callback:a,auth:l});const v=this;return{async destroy(){if(!v.sources.has(n))throw new Error(`destroy: source "${n}" not established`);return v.sources.delete(n),Promise.all([v._unsubscribeTopic(E),v._unsubscribeTopic(h)]).then(()=>{})}}}async fetch(e,...r){let n,a,s={},f,l;typeof e=="object"&&e!==null?(n=e.name,l=e.params,a=e.receiver,s=e.options??{},f=e.meta):(n=e,l=r);const y=kt(),E=this.options.topicMake(n,"source-fetch-response",this.options.id),h=this.options.topicMake(n,"source-fetch-chunk",this.options.id);await Promise.all([this._subscribeTopic(E,{qos:2}),this._subscribeTopic(h,{qos:2})]);const v=new Ut.Readable({read(P){}}),B=Wn(v);let q;const O=new Promise(P=>{q=P});let K=null;const C=(P=!1)=>{K!==null&&(clearTimeout(K),K=null),this._unsubscribeTopic(E).catch(()=>{}),this._unsubscribeTopic(h).catch(()=>{}),this.callbacks.delete(y),P&&q?.(void 0)};K=setTimeout(()=>{C(!0),v.destroy(new Error("communication timeout"))},this.options.timeout);let S=!0;this.callbacks.set(y,{name:n,callback:(P,D,G,V)=>{const te=S;S&&(S=!1,q?.(G)),P!==void 0?(C(!te),v.destroy(P)):(D!==void 0&&v.push(D),V&&(C(),v.push(null)))}});const R=this.authenticate(),I=this.metaStore(f),_=this.msg.makeSourceFetchRequest(y,n,l,this.options.id,a,R,I),x=this.codec.encode(_),F=this.options.topicMake(n,"source-fetch-request",a);return this._publishToTopic(F,x,{qos:2,...s}).catch(()=>{}),{stream:v,buffer:B,meta:O}}async _dispatchMessage(e,r){super._dispatchMessage(e,r);const n=this.options.topicMatch(e);if(n!==null&&n.operation==="source-fetch-request"&&r instanceof ki){const a=r.name,s=this.sources.get(a);if(s!==void 0){const f=r.id,l=r.name,y=r.params??[],E=r.sender??"",h=r.receiver,v={sender:E};h&&(v.receiver=h),r.meta&&(v.meta=r.meta),s?.auth&&(v.authenticated=await this.authenticated(r.sender,r.auth,s.auth));const B=this.options.topicMake(l,"source-fetch-response",E),q=this.options.topicMake(l,"source-fetch-chunk",E),O=async C=>{const S=this.authenticate(),R=this.metaStore(v.meta),I=this.msg.makeSourceFetchResponse(f,l,C,this.options.id,E,S,R),_=this.codec.encode(I);await this._publishToTopic(B,_,{qos:2}).catch(()=>{})},K=(C,S,R)=>{const I=this.msg.makeSourceFetchChunk(f,l,C,S,R,this.options.id,E),_=this.codec.encode(I);this._publishToTopic(q,_,{qos:2}).catch(()=>{})};Promise.resolve().then(()=>{if(v.authenticated!==void 0&&!v.authenticated)throw new Error(`source "${a}" failed authentication`);return s.callback(...y,v)}).then(async()=>{if(!(v.stream instanceof Ut.Readable)&&!(v.buffer instanceof Promise))throw new Error("handler did not provide data via info.stream or info.buffer fields");await O(),v.stream instanceof Ut.Readable?Gn(v.stream,this.options.chunkSize,K,()=>{},()=>{}):v.buffer instanceof Promise&&Hn(await v.buffer,this.options.chunkSize,K)}).catch(C=>{this.error(C),O(C.message)})}}else if(n!==null&&n.operation==="source-fetch-response"&&r instanceof Mi){const a=r.id,s=r.error,f=r.meta,l=this.callbacks.get(a);l!==void 0&&(s?l.callback(new Error(s),void 0,f,!0):l.callback(void 0,void 0,f,!1))}else if(n!==null&&n.operation==="source-fetch-chunk"&&r instanceof Li){const a=r.id,s=r.error,f=r.final,l=r.chunk!==void 0&&!(r.chunk instanceof Uint8Array)?Uint8Array.from(r.chunk):r.chunk,y=this.callbacks.get(a);y!==void 0&&y.callback(s?new Error(s):void 0,l,void 0,f)}}}class fa extends ua{constructor(){super(...arguments),this.sinks=new Map,this.pushStreams=new Map,this.pushTimers=new Map,this.pushCallbacks=new Map}async sink(e,...r){let n,a,s={},f="default",l;if(typeof e=="object"&&e!==null?(n=e.name,a=e.callback,s=e.options??{},f=e.share??"default",l=e.auth):(n=e,a=r[0]),this.sinks.has(n))throw new Error(`sink: sink "${n}" already established`);const y=`$share/${f}/${n}`,E=this.options.topicMake(y,"sink-push-request"),h=this.options.topicMake(y,"sink-push-request",this.options.id),v=this.options.topicMake(y,"sink-push-chunk",this.options.id);await Promise.all([this._subscribeTopic(E,{qos:2,...s}),this._subscribeTopic(h,{qos:2,...s}),this._subscribeTopic(v,{qos:2,...s})]).catch(O=>{throw this._unsubscribeTopic(E).catch(()=>{}),this._unsubscribeTopic(h).catch(()=>{}),this._unsubscribeTopic(v).catch(()=>{}),O}),this.sinks.set(n,{callback:a,auth:l});const B=this;return{async destroy(){if(!B.sinks.has(n))throw new Error(`destroy: sink "${n}" not established`);return B.sinks.delete(n),Promise.all([B._unsubscribeTopic(E),B._unsubscribeTopic(h),B._unsubscribeTopic(v)]).then(()=>{})}}}async push(e,...r){let n,a,s,f,l={},y;typeof e=="object"&&e!==null?(n=e.name,a=e.data,s=e.params,f=e.receiver,l=e.options??{},y=e.meta):(n=e,a=r[0],s=r.slice(1));const E=kt(),h=this.options.topicMake(n,"sink-push-response",this.options.id);await this._subscribeTopic(h,{qos:2});let v=null;const B=()=>{v!==null&&(clearTimeout(v),v=null),this._unsubscribeTopic(h).catch(()=>{}),this.pushCallbacks.delete(E)};await new Promise((K,C)=>{v=setTimeout(()=>{B(),C(new Error("communication timeout"))},this.options.timeout),this.pushCallbacks.set(E,{name:n,callback:F=>{const P=F.error;P?C(new Error(P)):(F.sender&&(f=F.sender),K())}});const S=this.authenticate(),R=this.metaStore(y),I=this.msg.makeSinkPushRequest(E,n,s,this.options.id,f,S,R),_=this.codec.encode(I),x=this.options.topicMake(n,"sink-push-request",f);this._publishToTopic(x,_,{qos:2,...l}).catch(F=>{C(F)})}).finally(()=>{B()});const q=this.options.topicMake(n,"sink-push-chunk",f),O=(K,C,S)=>{const R=this.msg.makeSinkPushChunk(E,n,K,C,S,this.options.id,f),I=this.codec.encode(R);this._publishToTopic(q,I,{qos:2,...l}).catch(()=>{})};return new Promise((K,C)=>{a instanceof Ut.Readable?Gn(a,this.options.chunkSize,O,()=>K(),S=>C(S)):a instanceof Uint8Array&&(Hn(a,this.options.chunkSize,O),K())})}async _dispatchMessage(e,r){super._dispatchMessage(e,r);const n=this.options.topicMatch(e);if(n!==null&&n.operation==="sink-push-request"&&r instanceof Ni){const a=r.name,s=this.sinks.get(a);if(s!==void 0){const f=r.id,l=r.params??[],y=r.sender??"",E=r.receiver,h={sender:y};E&&(h.receiver=E),r.meta&&(h.meta=r.meta),s?.auth&&(h.authenticated=await this.authenticated(r.sender,r.auth,s.auth));const v=this.options.topicMake(a,"sink-push-response",y),B=K=>{const C=this.authenticate(),S=this.metaStore(h.meta),R=this.msg.makeSinkPushResponse(f,a,K,this.options.id,y,C,S),I=this.codec.encode(R);this._publishToTopic(v,I,{qos:2}).catch(()=>{})},q=()=>{const K=this.pushTimers.get(f);K!==void 0&&(clearTimeout(K),this.pushTimers.delete(f));const C=this.pushStreams.get(f);C!==void 0&&(C.destroy(),this.pushStreams.delete(f))};let O=!1;Promise.resolve().then(()=>{if(h.authenticated!==void 0&&!h.authenticated)throw new Error(`sink "${a}" failed authentication`);const K=new Ut.Readable({read(R){}});this.pushStreams.set(f,K);const C=setTimeout(()=>{const R=this.pushStreams.get(f);R!==void 0&&(R.destroy(new Error("push stream timeout")),this.pushStreams.delete(f),this.pushTimers.delete(f))},this.options.timeout);this.pushTimers.set(f,C);const S=Wn(K);return h.stream=K,h.buffer=S,B(),O=!0,s.callback(...l,h)}).catch(K=>{q(),this.error(K),O||B(K.message)})}}else if(n!==null&&n.operation==="sink-push-response"&&r instanceof Fi){const a=r.id,s=this.pushCallbacks.get(a);s!==void 0&&s.callback(r)}else if(n!==null&&n.operation==="sink-push-chunk"&&r instanceof Ui){const a=r.id,s=r.error,f=r.final,l=r.chunk!==void 0&&!(r.chunk instanceof Uint8Array)?Uint8Array.from(r.chunk):r.chunk,y=this.pushStreams.get(a);if(y!==void 0){const E=()=>{const h=this.pushTimers.get(a);h!==void 0&&(clearTimeout(h),this.pushTimers.delete(a))};s!==void 0?(E(),y.destroy(new Error(s)),this.pushStreams.delete(a)):(l!==void 0&&y.push(l),f&&(E(),y.push(null),this.pushStreams.delete(a)))}}}}class la extends fa{}return la}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mqtt-plus",
3
- "version": "1.1.3",
3
+ "version": "1.1.4",
4
4
  "description": "MQTT Communication Patterns",
5
5
  "keywords": [ "mqtt",
6
6
  "event", "emit",
@@ -77,7 +77,7 @@ export class SourceTrait<T extends APISchema = APISchema> extends ServiceTrait<T
77
77
  share?: string,
78
78
  auth?: AuthOption
79
79
  },
80
- ...args: any[]
80
+ ...args: any[]
81
81
  ): Promise<Registration> {
82
82
  /* determine actual parameters */
83
83
  let name: K
@@ -319,13 +319,13 @@ export class SourceTrait<T extends APISchema = APISchema> extends ServiceTrait<T
319
319
  const chunkTopic = this.options.topicMake(source, "source-fetch-chunk", sender)
320
320
 
321
321
  /* callback for sending the ack/nak response */
322
- const sendResponse = (error?: string) => {
322
+ const sendResponse = async (error?: string) => {
323
323
  const auth = this.authenticate()
324
324
  const metaStore = this.metaStore(info.meta)
325
325
  const response = this.msg.makeSourceFetchResponse(requestId,
326
326
  source, error, this.options.id, sender, auth, metaStore)
327
327
  const message = this.codec.encode(response)
328
- this._publishToTopic(responseTopic, message, { qos: 2 }).catch(() => {})
328
+ await this._publishToTopic(responseTopic, message, { qos: 2 }).catch(() => {})
329
329
  }
330
330
 
331
331
  /* callback for creating and sending a chunk message */
@@ -347,12 +347,12 @@ export class SourceTrait<T extends APISchema = APISchema> extends ServiceTrait<T
347
347
  throw new Error("handler did not provide data via info.stream or info.buffer fields")
348
348
 
349
349
  /* send ack response */
350
- sendResponse()
350
+ await sendResponse()
351
351
 
352
352
  /* handle Readable stream result */
353
353
  if (info.stream instanceof Readable)
354
354
  sendStreamAsChunks(info.stream, this.options.chunkSize, sendChunk,
355
- () => {}, (err) => sendChunk(undefined, err.message, true))
355
+ () => {}, () => {})
356
356
 
357
357
  /* handle Buffer result */
358
358
  else if (info.buffer instanceof Promise)
@@ -73,7 +73,7 @@ const ACL = textframe(`
73
73
  pattern write example/client/+/sink-push-response/%c
74
74
  pattern read example/client/+/sink-push-chunk/%c
75
75
 
76
- # ==== server/autenticated ACL ====
76
+ # ==== server/authenticated ACL ====
77
77
 
78
78
  user example
79
79
 
@@ -78,8 +78,8 @@ describe("MQTT+ Library", function () {
78
78
  { clientId: "client" })
79
79
  apiC = new MQTTp<API>(mqttC, { id: "client", timeout: 1000 })
80
80
  await new Promise<void>((resolve, reject) => {
81
- mqttC.once("connect", () => { resolve() })
82
- mqttC.once("error", (err: any) => { reject(err) })
81
+ mqttC.once("connect", () => { resolve() })
82
+ mqttC.once("error", (err: Error) => { reject(err) })
83
83
  })
84
84
  apiC.on("log", async (entry) => {
85
85
  await entry.resolve()
@@ -91,8 +91,8 @@ describe("MQTT+ Library", function () {
91
91
  { clientId: "server", username: "example", password: "example" })
92
92
  apiS = new MQTTp<API>(mqttS, { id: "server", timeout: 1000 })
93
93
  await new Promise<void>((resolve, reject) => {
94
- mqttS.once("connect", () => { resolve() })
95
- mqttS.once("error", (err: any) => { reject(err) })
94
+ mqttS.once("connect", () => { resolve() })
95
+ mqttS.once("error", (err: Error) => { reject(err) })
96
96
  })
97
97
  apiS.on("log", async (entry) => {
98
98
  await entry.resolve()
@@ -277,8 +277,8 @@ describe("MQTT+ Library", function () {
277
277
  username: "example", password: "example"
278
278
  })
279
279
  await new Promise<void>((resolve, reject) => {
280
- mqttServer.once("connect", () => { resolve() })
281
- mqttServer.once("error", (err: any) => { reject(err) })
280
+ mqttServer.once("connect", () => { resolve() })
281
+ mqttServer.once("error", (err: Error) => { reject(err) })
282
282
  })
283
283
  const apiServer = new MQTTp<API>(mqttServer, { timeout: 1000 })
284
284
 
@@ -298,8 +298,8 @@ describe("MQTT+ Library", function () {
298
298
  }
299
299
  })
300
300
  await new Promise<void>((resolve, reject) => {
301
- mqttClient.once("connect", () => { resolve() })
302
- mqttClient.once("error", (err: any) => { reject(err) })
301
+ mqttClient.once("connect", () => { resolve() })
302
+ mqttClient.once("error", (err: Error) => { reject(err) })
303
303
  })
304
304
  const apiClient = new MQTTp<API>(mqttClient, { timeout: 1000 })
305
305