dsh-plugin-exe 0.0.0-stage → 0.1.1

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/lib/index.js ADDED
@@ -0,0 +1,4984 @@
1
+ // dsh-plugin-exe — built from plugins/dsh/src. Do not edit; see src/index.ts.
2
+
3
+ // src/index.ts
4
+ import Schema from "@deepseek-ai/schemastery";
5
+ import { defineTool } from "@deepseek-ai/dsh-tools";
6
+
7
+ // src/config.ts
8
+ import { existsSync, readFileSync } from "node:fs";
9
+ import { homedir } from "node:os";
10
+ import { join } from "node:path";
11
+
12
+ // ../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/error.js
13
+ function getLineColFromPtr(string, ptr) {
14
+ let lines = string.slice(0, ptr).split(/\r?\n/);
15
+ return [lines.length, lines.pop().length + 1];
16
+ }
17
+ function makeCodeBlock(string, line, column) {
18
+ let lines = string.split(/\r?\n/);
19
+ let codeblock = "";
20
+ let numberLen = (Math.log10(line + 1) | 0) + 1;
21
+ for (let i = line - 1; i <= line + 1; i++) {
22
+ let l = lines[i - 1];
23
+ if (!l)
24
+ continue;
25
+ codeblock += i.toString().padEnd(numberLen, " ");
26
+ codeblock += ": ";
27
+ codeblock += l;
28
+ codeblock += "\n";
29
+ if (i === line) {
30
+ codeblock += " ".repeat(numberLen + column + 2);
31
+ codeblock += "^\n";
32
+ }
33
+ }
34
+ return codeblock;
35
+ }
36
+ var TomlError = class _TomlError extends Error {
37
+ line;
38
+ column;
39
+ codeblock;
40
+ constructor(message2, options) {
41
+ const [line, column] = getLineColFromPtr(options.toml, options.ptr);
42
+ const codeblock = makeCodeBlock(options.toml, line, column);
43
+ super(`Invalid TOML document: ${message2}
44
+
45
+ ${codeblock}`, options);
46
+ this.line = line;
47
+ this.column = column;
48
+ this.codeblock = codeblock;
49
+ }
50
+ /** @internal */
51
+ static x(message2, ctx, ptr) {
52
+ throw new _TomlError(message2, { toml: ctx.s, ptr: ptr ?? ctx.p });
53
+ }
54
+ };
55
+
56
+ // ../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/primitive.js
57
+ function parseString(ctx) {
58
+ let startPtr = ctx.p;
59
+ let c = ctx.s.charCodeAt(ctx.p++);
60
+ let first = c;
61
+ let isLiteral = c === 39;
62
+ let isMultiline = c === ctx.s.charCodeAt(ctx.p) && c === ctx.s.charCodeAt(ctx.p + 1);
63
+ if (isMultiline) {
64
+ if ((c = ctx.s.charCodeAt(ctx.p += 2)) === 10)
65
+ ctx.p++;
66
+ else if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)
67
+ ctx.p += 2;
68
+ }
69
+ let parsed = "";
70
+ let sliceStart = ctx.p;
71
+ let state = 0;
72
+ for (; ctx.p < ctx.s.length; ctx.p++) {
73
+ c = ctx.s.charCodeAt(ctx.p);
74
+ if (isMultiline && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)) {
75
+ state = state && 3;
76
+ } else if (c < 32 && c !== 9 || c === 127) {
77
+ TomlError.x("control characters are not allowed in strings", ctx);
78
+ } else if ((!state || state === 3) && c === first && (!isMultiline || ctx.s.charCodeAt(ctx.p + 1) === first && ctx.s.charCodeAt(ctx.p + 2) === first)) {
79
+ if (isMultiline) {
80
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
81
+ ctx.p++;
82
+ if (ctx.s.charCodeAt(ctx.p + 3) === first)
83
+ ctx.p++;
84
+ }
85
+ if (!state) {
86
+ let s = ctx.s.slice(sliceStart, ctx.p);
87
+ parsed = parsed ? parsed + s : s;
88
+ }
89
+ ctx.p += isMultiline ? 3 : 1;
90
+ return parsed;
91
+ } else if (!state) {
92
+ if (!isLiteral && c === 92) {
93
+ parsed += ctx.s.slice(sliceStart, sliceStart = ctx.p);
94
+ state = 1;
95
+ }
96
+ } else if (state === 1) {
97
+ if (c === 120 || c === 117 || c === 85) {
98
+ let errPtr = ctx.p++ - 1;
99
+ let value = 0;
100
+ let len = c === 120 ? 2 : c === 117 ? 4 : 8;
101
+ for (let j = 0; j < len; j++, ctx.p++) {
102
+ let hex = ctx.s.charCodeAt(ctx.p);
103
+ let digit = (
104
+ /* 0-9 */
105
+ hex >= 48 && hex <= 57 ? hex - 48 : (
106
+ /* A-F */
107
+ hex >= 65 && hex <= 70 ? hex - 65 + 10 : (
108
+ /* a-f */
109
+ hex >= 97 && hex <= 102 ? hex - 97 + 10 : -1
110
+ )
111
+ )
112
+ );
113
+ if (digit < 0)
114
+ TomlError.x("invalid non-hex character in unicode escape", ctx);
115
+ value = value << 4 | digit;
116
+ }
117
+ if (value < 0 || value > 1114111 || value >= 55296 && value <= 57343) {
118
+ TomlError.x("invalid unicode escape", ctx, errPtr);
119
+ }
120
+ parsed += String.fromCodePoint(value);
121
+ sliceStart = ctx.p--;
122
+ state = 0;
123
+ } else if (isMultiline && (c === 32 || c === 9)) {
124
+ state = 2;
125
+ } else {
126
+ if (c === 98)
127
+ parsed += "\b";
128
+ else if (c === 116)
129
+ parsed += " ";
130
+ else if (c === 110)
131
+ parsed += "\n";
132
+ else if (c === 102)
133
+ parsed += "\f";
134
+ else if (c === 114)
135
+ parsed += "\r";
136
+ else if (c === 101)
137
+ parsed += "\x1B";
138
+ else if (c === 34)
139
+ parsed += '"';
140
+ else if (c === 92)
141
+ parsed += "\\";
142
+ else
143
+ TomlError.x("unrecognised escape sequence", ctx);
144
+ sliceStart = ctx.p + 1;
145
+ state = 0;
146
+ }
147
+ } else if (c !== 32 && c !== 9) {
148
+ if (state === 2)
149
+ TomlError.x("invalid escape: only line-ending whitespace may be escaped", ctx, sliceStart);
150
+ state = !isLiteral && c === 92 ? 1 : 0;
151
+ sliceStart = ctx.p;
152
+ }
153
+ }
154
+ TomlError.x("unfinished string", ctx, startPtr);
155
+ }
156
+
157
+ // ../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/date.js
158
+ var DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;
159
+ var TomlDate = class _TomlDate extends Date {
160
+ #hasDate = false;
161
+ #hasTime = false;
162
+ #offset = null;
163
+ constructor(date, fasttype, unsafeDelim) {
164
+ let hasDate = true;
165
+ let hasTime = true;
166
+ let offset = "Z";
167
+ let c;
168
+ if (typeof date === "string") {
169
+ if (fasttype)
170
+ prep: {
171
+ if (fasttype < 3) {
172
+ if (+date.slice(11, 13) > 23) {
173
+ date = "";
174
+ break prep;
175
+ }
176
+ if (fasttype === 2) {
177
+ offset = null;
178
+ date += "Z";
179
+ } else if ((c = date.charCodeAt(date.length - 1)) !== 90 && c !== 122) {
180
+ offset = date.slice(date.length - 6);
181
+ }
182
+ if (unsafeDelim)
183
+ date = date.slice(0, 10) + "T" + date.slice(11);
184
+ } else if (fasttype === 4) {
185
+ date = +date.slice(0, 2) > 23 ? "" : `0000-01-01T${date}Z`;
186
+ }
187
+ hasDate = fasttype !== 4;
188
+ hasTime = fasttype !== 3;
189
+ }
190
+ else {
191
+ let match = date.match(DATE_TIME_RE);
192
+ if (match) {
193
+ if (!match[1]) {
194
+ hasDate = false;
195
+ date = `0000-01-01T${date}`;
196
+ }
197
+ hasTime = !!match[2];
198
+ hasTime && date[10] === " " && (date = date.replace(" ", "T"));
199
+ if (match[2] && +match[2] > 23) {
200
+ date = "";
201
+ } else {
202
+ offset = match[3] || null;
203
+ if (!offset && hasTime)
204
+ date += "Z";
205
+ }
206
+ } else {
207
+ date = "";
208
+ }
209
+ }
210
+ }
211
+ super(date);
212
+ if (!isNaN(this.getTime())) {
213
+ this.#hasDate = hasDate;
214
+ this.#hasTime = hasTime;
215
+ this.#offset = offset;
216
+ }
217
+ }
218
+ isDateTime() {
219
+ return this.#hasDate && this.#hasTime;
220
+ }
221
+ isLocal() {
222
+ return !this.#hasDate || !this.#hasTime || !this.#offset;
223
+ }
224
+ isDate() {
225
+ return this.#hasDate && !this.#hasTime;
226
+ }
227
+ isTime() {
228
+ return this.#hasTime && !this.#hasDate;
229
+ }
230
+ isValid() {
231
+ return this.#hasDate || this.#hasTime;
232
+ }
233
+ toISOString() {
234
+ let iso = super.toISOString();
235
+ if (this.isDate())
236
+ return iso.slice(0, 10);
237
+ if (this.isTime())
238
+ return iso.slice(11, 23);
239
+ if (this.#offset === null)
240
+ return iso.slice(0, -1);
241
+ if (this.#offset === "Z" || this.#offset === "z")
242
+ return iso;
243
+ let offset = +this.#offset.slice(1, 3) * 60 + +this.#offset.slice(4, 6);
244
+ offset = this.#offset[0] === "-" ? offset : -offset;
245
+ let offsetDate = new Date(this.getTime() - offset * 6e4);
246
+ return offsetDate.toISOString().slice(0, -1) + this.#offset;
247
+ }
248
+ static wrapAsOffsetDateTime(jsDate, offset = "Z") {
249
+ let date = new _TomlDate(jsDate);
250
+ date.#offset = offset;
251
+ return date;
252
+ }
253
+ static wrapAsLocalDateTime(jsDate) {
254
+ let date = new _TomlDate(jsDate);
255
+ date.#offset = null;
256
+ return date;
257
+ }
258
+ static wrapAsLocalDate(jsDate) {
259
+ let date = new _TomlDate(jsDate);
260
+ date.#hasTime = false;
261
+ date.#offset = null;
262
+ return date;
263
+ }
264
+ static wrapAsLocalTime(jsDate) {
265
+ let date = new _TomlDate(jsDate);
266
+ date.#hasDate = false;
267
+ date.#offset = null;
268
+ return date;
269
+ }
270
+ };
271
+
272
+ // ../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/extract.js
273
+ function isDigit(char, base = 10) {
274
+ return base === 16 ? char > 47 && char < 58 || char > 64 && char < 71 || char > 96 && char < 103 : char > 47 && char < 48 + base;
275
+ }
276
+ function isEndOfValue(char, delim) {
277
+ return char === 32 || char === 9 || char === 10 || char === 13 || // Structure end or next value delimiter
278
+ delim && (char === delim || char === 44) || // Comment
279
+ char === 35;
280
+ }
281
+ function extractValue(ctx, end) {
282
+ let errPtr = ctx.p;
283
+ let c = ctx.s.charCodeAt(ctx.p);
284
+ if (c === 91 || c === 123) {
285
+ ctx.d-- || TomlError.x("document contains excessively nested structures. aborting.", ctx);
286
+ let value = c === 91 ? parseArray(ctx) : parseInlineTable(ctx);
287
+ ctx.d++;
288
+ return value;
289
+ }
290
+ if (c === 34 || c === 39) {
291
+ return parseString(ctx);
292
+ }
293
+ if (c === 116) {
294
+ if (ctx.s.charCodeAt(++ctx.p) !== 114 || ctx.s.charCodeAt(++ctx.p) !== 117 || ctx.s.charCodeAt(++ctx.p) !== 101)
295
+ TomlError.x("invalid value", ctx, errPtr);
296
+ return ctx.p++, true;
297
+ }
298
+ if (c === 102) {
299
+ if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 108 || ctx.s.charCodeAt(++ctx.p) !== 115 || ctx.s.charCodeAt(++ctx.p) !== 101)
300
+ TomlError.x("invalid value", ctx, errPtr);
301
+ return ctx.p++, false;
302
+ }
303
+ if (c === 43 || c === 45) {
304
+ return parseNumber(ctx, ctx.p, ctx.s.charCodeAt(++ctx.p), 44 - c, end);
305
+ }
306
+ if (ctx.s.charCodeAt(ctx.p + 4) === 45 && ctx.s.charCodeAt(ctx.p + 7) === 45) {
307
+ return parseDate(ctx, c, end);
308
+ }
309
+ if (ctx.s.charCodeAt(ctx.p + 2) === 58) {
310
+ return parseTime(ctx, c, end);
311
+ }
312
+ return parseNumber(ctx, ctx.p, c, 0, end);
313
+ }
314
+ function parseNumber(ctx, startPtr, startChr, sign2, endChr) {
315
+ let c = startChr;
316
+ let state = 0;
317
+ let hasUnderscores = false;
318
+ if (c === 105) {
319
+ if (ctx.s.charCodeAt(++ctx.p) !== 110 || ctx.s.charCodeAt(++ctx.p) !== 102)
320
+ TomlError.x("invalid value", ctx, startPtr);
321
+ return ctx.p++, (sign2 || 1) / 0;
322
+ }
323
+ if (c === 110) {
324
+ if (ctx.s.charCodeAt(++ctx.p) !== 97 || ctx.s.charCodeAt(++ctx.p) !== 110)
325
+ TomlError.x("invalid value", ctx, startPtr);
326
+ return ctx.p++, NaN;
327
+ }
328
+ if (c === 48) {
329
+ if (++ctx.p >= ctx.s.length || isEndOfValue(c = ctx.s.charCodeAt(ctx.p), endChr))
330
+ return ctx.bi === true ? 0n : 0;
331
+ if (!sign2) {
332
+ if (c === 120)
333
+ return parseIntegerBaseN(ctx, startPtr, 16, endChr);
334
+ else if (c === 98)
335
+ return parseIntegerBaseN(ctx, startPtr, 2, endChr);
336
+ else if (c === 111)
337
+ return parseIntegerBaseN(ctx, startPtr, 8, endChr);
338
+ }
339
+ if (c === 46)
340
+ state = 2;
341
+ else if (c === 101 || c === 69)
342
+ state = 4;
343
+ else
344
+ TomlError.x("illegal leading zero", ctx, startPtr);
345
+ } else if (!isDigit(c))
346
+ TomlError.x("invalid value", ctx, startPtr);
347
+ while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
348
+ if (!state)
349
+ state = 1;
350
+ if (c === 95) {
351
+ if (!(state & 1))
352
+ TomlError.x("illegal underscore", ctx);
353
+ state += 11;
354
+ hasUnderscores = true;
355
+ } else if (state === 1 && c === 46)
356
+ state = 2;
357
+ else if ((state === 1 || state === 3) && (c === 101 || c === 69))
358
+ state = 4;
359
+ else if (state === 4 && (c === 43 || c === 45)) {
360
+ state = 6;
361
+ } else if (!isDigit(c))
362
+ TomlError.x(`illegal character in numeric literal`, ctx);
363
+ else if (state > 9)
364
+ state -= 11;
365
+ else if (!(state & 1))
366
+ state++;
367
+ }
368
+ if (!state) {
369
+ let val = (startChr - 48) * (sign2 || 1);
370
+ return ctx.bi === true ? BigInt(val) : val;
371
+ }
372
+ if (!(state & 1))
373
+ TomlError.x("unfinished numeric value", ctx, startPtr);
374
+ let str = ctx.s.slice(startPtr, ctx.p);
375
+ if (hasUnderscores)
376
+ str = str.replaceAll("_", "");
377
+ return state > 1 ? parseFloat(str) : parseInteger(ctx, str, 10, startPtr);
378
+ }
379
+ function parseIntegerBaseN(ctx, startPtr, base, endChr) {
380
+ let c, underscore = 1;
381
+ while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {
382
+ if (c === 95) {
383
+ if (underscore & 1)
384
+ TomlError.x("illegal underscore", ctx);
385
+ underscore = 3;
386
+ } else if (!isDigit(c, base))
387
+ TomlError.x(`illegal character in numeric literal`, ctx);
388
+ else if (underscore & 1)
389
+ underscore--;
390
+ }
391
+ if (underscore & 1)
392
+ TomlError.x("unfinished numeric value", ctx);
393
+ let str = ctx.s.slice(startPtr + 2, ctx.p);
394
+ if (underscore)
395
+ str = str.replaceAll("_", "");
396
+ return parseInteger(ctx, str, base, startPtr);
397
+ }
398
+ function parseInteger(ctx, str, base, startPtr) {
399
+ if (ctx.bi !== true)
400
+ int: {
401
+ let val = parseInt(str, base);
402
+ if (!Number.isSafeInteger(val)) {
403
+ if (ctx.bi)
404
+ break int;
405
+ TomlError.x("integer value cannot be represented losslessly", ctx, startPtr);
406
+ }
407
+ return val;
408
+ }
409
+ return base === 10 ? BigInt(str) : BigInt((base === 2 ? "0b" : base === 8 ? "0o" : "0x") + str);
410
+ }
411
+ function parseDate(ctx, c, endChr) {
412
+ let startPtr = ctx.p++, unsafeSeparator;
413
+ if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++)) || !isDigit(ctx.s.charCodeAt(ctx.p++))) {
414
+ return parseNumber(ctx, ctx.p = startPtr, c, 0, endChr);
415
+ }
416
+ ctx.p += 5;
417
+ if (!isDigit(ctx.s.charCodeAt(ctx.p++)))
418
+ TomlError.x("invalid date-time: date part is malformed", ctx, startPtr);
419
+ if (ctx.p >= ctx.s.length || ((c = ctx.s.charCodeAt(ctx.p)) !== 32 || (unsafeSeparator = true, !isDigit(ctx.s.charCodeAt(ctx.p + 1)))) && c !== 84 && c !== 116) {
420
+ let t2 = ctx.s.slice(startPtr, ctx.p);
421
+ return readDate(ctx, t2, 3, false, startPtr);
422
+ }
423
+ if (ctx.s.charCodeAt(ctx.p += 3) !== 58)
424
+ TomlError.x("invalid date-time: time part is malformed", ctx, startPtr);
425
+ if (ctx.s.charCodeAt(ctx.p += 3) === 58)
426
+ ctx.p += 3;
427
+ if (ctx.s.charCodeAt(ctx.p) === 46)
428
+ while (isDigit(ctx.s.charCodeAt(++ctx.p)))
429
+ ;
430
+ if (c = ctx.s.charCodeAt(ctx.p)) {
431
+ if (c === 90 || c === 122) {
432
+ let t2 = ctx.s.slice(startPtr, ++ctx.p);
433
+ return readDate(ctx, t2, 1, unsafeSeparator, startPtr, "[+00:00]");
434
+ }
435
+ if (c === 43 || c === 45) {
436
+ let t2 = ctx.s.slice(startPtr, ctx.p += 6);
437
+ return readDate(ctx, t2, 1, unsafeSeparator, startPtr, !ctx.ld && "[" + ctx.s.slice(ctx.p - 6, ctx.p) + "]");
438
+ }
439
+ }
440
+ let t = ctx.s.slice(startPtr, ctx.p);
441
+ return readDate(ctx, t, 2, unsafeSeparator, startPtr);
442
+ }
443
+ function parseTime(ctx, c, endChr) {
444
+ let start = ctx.p;
445
+ if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(++ctx.p))) {
446
+ return parseNumber(ctx, --ctx.p, c, 0, endChr);
447
+ }
448
+ if (ctx.s.charCodeAt(ctx.p += 4) === 58)
449
+ ctx.p += 3;
450
+ if (ctx.s.charCodeAt(ctx.p) === 46)
451
+ while (isDigit(ctx.s.charCodeAt(++ctx.p)))
452
+ ;
453
+ let t = ctx.s.slice(start, ctx.p);
454
+ return readDate(ctx, t, 4, false, start);
455
+ }
456
+ function readDate(ctx, str, type, unsafeDelim, errPtr, temporalSuffix) {
457
+ if (ctx.ld) {
458
+ let date = new TomlDate(str, type, unsafeDelim);
459
+ if (!date.isValid())
460
+ TomlError.x("invalid date", ctx, errPtr);
461
+ return date;
462
+ }
463
+ try {
464
+ if (temporalSuffix)
465
+ str += temporalSuffix;
466
+ switch (type) {
467
+ case 1:
468
+ return Temporal.ZonedDateTime.from(str);
469
+ case 2:
470
+ return Temporal.PlainDateTime.from(str);
471
+ case 3:
472
+ return Temporal.PlainDate.from(str);
473
+ case 4:
474
+ return Temporal.PlainTime.from(str);
475
+ }
476
+ } catch (e) {
477
+ TomlError.x(e instanceof Error ? e.message : "" + e, ctx, errPtr);
478
+ }
479
+ }
480
+
481
+ // ../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/util.js
482
+ function skipComment(ctx) {
483
+ for (; ctx.p < ctx.s.length; ctx.p++) {
484
+ let c = ctx.s.charCodeAt(ctx.p);
485
+ if (c === 10)
486
+ break;
487
+ if (c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10) {
488
+ ctx.p++;
489
+ break;
490
+ }
491
+ if (c < 32 && c !== 9 || c === 127) {
492
+ TomlError.x("control characters are not allowed in comments", ctx);
493
+ }
494
+ }
495
+ }
496
+ function skipVoid(ctx, banNewLines, banComments) {
497
+ let c;
498
+ while (ctx.p < ctx.s.length) {
499
+ while (ctx.p < ctx.s.length && ((c = ctx.s.charCodeAt(ctx.p)) === 32 || c === 9 || !banNewLines && (c === 10 || c === 13 && ctx.s.charCodeAt(ctx.p + 1) === 10)))
500
+ ctx.p++;
501
+ if (banComments || c !== 35)
502
+ break;
503
+ skipComment(ctx);
504
+ }
505
+ }
506
+
507
+ // ../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/struct.js
508
+ function parseKey(ctx, end = 61) {
509
+ let startPtr;
510
+ let state = 0;
511
+ let parsed = [];
512
+ let sliceStart;
513
+ let c = ctx.s.charCodeAt(startPtr = ctx.p);
514
+ do {
515
+ if (c === end) {
516
+ if (!state)
517
+ TomlError.x("unexpected end of key", ctx);
518
+ if (state === 1)
519
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
520
+ return ctx.p++, parsed;
521
+ } else if (c === 46) {
522
+ if (!state)
523
+ TomlError.x("illegal empty bare key", ctx);
524
+ if (state === 1)
525
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
526
+ state = 0;
527
+ } else if (!state && (c === 34 || c === 39)) {
528
+ if (c === ctx.s.charCodeAt(ctx.p + 1) && c === ctx.s.charCodeAt(ctx.p + 2))
529
+ TomlError.x("illegal quoted key: multiline strings are not allowed", ctx);
530
+ parsed.push(parseString(ctx));
531
+ state = 2;
532
+ ctx.p--;
533
+ } else if (c === 32 || c === 9) {
534
+ if (state === 1) {
535
+ parsed.push(ctx.s.slice(sliceStart, ctx.p));
536
+ state = 2;
537
+ }
538
+ } else if (state === 2 || c < 48 && c !== 45 || c > 57 && c < 65 || c > 90 && c < 97 && c !== 95 || c > 122) {
539
+ TomlError.x("illegal character in key", ctx);
540
+ } else if (!state) {
541
+ state = 1;
542
+ sliceStart = ctx.p;
543
+ }
544
+ } while (c = ctx.s.charCodeAt(++ctx.p));
545
+ TomlError.x("incomplete key-value: cannot find end of key", ctx, startPtr);
546
+ }
547
+ function parseInlineTable(ctx) {
548
+ let startPtr = ctx.p++;
549
+ let res = /* @__PURE__ */ Object.create(null);
550
+ let seen = /* @__PURE__ */ new Set();
551
+ let c;
552
+ while (ctx.p < ctx.s.length) {
553
+ skipVoid(ctx);
554
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 125) {
555
+ ctx.p++;
556
+ return res;
557
+ }
558
+ let k;
559
+ let t = res;
560
+ let hasOwn = false;
561
+ let errPtr = ctx.p;
562
+ let key = parseKey(ctx);
563
+ for (let i = 0; i < key.length; i++) {
564
+ if (i)
565
+ t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
566
+ k = key[i];
567
+ if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== "object" || seen.has(t[k]))) {
568
+ TomlError.x("trying to redefine an already defined value", ctx, errPtr);
569
+ }
570
+ let unsafe = k === "__proto__";
571
+ if (ctx.uk && (unsafe || k === "constructor")) {
572
+ t = ctx.uk !== 1 && TomlError.x("document contains an unsafe property", ctx, errPtr);
573
+ break;
574
+ }
575
+ if (!hasOwn && unsafe) {
576
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
577
+ }
578
+ }
579
+ if (hasOwn) {
580
+ TomlError.x("trying to redefine an already defined value", ctx, errPtr);
581
+ }
582
+ skipVoid(ctx, true, true);
583
+ let value = extractValue(
584
+ ctx,
585
+ 125
586
+ /* } */
587
+ );
588
+ if (t && typeof (t[k] = value) === "object")
589
+ seen.add(value);
590
+ skipVoid(ctx);
591
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 125) {
592
+ return res;
593
+ }
594
+ if (c !== 44)
595
+ TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
596
+ }
597
+ TomlError.x("unfinished table", ctx, startPtr);
598
+ }
599
+ function parseArray(ctx) {
600
+ let startPtr = ctx.p++;
601
+ let res = [];
602
+ let c;
603
+ while (ctx.p < ctx.s.length) {
604
+ skipVoid(ctx);
605
+ if ((c = ctx.s.charCodeAt(ctx.p)) === 93) {
606
+ ctx.p++;
607
+ return res;
608
+ }
609
+ res.push(extractValue(
610
+ ctx,
611
+ 93
612
+ /* ] */
613
+ ));
614
+ skipVoid(ctx);
615
+ if ((c = ctx.s.charCodeAt(ctx.p++)) === 93) {
616
+ return res;
617
+ }
618
+ if (c !== 44)
619
+ TomlError.x("expected comma or end of structure", ctx, ctx.p - 1);
620
+ }
621
+ TomlError.x("unfinished array", ctx, startPtr);
622
+ }
623
+
624
+ // ../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/parse.js
625
+ function peekTable(ctx, key, table, meta, type) {
626
+ let t = table;
627
+ let m = meta;
628
+ let k;
629
+ let hasOwn = false;
630
+ let state;
631
+ for (let i = 0; i < key.length; i++) {
632
+ if (i) {
633
+ t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
634
+ m = (state = m[k]).c;
635
+ if (type === 0 && (state.t === 1 || state.t === 2)) {
636
+ return null;
637
+ }
638
+ if (state.t === 2) {
639
+ let l = t.length - 1;
640
+ t = t[l];
641
+ m = m[l].c;
642
+ }
643
+ }
644
+ k = key[i];
645
+ if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 && m[k]?.d) {
646
+ return null;
647
+ }
648
+ if (!hasOwn) {
649
+ let unsafe = k === "__proto__";
650
+ if (ctx.uk && (unsafe || k === "constructor"))
651
+ return false;
652
+ if (unsafe) {
653
+ Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });
654
+ Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });
655
+ }
656
+ m[k] = {
657
+ t: i < key.length - 1 && type === 2 ? 3 : type,
658
+ d: false,
659
+ i: 0,
660
+ c: /* @__PURE__ */ Object.create(null)
661
+ };
662
+ }
663
+ }
664
+ state = m[k];
665
+ if (state.t !== type && !(type === 1 && state.t === 3)) {
666
+ return null;
667
+ }
668
+ if (type === 2) {
669
+ if (!state.d) {
670
+ state.d = true;
671
+ t[k] = [];
672
+ }
673
+ t[k].push(t = /* @__PURE__ */ Object.create(null));
674
+ state.c[state.i++] = state = { t: 1, d: false, i: 0, c: /* @__PURE__ */ Object.create(null) };
675
+ }
676
+ if (state.d) {
677
+ return null;
678
+ }
679
+ state.d = true;
680
+ if (type === 1) {
681
+ t = hasOwn ? t[k] : t[k] = /* @__PURE__ */ Object.create(null);
682
+ } else if (type === 0 && hasOwn) {
683
+ return null;
684
+ }
685
+ return [k, t, state.c];
686
+ }
687
+ function validateTablePeek(ctx, peek, ptr) {
688
+ if (peek === null || ctx.uk === 2)
689
+ TomlError.x(peek === null ? "trying to redefine an already defined table or value" : "document contains an unsafe property", ctx, ptr);
690
+ }
691
+ function parse(toml, options = {}) {
692
+ let ctx = {
693
+ s: toml,
694
+ p: 0,
695
+ d: options.maxDepth ?? 1e3,
696
+ bi: options.integersAsBigInt ?? false,
697
+ ld: options.useLegacyDate ?? true,
698
+ uk: options.unsafeKeyBehaviour === "throw" ? 2 : options.unsafeKeyBehaviour === "drop" ? 1 : 0
699
+ };
700
+ let res = /* @__PURE__ */ Object.create(null);
701
+ let meta = /* @__PURE__ */ Object.create(null);
702
+ let tmp;
703
+ let skipping = false;
704
+ let tbl = res;
705
+ let m = meta;
706
+ if (toml.charCodeAt(0) === 65279)
707
+ ctx.p++;
708
+ skipVoid(ctx);
709
+ while (ctx.p < toml.length) {
710
+ if (toml.charCodeAt(ctx.p) === 91) {
711
+ let isTableArray = toml.charCodeAt(++ctx.p) === 91;
712
+ tmp = ctx.p += +isTableArray;
713
+ skipping = false;
714
+ let k = parseKey(
715
+ ctx,
716
+ 93
717
+ /* ] */
718
+ );
719
+ if (isTableArray) {
720
+ if (toml.charCodeAt(ctx.p) !== 93) {
721
+ TomlError.x("expected end of table array declaration", ctx);
722
+ }
723
+ ctx.p++;
724
+ }
725
+ let p = peekTable(
726
+ ctx,
727
+ k,
728
+ res,
729
+ meta,
730
+ isTableArray ? 2 : 1
731
+ /* Type.EXPLICIT */
732
+ );
733
+ if (!p) {
734
+ validateTablePeek(ctx, p, tmp);
735
+ skipping = true;
736
+ } else {
737
+ m = p[2];
738
+ tbl = p[1];
739
+ }
740
+ } else {
741
+ tmp = ctx.p;
742
+ let k = parseKey(ctx);
743
+ let p = peekTable(
744
+ ctx,
745
+ k,
746
+ tbl,
747
+ m,
748
+ 0
749
+ /* Type.DOTTED */
750
+ );
751
+ if (!p && !skipping)
752
+ validateTablePeek(ctx, p, tmp);
753
+ skipVoid(ctx, true, true);
754
+ let v = extractValue(ctx, void 0);
755
+ if (p && !skipping)
756
+ p[1][p[0]] = v;
757
+ }
758
+ skipVoid(ctx, true);
759
+ if (ctx.p < toml.length && (tmp = toml.charCodeAt(ctx.p)) !== 10 && (tmp !== 13 || toml.charCodeAt(ctx.p + 1) !== 10)) {
760
+ TomlError.x("each key-value declaration must be followed by an end-of-line", ctx);
761
+ }
762
+ skipVoid(ctx);
763
+ }
764
+ return res;
765
+ }
766
+
767
+ // ../../node_modules/.pnpm/smol-toml@1.9.1/node_modules/smol-toml/dist/stringify.js
768
+ var HAS_WELLFORMED = !!"".isWellFormed;
769
+
770
+ // ../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_u64.js
771
+ var U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();
772
+ var _32n = /* @__PURE__ */ BigInt(32);
773
+ function fromBig(n, le = false) {
774
+ if (le)
775
+ return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) };
776
+ return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
777
+ }
778
+ function split(lst, le = false) {
779
+ const len = lst.length;
780
+ let Ah = new Uint32Array(len);
781
+ let Al = new Uint32Array(len);
782
+ for (let i = 0; i < len; i++) {
783
+ const { h, l } = fromBig(lst[i], le);
784
+ [Ah[i], Al[i]] = [h, l];
785
+ }
786
+ return [Ah, Al];
787
+ }
788
+ var fromNumH = (n) => n / 2 ** 32 | 0;
789
+ var fromNumL = (n) => n >>> 0;
790
+ function setU64FromNum(view, byteOffset, n, isLE2) {
791
+ const h = fromNumH(n);
792
+ const l = fromNumL(n);
793
+ view.setUint32(byteOffset, isLE2 ? l : h, isLE2);
794
+ view.setUint32(byteOffset + 4, isLE2 ? h : l, isLE2);
795
+ }
796
+ var shrSH = (h, _l, s) => h >>> s;
797
+ var shrSL = (h, l, s) => h << 32 - s | l >>> s;
798
+ var rotrSH = (h, l, s) => h >>> s | l << 32 - s;
799
+ var rotrSL = (h, l, s) => h << 32 - s | l >>> s;
800
+ var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
801
+ var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
802
+ function add(Ah, Al, Bh, Bl) {
803
+ const l = (Al >>> 0) + (Bl >>> 0);
804
+ return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 };
805
+ }
806
+ var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
807
+ var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
808
+ var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
809
+ var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
810
+ var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
811
+ var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
812
+
813
+ // ../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/utils.js
814
+ function isBytes(a) {
815
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
816
+ }
817
+ var atitle = (title) => title ? `"${title}" ` : "";
818
+ function anumber(n, title = "") {
819
+ if (typeof n !== "number")
820
+ throw new TypeError(atitle(title) + "expected number, got " + typeof n);
821
+ if (!Number.isSafeInteger(n) || n < 0)
822
+ throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
823
+ return n;
824
+ }
825
+ function abytes(value, length, title = "") {
826
+ if (isBytes(value) && (length === void 0 || value.length === length))
827
+ return value;
828
+ if (length !== void 0)
829
+ anumber(length, "length");
830
+ const bytes = isBytes(value);
831
+ const ofLen = length !== void 0 ? ` of length ${length}` : "";
832
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
833
+ const message2 = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
834
+ if (!bytes)
835
+ throw new TypeError(message2);
836
+ throw new RangeError(message2);
837
+ }
838
+ var aobject = (value, label) => {
839
+ if (value === null || typeof value !== "object" || Array.isArray(value))
840
+ throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value);
841
+ };
842
+ var aopts = (value, label) => {
843
+ aobject(value, label);
844
+ const proto = Object.getPrototypeOf(value);
845
+ if (proto !== Object.prototype && proto !== null)
846
+ throw new TypeError(`"${label}" expected plain object`);
847
+ if (Object.hasOwn(value, "__proto__"))
848
+ throw new TypeError(`"${label}.__proto__" is not allowed`);
849
+ };
850
+ function aexists(instance, checkFinished = true) {
851
+ if (instance.destroyed)
852
+ throw new Error("hash was destroyed");
853
+ if (checkFinished && instance.finished)
854
+ throw new Error("digest() was already called");
855
+ }
856
+ function aoutput(out, instance) {
857
+ abytes(out, void 0, "output");
858
+ const min = instance.outputLen;
859
+ if (!(out.length >= min)) {
860
+ throw new RangeError('"output" expected length >= ' + min);
861
+ }
862
+ }
863
+ function clean(...arrays) {
864
+ for (let i = 0; i < arrays.length; i++) {
865
+ arrays[i].fill(0);
866
+ }
867
+ }
868
+ function createView(arr) {
869
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
870
+ }
871
+ var hasHexBuiltin = /* @__PURE__ */ (() => (
872
+ // @ts-ignore
873
+ typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"
874
+ ))();
875
+ var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
876
+ function bytesToHex(bytes) {
877
+ abytes(bytes);
878
+ if (hasHexBuiltin)
879
+ return bytes.toHex();
880
+ let hex = "";
881
+ for (let i = 0; i < bytes.length; i++) {
882
+ hex += hexes[bytes[i]];
883
+ }
884
+ return hex;
885
+ }
886
+ function asciiToBase16(ch) {
887
+ return ch >= 48 && ch <= 57 ? ch - 48 : ch >= 65 && ch <= 70 ? ch - (65 - 10) : ch >= 97 && ch <= 102 ? ch - (97 - 10) : void 0;
888
+ }
889
+ function hexToBytes(hex) {
890
+ if (typeof hex !== "string")
891
+ throw new TypeError("hex string expected, got " + typeof hex);
892
+ if (hasHexBuiltin) {
893
+ try {
894
+ return Uint8Array.fromHex(hex);
895
+ } catch (error) {
896
+ if (error instanceof SyntaxError)
897
+ throw new RangeError(error.message);
898
+ throw error;
899
+ }
900
+ }
901
+ const hl = hex.length;
902
+ const al = hl / 2;
903
+ if (hl % 2)
904
+ throw new RangeError("hex string expected, got unpadded hex of length " + hl);
905
+ const array = new Uint8Array(al);
906
+ for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
907
+ const n1 = asciiToBase16(hex.charCodeAt(hi));
908
+ const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
909
+ if (n1 === void 0 || n2 === void 0) {
910
+ const char = hex[hi] + hex[hi + 1];
911
+ throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi);
912
+ }
913
+ array[ai] = n1 * 16 + n2;
914
+ }
915
+ return array;
916
+ }
917
+ function concatBytes(...arrays) {
918
+ let sum = 0;
919
+ for (let i = 0; i < arrays.length; i++) {
920
+ const a = arrays[i];
921
+ abytes(a);
922
+ sum += a.length;
923
+ }
924
+ const res = new Uint8Array(sum);
925
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
926
+ const a = arrays[i];
927
+ res.set(a, pad);
928
+ pad += a.length;
929
+ }
930
+ return res;
931
+ }
932
+ function checkOpts(defaults, opts, title = "opts") {
933
+ aopts(defaults, "defaults");
934
+ if (opts !== void 0)
935
+ aopts(opts, title);
936
+ const merged = Object.assign(/* @__PURE__ */ Object.create(null), defaults, opts);
937
+ return merged;
938
+ }
939
+ function createHasher(hashCons, info = {}) {
940
+ if (typeof hashCons !== "function")
941
+ throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
942
+ info = checkOpts({}, info, "info");
943
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
944
+ const tmp = hashCons(void 0);
945
+ hashC.outputLen = tmp.outputLen;
946
+ hashC.blockLen = tmp.blockLen;
947
+ hashC.canXOF = tmp.canXOF;
948
+ hashC.create = (opts) => hashCons(opts);
949
+ Object.assign(hashC, info);
950
+ return Object.freeze(hashC);
951
+ }
952
+ function randomBytes(bytesLength = 32) {
953
+ anumber(bytesLength, "bytesLength");
954
+ const cr = typeof globalThis === "object" ? globalThis.crypto : null;
955
+ if (typeof cr?.getRandomValues !== "function")
956
+ throw new Error("crypto.getRandomValues must be defined");
957
+ if (bytesLength > 65536)
958
+ throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
959
+ return cr.getRandomValues(new Uint8Array(bytesLength));
960
+ }
961
+ var oidNist = (suffix) => ({
962
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
963
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
964
+ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
965
+ });
966
+
967
+ // ../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_md.js
968
+ var HashMD = class {
969
+ blockLen;
970
+ outputLen;
971
+ canXOF = false;
972
+ padOffset;
973
+ isLE;
974
+ // For partial updates less than block size
975
+ buffer;
976
+ view;
977
+ finished = false;
978
+ length = 0;
979
+ pos = 0;
980
+ destroyed = false;
981
+ constructor(blockLen, outputLen, padOffset, isLE2) {
982
+ this.blockLen = blockLen;
983
+ this.outputLen = outputLen;
984
+ this.padOffset = padOffset;
985
+ this.isLE = isLE2;
986
+ this.buffer = new Uint8Array(blockLen);
987
+ this.view = createView(this.buffer);
988
+ }
989
+ update(data) {
990
+ aexists(this);
991
+ abytes(data);
992
+ const { view, buffer, blockLen } = this;
993
+ const len = data.length;
994
+ let processed = false;
995
+ for (let pos = 0; pos < len; ) {
996
+ const take = Math.min(blockLen - this.pos, len - pos);
997
+ if (take === blockLen) {
998
+ const dataView = createView(data);
999
+ for (; blockLen <= len - pos; pos += blockLen)
1000
+ this.process(dataView, pos);
1001
+ processed = true;
1002
+ continue;
1003
+ }
1004
+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
1005
+ this.pos += take;
1006
+ pos += take;
1007
+ if (this.pos === blockLen) {
1008
+ this.process(view, 0);
1009
+ this.pos = 0;
1010
+ processed = true;
1011
+ }
1012
+ }
1013
+ this.length += data.length;
1014
+ if (processed)
1015
+ this.roundClean();
1016
+ return this;
1017
+ }
1018
+ digestInto(out) {
1019
+ aexists(this);
1020
+ aoutput(out, this);
1021
+ this.finished = true;
1022
+ const { buffer, view, blockLen, isLE: isLE2 } = this;
1023
+ let { pos } = this;
1024
+ buffer[pos++] = 128;
1025
+ buffer.fill(0, pos);
1026
+ if (this.padOffset > blockLen - pos) {
1027
+ this.process(view, 0);
1028
+ buffer.fill(0);
1029
+ }
1030
+ setU64FromNum(view, blockLen - 8, this.length * 8, isLE2);
1031
+ this.process(view, 0);
1032
+ this.roundClean();
1033
+ const oview = out === buffer ? view : createView(out);
1034
+ const len = this.outputLen;
1035
+ const outLen = len / 4;
1036
+ const state = this.get();
1037
+ if (len % 4 || outLen > state.length)
1038
+ throw new Error("invalid outputLen");
1039
+ for (let i = 0; i < outLen; i++)
1040
+ oview.setUint32(4 * i, state[i], isLE2);
1041
+ }
1042
+ digest() {
1043
+ const { buffer, outputLen } = this;
1044
+ this.digestInto(buffer);
1045
+ const res = buffer.slice(0, outputLen);
1046
+ this.destroy();
1047
+ return res;
1048
+ }
1049
+ _cloneIntoMeta(to) {
1050
+ const { buffer, length, finished, destroyed, pos } = this;
1051
+ to.destroyed = destroyed;
1052
+ to.finished = finished;
1053
+ to.length = length;
1054
+ to.pos = pos;
1055
+ if (pos)
1056
+ to.buffer.set(buffer);
1057
+ return to;
1058
+ }
1059
+ clone() {
1060
+ return this._cloneInto();
1061
+ }
1062
+ };
1063
+ var SHA512_IV = /* @__PURE__ */ Uint32Array.from([
1064
+ 1779033703,
1065
+ 4089235720,
1066
+ 3144134277,
1067
+ 2227873595,
1068
+ 1013904242,
1069
+ 4271175723,
1070
+ 2773480762,
1071
+ 1595750129,
1072
+ 1359893119,
1073
+ 2917565137,
1074
+ 2600822924,
1075
+ 725511199,
1076
+ 528734635,
1077
+ 4215389547,
1078
+ 1541459225,
1079
+ 327033209
1080
+ ]);
1081
+
1082
+ // ../../node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/sha2.js
1083
+ var K512 = /* @__PURE__ */ (() => split([
1084
+ "0x428a2f98d728ae22",
1085
+ "0x7137449123ef65cd",
1086
+ "0xb5c0fbcfec4d3b2f",
1087
+ "0xe9b5dba58189dbbc",
1088
+ "0x3956c25bf348b538",
1089
+ "0x59f111f1b605d019",
1090
+ "0x923f82a4af194f9b",
1091
+ "0xab1c5ed5da6d8118",
1092
+ "0xd807aa98a3030242",
1093
+ "0x12835b0145706fbe",
1094
+ "0x243185be4ee4b28c",
1095
+ "0x550c7dc3d5ffb4e2",
1096
+ "0x72be5d74f27b896f",
1097
+ "0x80deb1fe3b1696b1",
1098
+ "0x9bdc06a725c71235",
1099
+ "0xc19bf174cf692694",
1100
+ "0xe49b69c19ef14ad2",
1101
+ "0xefbe4786384f25e3",
1102
+ "0x0fc19dc68b8cd5b5",
1103
+ "0x240ca1cc77ac9c65",
1104
+ "0x2de92c6f592b0275",
1105
+ "0x4a7484aa6ea6e483",
1106
+ "0x5cb0a9dcbd41fbd4",
1107
+ "0x76f988da831153b5",
1108
+ "0x983e5152ee66dfab",
1109
+ "0xa831c66d2db43210",
1110
+ "0xb00327c898fb213f",
1111
+ "0xbf597fc7beef0ee4",
1112
+ "0xc6e00bf33da88fc2",
1113
+ "0xd5a79147930aa725",
1114
+ "0x06ca6351e003826f",
1115
+ "0x142929670a0e6e70",
1116
+ "0x27b70a8546d22ffc",
1117
+ "0x2e1b21385c26c926",
1118
+ "0x4d2c6dfc5ac42aed",
1119
+ "0x53380d139d95b3df",
1120
+ "0x650a73548baf63de",
1121
+ "0x766a0abb3c77b2a8",
1122
+ "0x81c2c92e47edaee6",
1123
+ "0x92722c851482353b",
1124
+ "0xa2bfe8a14cf10364",
1125
+ "0xa81a664bbc423001",
1126
+ "0xc24b8b70d0f89791",
1127
+ "0xc76c51a30654be30",
1128
+ "0xd192e819d6ef5218",
1129
+ "0xd69906245565a910",
1130
+ "0xf40e35855771202a",
1131
+ "0x106aa07032bbd1b8",
1132
+ "0x19a4c116b8d2d0c8",
1133
+ "0x1e376c085141ab53",
1134
+ "0x2748774cdf8eeb99",
1135
+ "0x34b0bcb5e19b48a8",
1136
+ "0x391c0cb3c5c95a63",
1137
+ "0x4ed8aa4ae3418acb",
1138
+ "0x5b9cca4f7763e373",
1139
+ "0x682e6ff3d6b2b8a3",
1140
+ "0x748f82ee5defb2fc",
1141
+ "0x78a5636f43172f60",
1142
+ "0x84c87814a1f0ab72",
1143
+ "0x8cc702081a6439ec",
1144
+ "0x90befffa23631e28",
1145
+ "0xa4506cebde82bde9",
1146
+ "0xbef9a3f7b2c67915",
1147
+ "0xc67178f2e372532b",
1148
+ "0xca273eceea26619c",
1149
+ "0xd186b8c721c0c207",
1150
+ "0xeada7dd6cde0eb1e",
1151
+ "0xf57d4f7fee6ed178",
1152
+ "0x06f067aa72176fba",
1153
+ "0x0a637dc5a2c898a6",
1154
+ "0x113f9804bef90dae",
1155
+ "0x1b710b35131c471b",
1156
+ "0x28db77f523047d84",
1157
+ "0x32caab7b40c72493",
1158
+ "0x3c9ebe0a15c9bebc",
1159
+ "0x431d67c49c100d4c",
1160
+ "0x4cc5d4becb3e42b6",
1161
+ "0x597f299cfc657e2a",
1162
+ "0x5fcb6fab3ad6faec",
1163
+ "0x6c44198c4a475817"
1164
+ ].map((n) => BigInt(n))))();
1165
+ var SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
1166
+ var SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
1167
+ var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
1168
+ var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
1169
+ var SHA2_64B = class extends HashMD {
1170
+ // We cannot use array here since array allows indexing by variable
1171
+ // which means optimizer/compiler cannot use registers.
1172
+ // h -- high 32 bits, l -- low 32 bits
1173
+ // Numeric initializers matter: starting the fields as `undefined` changes
1174
+ // V8's field representation and slows hashing down (measured on sha256).
1175
+ Ah = 0;
1176
+ Al = 0;
1177
+ Bh = 0;
1178
+ Bl = 0;
1179
+ Ch = 0;
1180
+ Cl = 0;
1181
+ Dh = 0;
1182
+ Dl = 0;
1183
+ Eh = 0;
1184
+ El = 0;
1185
+ Fh = 0;
1186
+ Fl = 0;
1187
+ Gh = 0;
1188
+ Gl = 0;
1189
+ Hh = 0;
1190
+ Hl = 0;
1191
+ constructor(outputLen, IV) {
1192
+ super(128, outputLen, 16, false);
1193
+ this.Ah = IV[0] | 0;
1194
+ this.Al = IV[1] | 0;
1195
+ this.Bh = IV[2] | 0;
1196
+ this.Bl = IV[3] | 0;
1197
+ this.Ch = IV[4] | 0;
1198
+ this.Cl = IV[5] | 0;
1199
+ this.Dh = IV[6] | 0;
1200
+ this.Dl = IV[7] | 0;
1201
+ this.Eh = IV[8] | 0;
1202
+ this.El = IV[9] | 0;
1203
+ this.Fh = IV[10] | 0;
1204
+ this.Fl = IV[11] | 0;
1205
+ this.Gh = IV[12] | 0;
1206
+ this.Gl = IV[13] | 0;
1207
+ this.Hh = IV[14] | 0;
1208
+ this.Hl = IV[15] | 0;
1209
+ }
1210
+ // prettier-ignore
1211
+ get() {
1212
+ const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1213
+ return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];
1214
+ }
1215
+ // prettier-ignore
1216
+ set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
1217
+ this.Ah = Ah | 0;
1218
+ this.Al = Al | 0;
1219
+ this.Bh = Bh | 0;
1220
+ this.Bl = Bl | 0;
1221
+ this.Ch = Ch | 0;
1222
+ this.Cl = Cl | 0;
1223
+ this.Dh = Dh | 0;
1224
+ this.Dl = Dl | 0;
1225
+ this.Eh = Eh | 0;
1226
+ this.El = El | 0;
1227
+ this.Fh = Fh | 0;
1228
+ this.Fl = Fl | 0;
1229
+ this.Gh = Gh | 0;
1230
+ this.Gl = Gl | 0;
1231
+ this.Hh = Hh | 0;
1232
+ this.Hl = Hl | 0;
1233
+ }
1234
+ _cloneInto(to) {
1235
+ (to ||= new this.constructor()).set(...this.get());
1236
+ return this._cloneIntoMeta(to);
1237
+ }
1238
+ process(view, offset) {
1239
+ for (let i = 0; i < 16; i++, offset += 4) {
1240
+ SHA512_W_H[i] = view.getUint32(offset);
1241
+ SHA512_W_L[i] = view.getUint32(offset += 4);
1242
+ }
1243
+ for (let i = 16; i < 80; i++) {
1244
+ const W15h = SHA512_W_H[i - 15] | 0;
1245
+ const W15l = SHA512_W_L[i - 15] | 0;
1246
+ const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
1247
+ const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
1248
+ const W2h = SHA512_W_H[i - 2] | 0;
1249
+ const W2l = SHA512_W_L[i - 2] | 0;
1250
+ const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
1251
+ const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
1252
+ const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
1253
+ const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
1254
+ SHA512_W_H[i] = SUMh | 0;
1255
+ SHA512_W_L[i] = SUMl | 0;
1256
+ }
1257
+ let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
1258
+ for (let i = 0; i < 80; i++) {
1259
+ const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
1260
+ const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
1261
+ const CHIh = Eh & Fh ^ ~Eh & Gh;
1262
+ const CHIl = El & Fl ^ ~El & Gl;
1263
+ const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
1264
+ const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
1265
+ const T1l = T1ll | 0;
1266
+ const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
1267
+ const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
1268
+ const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
1269
+ const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
1270
+ Hh = Gh | 0;
1271
+ Hl = Gl | 0;
1272
+ Gh = Fh | 0;
1273
+ Gl = Fl | 0;
1274
+ Fh = Eh | 0;
1275
+ Fl = El | 0;
1276
+ ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
1277
+ Dh = Ch | 0;
1278
+ Dl = Cl | 0;
1279
+ Ch = Bh | 0;
1280
+ Cl = Bl | 0;
1281
+ Bh = Ah | 0;
1282
+ Bl = Al | 0;
1283
+ const All = add3L(T1l, sigma0l, MAJl);
1284
+ Ah = add3H(All, T1h, sigma0h, MAJh);
1285
+ Al = All | 0;
1286
+ }
1287
+ ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
1288
+ ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
1289
+ ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
1290
+ ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
1291
+ ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
1292
+ ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
1293
+ ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
1294
+ ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
1295
+ this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
1296
+ }
1297
+ roundClean() {
1298
+ clean(SHA512_W_H, SHA512_W_L);
1299
+ }
1300
+ destroy() {
1301
+ this.destroyed = true;
1302
+ clean(this.buffer);
1303
+ this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1304
+ }
1305
+ };
1306
+ var _SHA512 = class extends SHA2_64B {
1307
+ constructor() {
1308
+ super(64, SHA512_IV);
1309
+ }
1310
+ };
1311
+ var sha512 = /* @__PURE__ */ createHasher(
1312
+ () => new _SHA512(),
1313
+ /* @__PURE__ */ oidNist(3)
1314
+ );
1315
+
1316
+ // ../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/utils.js
1317
+ function aarray(item, title, inner = () => {
1318
+ }) {
1319
+ if (!Array.isArray(item))
1320
+ throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
1321
+ for (let i = 0; i < item.length; i++)
1322
+ inner(item[i], `${title}[${i}]`);
1323
+ return item;
1324
+ }
1325
+ var abytes2 = (value, length, title) => abytes(value, length, title);
1326
+ var anumber2 = anumber;
1327
+ function aobject2(value, title = "object") {
1328
+ if (value === null || typeof value !== "object" || Array.isArray(value))
1329
+ throw new TypeError(title === "object" ? "expected valid options object" : `"${title}" expected object, got type=${typeof value}`);
1330
+ return value;
1331
+ }
1332
+ function afunction(value, title) {
1333
+ if (typeof value !== "function")
1334
+ throw new TypeError(`"${title}" is invalid: expected function, got ${typeof value}`);
1335
+ return value;
1336
+ }
1337
+ var bytesToHex2 = bytesToHex;
1338
+ var concatBytes2 = (...arrays) => concatBytes(...arrays);
1339
+ var hexToBytes2 = (hex) => hexToBytes(hex);
1340
+ var isBytes2 = isBytes;
1341
+ var randomBytes2 = (bytesLength) => randomBytes(bytesLength);
1342
+ var _0n = /* @__PURE__ */ BigInt(0);
1343
+ var _1n = /* @__PURE__ */ BigInt(1);
1344
+ var atitle2 = (title) => title ? `"${title}" ` : "";
1345
+ function abool(value, title = "") {
1346
+ if (typeof value !== "boolean")
1347
+ throw new TypeError(atitle2(title) + "expected boolean, got type=" + typeof value);
1348
+ return value;
1349
+ }
1350
+ function abignumber(n) {
1351
+ if (typeof n === "bigint") {
1352
+ if (!isPosBig(n))
1353
+ throw new RangeError("positive bigint expected, got " + n);
1354
+ } else
1355
+ anumber2(n);
1356
+ return n;
1357
+ }
1358
+ function asafenumber(value, title = "") {
1359
+ if (typeof value !== "number") {
1360
+ const prefix = title && `"${title}" `;
1361
+ throw new TypeError(prefix + "expected number, got type=" + typeof value);
1362
+ }
1363
+ if (!Number.isSafeInteger(value)) {
1364
+ const prefix = title && `"${title}" `;
1365
+ throw new RangeError(prefix + "expected safe integer, got " + value);
1366
+ }
1367
+ }
1368
+ function hexToNumber(hex) {
1369
+ if (typeof hex !== "string")
1370
+ throw new TypeError("hex string expected, got " + typeof hex);
1371
+ return hex === "" ? _0n : BigInt("0x" + hex);
1372
+ }
1373
+ function bytesToNumberBE(bytes) {
1374
+ return hexToNumber(bytesToHex(bytes));
1375
+ }
1376
+ function bytesToNumberLE(bytes) {
1377
+ return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse()));
1378
+ }
1379
+ function numberToBytesBE(n, len) {
1380
+ anumber(len);
1381
+ if (len === 0)
1382
+ throw new Error("zero output length is invalid");
1383
+ n = abignumber(n);
1384
+ const expectedLen = len * 2;
1385
+ const hex = n.toString(16);
1386
+ if (hex.length > expectedLen)
1387
+ throw new RangeError("number is too large");
1388
+ return hexToBytes(hex.padStart(expectedLen, "0"));
1389
+ }
1390
+ function numberToBytesLE(n, len) {
1391
+ return numberToBytesBE(n, len).reverse();
1392
+ }
1393
+ function copyBytes(bytes) {
1394
+ return Uint8Array.from(abytes2(bytes));
1395
+ }
1396
+ function isPosBig(n) {
1397
+ return typeof n === "bigint" && _0n <= n;
1398
+ }
1399
+ function inRange(n, min, max) {
1400
+ return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
1401
+ }
1402
+ function aInRange(title, n, min, max) {
1403
+ if (!inRange(n, min, max))
1404
+ throw new RangeError("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
1405
+ }
1406
+ function bitLen(n) {
1407
+ if (n < _0n)
1408
+ throw new Error("expected non-negative bigint, got " + n);
1409
+ return n === _0n ? 0 : n.toString(2).length;
1410
+ }
1411
+ var bitMask = (n) => {
1412
+ asafenumber(n, "n");
1413
+ return (_1n << BigInt(n)) - _1n;
1414
+ };
1415
+ function validateObject(object, fields = {}, optFields = {}, title = "object") {
1416
+ aobject2(object, title);
1417
+ aobject2(fields, "fields");
1418
+ aobject2(optFields, "optFields");
1419
+ function checkField(fieldName, expectedType, isOpt) {
1420
+ const label = title === "object" ? `param "${String(fieldName)}"` : `"${title}.${String(fieldName)}"`;
1421
+ const val = object[fieldName];
1422
+ if (!Object.hasOwn(object, fieldName) && (isOpt ? val !== void 0 : expectedType !== "function")) {
1423
+ throw new TypeError(`${label} is invalid: expected own property`);
1424
+ }
1425
+ if (isOpt && val === void 0)
1426
+ return;
1427
+ const current = typeof val;
1428
+ if (current !== expectedType || val === null)
1429
+ throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);
1430
+ }
1431
+ const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));
1432
+ iter(fields, false);
1433
+ iter(optFields, true);
1434
+ }
1435
+
1436
+ // ../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/modular.js
1437
+ var _0n2 = /* @__PURE__ */ BigInt(0);
1438
+ var _1n2 = /* @__PURE__ */ BigInt(1);
1439
+ var _2n = /* @__PURE__ */ BigInt(2);
1440
+ var _3n = /* @__PURE__ */ BigInt(3);
1441
+ var _4n = /* @__PURE__ */ BigInt(4);
1442
+ var _5n = /* @__PURE__ */ BigInt(5);
1443
+ var _7n = /* @__PURE__ */ BigInt(7);
1444
+ var _8n = /* @__PURE__ */ BigInt(8);
1445
+ var _9n = /* @__PURE__ */ BigInt(9);
1446
+ var _15n = /* @__PURE__ */ BigInt(15);
1447
+ var _16n = /* @__PURE__ */ BigInt(16);
1448
+ var POW_WINDOWED_MIN = /* @__PURE__ */ BigInt("0x10000000000000000");
1449
+ function mod(a, b) {
1450
+ if (b <= _0n2)
1451
+ throw new Error("mod: expected positive modulus, got " + b);
1452
+ const result = a % b;
1453
+ return result >= _0n2 ? result : b + result;
1454
+ }
1455
+ function pow(num, power, modulo) {
1456
+ if (modulo <= _1n2)
1457
+ throw new Error("pow: expected modulus > 1, got " + modulo);
1458
+ if (typeof power !== "bigint")
1459
+ throw new TypeError("invalid exponent: expected bigint, got " + typeof power);
1460
+ if (power < _0n2)
1461
+ throw new Error("invalid exponent, negatives unsupported");
1462
+ if (power === _0n2)
1463
+ return _1n2;
1464
+ if (power === _1n2)
1465
+ return num;
1466
+ let d = num % modulo;
1467
+ if (d < _0n2)
1468
+ d += modulo;
1469
+ if (power < POW_WINDOWED_MIN) {
1470
+ let p2 = _1n2;
1471
+ while (power > _0n2) {
1472
+ if (power & _1n2)
1473
+ p2 = p2 * d % modulo;
1474
+ d = d * d % modulo;
1475
+ power >>= _1n2;
1476
+ }
1477
+ return p2;
1478
+ }
1479
+ const digits = [];
1480
+ while (power > _0n2) {
1481
+ digits.push(Number(power & _15n));
1482
+ power >>= _4n;
1483
+ }
1484
+ const table = new Array(16);
1485
+ table[0] = _1n2;
1486
+ table[1] = d;
1487
+ for (let i = 2; i < 16; i++)
1488
+ table[i] = table[i - 1] * d % modulo;
1489
+ let p = table[digits[digits.length - 1]];
1490
+ for (let w = digits.length - 2; w >= 0; w--) {
1491
+ p = p * p % modulo;
1492
+ p = p * p % modulo;
1493
+ p = p * p % modulo;
1494
+ p = p * p % modulo;
1495
+ const digit = digits[w];
1496
+ if (digit !== 0)
1497
+ p = p * table[digit] % modulo;
1498
+ }
1499
+ return p;
1500
+ }
1501
+ function pow2(x, power, modulo) {
1502
+ if (modulo <= _1n2)
1503
+ throw new Error("pow2: expected modulus > 1, got " + modulo);
1504
+ if (power < _0n2)
1505
+ throw new Error("pow2: expected non-negative exponent, got " + power);
1506
+ let res = x;
1507
+ while (power-- > _0n2) {
1508
+ res *= res;
1509
+ res %= modulo;
1510
+ }
1511
+ return res;
1512
+ }
1513
+ function invert(number, modulo) {
1514
+ if (number === _0n2)
1515
+ throw new Error("invert: expected non-zero number");
1516
+ if (modulo <= _1n2)
1517
+ throw new Error("invert: expected modulus > 1, got " + modulo);
1518
+ let a = mod(number, modulo);
1519
+ let b = modulo;
1520
+ let x = _0n2, u = _1n2;
1521
+ while (a !== _0n2) {
1522
+ const q = b / a;
1523
+ const r = b - a * q;
1524
+ const m = x - u * q;
1525
+ b = a, a = r, x = u, u = m;
1526
+ }
1527
+ const gcd = b;
1528
+ if (gcd !== _1n2)
1529
+ throw new Error("invert: does not exist");
1530
+ return mod(x, modulo);
1531
+ }
1532
+ function assertIsSquare(Fp2, root, n) {
1533
+ const F = Fp2;
1534
+ if (!F.eql(F.sqr(root), n))
1535
+ throw new Error("Cannot find square root");
1536
+ }
1537
+ function aoddModulus(order, fnName) {
1538
+ if ((order & _1n2) === _0n2)
1539
+ throw new Error(fnName + ": expected odd modulus, got " + order);
1540
+ }
1541
+ function sqrt3mod4(Fp2, n) {
1542
+ const F = Fp2;
1543
+ const p1div4 = (F.ORDER + _1n2) / _4n;
1544
+ const root = F.pow(n, p1div4);
1545
+ assertIsSquare(F, root, n);
1546
+ return root;
1547
+ }
1548
+ function sqrt5mod8(Fp2, n) {
1549
+ const F = Fp2;
1550
+ const p5div8 = (F.ORDER - _5n) / _8n;
1551
+ const n2 = F.mul(n, _2n);
1552
+ const v = F.pow(n2, p5div8);
1553
+ const nv = F.mul(n, v);
1554
+ const i = F.mul(F.mul(nv, _2n), v);
1555
+ const root = F.mul(nv, F.sub(i, F.ONE));
1556
+ assertIsSquare(F, root, n);
1557
+ return root;
1558
+ }
1559
+ function sqrt9mod16(P) {
1560
+ const Fp_ = Field(P);
1561
+ const tn = tonelliShanks(P);
1562
+ const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
1563
+ const c2 = tn(Fp_, c1);
1564
+ const c3 = tn(Fp_, Fp_.neg(c1));
1565
+ const c4 = (P + _7n) / _16n;
1566
+ return ((Fp2, n) => {
1567
+ const F = Fp2;
1568
+ let tv1 = F.pow(n, c4);
1569
+ let tv2 = F.mul(tv1, c1);
1570
+ const tv3 = F.mul(tv1, c2);
1571
+ const tv4 = F.mul(tv1, c3);
1572
+ const e1 = F.eql(F.sqr(tv2), n);
1573
+ const e2 = F.eql(F.sqr(tv3), n);
1574
+ tv1 = F.cmov(tv1, tv2, e1);
1575
+ tv2 = F.cmov(tv4, tv3, e2);
1576
+ const e3 = F.eql(F.sqr(tv2), n);
1577
+ const root = F.cmov(tv1, tv2, e3);
1578
+ assertIsSquare(F, root, n);
1579
+ return root;
1580
+ });
1581
+ }
1582
+ function tonelliShanks(P) {
1583
+ if (P < _3n)
1584
+ throw new Error("sqrt is not defined for small field");
1585
+ aoddModulus(P, "tonelliShanks");
1586
+ let Q = P - _1n2;
1587
+ let S = 0;
1588
+ while (Q % _2n === _0n2) {
1589
+ Q /= _2n;
1590
+ S++;
1591
+ }
1592
+ let Z = _2n;
1593
+ const _Fp = Field(P);
1594
+ while (FpLegendre(_Fp, Z) === 1) {
1595
+ if (Z++ > 1e3)
1596
+ throw new Error("Cannot find square root: probably non-prime P");
1597
+ }
1598
+ if (S === 1)
1599
+ return sqrt3mod4;
1600
+ let cc = _Fp.pow(Z, Q);
1601
+ const Q1div2 = (Q + _1n2) / _2n;
1602
+ return function tonelliSlow(Fp2, n) {
1603
+ const F = Fp2;
1604
+ if (F.is0(n))
1605
+ return n;
1606
+ if (FpLegendre(F, n) !== 1)
1607
+ throw new Error("Cannot find square root");
1608
+ let M = S;
1609
+ let c = F.mul(F.ONE, cc);
1610
+ let t = F.pow(n, Q);
1611
+ let R = F.pow(n, Q1div2);
1612
+ while (!F.eql(t, F.ONE)) {
1613
+ if (F.is0(t))
1614
+ throw new Error("Cannot find square root: probably non-prime P");
1615
+ let i = 1;
1616
+ let t_tmp = F.sqr(t);
1617
+ while (!F.eql(t_tmp, F.ONE)) {
1618
+ i++;
1619
+ t_tmp = F.sqr(t_tmp);
1620
+ if (i === M)
1621
+ throw new Error("Cannot find square root");
1622
+ }
1623
+ const exponent = _1n2 << BigInt(M - i - 1);
1624
+ const b = F.pow(c, exponent);
1625
+ M = i;
1626
+ c = F.sqr(b);
1627
+ t = F.mul(t, c);
1628
+ R = F.mul(R, b);
1629
+ }
1630
+ return R;
1631
+ };
1632
+ }
1633
+ function FpSqrt(P) {
1634
+ aoddModulus(P, "Fp.sqrt");
1635
+ if (P % _4n === _3n)
1636
+ return sqrt3mod4;
1637
+ if (P % _8n === _5n)
1638
+ return sqrt5mod8;
1639
+ if (P % _16n === _9n)
1640
+ return sqrt9mod16(P);
1641
+ return tonelliShanks(P);
1642
+ }
1643
+ var isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n2) === _1n2;
1644
+ var FIELD_FIELDS = [
1645
+ "create",
1646
+ "isValid",
1647
+ "is0",
1648
+ "neg",
1649
+ "inv",
1650
+ "sqrt",
1651
+ "sqr",
1652
+ "eql",
1653
+ "add",
1654
+ "sub",
1655
+ "mul",
1656
+ "pow",
1657
+ "div",
1658
+ "addN",
1659
+ "subN",
1660
+ "mulN",
1661
+ "sqrN"
1662
+ ];
1663
+ function validateField(field) {
1664
+ aobject2(field, "field");
1665
+ if (typeof field.ORDER !== "bigint")
1666
+ throw new TypeError('param "ORDER" is invalid: expected bigint, got ' + typeof field.ORDER);
1667
+ asafenumber(field.BYTES, "BYTES");
1668
+ asafenumber(field.BITS, "BITS");
1669
+ for (const name2 of FIELD_FIELDS)
1670
+ afunction(field[name2], "field." + name2);
1671
+ if (field.BYTES < 1 || field.BITS < 1)
1672
+ throw new Error("invalid field: expected BYTES/BITS > 0");
1673
+ if (field.ORDER <= _1n2)
1674
+ throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER);
1675
+ return field;
1676
+ }
1677
+ function FpInvertBatch(Fp2, nums, passZero = false) {
1678
+ validateField(Fp2);
1679
+ aarray(nums, "nums");
1680
+ abool(passZero, "passZero");
1681
+ const F = Fp2;
1682
+ const inverted = new Array(nums.length).fill(passZero ? F.ZERO : void 0);
1683
+ const multipliedAcc = nums.reduce((acc, num, i) => {
1684
+ if (F.is0(num))
1685
+ return acc;
1686
+ inverted[i] = acc;
1687
+ return F.mul(acc, num);
1688
+ }, F.ONE);
1689
+ const invertedAcc = F.inv(multipliedAcc);
1690
+ nums.reduceRight((acc, num, i) => {
1691
+ if (F.is0(num))
1692
+ return acc;
1693
+ inverted[i] = F.mul(acc, inverted[i]);
1694
+ return F.mul(acc, num);
1695
+ }, invertedAcc);
1696
+ return inverted;
1697
+ }
1698
+ function FpLegendre(Fp2, n) {
1699
+ validateField(Fp2);
1700
+ const F = Fp2;
1701
+ aoddModulus(F.ORDER, "FpLegendre");
1702
+ const p1mod2 = (F.ORDER - _1n2) / _2n;
1703
+ const powered = F.pow(n, p1mod2);
1704
+ const yes = F.eql(powered, F.ONE);
1705
+ const zero = F.eql(powered, F.ZERO);
1706
+ const no = F.eql(powered, F.neg(F.ONE));
1707
+ if (!yes && !zero && !no)
1708
+ throw new Error("invalid Legendre symbol result");
1709
+ return yes ? 1 : zero ? 0 : -1;
1710
+ }
1711
+ function nLength(n, nBitLength) {
1712
+ if (nBitLength !== void 0)
1713
+ anumber2(nBitLength);
1714
+ if (n <= _0n2)
1715
+ throw new Error("invalid n length: expected positive n, got " + n);
1716
+ if (nBitLength !== void 0 && nBitLength < 1)
1717
+ throw new Error("invalid n length: expected positive bit length, got " + nBitLength);
1718
+ const bits = bitLen(n);
1719
+ if (nBitLength !== void 0 && nBitLength < bits)
1720
+ throw new Error(`invalid n length: expected nBitLength (${nBitLength}) >= bitLen(n) (${bits})`);
1721
+ const _nBitLength = nBitLength !== void 0 ? nBitLength : bits;
1722
+ const nByteLength = Math.ceil(_nBitLength / 8);
1723
+ return { nBitLength: _nBitLength, nByteLength };
1724
+ }
1725
+ var FIELD_SQRT = /* @__PURE__ */ new WeakMap();
1726
+ var _Field = class {
1727
+ ORDER;
1728
+ BITS;
1729
+ BYTES;
1730
+ isLE;
1731
+ ZERO = _0n2;
1732
+ ONE = _1n2;
1733
+ _lengths;
1734
+ _mod;
1735
+ constructor(ORDER, opts = {}) {
1736
+ if (ORDER <= _1n2)
1737
+ throw new Error("invalid field: expected ORDER > 1, got " + ORDER);
1738
+ let _nbitLength = void 0;
1739
+ this.isLE = false;
1740
+ if (opts != null && typeof opts === "object") {
1741
+ if (typeof opts.BITS === "number")
1742
+ _nbitLength = opts.BITS;
1743
+ if (typeof opts.sqrt === "function")
1744
+ Object.defineProperty(this, "sqrt", { value: opts.sqrt, enumerable: true });
1745
+ if (typeof opts.isLE === "boolean")
1746
+ this.isLE = opts.isLE;
1747
+ if (opts.allowedLengths)
1748
+ this._lengths = Object.freeze(opts.allowedLengths.slice());
1749
+ if (typeof opts.modFromBytes === "boolean")
1750
+ this._mod = opts.modFromBytes;
1751
+ }
1752
+ const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);
1753
+ if (nByteLength > 2048)
1754
+ throw new Error("invalid field: expected ORDER of <= 2048 bytes");
1755
+ this.ORDER = ORDER;
1756
+ this.BITS = nBitLength;
1757
+ this.BYTES = nByteLength;
1758
+ Object.freeze(this);
1759
+ }
1760
+ create(num) {
1761
+ return mod(num, this.ORDER);
1762
+ }
1763
+ isValid(num) {
1764
+ if (typeof num !== "bigint")
1765
+ throw new TypeError("invalid field element: expected bigint, got " + typeof num);
1766
+ return _0n2 <= num && num < this.ORDER;
1767
+ }
1768
+ is0(num) {
1769
+ return num === _0n2;
1770
+ }
1771
+ // is valid and invertible
1772
+ isValidNot0(num) {
1773
+ return !this.is0(num) && this.isValid(num);
1774
+ }
1775
+ isOdd(num) {
1776
+ return (num & _1n2) === _1n2;
1777
+ }
1778
+ neg(num) {
1779
+ return mod(-num, this.ORDER);
1780
+ }
1781
+ eql(lhs, rhs) {
1782
+ return lhs === rhs;
1783
+ }
1784
+ sqr(num) {
1785
+ return mod(num * num, this.ORDER);
1786
+ }
1787
+ add(lhs, rhs) {
1788
+ return mod(lhs + rhs, this.ORDER);
1789
+ }
1790
+ sub(lhs, rhs) {
1791
+ return mod(lhs - rhs, this.ORDER);
1792
+ }
1793
+ mul(lhs, rhs) {
1794
+ return mod(lhs * rhs, this.ORDER);
1795
+ }
1796
+ pow(num, power) {
1797
+ return pow(num, power, this.ORDER);
1798
+ }
1799
+ div(lhs, rhs) {
1800
+ return mod(lhs * invert(rhs, this.ORDER), this.ORDER);
1801
+ }
1802
+ // Same as above, but doesn't normalize
1803
+ sqrN(num) {
1804
+ return num * num;
1805
+ }
1806
+ addN(lhs, rhs) {
1807
+ return lhs + rhs;
1808
+ }
1809
+ subN(lhs, rhs) {
1810
+ return lhs - rhs;
1811
+ }
1812
+ mulN(lhs, rhs) {
1813
+ return lhs * rhs;
1814
+ }
1815
+ inv(num) {
1816
+ return invert(num, this.ORDER);
1817
+ }
1818
+ sqrt(num) {
1819
+ let sqrt = FIELD_SQRT.get(this);
1820
+ if (!sqrt)
1821
+ FIELD_SQRT.set(this, sqrt = FpSqrt(this.ORDER));
1822
+ return sqrt(this, num);
1823
+ }
1824
+ toBytes(num) {
1825
+ return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES);
1826
+ }
1827
+ fromBytes(bytes, skipValidation = false) {
1828
+ abytes2(bytes);
1829
+ const { _lengths: allowedLengths, BYTES, isLE: isLE2, ORDER, _mod: modFromBytes } = this;
1830
+ if (allowedLengths) {
1831
+ if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) {
1832
+ throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
1833
+ }
1834
+ const padded = new Uint8Array(BYTES);
1835
+ padded.set(bytes, isLE2 ? 0 : padded.length - bytes.length);
1836
+ bytes = padded;
1837
+ }
1838
+ if (bytes.length !== BYTES)
1839
+ throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
1840
+ let scalar = isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
1841
+ if (modFromBytes)
1842
+ scalar = mod(scalar, ORDER);
1843
+ if (!skipValidation) {
1844
+ if (!this.isValid(scalar))
1845
+ throw new Error("invalid field element: outside of range 0..ORDER");
1846
+ }
1847
+ return scalar;
1848
+ }
1849
+ // TODO: we don't need it here, move out to separate fn
1850
+ invertBatch(lst) {
1851
+ return FpInvertBatch(this, lst, true);
1852
+ }
1853
+ // We can't move this out because Fp6, Fp12 implement it
1854
+ // and it's unclear what to return in there.
1855
+ cmov(a, b, condition) {
1856
+ abool(condition, "condition");
1857
+ return condition ? b : a;
1858
+ }
1859
+ };
1860
+ function Field(ORDER, opts = {}) {
1861
+ Object.freeze(_Field.prototype);
1862
+ return new _Field(ORDER, opts);
1863
+ }
1864
+
1865
+ // ../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/curve.js
1866
+ var _0n3 = /* @__PURE__ */ BigInt(0);
1867
+ var _1n3 = /* @__PURE__ */ BigInt(1);
1868
+ var _4n2 = /* @__PURE__ */ BigInt(4);
1869
+ var BLIND_BYTES = 16;
1870
+ var BLIND_BITS = 128;
1871
+ var FW_WINDOW = 5;
1872
+ var TABLE_BYTES_MAX = /* @__PURE__ */ (() => 2 ** 31)();
1873
+ function validatePointCons(Point) {
1874
+ const pc = Point;
1875
+ if (typeof pc !== "function")
1876
+ throw new TypeError('"Point" expected constructor, got type=' + typeof Point);
1877
+ afunction(pc.fromAffine, "Point.fromAffine");
1878
+ afunction(pc.fromBytes, "Point.fromBytes");
1879
+ afunction(pc.fromHex, "Point.fromHex");
1880
+ aobject2(pc.BASE, "Point.BASE");
1881
+ aobject2(pc.ZERO, "Point.ZERO");
1882
+ validateField(pc.Fp);
1883
+ validateField(pc.Fn);
1884
+ }
1885
+ function normalizeZ(c, points) {
1886
+ validatePointCons(c);
1887
+ validateMSMPoints(points, c);
1888
+ const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
1889
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
1890
+ }
1891
+ function validateW(W, bits, min = 1) {
1892
+ if (!Number.isSafeInteger(W) || W < min || W > bits)
1893
+ throw new Error("invalid window size, expected [" + min + ".." + bits + "], got W=" + W);
1894
+ }
1895
+ function validateTableBytes(numPoints, fpBytes) {
1896
+ const bytes = numPoints * (4 * fpBytes + 128);
1897
+ if (bytes > TABLE_BYTES_MAX)
1898
+ throw new Error("invalid window size: table would need ~" + Math.ceil(bytes / 2 ** 20) + " MiB, max " + TABLE_BYTES_MAX / 2 ** 20 + " MiB");
1899
+ }
1900
+ function probeRandomBytes(randomBytes5, length) {
1901
+ if (randomBytes5 === void 0)
1902
+ return void 0;
1903
+ afunction(randomBytes5, "randomBytes");
1904
+ try {
1905
+ const probe = randomBytes5(length);
1906
+ if (!isBytes2(probe) || probe.length !== length)
1907
+ return void 0;
1908
+ } catch {
1909
+ return void 0;
1910
+ }
1911
+ return randomBytes5;
1912
+ }
1913
+ function validateMSMPoints(points, c) {
1914
+ aarray(points, "points");
1915
+ points.forEach((p, i) => {
1916
+ if (!(p instanceof c))
1917
+ throw new Error("invalid point at index " + i);
1918
+ });
1919
+ }
1920
+ function validateMSMScalars(scalars, field, maxScalar) {
1921
+ if (!Array.isArray(scalars))
1922
+ throw new Error("array of scalars expected");
1923
+ scalars.forEach((s, i) => {
1924
+ const ok = maxScalar === void 0 ? field.isValid(s) : isPosBig(s) && s < maxScalar;
1925
+ if (!ok)
1926
+ throw new Error("invalid scalar at index " + i);
1927
+ });
1928
+ }
1929
+ var pointWindowSizes = /* @__PURE__ */ new WeakMap();
1930
+ function getWindowSize(P) {
1931
+ return pointWindowSizes.get(P) || 1;
1932
+ }
1933
+ function oddMultiples(p, size) {
1934
+ const dbl = p.double();
1935
+ const t = [p];
1936
+ for (let j = 1; j < size; j++)
1937
+ t.push(t[j - 1].add(dbl));
1938
+ return t;
1939
+ }
1940
+ function wnafDigits(n, W) {
1941
+ const size = 2 ** W;
1942
+ const half = size / 2;
1943
+ const mask = BigInt(size - 1);
1944
+ const d = [];
1945
+ while (n > _0n3) {
1946
+ let w = 0;
1947
+ if (n & _1n3) {
1948
+ w = Number(n & mask);
1949
+ if (w >= half)
1950
+ w -= size;
1951
+ n -= BigInt(w);
1952
+ }
1953
+ d.push(w);
1954
+ n >>= _1n3;
1955
+ }
1956
+ return d;
1957
+ }
1958
+ function signedWindowDigits(n, W, windows) {
1959
+ const size = 2 ** W;
1960
+ const half = size / 2;
1961
+ const mask = BigInt(size - 1);
1962
+ const shiftBy = BigInt(W);
1963
+ const d = [];
1964
+ for (let w = 0; w < windows; w++) {
1965
+ let v = Number(n & mask);
1966
+ n >>= shiftBy;
1967
+ if (v > half) {
1968
+ v -= size;
1969
+ n += _1n3;
1970
+ }
1971
+ d.push(v);
1972
+ }
1973
+ if (n !== _0n3)
1974
+ throw new Error("invalid wnaf");
1975
+ return d;
1976
+ }
1977
+ function wnafWalk(zero, tables, digits) {
1978
+ let max = 0;
1979
+ for (const d of digits)
1980
+ max = Math.max(max, d.length);
1981
+ let acc = zero;
1982
+ for (let bit = max - 1; bit >= 0; bit--) {
1983
+ if (bit !== max - 1)
1984
+ acc = acc.double();
1985
+ for (let i = 0; i < digits.length; i++) {
1986
+ const w = digits[i][bit];
1987
+ if (w) {
1988
+ const item = tables[i][Math.abs(w) - 1 >> 1];
1989
+ acc = acc.add(w < 0 ? item.negate() : item);
1990
+ }
1991
+ }
1992
+ }
1993
+ return acc;
1994
+ }
1995
+ var ScalarMultiplier = class {
1996
+ Point;
1997
+ BASE;
1998
+ ZERO;
1999
+ randomBytes;
2000
+ wnafPrecomputes = /* @__PURE__ */ new WeakMap();
2001
+ baseCanBeBlinded;
2002
+ bits;
2003
+ // Parametrized with a given Point class (not individual point)
2004
+ constructor(Point, randomBytes5) {
2005
+ validatePointCons(Point);
2006
+ this.randomBytes = probeRandomBytes(randomBytes5, BLIND_BYTES);
2007
+ this.Point = Point;
2008
+ this.BASE = Point.BASE;
2009
+ this.ZERO = Point.ZERO;
2010
+ this.bits = Point.Fn.BITS;
2011
+ }
2012
+ /**
2013
+ * Creates a signed fixed-window wNAF precomputation table: for every window w, the
2014
+ * multiples `[1..2^(W−1)]⋅2^(w⋅W)⋅P`, flattened. All doublings are baked into the table,
2015
+ * so cached multiplication is additions-only. `windows = ceil(bits/W) + 1`: the extra
2016
+ * window absorbs the final carry of signed-digit recoding.
2017
+ * For a 256-bit curve and W=6, the table is 44⋅32 = 1408 points.
2018
+ * @param point - Point instance
2019
+ * @param W - window size
2020
+ * @param bits - scalar bitlength the table must cover
2021
+ */
2022
+ buildWnafTable(point, W, bits) {
2023
+ const windows = Math.ceil(bits / W) + 1;
2024
+ const half = 2 ** (W - 1);
2025
+ const comp = [];
2026
+ let base = point;
2027
+ for (let w = 0; w < windows; w++) {
2028
+ let acc = base;
2029
+ for (let i = 0; i < half; i++) {
2030
+ comp.push(acc);
2031
+ acc = acc.add(base);
2032
+ }
2033
+ base = comp[comp.length - 1].double();
2034
+ }
2035
+ return { W, bits, windows, comp };
2036
+ }
2037
+ /**
2038
+ * Implements ec multiplication using precomputed signed fixed-window wNAF tables.
2039
+ * Constant-time: fixed window count with one table addition per window — zero digits feed
2040
+ * the fake accumulator — and no doublings; the lookup scans the whole window slice.
2041
+ * Scalar bounds are validated by the public entry points ({@link ScalarMultiplier.mulCT},
2042
+ * {@link ScalarMultiplier.mulCTBlinded}, {@link ScalarMultiplier.mulUnsafe});
2043
+ * signedWindowDigits throws if `n` exceeds the table.
2044
+ * @returns real and fake (for const-time) points
2045
+ */
2046
+ wnafCachedCT(precomputes, n) {
2047
+ const { W, windows, comp } = precomputes;
2048
+ const half = 2 ** (W - 1);
2049
+ const digits = signedWindowDigits(n, W, windows);
2050
+ let p = this.ZERO;
2051
+ let f = this.BASE;
2052
+ for (let w = 0; w < windows; w++) {
2053
+ const digit = digits[w];
2054
+ const start = w * half;
2055
+ const idx = Math.abs(digit) - 1;
2056
+ let sel = comp[start];
2057
+ for (let i = 1; i < half; i++)
2058
+ sel = i === idx ? comp[start + i] : sel;
2059
+ const neg = sel.negate();
2060
+ if (digit === 0)
2061
+ f = f.add(comp[start]);
2062
+ else
2063
+ p = p.add(digit < 0 ? neg : sel);
2064
+ }
2065
+ return { p, f };
2066
+ }
2067
+ // Cache key is point identity plus (W, bits); at most two entries exist per point (public-width
2068
+ // `Fn.BITS` and blinded `Fn.BITS + BLIND_BITS`). Callers must not reuse the same point with
2069
+ // incompatible `transform(...)` layouts and expect a separate cache entry.
2070
+ getWnafPrecomputes(W, point, bits, transform) {
2071
+ let entries = this.wnafPrecomputes.get(point);
2072
+ let comp = entries?.find((entry) => entry.W === W && entry.bits === bits);
2073
+ if (!comp) {
2074
+ comp = this.buildWnafTable(point, W, bits);
2075
+ if (typeof transform === "function")
2076
+ comp = { ...comp, comp: transform(comp.comp) };
2077
+ if (!entries) {
2078
+ entries = [];
2079
+ this.wnafPrecomputes.set(point, entries);
2080
+ }
2081
+ entries.push(comp);
2082
+ }
2083
+ return comp;
2084
+ }
2085
+ assertPoint(point) {
2086
+ if (!(point instanceof this.Point))
2087
+ throw new TypeError('"point" expected Point instance, got type=' + typeof point);
2088
+ }
2089
+ // Shared prologue of the constant-time entry points. Rejects scalar 0: in key/signature-style
2090
+ // callers a zero scalar means broken upstream plumbing, and concrete Points already reject it.
2091
+ // Uses inRange instead of Fn.isValidNot0: validateField() only certifies the arithmetic subset.
2092
+ validateMulInput(point, scalar) {
2093
+ this.assertPoint(point);
2094
+ if (!inRange(scalar, _1n3, this.Point.Fn.ORDER))
2095
+ throw new Error("invalid scalar");
2096
+ }
2097
+ // Constant-time dispatch shared by mulCT / mulCTBlinded. Un-precomputed points (W===1, e.g.
2098
+ // ECDH peer keys) skip building a throwaway cached table in favor of a small fixed-window
2099
+ // multiply. `n` must be < 2^bits.
2100
+ runCT(point, n, bits, transform) {
2101
+ const W = getWindowSize(point);
2102
+ if (W === 1)
2103
+ return this.fixedWindowCT(point, n, bits);
2104
+ return this.wnafCachedCT(this.getWnafPrecomputes(W, point, bits, transform), n);
2105
+ }
2106
+ mulCT(point, scalar, transform) {
2107
+ this.validateMulInput(point, scalar);
2108
+ return this.runCT(point, scalar, this.bits, transform);
2109
+ }
2110
+ mulCTBlinded(point, scalar, transform) {
2111
+ this.validateMulInput(point, scalar);
2112
+ if (this.randomBytes === void 0)
2113
+ throw new Error("randomBytes is required for scalar blinding");
2114
+ const bits = this.Point.Fn.BITS + BLIND_BITS;
2115
+ const blind = this.randomBytes(BLIND_BYTES);
2116
+ if (!isBytes2(blind) || blind.length !== BLIND_BYTES)
2117
+ throw new Error("randomBytes returned invalid byte array");
2118
+ blind[0] = blind[0] & 63 | 128;
2119
+ const n = scalar + bytesToNumberBE(blind) * this.Point.Fn.ORDER;
2120
+ return this.runCT(point, n, bits, transform);
2121
+ }
2122
+ /**
2123
+ * Constant-time multiplication `n*point` for an un-precomputed point, via a small fixed window.
2124
+ * A cached wNAF table only pays off when reused; a flat 2^FW_WINDOW table (`size-1` adds) is
2125
+ * far cheaper to build for a single use. The point-operation sequence is independent of `n`:
2126
+ * build the table, then per window exactly FW_WINDOW doublings, a data-oblivious scan over
2127
+ * every table entry, and one addition (adds the identity when the window digit is 0 — never
2128
+ * skipped).
2129
+ *
2130
+ * `n` must be `< 2^bits`. Assumes complete addition (adding the identity costs the same as any
2131
+ * add), which holds for the Weierstrass/Edwards point types used here. The table is left in
2132
+ * projective form (no normalizeZ): normalizing this small a table costs more than the
2133
+ * mixed-add savings it would buy for a single multiply.
2134
+ * @returns real point `p`; `f` duplicates it only to match {@link wnafCachedCT}'s return shape
2135
+ * (this path needs no fake accumulator — its op-count is already scalar-independent).
2136
+ */
2137
+ fixedWindowCT(point, n, bits) {
2138
+ const W = FW_WINDOW;
2139
+ const size = 1 << W;
2140
+ const mask = bitMask(W);
2141
+ const table = new Array(size);
2142
+ table[0] = this.ZERO;
2143
+ for (let i = 1; i < size; i++)
2144
+ table[i] = table[i - 1].add(point);
2145
+ const windows = Math.ceil(bits / W);
2146
+ let acc = this.ZERO;
2147
+ for (let window = windows - 1; window >= 0; window--) {
2148
+ if (window !== windows - 1)
2149
+ for (let d = 0; d < W; d++)
2150
+ acc = acc.double();
2151
+ const digit = Number(n >> BigInt(window * W) & mask);
2152
+ let sel = table[0];
2153
+ for (let i = 1; i < size; i++)
2154
+ sel = i === digit ? table[i] : sel;
2155
+ acc = acc.add(sel);
2156
+ }
2157
+ return { p: acc, f: acc };
2158
+ }
2159
+ shouldBlind(point, cofactor) {
2160
+ if (this.randomBytes === void 0)
2161
+ return false;
2162
+ if (cofactor === _1n3)
2163
+ return true;
2164
+ if (point !== this.BASE)
2165
+ return false;
2166
+ if (this.baseCanBeBlinded === void 0)
2167
+ this.baseCanBeBlinded = this.mulUnsafe(this.BASE, this.Point.Fn.ORDER).is0();
2168
+ return this.baseCanBeBlinded;
2169
+ }
2170
+ mulSecret(point, scalar, cofactor, transform) {
2171
+ return this.shouldBlind(point, cofactor) ? this.mulCTBlinded(point, scalar, transform) : this.mulCT(point, scalar, transform);
2172
+ }
2173
+ mulUnsafe(point, scalar, transform) {
2174
+ this.assertPoint(point);
2175
+ if (!isPosBig(scalar))
2176
+ throw new Error("invalid scalar");
2177
+ const W = getWindowSize(point);
2178
+ if (W === 1 || scalar >= this.Point.Fn.ORDER)
2179
+ return mulAddUnsafe(this.Point, [point], [scalar], true);
2180
+ const precomputes = this.getWnafPrecomputes(W, point, this.bits, transform);
2181
+ return this.wnafCachedCT(precomputes, scalar).p;
2182
+ }
2183
+ // Remembers the window size used for precomputed wNAF multiplication of the given point
2184
+ // and drops any previously built tables. Usually only the base point is precomputed.
2185
+ // W=1 resets the point to the un-precomputed (table-less) paths.
2186
+ // W is additionally capped so tables stay under ~2 GiB ({@link TABLE_BYTES_MAX}).
2187
+ setWindowSize(point, W) {
2188
+ this.assertPoint(point);
2189
+ validateW(W, this.bits);
2190
+ const windows = Math.ceil((this.bits + BLIND_BITS) / W) + 1;
2191
+ validateTableBytes(windows * 2 ** (W - 1), this.Point.Fp.BYTES);
2192
+ pointWindowSizes.set(point, W);
2193
+ this.wnafPrecomputes.delete(point);
2194
+ }
2195
+ // True when a window size is set: tables themselves are built lazily on first multiply.
2196
+ hasWindowSize(point) {
2197
+ return getWindowSize(point) !== 1;
2198
+ }
2199
+ };
2200
+ function mulAddUnsafe(c, points, scalars, allowOversized = false) {
2201
+ validatePointCons(c);
2202
+ validateMSMPoints(points, c);
2203
+ abool(allowOversized, "allowOversized");
2204
+ validateMSMScalars(scalars, c.Fn, allowOversized ? c.Fn.ORDER ** _4n2 : void 0);
2205
+ if (points.length !== scalars.length)
2206
+ throw new Error("arrays of points and scalars must have equal length");
2207
+ const tables = points.map((p) => oddMultiples(p, 4));
2208
+ const digits = scalars.map((n) => wnafDigits(n, 4));
2209
+ return wnafWalk(c.ZERO, tables, digits);
2210
+ }
2211
+ function createField(order, field, isLE2) {
2212
+ if (field) {
2213
+ if (field.ORDER !== order)
2214
+ throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
2215
+ validateField(field);
2216
+ return field;
2217
+ } else {
2218
+ return Field(order, { isLE: isLE2 });
2219
+ }
2220
+ }
2221
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
2222
+ if (type !== "weierstrass" && type !== "edwards")
2223
+ throw new Error('expected curve type "weierstrass" or "edwards"');
2224
+ if (FpFnLE === void 0)
2225
+ FpFnLE = type === "edwards";
2226
+ if (!CURVE || typeof CURVE !== "object")
2227
+ throw new Error(`expected valid ${type} CURVE object`);
2228
+ validateObject(curveOpts);
2229
+ for (const p of ["p", "n", "h"]) {
2230
+ const val = CURVE[p];
2231
+ if (!(isPosBig(val) && val !== _0n3))
2232
+ throw new Error(`CURVE.${p} must be positive bigint`);
2233
+ }
2234
+ const Fp2 = createField(CURVE.p, curveOpts.Fp, FpFnLE);
2235
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
2236
+ const _b = type === "weierstrass" ? "b" : "d";
2237
+ const params = ["Gx", "Gy", "a", _b];
2238
+ for (const p of params) {
2239
+ if (!Fp2.isValid(CURVE[p]))
2240
+ throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
2241
+ }
2242
+ CURVE = Object.freeze(Object.assign({}, CURVE));
2243
+ return { CURVE, Fp: Fp2, Fn };
2244
+ }
2245
+ function createKeygen(randomSecretKey, getPublicKey) {
2246
+ return function keygen(seed) {
2247
+ const secretKey = randomSecretKey(seed);
2248
+ return { secretKey, publicKey: getPublicKey(secretKey) };
2249
+ };
2250
+ }
2251
+
2252
+ // ../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/edwards.js
2253
+ var _0n4 = /* @__PURE__ */ BigInt(0);
2254
+ var _1n4 = /* @__PURE__ */ BigInt(1);
2255
+ var _2n2 = /* @__PURE__ */ BigInt(2);
2256
+ var _4n3 = /* @__PURE__ */ BigInt(4);
2257
+ var _8n2 = /* @__PURE__ */ BigInt(8);
2258
+ function isEdValidXY(Fp2, CURVE, x, y) {
2259
+ const x2 = Fp2.sqr(x);
2260
+ const y2 = Fp2.sqr(y);
2261
+ const left = Fp2.add(Fp2.mul(CURVE.a, x2), y2);
2262
+ const right = Fp2.add(Fp2.ONE, Fp2.mul(CURVE.d, Fp2.mul(x2, y2)));
2263
+ return Fp2.eql(left, right);
2264
+ }
2265
+ function edwards(params, extraOpts = {}) {
2266
+ validateObject(extraOpts, {}, {}, "extraOpts");
2267
+ const opts = extraOpts;
2268
+ const validated = createCurveFields("edwards", params, opts, opts.FpFnLE);
2269
+ const { Fp: Fp2, Fn } = validated;
2270
+ let CURVE = validated.CURVE;
2271
+ const { h: cofactor } = CURVE;
2272
+ if (FpLegendre(Fp2, CURVE.a) !== 1)
2273
+ throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");
2274
+ if (FpLegendre(Fp2, CURVE.d) !== -1)
2275
+ throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");
2276
+ validateObject(opts, {}, { uvRatio: "function", randomBytes: "function" });
2277
+ const randomBytes5 = opts.randomBytes === void 0 ? randomBytes2 : opts.randomBytes;
2278
+ const MASK = _2n2 << BigInt(Fp2.BYTES * 8) - _1n4;
2279
+ function isOdd(n) {
2280
+ if (!Fp2.isOdd)
2281
+ throw new Error("Field does not have .isOdd()");
2282
+ return Fp2.isOdd(n);
2283
+ }
2284
+ const uvRatio2 = opts.uvRatio === void 0 ? (u, v) => {
2285
+ try {
2286
+ return { isValid: true, value: Fp2.sqrt(Fp2.div(u, v)) };
2287
+ } catch (e) {
2288
+ return { isValid: false, value: _0n4 };
2289
+ }
2290
+ } : opts.uvRatio;
2291
+ if (!isEdValidXY(Fp2, CURVE, CURVE.Gx, CURVE.Gy))
2292
+ throw new Error("bad curve params: generator point");
2293
+ const mulA = Fp2.eql(CURVE.a, Fp2.neg(Fp2.ONE)) ? (x) => Fp2.neg(x) : Fp2.eql(CURVE.a, Fp2.ONE) ? (x) => x : (x) => Fp2.mul(CURVE.a, x);
2294
+ function acoord(title, n, banZero = false) {
2295
+ const min = banZero ? _1n4 : _0n4;
2296
+ aInRange("coordinate " + title, n, min, MASK);
2297
+ return n;
2298
+ }
2299
+ function aedpoint(other) {
2300
+ if (!(other instanceof Point))
2301
+ throw new Error("EdwardsPoint expected");
2302
+ }
2303
+ class Point {
2304
+ static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp2.ONE, Fp2.mul(CURVE.Gx, CURVE.Gy));
2305
+ static ZERO = new Point(Fp2.ZERO, Fp2.ONE, Fp2.ONE, Fp2.ZERO);
2306
+ static Fp = Fp2;
2307
+ static Fn = Fn;
2308
+ X;
2309
+ Y;
2310
+ Z;
2311
+ T;
2312
+ constructor(X, Y, Z, T) {
2313
+ this.X = acoord("x", X);
2314
+ this.Y = acoord("y", Y);
2315
+ this.Z = acoord("z", Z, true);
2316
+ this.T = acoord("t", T);
2317
+ Object.freeze(this);
2318
+ }
2319
+ static CURVE() {
2320
+ return CURVE;
2321
+ }
2322
+ /**
2323
+ * Create one extended Edwards point from affine coordinates.
2324
+ * Does NOT validate that the point is on-curve or torsion-free.
2325
+ * Use `.assertValidity()` on adversarial inputs.
2326
+ */
2327
+ static fromAffine(p) {
2328
+ if (p instanceof Point)
2329
+ throw new Error("extended point not allowed");
2330
+ const { x, y } = p || {};
2331
+ acoord("x", x);
2332
+ acoord("y", y);
2333
+ return new Point(x, y, Fp2.ONE, Fp2.mul(x, y));
2334
+ }
2335
+ // Uses algo from RFC8032 5.1.3.
2336
+ static fromBytes(bytes, zip215 = false) {
2337
+ const len = Fp2.BYTES;
2338
+ const { a, d } = CURVE;
2339
+ bytes = copyBytes(abytes2(bytes, len, "point"));
2340
+ abool(zip215, "zip215");
2341
+ const normed = copyBytes(bytes);
2342
+ const lastByte = bytes[len - 1];
2343
+ normed[len - 1] = lastByte & ~128;
2344
+ const y = bytesToNumberLE(normed);
2345
+ const max = zip215 ? MASK : Fp2.ORDER;
2346
+ aInRange("point.y", y, _0n4, max);
2347
+ const y2 = Fp2.sqr(y);
2348
+ const u = Fp2.sub(y2, Fp2.ONE);
2349
+ const v = Fp2.sub(Fp2.mulN(d, y2), a);
2350
+ let { isValid, value: x } = uvRatio2(u, v);
2351
+ if (!isValid)
2352
+ throw new Error("bad point: invalid y coordinate");
2353
+ const isXOdd = isOdd(x);
2354
+ const isLastByteOdd = (lastByte & 128) !== 0;
2355
+ if (!zip215 && Fp2.is0(x) && isLastByteOdd)
2356
+ throw new Error("bad point: x=0 and x_0=1");
2357
+ if (isLastByteOdd !== isXOdd)
2358
+ x = Fp2.neg(x);
2359
+ return Point.fromAffine({ x, y });
2360
+ }
2361
+ static fromHex(hex, zip215 = false) {
2362
+ return Point.fromBytes(hexToBytes2(hex), zip215);
2363
+ }
2364
+ get x() {
2365
+ return this.toAffine().x;
2366
+ }
2367
+ get y() {
2368
+ return this.toAffine().y;
2369
+ }
2370
+ precompute(windowSize = 6, isLazy = true) {
2371
+ wnaf.setWindowSize(this, windowSize);
2372
+ if (!isLazy)
2373
+ this.multiply(_2n2);
2374
+ return this;
2375
+ }
2376
+ // Useful in fromAffine() - not for fromBytes(), which always created valid points.
2377
+ assertValidity() {
2378
+ const p = this;
2379
+ const { a, d } = CURVE;
2380
+ if (p.is0())
2381
+ throw new Error("bad point: ZERO");
2382
+ const { X, Y, Z, T } = p;
2383
+ const X2 = Fp2.sqr(X);
2384
+ const Y2 = Fp2.sqr(Y);
2385
+ const Z2 = Fp2.sqr(Z);
2386
+ const Z4 = Fp2.sqr(Z2);
2387
+ const aX2 = Fp2.mul(X2, a);
2388
+ const left = Fp2.mul(Fp2.add(aX2, Y2), Z2);
2389
+ const right = Fp2.add(Z4, Fp2.mul(d, Fp2.mul(X2, Y2)));
2390
+ if (!Fp2.eql(left, right))
2391
+ throw new Error("bad point: equation left != right (1)");
2392
+ const XY = Fp2.mul(X, Y);
2393
+ const ZT = Fp2.mul(Z, T);
2394
+ if (!Fp2.eql(XY, ZT))
2395
+ throw new Error("bad point: equation left != right (2)");
2396
+ }
2397
+ // Compare one point to another.
2398
+ equals(other) {
2399
+ aedpoint(other);
2400
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2401
+ const { X: X2, Y: Y2, Z: Z2 } = other;
2402
+ const X1Z2 = Fp2.mul(X1, Z2);
2403
+ const X2Z1 = Fp2.mul(X2, Z1);
2404
+ const Y1Z2 = Fp2.mul(Y1, Z2);
2405
+ const Y2Z1 = Fp2.mul(Y2, Z1);
2406
+ return Fp2.eql(X1Z2, X2Z1) && Fp2.eql(Y1Z2, Y2Z1);
2407
+ }
2408
+ is0() {
2409
+ return this.equals(Point.ZERO);
2410
+ }
2411
+ negate() {
2412
+ return new Point(Fp2.neg(this.X), this.Y, this.Z, Fp2.neg(this.T));
2413
+ }
2414
+ // Fast algo for doubling Extended Point.
2415
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
2416
+ // Cost: 4M + 4S + 1*a + 6add + 1*2.
2417
+ double() {
2418
+ const { X: X1, Y: Y1, Z: Z1 } = this;
2419
+ const A = Fp2.sqr(X1);
2420
+ const B = Fp2.sqr(Y1);
2421
+ const C = Fp2.mul(Fp2.sqr(Z1), _2n2);
2422
+ const D = mulA(A);
2423
+ const x1y1 = Fp2.addN(X1, Y1);
2424
+ const E = Fp2.sub(Fp2.subN(Fp2.sqr(x1y1), A), B);
2425
+ const G = Fp2.addN(D, B);
2426
+ const F = Fp2.subN(G, C);
2427
+ const H = Fp2.subN(D, B);
2428
+ const X3 = Fp2.mul(E, F);
2429
+ const Y3 = Fp2.mul(G, H);
2430
+ const T3 = Fp2.mul(E, H);
2431
+ const Z3 = Fp2.mul(F, G);
2432
+ return new Point(X3, Y3, Z3, T3);
2433
+ }
2434
+ // Fast algo for adding 2 Extended Points.
2435
+ // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd
2436
+ // Cost: 9M + 1*a + 1*d + 7add.
2437
+ add(other) {
2438
+ aedpoint(other);
2439
+ const { d } = CURVE;
2440
+ const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
2441
+ const { X: X2, Y: Y2, Z: Z2, T: T2 } = other;
2442
+ const A = Fp2.mul(X1, X2);
2443
+ const B = Fp2.mul(Y1, Y2);
2444
+ const C = Fp2.mul(Fp2.mulN(T1, d), T2);
2445
+ const D = Fp2.mul(Z1, Z2);
2446
+ const E = Fp2.sub(Fp2.subN(Fp2.mulN(Fp2.addN(X1, Y1), Fp2.addN(X2, Y2)), A), B);
2447
+ const F = Fp2.subN(D, C);
2448
+ const G = Fp2.addN(D, C);
2449
+ const H = Fp2.sub(B, mulA(A));
2450
+ const X3 = Fp2.mul(E, F);
2451
+ const Y3 = Fp2.mul(G, H);
2452
+ const T3 = Fp2.mul(E, H);
2453
+ const Z3 = Fp2.mul(F, G);
2454
+ return new Point(X3, Y3, Z3, T3);
2455
+ }
2456
+ subtract(other) {
2457
+ aedpoint(other);
2458
+ return this.add(other.negate());
2459
+ }
2460
+ // Constant-time multiplication.
2461
+ multiply(scalar) {
2462
+ if (!Fn.isValidNot0(scalar))
2463
+ throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");
2464
+ const { p, f } = wnaf.mulSecret(this, scalar, cofactor, normalize);
2465
+ return normalize([p, f])[0];
2466
+ }
2467
+ // Non-constant-time multiplication. Uses double-and-add algorithm.
2468
+ // It's faster, but should only be used when you don't care about
2469
+ // an exposed private key e.g. sig verification.
2470
+ // Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but
2471
+ // n and larger values are rejected instead of being reduced mod n to the identity point.
2472
+ multiplyUnsafe(scalar) {
2473
+ if (!Fn.isValid(scalar))
2474
+ throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");
2475
+ if (scalar === _0n4)
2476
+ return Point.ZERO;
2477
+ if (this.is0() || scalar === _1n4)
2478
+ return this;
2479
+ return wnaf.mulUnsafe(this, scalar, normalize);
2480
+ }
2481
+ // Checks if point is of small order.
2482
+ // If you add something to small order point, you will have "dirty"
2483
+ // point with torsion component.
2484
+ // Clears cofactor and checks if the result is 0.
2485
+ isSmallOrder() {
2486
+ return this.clearCofactor().is0();
2487
+ }
2488
+ // Multiplies point by curve order and checks if the result is 0.
2489
+ // Returns `false` is the point is dirty.
2490
+ isTorsionFree() {
2491
+ return wnaf.mulUnsafe(this, CURVE.n).is0();
2492
+ }
2493
+ // Converts Extended point to default (x, y) coordinates.
2494
+ // Can accept precomputed Z^-1 - for example, from invertBatch.
2495
+ toAffine(invertedZ) {
2496
+ const p = this;
2497
+ let iz = invertedZ;
2498
+ if (iz != null && typeof iz !== "bigint")
2499
+ throw new TypeError('"invertedZ" expected bigint, got type=' + typeof iz);
2500
+ const { X, Y, Z } = p;
2501
+ const is0 = p.is0();
2502
+ if (iz == null)
2503
+ iz = is0 ? Fp2.create(_8n2) : Fp2.inv(Z);
2504
+ const x = Fp2.mul(X, iz);
2505
+ const y = Fp2.mul(Y, iz);
2506
+ const zz = Fp2.mul(Z, iz);
2507
+ if (is0)
2508
+ return { x: Fp2.ZERO, y: Fp2.ONE };
2509
+ if (!Fp2.eql(zz, Fp2.ONE))
2510
+ throw new Error("invZ was invalid");
2511
+ return { x, y };
2512
+ }
2513
+ clearCofactor() {
2514
+ if (cofactor === _1n4)
2515
+ return this;
2516
+ if (cofactor === _2n2)
2517
+ return this.double();
2518
+ if (cofactor === _4n3)
2519
+ return this.double().double();
2520
+ if (cofactor === _8n2)
2521
+ return this.double().double().double();
2522
+ return this.multiplyUnsafe(cofactor);
2523
+ }
2524
+ toBytes() {
2525
+ const { x, y } = this.toAffine();
2526
+ const bytes = Fp2.toBytes(y);
2527
+ bytes[bytes.length - 1] |= isOdd(x) ? 128 : 0;
2528
+ return bytes;
2529
+ }
2530
+ toHex() {
2531
+ return bytesToHex2(this.toBytes());
2532
+ }
2533
+ toString() {
2534
+ return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
2535
+ }
2536
+ }
2537
+ const normalize = (points) => normalizeZ(Point, points);
2538
+ const wnaf = new ScalarMultiplier(Point, randomBytes5);
2539
+ if (wnaf.bits >= 6)
2540
+ Point.BASE.precompute(6);
2541
+ Object.freeze(Point.prototype);
2542
+ Object.freeze(Point);
2543
+ return Point;
2544
+ }
2545
+ function eddsa(Point, cHash, eddsaOpts = {}) {
2546
+ validatePointCons(Point);
2547
+ if (typeof cHash !== "function")
2548
+ throw new Error('"hash" function param is required');
2549
+ const hash = cHash;
2550
+ const opts = eddsaOpts;
2551
+ validateObject(opts, {}, {
2552
+ adjustScalarBytes: "function",
2553
+ randomBytes: "function",
2554
+ domain: "function",
2555
+ prehash: "function",
2556
+ zip215: "boolean",
2557
+ mapToCurve: "function",
2558
+ toMontgomery: "function",
2559
+ toMontgomerySecret: "function"
2560
+ });
2561
+ const { prehash } = opts;
2562
+ const { BASE, Fp: Fp2, Fn } = Point;
2563
+ const outputLen = hash.outputLen;
2564
+ const expectedLen = 2 * Fp2.BYTES;
2565
+ if (outputLen !== void 0) {
2566
+ asafenumber(outputLen, "hash.outputLen");
2567
+ if (outputLen !== expectedLen)
2568
+ throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`);
2569
+ }
2570
+ const randomBytes5 = opts.randomBytes === void 0 ? randomBytes2 : opts.randomBytes;
2571
+ const toMontgomery2 = opts.toMontgomery;
2572
+ const toMontgomerySecret2 = opts.toMontgomerySecret;
2573
+ const adjustScalarBytes2 = opts.adjustScalarBytes === void 0 ? (bytes) => bytes : opts.adjustScalarBytes;
2574
+ const domain = opts.domain === void 0 ? (data, ctx, phflag) => {
2575
+ abool(phflag, "phflag");
2576
+ if (ctx.length || phflag)
2577
+ throw new Error("Contexts/pre-hash are not supported");
2578
+ return data;
2579
+ } : opts.domain;
2580
+ function modN_LE(hash2) {
2581
+ return Fn.create(bytesToNumberLE(hash2));
2582
+ }
2583
+ function getPrivateScalar(key) {
2584
+ const len = lengths.secretKey;
2585
+ abytes2(key, lengths.secretKey, "secretKey");
2586
+ const hashed = abytes2(hash(key), 2 * len, "hashedSecretKey");
2587
+ const head = adjustScalarBytes2(hashed.slice(0, len));
2588
+ const prefix = hashed.slice(len, 2 * len);
2589
+ const scalar = modN_LE(head);
2590
+ return { head, prefix, scalar };
2591
+ }
2592
+ function getExtendedPublicKey(secretKey) {
2593
+ const { head, prefix, scalar } = getPrivateScalar(secretKey);
2594
+ const point = BASE.multiply(scalar);
2595
+ const pointBytes = point.toBytes();
2596
+ return { head, prefix, scalar, point, pointBytes };
2597
+ }
2598
+ function getPublicKey(secretKey) {
2599
+ return getExtendedPublicKey(secretKey).pointBytes;
2600
+ }
2601
+ function hashDomainToScalar(context = Uint8Array.of(), ...msgs) {
2602
+ const msg = concatBytes2(...msgs);
2603
+ return modN_LE(hash(domain(msg, abytes2(context, void 0, "context"), !!prehash)));
2604
+ }
2605
+ function sign2(msg, secretKey, options = {}) {
2606
+ validateObject(options, {}, {}, "options");
2607
+ msg = copyBytes(abytes2(msg, void 0, "message"));
2608
+ if (prehash)
2609
+ msg = prehash(msg);
2610
+ const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey);
2611
+ const r = hashDomainToScalar(options.context, prefix, msg);
2612
+ const R = BASE.multiply(r).toBytes();
2613
+ const k = hashDomainToScalar(options.context, R, pointBytes, msg);
2614
+ const s = Fn.create(r + k * scalar);
2615
+ if (!Fn.isValid(s))
2616
+ throw new Error("sign failed: invalid s");
2617
+ const rs = concatBytes2(R, Fn.toBytes(s));
2618
+ return abytes2(rs, lengths.signature, "result");
2619
+ }
2620
+ const verifyOpts = {
2621
+ zip215: opts.zip215
2622
+ };
2623
+ function verify(sig, msg, publicKey, options = verifyOpts) {
2624
+ validateObject(options);
2625
+ const { context } = options;
2626
+ const zip215 = options.zip215 === void 0 ? !!verifyOpts.zip215 : options.zip215;
2627
+ const len = lengths.signature;
2628
+ sig = abytes2(sig, len, "signature");
2629
+ msg = abytes2(msg, void 0, "message");
2630
+ publicKey = abytes2(publicKey, lengths.publicKey, "publicKey");
2631
+ if (zip215 !== void 0)
2632
+ abool(zip215, "zip215");
2633
+ if (prehash)
2634
+ msg = prehash(msg);
2635
+ const mid = len / 2;
2636
+ const r = sig.subarray(0, mid);
2637
+ const s = bytesToNumberLE(sig.subarray(mid, len));
2638
+ let A, R, SB;
2639
+ try {
2640
+ A = Point.fromBytes(publicKey, zip215);
2641
+ R = Point.fromBytes(r, zip215);
2642
+ SB = BASE.multiplyUnsafe(s);
2643
+ } catch (error) {
2644
+ return false;
2645
+ }
2646
+ if (!zip215 && A.isSmallOrder())
2647
+ return false;
2648
+ const k = hashDomainToScalar(context, r, publicKey, msg);
2649
+ const RkA = R.add(A.multiplyUnsafe(k));
2650
+ return RkA.subtract(SB).clearCofactor().is0();
2651
+ }
2652
+ const _size = Fp2.BYTES;
2653
+ const lengths = {
2654
+ secretKey: _size,
2655
+ publicKey: _size,
2656
+ signature: 2 * _size,
2657
+ seed: _size
2658
+ };
2659
+ function randomSecretKey(seed) {
2660
+ seed = seed === void 0 ? randomBytes5(lengths.seed) : seed;
2661
+ return abytes2(seed, lengths.seed, "seed");
2662
+ }
2663
+ function isValidSecretKey(key) {
2664
+ return isBytes2(key) && key.length === lengths.secretKey;
2665
+ }
2666
+ function isValidPublicKey(key, zip215) {
2667
+ try {
2668
+ return !!Point.fromBytes(key, zip215 === void 0 ? verifyOpts.zip215 : zip215);
2669
+ } catch (error) {
2670
+ return false;
2671
+ }
2672
+ }
2673
+ const utils = {
2674
+ getExtendedPublicKey,
2675
+ randomSecretKey,
2676
+ isValidSecretKey,
2677
+ isValidPublicKey,
2678
+ /** Converts an Edwards public key to a companion Montgomery public key. */
2679
+ toMontgomery(publicKey) {
2680
+ if (toMontgomery2 === void 0)
2681
+ throw new Error("Montgomery conversion is not supported for this curve");
2682
+ return toMontgomery2(Point.fromBytes(publicKey));
2683
+ },
2684
+ toMontgomerySecret(secretKey) {
2685
+ if (toMontgomerySecret2 === void 0)
2686
+ throw new Error("Montgomery conversion is not supported for this curve");
2687
+ return toMontgomerySecret2(secretKey);
2688
+ }
2689
+ };
2690
+ Object.freeze(lengths);
2691
+ Object.freeze(utils);
2692
+ return Object.freeze({
2693
+ keygen: createKeygen(randomSecretKey, getPublicKey),
2694
+ getPublicKey,
2695
+ sign: sign2,
2696
+ verify,
2697
+ utils,
2698
+ Point,
2699
+ lengths
2700
+ });
2701
+ }
2702
+
2703
+ // ../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/abstract/montgomery.js
2704
+ var _0n5 = /* @__PURE__ */ BigInt(0);
2705
+ var _1n5 = /* @__PURE__ */ BigInt(1);
2706
+ var _2n3 = /* @__PURE__ */ BigInt(2);
2707
+ function cmask(P, swap) {
2708
+ return P + swap - (swap >> _1n5 << _1n5);
2709
+ }
2710
+ function cswap(P) {
2711
+ const offset = BigInt(6) * P;
2712
+ return (mask, x_2, x_3) => {
2713
+ const sum = x_2 + x_3;
2714
+ const d = offset + x_3 - x_2;
2715
+ const a = (d * mask + x_2) % P;
2716
+ return { x_2: a, x_3: sum - a };
2717
+ };
2718
+ }
2719
+ function validateOpts(curve) {
2720
+ validateObject(curve, {
2721
+ P: "bigint",
2722
+ type: "string",
2723
+ adjustScalarBytes: "function",
2724
+ powPminus2: "function"
2725
+ }, {
2726
+ randomBytes: "function",
2727
+ scalarMultBase: "function"
2728
+ });
2729
+ return Object.freeze({ ...curve });
2730
+ }
2731
+ function montgomery(curveDef) {
2732
+ const CURVE = validateOpts(curveDef);
2733
+ const { P, type, adjustScalarBytes: adjustScalarBytes2, powPminus2, randomBytes: rand } = CURVE;
2734
+ const mulBaseHook = CURVE.scalarMultBase;
2735
+ const is25519 = type === "x25519";
2736
+ if (!is25519 && type !== "x448")
2737
+ throw new Error("invalid type");
2738
+ const randomBytes_ = rand === void 0 ? randomBytes2 : rand;
2739
+ const montgomeryBits = is25519 ? 255 : 448;
2740
+ const swap = cswap(P);
2741
+ const fieldLen = is25519 ? 32 : 56;
2742
+ const Gu = is25519 ? BigInt(9) : BigInt(5);
2743
+ const a24 = is25519 ? BigInt(121665) : BigInt(39081);
2744
+ const minScalar = is25519 ? _2n3 ** BigInt(254) : _2n3 ** BigInt(447);
2745
+ const maxAdded = is25519 ? BigInt(8) * (_2n3 ** BigInt(251) - _1n5) : BigInt(4) * (_2n3 ** BigInt(445) - _1n5);
2746
+ const maxScalar = minScalar + maxAdded + _1n5;
2747
+ const modP = (n) => mod(n, P);
2748
+ const GuBytes = encodeU(Gu);
2749
+ function encodeU(u) {
2750
+ return numberToBytesLE(modP(u), fieldLen);
2751
+ }
2752
+ function decodeU(u) {
2753
+ const _u = copyBytes(abytes2(u, fieldLen, "uCoordinate"));
2754
+ if (is25519)
2755
+ _u[31] &= 127;
2756
+ return modP(bytesToNumberLE(_u));
2757
+ }
2758
+ function decodeScalar(scalar) {
2759
+ return bytesToNumberLE(adjustScalarBytes2(copyBytes(abytes2(scalar, fieldLen, "scalar"))));
2760
+ }
2761
+ const lowOrderU = new Set(is25519 ? [
2762
+ _0n5,
2763
+ _1n5,
2764
+ P - _1n5,
2765
+ BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),
2766
+ BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")
2767
+ ] : [_0n5, _1n5, P - _1n5]);
2768
+ function scalarMult(scalar, u) {
2769
+ const pointU = decodeU(u);
2770
+ if (lowOrderU.has(pointU))
2771
+ throw new Error("invalid private or public key received");
2772
+ const pu = montgomeryLadder(pointU, decodeScalar(scalar));
2773
+ if (pu === _0n5)
2774
+ throw new Error("invalid private or public key received");
2775
+ return encodeU(pu);
2776
+ }
2777
+ function scalarMultBase(scalar) {
2778
+ if (mulBaseHook === void 0)
2779
+ return scalarMult(scalar, GuBytes);
2780
+ const k = decodeScalar(scalar);
2781
+ aInRange("scalar", k, minScalar, maxScalar);
2782
+ const pu = modP(mulBaseHook(k));
2783
+ if (pu === _0n5)
2784
+ throw new Error("invalid private or public key received");
2785
+ return encodeU(pu);
2786
+ }
2787
+ const getPublicKey = scalarMultBase;
2788
+ const getSharedSecret = scalarMult;
2789
+ function montgomeryLadder(u, scalar) {
2790
+ aInRange("u", u, _0n5, P);
2791
+ aInRange("scalar", scalar, minScalar, maxScalar);
2792
+ const k = scalar;
2793
+ const x_1 = u;
2794
+ let x_2 = _1n5;
2795
+ let z_2 = _0n5;
2796
+ let x_3 = u;
2797
+ let z_3 = _1n5;
2798
+ const kx = k ^ k >> _1n5;
2799
+ for (let t = BigInt(montgomeryBits - 1); t >= _0n5; t--) {
2800
+ const mask2 = cmask(P, kx >> t);
2801
+ ({ x_2, x_3 } = swap(mask2, x_2, x_3));
2802
+ ({ x_2: z_2, x_3: z_3 } = swap(mask2, z_2, z_3));
2803
+ const A = x_2 + z_2;
2804
+ const AA = modP(A * A);
2805
+ const B = x_2 - z_2;
2806
+ const BB = modP(B * B);
2807
+ const E = AA - BB;
2808
+ const C = x_3 + z_3;
2809
+ const D = x_3 - z_3;
2810
+ const DA = modP(D * A);
2811
+ const CB = modP(C * B);
2812
+ const dacb = DA + CB;
2813
+ const da_cb = DA - CB;
2814
+ x_3 = modP(dacb * dacb);
2815
+ z_3 = modP(x_1 * modP(da_cb * da_cb));
2816
+ x_2 = modP(AA * BB);
2817
+ z_2 = modP(E * (AA + modP(a24 * E)));
2818
+ }
2819
+ const mask = cmask(P, k);
2820
+ ({ x_2, x_3 } = swap(mask, x_2, x_3));
2821
+ ({ x_2: z_2, x_3: z_3 } = swap(mask, z_2, z_3));
2822
+ const z2 = powPminus2(z_2);
2823
+ return modP(x_2 * z2);
2824
+ }
2825
+ const lengths = {
2826
+ secretKey: fieldLen,
2827
+ publicKey: fieldLen,
2828
+ seed: fieldLen
2829
+ };
2830
+ const randomSecretKey = (seed) => {
2831
+ seed = seed === void 0 ? randomBytes_(fieldLen) : seed;
2832
+ abytes2(seed, lengths.seed, "seed");
2833
+ return seed;
2834
+ };
2835
+ const utils = { randomSecretKey };
2836
+ Object.freeze(lengths);
2837
+ Object.freeze(utils);
2838
+ return Object.freeze({
2839
+ keygen: createKeygen(randomSecretKey, getPublicKey),
2840
+ getSharedSecret,
2841
+ getPublicKey,
2842
+ scalarMult,
2843
+ scalarMultBase,
2844
+ utils,
2845
+ GuBytes: GuBytes.slice(),
2846
+ lengths
2847
+ });
2848
+ }
2849
+
2850
+ // ../../node_modules/.pnpm/@noble+curves@2.4.0/node_modules/@noble/curves/ed25519.js
2851
+ var _0n6 = /* @__PURE__ */ BigInt(0);
2852
+ var _1n6 = /* @__PURE__ */ BigInt(1);
2853
+ var _2n4 = /* @__PURE__ */ BigInt(2);
2854
+ var _3n2 = /* @__PURE__ */ BigInt(3);
2855
+ var _5n2 = /* @__PURE__ */ BigInt(5);
2856
+ var _8n3 = /* @__PURE__ */ BigInt(8);
2857
+ var ed25519_CURVE_p = /* @__PURE__ */ BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed");
2858
+ var ed25519_CURVE = /* @__PURE__ */ (() => ({
2859
+ p: ed25519_CURVE_p,
2860
+ n: BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),
2861
+ h: _8n3,
2862
+ a: BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),
2863
+ d: BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),
2864
+ Gx: BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),
2865
+ Gy: BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")
2866
+ }))();
2867
+ function ed25519_pow_2_252_3(x) {
2868
+ const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);
2869
+ const P = ed25519_CURVE_p;
2870
+ const x2 = x * x % P;
2871
+ const b2 = x2 * x % P;
2872
+ const b4 = pow2(b2, _2n4, P) * b2 % P;
2873
+ const b5 = pow2(b4, _1n6, P) * x % P;
2874
+ const b10 = pow2(b5, _5n2, P) * b5 % P;
2875
+ const b20 = pow2(b10, _10n, P) * b10 % P;
2876
+ const b40 = pow2(b20, _20n, P) * b20 % P;
2877
+ const b80 = pow2(b40, _40n, P) * b40 % P;
2878
+ const b160 = pow2(b80, _80n, P) * b80 % P;
2879
+ const b240 = pow2(b160, _80n, P) * b80 % P;
2880
+ const b250 = pow2(b240, _10n, P) * b10 % P;
2881
+ const pow_p_5_8 = pow2(b250, _2n4, P) * x % P;
2882
+ return { pow_p_5_8, b2 };
2883
+ }
2884
+ function adjustScalarBytes(bytes) {
2885
+ bytes[0] &= 248;
2886
+ bytes[31] &= 127;
2887
+ bytes[31] |= 64;
2888
+ return bytes;
2889
+ }
2890
+ var ED25519_SQRT_M1 = /* @__PURE__ */ BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");
2891
+ function uvRatio(u, v) {
2892
+ const P = ed25519_CURVE_p;
2893
+ const v3 = mod(v * v * v, P);
2894
+ const v7 = mod(v3 * v3 * v, P);
2895
+ const pow3 = ed25519_pow_2_252_3(u * v7).pow_p_5_8;
2896
+ let x = mod(u * v3 * pow3, P);
2897
+ const vx2 = mod(v * x * x, P);
2898
+ const root1 = x;
2899
+ const root2 = mod(x * ED25519_SQRT_M1, P);
2900
+ const useRoot1 = vx2 === u;
2901
+ const useRoot2 = vx2 === mod(-u, P);
2902
+ const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P);
2903
+ if (useRoot1)
2904
+ x = root1;
2905
+ if (useRoot2 || noRoot)
2906
+ x = root2;
2907
+ if (isNegativeLE(x, P))
2908
+ x = mod(-x, P);
2909
+ return { isValid: useRoot1 || useRoot2, value: x };
2910
+ }
2911
+ var ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio });
2912
+ var Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)();
2913
+ function toMontgomery(point) {
2914
+ const { y } = point;
2915
+ return Fp.toBytes(Fp.div(_1n6 + y, _1n6 - y));
2916
+ }
2917
+ function toMontgomerySecret(secretKey) {
2918
+ const size = ed25519_Point.Fp.BYTES;
2919
+ abytes(secretKey, size);
2920
+ return adjustScalarBytes(sha512(secretKey.subarray(0, size))).subarray(0, size);
2921
+ }
2922
+ function ed(opts) {
2923
+ return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes, toMontgomery, toMontgomerySecret, zip215: true }, opts));
2924
+ }
2925
+ var ed25519 = /* @__PURE__ */ ed({});
2926
+ var x25519 = /* @__PURE__ */ (() => {
2927
+ const P = ed25519_CURVE_p;
2928
+ const powPminus2 = (x) => {
2929
+ const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);
2930
+ return mod(pow2(pow_p_5_8, _3n2, P) * b2, P);
2931
+ };
2932
+ return montgomery({
2933
+ P,
2934
+ type: "x25519",
2935
+ powPminus2,
2936
+ adjustScalarBytes,
2937
+ // ~3x faster fixed-base: [k]B on the birationally-equivalent Edwards curve using cached
2938
+ // base tables, mapped back via u = (1+y)/(1-y) = (Z+Y)/(Z-Y) with one Fermat inversion.
2939
+ // Same construction as libsodium's crypto_scalarmult_curve25519_base.
2940
+ scalarMultBase: (k) => {
2941
+ const kn = mod(k, ed25519_Point.Fn.ORDER);
2942
+ if (kn === _0n6)
2943
+ return _0n6;
2944
+ const p = ed25519_Point.BASE.multiply(kn);
2945
+ return mod((p.Z + p.Y) * powPminus2(mod(p.Z - p.Y, P)), P);
2946
+ }
2947
+ });
2948
+ })();
2949
+
2950
+ // ../../node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/utils.js
2951
+ function isBytes3(a) {
2952
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
2953
+ }
2954
+ var atitle3 = (title) => title ? `"${title}" ` : "";
2955
+ function abool2(value, title = "") {
2956
+ if (typeof value !== "boolean")
2957
+ throw new TypeError(atitle3(title) + "expected boolean, got type=" + typeof value);
2958
+ return value;
2959
+ }
2960
+ function anumber3(n, title = "") {
2961
+ if (typeof n !== "number")
2962
+ throw new TypeError(atitle3(title) + "expected number, got " + typeof n);
2963
+ if (!Number.isSafeInteger(n) || n < 0)
2964
+ throw new RangeError(atitle3(title) + "expected integer >= 0, got " + n);
2965
+ return n;
2966
+ }
2967
+ function abytes3(value, length, title = "") {
2968
+ if (isBytes3(value) && (length === void 0 || value.length === length))
2969
+ return value;
2970
+ if (length !== void 0)
2971
+ anumber3(length, "length");
2972
+ const bytes = isBytes3(value);
2973
+ const ofLen = length !== void 0 ? ` of length ${length}` : "";
2974
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
2975
+ const message2 = atitle3(title) + "expected Uint8Array" + ofLen + ", got " + got;
2976
+ if (!bytes)
2977
+ throw new TypeError(message2);
2978
+ throw new RangeError(message2);
2979
+ }
2980
+ var aobject3 = (value, label) => {
2981
+ if (value === null || typeof value !== "object" || Array.isArray(value))
2982
+ throw new TypeError(label === "object" ? "expected valid options object" : `"${label}" expected object, got type=${typeof value}`);
2983
+ };
2984
+ function aexists2(instance, checkFinished = true) {
2985
+ if (instance.destroyed)
2986
+ throw new Error("hash was destroyed");
2987
+ if (checkFinished && instance.finished)
2988
+ throw new Error("digest() was already called");
2989
+ }
2990
+ function aoutput2(out, instance) {
2991
+ abytes3(out, void 0, "output");
2992
+ const min = instance.outputLen;
2993
+ if (!(out.length >= min)) {
2994
+ throw new RangeError('"output" expected length >= ' + min);
2995
+ }
2996
+ }
2997
+ function aoutput32(out, instance) {
2998
+ aoutput2(out, instance);
2999
+ if (!isAligned32(out))
3000
+ throw new Error("invalid output, must be aligned");
3001
+ }
3002
+ function u8(arr) {
3003
+ return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
3004
+ }
3005
+ function u32(arr) {
3006
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
3007
+ }
3008
+ function clean2(...arrays) {
3009
+ for (let i = 0; i < arrays.length; i++) {
3010
+ arrays[i].fill(0);
3011
+ }
3012
+ }
3013
+ function createView2(arr) {
3014
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
3015
+ }
3016
+ var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
3017
+ function byteSwap(word) {
3018
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
3019
+ }
3020
+ var swap8IfBE = isLE ? (n) => n : (n) => byteSwap(n) >>> 0;
3021
+ function byteSwap32(arr) {
3022
+ for (let i = 0; i < arr.length; i++) {
3023
+ arr[i] = byteSwap(arr[i]);
3024
+ }
3025
+ return arr;
3026
+ }
3027
+ var swap32IfBE = isLE ? (u) => u : byteSwap32;
3028
+ function overlapBytes(a, b) {
3029
+ if (!a.byteLength || !b.byteLength)
3030
+ return false;
3031
+ return a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
3032
+ a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
3033
+ b.byteOffset < a.byteOffset + a.byteLength;
3034
+ }
3035
+ function complexOverlapBytes(input, output) {
3036
+ if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
3037
+ throw new Error("complex overlap of input and output is not supported");
3038
+ }
3039
+ function checkOpts2(defaults, opts) {
3040
+ aobject3(defaults, "defaults");
3041
+ aobject3(opts, "opts");
3042
+ const merged = Object.assign(defaults, opts);
3043
+ return merged;
3044
+ }
3045
+ function equalBytes(a, b) {
3046
+ a = abytes3(a);
3047
+ b = abytes3(b);
3048
+ if (a.length !== b.length)
3049
+ return false;
3050
+ let diff = 0;
3051
+ for (let i = 0; i < a.length; i++)
3052
+ diff |= a[i] ^ b[i];
3053
+ return diff === 0;
3054
+ }
3055
+ function wrapMacConstructor(keyLen, macCons, fromMsg) {
3056
+ const mac = macCons;
3057
+ const getArgs = fromMsg || (() => []);
3058
+ const macC = (msg, key) => mac(key, ...getArgs(msg)).update(msg).digest();
3059
+ const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0)));
3060
+ macC.outputLen = tmp.outputLen;
3061
+ macC.blockLen = tmp.blockLen;
3062
+ macC.create = (key, ...args) => mac(key, ...args);
3063
+ return macC;
3064
+ }
3065
+ var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => {
3066
+ function wrappedCipher(key, ...args) {
3067
+ abytes3(key, void 0, "key");
3068
+ if (params.nonceLength !== void 0) {
3069
+ const nonce = args[0];
3070
+ abytes3(nonce, params.varSizeNonce ? void 0 : params.nonceLength, "nonce");
3071
+ }
3072
+ const tagl = params.tagLength;
3073
+ const aadStart = params.nonceLength !== void 0 ? 1 : 0;
3074
+ if (!params.withAAD) {
3075
+ for (let i = aadStart; i < args.length; i++)
3076
+ if (isBytes3(args[i]))
3077
+ throw new Error("AAD not supported");
3078
+ }
3079
+ if (params.withAAD && args[aadStart] !== void 0)
3080
+ abytes3(args[aadStart], void 0, "AAD");
3081
+ const cipher = constructor(key, ...args);
3082
+ const checkOutput = (fnLength, output) => {
3083
+ if (output !== void 0) {
3084
+ if (fnLength !== 2)
3085
+ throw new Error("cipher output not supported");
3086
+ abytes3(output, void 0, "output");
3087
+ }
3088
+ };
3089
+ let called = false;
3090
+ const wrCipher = {
3091
+ encrypt(data, output) {
3092
+ if (called)
3093
+ throw new Error("cannot encrypt() twice with same key + nonce");
3094
+ called = true;
3095
+ abytes3(data, void 0, "data");
3096
+ checkOutput(cipher.encrypt.length, output);
3097
+ return cipher.encrypt(data, output);
3098
+ },
3099
+ decrypt(data, output) {
3100
+ abytes3(data, void 0, "data");
3101
+ if (tagl && data.length < tagl)
3102
+ throw new Error('"ciphertext" expected length >= tagLength=' + tagl);
3103
+ checkOutput(cipher.decrypt.length, output);
3104
+ return cipher.decrypt(data, output);
3105
+ }
3106
+ };
3107
+ return wrCipher;
3108
+ }
3109
+ Object.assign(wrappedCipher, params);
3110
+ return wrappedCipher;
3111
+ };
3112
+ function getOutput(expectedLength, out, onlyAligned = true) {
3113
+ if (out === void 0)
3114
+ return new Uint8Array(expectedLength);
3115
+ abytes3(out, expectedLength, "output");
3116
+ if (onlyAligned && !isAligned32(out))
3117
+ throw new Error("invalid output, must be aligned");
3118
+ return out;
3119
+ }
3120
+ function u64Lengths(dataLength, aadLength, isLE2) {
3121
+ anumber3(dataLength);
3122
+ anumber3(aadLength);
3123
+ abool2(isLE2);
3124
+ const num = new Uint8Array(16);
3125
+ const view = createView2(num);
3126
+ view.setBigUint64(0, BigInt(aadLength), isLE2);
3127
+ view.setBigUint64(8, BigInt(dataLength), isLE2);
3128
+ return num;
3129
+ }
3130
+ function isAligned32(bytes) {
3131
+ return bytes.byteOffset % 4 === 0;
3132
+ }
3133
+ function copyBytes2(bytes) {
3134
+ return Uint8Array.from(abytes3(bytes));
3135
+ }
3136
+
3137
+ // ../../node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/_polyval.js
3138
+ var BLOCK_SIZE = 16;
3139
+ var ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
3140
+ var ZEROS32 = /* @__PURE__ */ u32(ZEROS16);
3141
+ var POLY = 225;
3142
+ var mul2 = (s0, s1, s2, s3) => {
3143
+ const hiBit = s3 & 1;
3144
+ return {
3145
+ s3: s2 << 31 | s3 >>> 1,
3146
+ s2: s1 << 31 | s2 >>> 1,
3147
+ s1: s0 << 31 | s1 >>> 1,
3148
+ // NIST SP 800-38D §6.3 applies `V >> 1` and XORs R on carry. In this
3149
+ // 4x32-bit split, R = 0xe1 || 0^120 lives in the top byte of s0.
3150
+ s0: s0 >>> 1 ^ POLY << 24 & -(hiBit & 1)
3151
+ // reduce % poly
3152
+ };
3153
+ };
3154
+ var swapLE = (n) => (n >>> 0 & 255) << 24 | (n >>> 8 & 255) << 16 | (n >>> 16 & 255) << 8 | n >>> 24 & 255 | 0;
3155
+ var estimateWindow = (bytes) => {
3156
+ if (bytes > 64 * 1024)
3157
+ return 8;
3158
+ if (bytes > 1024)
3159
+ return 4;
3160
+ return 2;
3161
+ };
3162
+ var GHASH = class {
3163
+ blockLen = BLOCK_SIZE;
3164
+ outputLen = BLOCK_SIZE;
3165
+ s0 = 0;
3166
+ s1 = 0;
3167
+ s2 = 0;
3168
+ s3 = 0;
3169
+ finished = false;
3170
+ destroyed = false;
3171
+ t;
3172
+ W;
3173
+ windowSize;
3174
+ // We select bits per window adaptively based on expectedLength
3175
+ constructor(key, expectedLength) {
3176
+ abytes3(key, 16, "key");
3177
+ key = copyBytes2(key);
3178
+ const kView = createView2(key);
3179
+ let k0 = kView.getUint32(0, false);
3180
+ let k1 = kView.getUint32(4, false);
3181
+ let k2 = kView.getUint32(8, false);
3182
+ let k3 = kView.getUint32(12, false);
3183
+ const doubles = [];
3184
+ for (let i = 0; i < 128; i++) {
3185
+ doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) });
3186
+ ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3));
3187
+ }
3188
+ const W = estimateWindow(expectedLength || 1024);
3189
+ if (![1, 2, 4, 8].includes(W))
3190
+ throw new Error("ghash: invalid window size, expected 2, 4 or 8");
3191
+ this.W = W;
3192
+ const bits = 128;
3193
+ const windows = bits / W;
3194
+ const windowSize = this.windowSize = 2 ** W;
3195
+ const items = [];
3196
+ for (let w = 0; w < windows; w++) {
3197
+ for (let byte = 0; byte < windowSize; byte++) {
3198
+ let s0 = 0, s1 = 0, s2 = 0, s3 = 0;
3199
+ for (let j = 0; j < W; j++) {
3200
+ const bit = byte >>> W - j - 1 & 1;
3201
+ if (!bit)
3202
+ continue;
3203
+ const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j];
3204
+ s0 ^= d0, s1 ^= d1, s2 ^= d2, s3 ^= d3;
3205
+ }
3206
+ items.push({ s0, s1, s2, s3 });
3207
+ }
3208
+ }
3209
+ this.t = items;
3210
+ }
3211
+ _updateBlock(s0, s1, s2, s3) {
3212
+ s0 ^= this.s0, s1 ^= this.s1, s2 ^= this.s2, s3 ^= this.s3;
3213
+ const { W, t, windowSize } = this;
3214
+ let o0 = 0, o1 = 0, o2 = 0, o3 = 0;
3215
+ const mask = (1 << W) - 1;
3216
+ let w = 0;
3217
+ for (const num of [s0, s1, s2, s3]) {
3218
+ for (let bytePos = 0; bytePos < 4; bytePos++) {
3219
+ const byte = num >>> 8 * bytePos & 255;
3220
+ for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) {
3221
+ const bit = byte >>> W * bitPos & mask;
3222
+ const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit];
3223
+ o0 ^= e0, o1 ^= e1, o2 ^= e2, o3 ^= e3;
3224
+ w += 1;
3225
+ }
3226
+ }
3227
+ }
3228
+ this.s0 = o0;
3229
+ this.s1 = o1;
3230
+ this.s2 = o2;
3231
+ this.s3 = o3;
3232
+ }
3233
+ update(data) {
3234
+ aexists2(this);
3235
+ abytes3(data);
3236
+ data = copyBytes2(data);
3237
+ const b32 = u32(data);
3238
+ const blocks = Math.floor(data.length / BLOCK_SIZE);
3239
+ const left = data.length % BLOCK_SIZE;
3240
+ for (let i = 0; i < blocks; i++) {
3241
+ this._updateBlock(swap8IfBE(b32[i * 4 + 0]), swap8IfBE(b32[i * 4 + 1]), swap8IfBE(b32[i * 4 + 2]), swap8IfBE(b32[i * 4 + 3]));
3242
+ }
3243
+ if (left) {
3244
+ ZEROS16.set(data.subarray(blocks * BLOCK_SIZE));
3245
+ this._updateBlock(swap8IfBE(ZEROS32[0]), swap8IfBE(ZEROS32[1]), swap8IfBE(ZEROS32[2]), swap8IfBE(ZEROS32[3]));
3246
+ clean2(ZEROS32);
3247
+ }
3248
+ return this;
3249
+ }
3250
+ destroy() {
3251
+ this.destroyed = true;
3252
+ const { t } = this;
3253
+ for (const elm of t) {
3254
+ elm.s0 = 0, elm.s1 = 0, elm.s2 = 0, elm.s3 = 0;
3255
+ }
3256
+ }
3257
+ digestInto(out) {
3258
+ aexists2(this);
3259
+ aoutput32(out, this);
3260
+ this.finished = true;
3261
+ const { s0, s1, s2, s3 } = this;
3262
+ const o32 = u32(out);
3263
+ o32[0] = s0;
3264
+ o32[1] = s1;
3265
+ o32[2] = s2;
3266
+ o32[3] = s3;
3267
+ if (!isLE)
3268
+ swap32IfBE(o32.subarray(0, BLOCK_SIZE / 4));
3269
+ }
3270
+ digest() {
3271
+ const res = new Uint8Array(BLOCK_SIZE);
3272
+ this.digestInto(res);
3273
+ this.destroy();
3274
+ return res;
3275
+ }
3276
+ };
3277
+ var ghash = /* @__PURE__ */ wrapMacConstructor(16, (key, expectedLength) => new GHASH(key, expectedLength), (msg) => [msg.length]);
3278
+
3279
+ // ../../node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/aes.js
3280
+ var BLOCK_SIZE2 = 16;
3281
+ var BLOCK_SIZE32 = 4;
3282
+ var EMPTY_BLOCK = /* @__PURE__ */ new Uint8Array(BLOCK_SIZE2);
3283
+ var POLY2 = 283;
3284
+ function validateKeyLength(key) {
3285
+ if (![16, 24, 32].includes(key.length))
3286
+ throw new Error('"aes key" expected Uint8Array of length 16/24/32, got length=' + key.length);
3287
+ }
3288
+ function mul22(n) {
3289
+ return n << 1 ^ POLY2 & -(n >> 7);
3290
+ }
3291
+ function mul(a, b) {
3292
+ let res = 0;
3293
+ for (; b > 0; b >>= 1) {
3294
+ res ^= a & -(b & 1);
3295
+ a = mul22(a);
3296
+ }
3297
+ return res;
3298
+ }
3299
+ var sbox = /* @__PURE__ */ (() => {
3300
+ const t = new Uint8Array(256);
3301
+ for (let i = 0, x = 1; i < 256; i++, x ^= mul22(x))
3302
+ t[i] = x;
3303
+ const box = new Uint8Array(256);
3304
+ box[0] = 99;
3305
+ for (let i = 0; i < 255; i++) {
3306
+ let x = t[255 - i];
3307
+ x |= x << 8;
3308
+ box[t[i]] = (x ^ x >> 4 ^ x >> 5 ^ x >> 6 ^ x >> 7 ^ 99) & 255;
3309
+ }
3310
+ clean2(t);
3311
+ return box;
3312
+ })();
3313
+ var rotr32_8 = (n) => n << 24 | n >>> 8;
3314
+ var rotl32_8 = (n) => n << 8 | n >>> 24;
3315
+ function genTtable(sbox2, fn) {
3316
+ if (sbox2.length !== 256)
3317
+ throw new Error("wrong sbox length");
3318
+ const T0 = new Uint32Array(256).map((_, j) => fn(sbox2[j]));
3319
+ const T1 = T0.map(rotl32_8);
3320
+ const T2 = T1.map(rotl32_8);
3321
+ const T3 = T2.map(rotl32_8);
3322
+ const T01 = new Uint32Array(256 * 256);
3323
+ const T23 = new Uint32Array(256 * 256);
3324
+ const sbox22 = new Uint16Array(256 * 256);
3325
+ for (let i = 0; i < 256; i++) {
3326
+ for (let j = 0; j < 256; j++) {
3327
+ const idx = i * 256 + j;
3328
+ T01[idx] = T0[i] ^ T1[j];
3329
+ T23[idx] = T2[i] ^ T3[j];
3330
+ sbox22[idx] = sbox2[i] << 8 | sbox2[j];
3331
+ }
3332
+ }
3333
+ return { sbox: sbox2, sbox2: sbox22, T0, T1, T2, T3, T01, T23 };
3334
+ }
3335
+ var tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => mul(s, 3) << 24 | s << 16 | s << 8 | mul(s, 2));
3336
+ var xPowers = /* @__PURE__ */ (() => {
3337
+ const p = new Uint8Array(16);
3338
+ for (let i = 0, x = 1; i < 16; i++, x = mul22(x))
3339
+ p[i] = x;
3340
+ return p;
3341
+ })();
3342
+ function expandKeyLE(key) {
3343
+ abytes3(key);
3344
+ const len = key.length;
3345
+ validateKeyLength(key);
3346
+ const { sbox2 } = tableEncoding;
3347
+ const toClean = [];
3348
+ if (!isLE || !isAligned32(key))
3349
+ toClean.push(key = copyBytes2(key));
3350
+ const k32 = swap32IfBE(u32(key));
3351
+ const Nk = k32.length;
3352
+ const subByte = (n) => applySbox(sbox2, n, n, n, n);
3353
+ const xk = new Uint32Array(len + 28);
3354
+ xk.set(k32);
3355
+ for (let i = Nk; i < xk.length; i++) {
3356
+ let t = xk[i - 1];
3357
+ if (i % Nk === 0)
3358
+ t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];
3359
+ else if (Nk > 6 && i % Nk === 4)
3360
+ t = subByte(t);
3361
+ xk[i] = xk[i - Nk] ^ t;
3362
+ }
3363
+ clean2(...toClean);
3364
+ return xk;
3365
+ }
3366
+ function apply0123(T01, T23, s0, s1, s2, s3) {
3367
+ return T01[s0 << 8 & 65280 | s1 >>> 8 & 255] ^ T23[s2 >>> 8 & 65280 | s3 >>> 24 & 255];
3368
+ }
3369
+ function applySbox(sbox2, s0, s1, s2, s3) {
3370
+ return sbox2[s0 & 255 | s1 & 65280] | sbox2[s2 >>> 16 & 255 | s3 >>> 16 & 65280] << 16;
3371
+ }
3372
+ function encrypt(xk, s0, s1, s2, s3) {
3373
+ const { sbox2, T01, T23 } = tableEncoding;
3374
+ let k = 0;
3375
+ s0 ^= xk[k++], s1 ^= xk[k++], s2 ^= xk[k++], s3 ^= xk[k++];
3376
+ const rounds = xk.length / 4 - 2;
3377
+ for (let i = 0; i < rounds; i++) {
3378
+ const t02 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);
3379
+ const t12 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);
3380
+ const t22 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);
3381
+ const t32 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);
3382
+ s0 = t02, s1 = t12, s2 = t22, s3 = t32;
3383
+ }
3384
+ const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);
3385
+ const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);
3386
+ const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);
3387
+ const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);
3388
+ return { s0: t0, s1: t1, s2: t2, s3: t3 };
3389
+ }
3390
+ function ctr32(xk, isLE2, nonce, src, dst) {
3391
+ abytes3(nonce, BLOCK_SIZE2, "nonce");
3392
+ abytes3(src);
3393
+ dst = getOutput(src.length, dst);
3394
+ const ctr = nonce;
3395
+ const c32 = u32(ctr);
3396
+ const view = createView2(ctr);
3397
+ const src32 = u32(src);
3398
+ const dst32 = u32(dst);
3399
+ const ctrPos = isLE2 ? 0 : 12;
3400
+ const srcLen = src.length;
3401
+ let ctrNum = view.getUint32(ctrPos, isLE2);
3402
+ for (let i = 0; i + 4 <= src32.length; i += 4) {
3403
+ const { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));
3404
+ dst32[i + 0] = src32[i + 0] ^ swap8IfBE(s0);
3405
+ dst32[i + 1] = src32[i + 1] ^ swap8IfBE(s1);
3406
+ dst32[i + 2] = src32[i + 2] ^ swap8IfBE(s2);
3407
+ dst32[i + 3] = src32[i + 3] ^ swap8IfBE(s3);
3408
+ ctrNum = ctrNum + 1 >>> 0;
3409
+ view.setUint32(ctrPos, ctrNum, isLE2);
3410
+ }
3411
+ const start = BLOCK_SIZE2 * Math.floor(src32.length / BLOCK_SIZE32);
3412
+ if (start < srcLen) {
3413
+ const { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]));
3414
+ const b32 = new Uint32Array([s0, s1, s2, s3]);
3415
+ swap32IfBE(b32);
3416
+ const buf = u8(b32);
3417
+ for (let i = start, pos = 0; i < srcLen; i++, pos++)
3418
+ dst[i] = src[i] ^ buf[pos];
3419
+ clean2(b32);
3420
+ }
3421
+ return dst;
3422
+ }
3423
+ function computeTag(fn, isLE2, key, data, AAD) {
3424
+ const aadLength = AAD ? AAD.length : 0;
3425
+ const h = fn.create(key, data.length + aadLength);
3426
+ if (AAD)
3427
+ h.update(AAD);
3428
+ const num = u64Lengths(8 * data.length, 8 * aadLength, isLE2);
3429
+ h.update(data);
3430
+ h.update(num);
3431
+ const res = h.digest();
3432
+ clean2(num);
3433
+ return res;
3434
+ }
3435
+ var gcm = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, withAAD: true, varSizeNonce: true }, function aesgcm(key, nonce, AAD) {
3436
+ if (nonce.length < 8)
3437
+ throw new Error("aes/gcm: invalid nonce length");
3438
+ const tagLength = 16;
3439
+ function _computeTag(authKey, tagMask, data) {
3440
+ const tag = computeTag(ghash, false, authKey, data, AAD);
3441
+ for (let i = 0; i < tagMask.length; i++)
3442
+ tag[i] ^= tagMask[i];
3443
+ return tag;
3444
+ }
3445
+ function deriveKeys() {
3446
+ const xk = expandKeyLE(key);
3447
+ const authKey = EMPTY_BLOCK.slice();
3448
+ const counter = EMPTY_BLOCK.slice();
3449
+ ctr32(xk, false, counter, counter, authKey);
3450
+ if (nonce.length === 12) {
3451
+ counter.set(nonce);
3452
+ } else {
3453
+ const nonceLen = EMPTY_BLOCK.slice();
3454
+ const view = createView2(nonceLen);
3455
+ view.setBigUint64(8, BigInt(nonce.length * 8), false);
3456
+ const g = ghash.create(authKey).update(nonce).update(nonceLen);
3457
+ g.digestInto(counter);
3458
+ g.destroy();
3459
+ }
3460
+ const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK);
3461
+ return { xk, authKey, counter, tagMask };
3462
+ }
3463
+ return {
3464
+ encrypt(plaintext) {
3465
+ const { xk, authKey, counter, tagMask } = deriveKeys();
3466
+ const out = new Uint8Array(plaintext.length + tagLength);
3467
+ const toClean = [xk, authKey, counter, tagMask];
3468
+ if (!isAligned32(plaintext))
3469
+ toClean.push(plaintext = copyBytes2(plaintext));
3470
+ ctr32(xk, false, counter, plaintext, out.subarray(0, plaintext.length));
3471
+ const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength));
3472
+ toClean.push(tag);
3473
+ out.set(tag, plaintext.length);
3474
+ clean2(...toClean);
3475
+ return out;
3476
+ },
3477
+ decrypt(ciphertext) {
3478
+ const { xk, authKey, counter, tagMask } = deriveKeys();
3479
+ const toClean = [xk, authKey, tagMask, counter];
3480
+ if (!isAligned32(ciphertext))
3481
+ toClean.push(ciphertext = copyBytes2(ciphertext));
3482
+ const data = ciphertext.subarray(0, -tagLength);
3483
+ const passedTag = ciphertext.subarray(-tagLength);
3484
+ const tag = _computeTag(authKey, tagMask, data);
3485
+ toClean.push(tag);
3486
+ if (!equalBytes(tag, passedTag)) {
3487
+ clean2(...toClean);
3488
+ throw new Error("aes-gcm: invalid tag");
3489
+ }
3490
+ const out = ctr32(xk, false, counter, data);
3491
+ clean2(...toClean);
3492
+ return out;
3493
+ }
3494
+ };
3495
+ });
3496
+
3497
+ // ../../node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/_arx.js
3498
+ var encodeStr = (str) => Uint8Array.from(str.split(""), (c) => c.charCodeAt(0));
3499
+ var sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 16-byte k"))))();
3500
+ var sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr("expand 32-byte k"))))();
3501
+ function rotl(a, b) {
3502
+ return a << b | a >>> 32 - b;
3503
+ }
3504
+ var BLOCK_LEN = 64;
3505
+ var BLOCK_LEN32 = 16;
3506
+ var MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)();
3507
+ var U32_EMPTY = /* @__PURE__ */ Uint32Array.of();
3508
+ function runCipher(core, sigma, key, nonce, data, output, counter, rounds) {
3509
+ const len = data.length;
3510
+ const block = new Uint8Array(BLOCK_LEN);
3511
+ const b32 = u32(block);
3512
+ const isAligned = isLE && isAligned32(data) && isAligned32(output);
3513
+ const d32 = isAligned ? u32(data) : U32_EMPTY;
3514
+ const o32 = isAligned ? u32(output) : U32_EMPTY;
3515
+ if (!isLE) {
3516
+ for (let pos = 0; pos < len; counter++) {
3517
+ core(sigma, key, nonce, b32, counter, rounds);
3518
+ swap32IfBE(b32);
3519
+ if (counter >= MAX_COUNTER)
3520
+ throw new Error("arx: counter overflow");
3521
+ const take = Math.min(BLOCK_LEN, len - pos);
3522
+ for (let j = 0, posj; j < take; j++) {
3523
+ posj = pos + j;
3524
+ output[posj] = data[posj] ^ block[j];
3525
+ }
3526
+ pos += take;
3527
+ }
3528
+ return;
3529
+ }
3530
+ for (let pos = 0; pos < len; counter++) {
3531
+ core(sigma, key, nonce, b32, counter, rounds);
3532
+ if (counter >= MAX_COUNTER)
3533
+ throw new Error("arx: counter overflow");
3534
+ const take = Math.min(BLOCK_LEN, len - pos);
3535
+ if (isAligned && take === BLOCK_LEN) {
3536
+ const pos32 = pos / 4;
3537
+ if (pos % 4 !== 0)
3538
+ throw new Error("arx: invalid block position");
3539
+ for (let j = 0, posj; j < BLOCK_LEN32; j++) {
3540
+ posj = pos32 + j;
3541
+ o32[posj] = d32[posj] ^ b32[j];
3542
+ }
3543
+ pos += BLOCK_LEN;
3544
+ continue;
3545
+ }
3546
+ for (let j = 0, posj; j < take; j++) {
3547
+ posj = pos + j;
3548
+ output[posj] = data[posj] ^ block[j];
3549
+ }
3550
+ pos += take;
3551
+ }
3552
+ }
3553
+ function createCipher(core, opts) {
3554
+ const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts2({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts);
3555
+ if (typeof core !== "function")
3556
+ throw new Error("core must be a function");
3557
+ anumber3(counterLength);
3558
+ anumber3(rounds);
3559
+ abool2(counterRight);
3560
+ abool2(allowShortKeys);
3561
+ return (key, nonce, data, output, counter = 0) => {
3562
+ abytes3(key, void 0, "key");
3563
+ abytes3(nonce, void 0, "nonce");
3564
+ abytes3(data, void 0, "data");
3565
+ const len = data.length;
3566
+ const hasOutput = output !== void 0;
3567
+ output = getOutput(len, output, false);
3568
+ if (hasOutput)
3569
+ complexOverlapBytes(data, output);
3570
+ anumber3(counter);
3571
+ if (counter < 0 || counter >= MAX_COUNTER)
3572
+ throw new Error("arx: counter overflow");
3573
+ const toClean = [];
3574
+ let l = key.length;
3575
+ let k;
3576
+ let sigma;
3577
+ if (l === 32) {
3578
+ toClean.push(k = copyBytes2(key));
3579
+ sigma = sigma32_32;
3580
+ } else if (l === 16 && allowShortKeys) {
3581
+ k = new Uint8Array(32);
3582
+ k.set(key);
3583
+ k.set(key, 16);
3584
+ sigma = sigma16_32;
3585
+ toClean.push(k);
3586
+ } else {
3587
+ abytes3(key, 32, "arx key");
3588
+ throw new Error("invalid key size");
3589
+ }
3590
+ if (!isLE || !isAligned32(nonce))
3591
+ toClean.push(nonce = copyBytes2(nonce));
3592
+ let k32 = u32(k);
3593
+ if (extendNonceFn) {
3594
+ if (nonce.length !== 24)
3595
+ throw new Error("arx: extended nonce must be 24 bytes");
3596
+ const n16 = nonce.subarray(0, 16);
3597
+ if (isLE)
3598
+ extendNonceFn(sigma, k32, u32(n16), k32);
3599
+ else {
3600
+ const sigmaRaw = swap32IfBE(Uint32Array.from(sigma));
3601
+ extendNonceFn(sigmaRaw, k32, u32(n16), k32);
3602
+ clean2(sigmaRaw);
3603
+ swap32IfBE(k32);
3604
+ }
3605
+ nonce = nonce.subarray(16);
3606
+ } else if (!isLE)
3607
+ swap32IfBE(k32);
3608
+ const nonceNcLen = 16 - counterLength;
3609
+ if (nonceNcLen !== nonce.length)
3610
+ throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
3611
+ if (nonceNcLen !== 12) {
3612
+ const nc = new Uint8Array(12);
3613
+ nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
3614
+ nonce = nc;
3615
+ toClean.push(nonce);
3616
+ }
3617
+ const n32 = swap32IfBE(u32(nonce));
3618
+ try {
3619
+ runCipher(core, sigma, k32, n32, data, output, counter, rounds);
3620
+ return output;
3621
+ } finally {
3622
+ clean2(...toClean);
3623
+ }
3624
+ };
3625
+ }
3626
+
3627
+ // ../../node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/_poly1305.js
3628
+ function u8to16(a, i) {
3629
+ return a[i++] & 255 | (a[i++] & 255) << 8;
3630
+ }
3631
+ var Poly1305 = class {
3632
+ blockLen = 16;
3633
+ outputLen = 16;
3634
+ buffer = new Uint8Array(16);
3635
+ r = new Uint16Array(10);
3636
+ // Allocating 1 array with .subarray() here is slower than 3
3637
+ h = new Uint16Array(10);
3638
+ pad = new Uint16Array(8);
3639
+ pos = 0;
3640
+ finished = false;
3641
+ destroyed = false;
3642
+ // Can be speed-up using BigUint64Array, at the cost of complexity
3643
+ constructor(key) {
3644
+ key = copyBytes2(abytes3(key, 32, "key"));
3645
+ const t0 = u8to16(key, 0);
3646
+ const t1 = u8to16(key, 2);
3647
+ const t2 = u8to16(key, 4);
3648
+ const t3 = u8to16(key, 6);
3649
+ const t4 = u8to16(key, 8);
3650
+ const t5 = u8to16(key, 10);
3651
+ const t6 = u8to16(key, 12);
3652
+ const t7 = u8to16(key, 14);
3653
+ this.r[0] = t0 & 8191;
3654
+ this.r[1] = (t0 >>> 13 | t1 << 3) & 8191;
3655
+ this.r[2] = (t1 >>> 10 | t2 << 6) & 7939;
3656
+ this.r[3] = (t2 >>> 7 | t3 << 9) & 8191;
3657
+ this.r[4] = (t3 >>> 4 | t4 << 12) & 255;
3658
+ this.r[5] = t4 >>> 1 & 8190;
3659
+ this.r[6] = (t4 >>> 14 | t5 << 2) & 8191;
3660
+ this.r[7] = (t5 >>> 11 | t6 << 5) & 8065;
3661
+ this.r[8] = (t6 >>> 8 | t7 << 8) & 8191;
3662
+ this.r[9] = t7 >>> 5 & 127;
3663
+ for (let i = 0; i < 8; i++)
3664
+ this.pad[i] = u8to16(key, 16 + 2 * i);
3665
+ }
3666
+ process(data, offset, isLast = false) {
3667
+ const hibit = isLast ? 0 : 1 << 11;
3668
+ const { h, r } = this;
3669
+ const r0 = r[0];
3670
+ const r1 = r[1];
3671
+ const r2 = r[2];
3672
+ const r3 = r[3];
3673
+ const r4 = r[4];
3674
+ const r5 = r[5];
3675
+ const r6 = r[6];
3676
+ const r7 = r[7];
3677
+ const r8 = r[8];
3678
+ const r9 = r[9];
3679
+ const t0 = u8to16(data, offset + 0);
3680
+ const t1 = u8to16(data, offset + 2);
3681
+ const t2 = u8to16(data, offset + 4);
3682
+ const t3 = u8to16(data, offset + 6);
3683
+ const t4 = u8to16(data, offset + 8);
3684
+ const t5 = u8to16(data, offset + 10);
3685
+ const t6 = u8to16(data, offset + 12);
3686
+ const t7 = u8to16(data, offset + 14);
3687
+ let h0 = h[0] + (t0 & 8191);
3688
+ let h1 = h[1] + ((t0 >>> 13 | t1 << 3) & 8191);
3689
+ let h2 = h[2] + ((t1 >>> 10 | t2 << 6) & 8191);
3690
+ let h3 = h[3] + ((t2 >>> 7 | t3 << 9) & 8191);
3691
+ let h4 = h[4] + ((t3 >>> 4 | t4 << 12) & 8191);
3692
+ let h5 = h[5] + (t4 >>> 1 & 8191);
3693
+ let h6 = h[6] + ((t4 >>> 14 | t5 << 2) & 8191);
3694
+ let h7 = h[7] + ((t5 >>> 11 | t6 << 5) & 8191);
3695
+ let h8 = h[8] + ((t6 >>> 8 | t7 << 8) & 8191);
3696
+ let h9 = h[9] + (t7 >>> 5 | hibit);
3697
+ let c = 0;
3698
+ let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);
3699
+ c = d0 >>> 13;
3700
+ d0 &= 8191;
3701
+ d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);
3702
+ c += d0 >>> 13;
3703
+ d0 &= 8191;
3704
+ let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);
3705
+ c = d1 >>> 13;
3706
+ d1 &= 8191;
3707
+ d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);
3708
+ c += d1 >>> 13;
3709
+ d1 &= 8191;
3710
+ let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);
3711
+ c = d2 >>> 13;
3712
+ d2 &= 8191;
3713
+ d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);
3714
+ c += d2 >>> 13;
3715
+ d2 &= 8191;
3716
+ let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);
3717
+ c = d3 >>> 13;
3718
+ d3 &= 8191;
3719
+ d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);
3720
+ c += d3 >>> 13;
3721
+ d3 &= 8191;
3722
+ let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;
3723
+ c = d4 >>> 13;
3724
+ d4 &= 8191;
3725
+ d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);
3726
+ c += d4 >>> 13;
3727
+ d4 &= 8191;
3728
+ let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;
3729
+ c = d5 >>> 13;
3730
+ d5 &= 8191;
3731
+ d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);
3732
+ c += d5 >>> 13;
3733
+ d5 &= 8191;
3734
+ let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;
3735
+ c = d6 >>> 13;
3736
+ d6 &= 8191;
3737
+ d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);
3738
+ c += d6 >>> 13;
3739
+ d6 &= 8191;
3740
+ let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;
3741
+ c = d7 >>> 13;
3742
+ d7 &= 8191;
3743
+ d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);
3744
+ c += d7 >>> 13;
3745
+ d7 &= 8191;
3746
+ let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;
3747
+ c = d8 >>> 13;
3748
+ d8 &= 8191;
3749
+ d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);
3750
+ c += d8 >>> 13;
3751
+ d8 &= 8191;
3752
+ let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;
3753
+ c = d9 >>> 13;
3754
+ d9 &= 8191;
3755
+ d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;
3756
+ c += d9 >>> 13;
3757
+ d9 &= 8191;
3758
+ c = (c << 2) + c | 0;
3759
+ c = c + d0 | 0;
3760
+ d0 = c & 8191;
3761
+ c = c >>> 13;
3762
+ d1 += c;
3763
+ h[0] = d0;
3764
+ h[1] = d1;
3765
+ h[2] = d2;
3766
+ h[3] = d3;
3767
+ h[4] = d4;
3768
+ h[5] = d5;
3769
+ h[6] = d6;
3770
+ h[7] = d7;
3771
+ h[8] = d8;
3772
+ h[9] = d9;
3773
+ }
3774
+ finalize() {
3775
+ const { h, pad } = this;
3776
+ const g = new Uint16Array(10);
3777
+ let c = h[1] >>> 13;
3778
+ h[1] &= 8191;
3779
+ for (let i = 2; i < 10; i++) {
3780
+ h[i] += c;
3781
+ c = h[i] >>> 13;
3782
+ h[i] &= 8191;
3783
+ }
3784
+ h[0] += c * 5;
3785
+ c = h[0] >>> 13;
3786
+ h[0] &= 8191;
3787
+ h[1] += c;
3788
+ c = h[1] >>> 13;
3789
+ h[1] &= 8191;
3790
+ h[2] += c;
3791
+ g[0] = h[0] + 5;
3792
+ c = g[0] >>> 13;
3793
+ g[0] &= 8191;
3794
+ for (let i = 1; i < 10; i++) {
3795
+ g[i] = h[i] + c;
3796
+ c = g[i] >>> 13;
3797
+ g[i] &= 8191;
3798
+ }
3799
+ g[9] -= 1 << 13;
3800
+ let mask = (c ^ 1) - 1;
3801
+ for (let i = 0; i < 10; i++)
3802
+ g[i] &= mask;
3803
+ mask = ~mask;
3804
+ for (let i = 0; i < 10; i++)
3805
+ h[i] = h[i] & mask | g[i];
3806
+ h[0] = (h[0] | h[1] << 13) & 65535;
3807
+ h[1] = (h[1] >>> 3 | h[2] << 10) & 65535;
3808
+ h[2] = (h[2] >>> 6 | h[3] << 7) & 65535;
3809
+ h[3] = (h[3] >>> 9 | h[4] << 4) & 65535;
3810
+ h[4] = (h[4] >>> 12 | h[5] << 1 | h[6] << 14) & 65535;
3811
+ h[5] = (h[6] >>> 2 | h[7] << 11) & 65535;
3812
+ h[6] = (h[7] >>> 5 | h[8] << 8) & 65535;
3813
+ h[7] = (h[8] >>> 8 | h[9] << 5) & 65535;
3814
+ let f = h[0] + pad[0];
3815
+ h[0] = f & 65535;
3816
+ for (let i = 1; i < 8; i++) {
3817
+ f = (h[i] + pad[i] | 0) + (f >>> 16) | 0;
3818
+ h[i] = f & 65535;
3819
+ }
3820
+ clean2(g);
3821
+ }
3822
+ update(data) {
3823
+ aexists2(this);
3824
+ abytes3(data);
3825
+ data = copyBytes2(data);
3826
+ const { buffer, blockLen } = this;
3827
+ const len = data.length;
3828
+ for (let pos = 0; pos < len; ) {
3829
+ const take = Math.min(blockLen - this.pos, len - pos);
3830
+ if (take === blockLen) {
3831
+ for (; blockLen <= len - pos; pos += blockLen)
3832
+ this.process(data, pos);
3833
+ continue;
3834
+ }
3835
+ buffer.set(data.subarray(pos, pos + take), this.pos);
3836
+ this.pos += take;
3837
+ pos += take;
3838
+ if (this.pos === blockLen) {
3839
+ this.process(buffer, 0, false);
3840
+ this.pos = 0;
3841
+ }
3842
+ }
3843
+ return this;
3844
+ }
3845
+ destroy() {
3846
+ this.destroyed = true;
3847
+ clean2(this.h, this.r, this.buffer, this.pad);
3848
+ }
3849
+ digestInto(out) {
3850
+ aexists2(this);
3851
+ aoutput2(out, this);
3852
+ this.finished = true;
3853
+ const { buffer, h } = this;
3854
+ let { pos } = this;
3855
+ if (pos) {
3856
+ buffer[pos++] = 1;
3857
+ for (; pos < 16; pos++)
3858
+ buffer[pos] = 0;
3859
+ this.process(buffer, 0, true);
3860
+ }
3861
+ this.finalize();
3862
+ let opos = 0;
3863
+ for (let i = 0; i < 8; i++) {
3864
+ out[opos++] = h[i] >>> 0;
3865
+ out[opos++] = h[i] >>> 8;
3866
+ }
3867
+ }
3868
+ digest() {
3869
+ const { buffer, outputLen } = this;
3870
+ this.digestInto(buffer);
3871
+ const res = buffer.slice(0, outputLen);
3872
+ this.destroy();
3873
+ return res;
3874
+ }
3875
+ };
3876
+ var poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key));
3877
+
3878
+ // ../../node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/salsa.js
3879
+ function salsaCore(s, k, n, out, cnt, rounds = 20, cntHi = 0) {
3880
+ let y00 = s[0], y01 = k[0], y02 = k[1], y03 = k[2], y04 = k[3], y05 = s[1], y06 = n[0], y07 = n[1], y08 = cnt, y09 = cntHi, y10 = s[2], y11 = k[4], y12 = k[5], y13 = k[6], y14 = k[7], y15 = s[3];
3881
+ let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
3882
+ for (let r = 0; r < rounds; r += 2) {
3883
+ x04 ^= rotl(x00 + x12 | 0, 7);
3884
+ x08 ^= rotl(x04 + x00 | 0, 9);
3885
+ x12 ^= rotl(x08 + x04 | 0, 13);
3886
+ x00 ^= rotl(x12 + x08 | 0, 18);
3887
+ x09 ^= rotl(x05 + x01 | 0, 7);
3888
+ x13 ^= rotl(x09 + x05 | 0, 9);
3889
+ x01 ^= rotl(x13 + x09 | 0, 13);
3890
+ x05 ^= rotl(x01 + x13 | 0, 18);
3891
+ x14 ^= rotl(x10 + x06 | 0, 7);
3892
+ x02 ^= rotl(x14 + x10 | 0, 9);
3893
+ x06 ^= rotl(x02 + x14 | 0, 13);
3894
+ x10 ^= rotl(x06 + x02 | 0, 18);
3895
+ x03 ^= rotl(x15 + x11 | 0, 7);
3896
+ x07 ^= rotl(x03 + x15 | 0, 9);
3897
+ x11 ^= rotl(x07 + x03 | 0, 13);
3898
+ x15 ^= rotl(x11 + x07 | 0, 18);
3899
+ x01 ^= rotl(x00 + x03 | 0, 7);
3900
+ x02 ^= rotl(x01 + x00 | 0, 9);
3901
+ x03 ^= rotl(x02 + x01 | 0, 13);
3902
+ x00 ^= rotl(x03 + x02 | 0, 18);
3903
+ x06 ^= rotl(x05 + x04 | 0, 7);
3904
+ x07 ^= rotl(x06 + x05 | 0, 9);
3905
+ x04 ^= rotl(x07 + x06 | 0, 13);
3906
+ x05 ^= rotl(x04 + x07 | 0, 18);
3907
+ x11 ^= rotl(x10 + x09 | 0, 7);
3908
+ x08 ^= rotl(x11 + x10 | 0, 9);
3909
+ x09 ^= rotl(x08 + x11 | 0, 13);
3910
+ x10 ^= rotl(x09 + x08 | 0, 18);
3911
+ x12 ^= rotl(x15 + x14 | 0, 7);
3912
+ x13 ^= rotl(x12 + x15 | 0, 9);
3913
+ x14 ^= rotl(x13 + x12 | 0, 13);
3914
+ x15 ^= rotl(x14 + x13 | 0, 18);
3915
+ }
3916
+ let oi = 0;
3917
+ out[oi++] = y00 + x00 | 0;
3918
+ out[oi++] = y01 + x01 | 0;
3919
+ out[oi++] = y02 + x02 | 0;
3920
+ out[oi++] = y03 + x03 | 0;
3921
+ out[oi++] = y04 + x04 | 0;
3922
+ out[oi++] = y05 + x05 | 0;
3923
+ out[oi++] = y06 + x06 | 0;
3924
+ out[oi++] = y07 + x07 | 0;
3925
+ out[oi++] = y08 + x08 | 0;
3926
+ out[oi++] = y09 + x09 | 0;
3927
+ out[oi++] = y10 + x10 | 0;
3928
+ out[oi++] = y11 + x11 | 0;
3929
+ out[oi++] = y12 + x12 | 0;
3930
+ out[oi++] = y13 + x13 | 0;
3931
+ out[oi++] = y14 + x14 | 0;
3932
+ out[oi++] = y15 + x15 | 0;
3933
+ }
3934
+ function hsalsa(s, k, i, out) {
3935
+ const s2 = isLE ? s : swap32IfBE(s.slice(0, 4));
3936
+ const k2 = isLE ? k : swap32IfBE(k.slice(0, 8));
3937
+ const i2 = isLE ? i : swap32IfBE(i.slice(0, 4));
3938
+ const t = new Uint32Array(16);
3939
+ salsaCore(s2, k2, i2.subarray(0, 2), t, i2[2], 20, i2[3]);
3940
+ let oi = 0;
3941
+ out[oi++] = t[0] - s2[0] | 0;
3942
+ out[oi++] = t[5] - s2[1] | 0;
3943
+ out[oi++] = t[10] - s2[2] | 0;
3944
+ out[oi++] = t[15] - s2[3] | 0;
3945
+ out[oi++] = t[6] - i2[0] | 0;
3946
+ out[oi++] = t[7] - i2[1] | 0;
3947
+ out[oi++] = t[8] - i2[2] | 0;
3948
+ out[oi++] = t[9] - i2[3] | 0;
3949
+ swap32IfBE(out);
3950
+ if (!isLE)
3951
+ clean2(s2, k2, i2);
3952
+ clean2(t);
3953
+ }
3954
+ var xsalsa20 = /* @__PURE__ */ createCipher(salsaCore, {
3955
+ counterRight: true,
3956
+ extendNonceFn: hsalsa
3957
+ });
3958
+ var xsalsa20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, (key, nonce) => {
3959
+ return {
3960
+ encrypt(plaintext, output) {
3961
+ output = getOutput(plaintext.length + 32, output, false);
3962
+ const authKey = output.subarray(0, 32);
3963
+ const ciphPlaintext = output.subarray(32);
3964
+ output.set(plaintext, 32);
3965
+ clean2(authKey);
3966
+ xsalsa20(key, nonce, output, output);
3967
+ const tag = poly1305(ciphPlaintext, authKey);
3968
+ output.set(tag, 16);
3969
+ clean2(output.subarray(0, 16), tag);
3970
+ return output.subarray(16);
3971
+ },
3972
+ decrypt(ciphertext, output) {
3973
+ abytes3(ciphertext, void 0, "data");
3974
+ output = getOutput(ciphertext.length + 32, output, false);
3975
+ const tmp = output.subarray(0, 32);
3976
+ const passedTag = output.subarray(32, 48);
3977
+ const ciphPlaintext = output.subarray(48);
3978
+ output.set(ciphertext, 32);
3979
+ clean2(tmp);
3980
+ const authKey = xsalsa20(key, nonce, tmp, tmp);
3981
+ const tag = poly1305(ciphPlaintext, authKey);
3982
+ if (!equalBytes(passedTag, tag)) {
3983
+ clean2(output);
3984
+ throw new Error("invalid tag");
3985
+ }
3986
+ xsalsa20(key, nonce, output.subarray(16), output.subarray(16));
3987
+ clean2(tmp, passedTag, tag);
3988
+ return ciphPlaintext;
3989
+ }
3990
+ };
3991
+ });
3992
+
3993
+ // ../../shared/protocol.ts
3994
+ var encoder = new TextEncoder();
3995
+ var decoder = new TextDecoder();
3996
+ function utf8(value) {
3997
+ return encoder.encode(value);
3998
+ }
3999
+ function fromUtf8(value) {
4000
+ return decoder.decode(value);
4001
+ }
4002
+ function randomBytes4(length) {
4003
+ const out = new Uint8Array(length);
4004
+ crypto.getRandomValues(out);
4005
+ return out;
4006
+ }
4007
+ function cat(...parts) {
4008
+ return concatBytes(...parts);
4009
+ }
4010
+ function lp(bytes) {
4011
+ const out = new Uint8Array(4 + bytes.length);
4012
+ new DataView(out.buffer).setUint32(0, bytes.length, false);
4013
+ out.set(bytes, 4);
4014
+ return out;
4015
+ }
4016
+ function u64be(value) {
4017
+ const out = new Uint8Array(8);
4018
+ new DataView(out.buffer).setBigUint64(0, BigInt(Math.trunc(value)), false);
4019
+ return out;
4020
+ }
4021
+ function b64u(bytes) {
4022
+ let binary = "";
4023
+ for (const byte of bytes) binary += String.fromCharCode(byte);
4024
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
4025
+ }
4026
+ function unb64u(value) {
4027
+ const normalized = value.replaceAll("-", "+").replaceAll("_", "/");
4028
+ const padded = normalized + "=".repeat((4 - normalized.length % 4) % 4);
4029
+ const binary = atob(padded);
4030
+ const out = new Uint8Array(binary.length);
4031
+ for (let i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i);
4032
+ return out;
4033
+ }
4034
+ var BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
4035
+ var BASE58_INDEX = new Map([...BASE58_ALPHABET].map((char, index) => [char, BigInt(index)]));
4036
+ function b58(bytes) {
4037
+ let value = 0n;
4038
+ for (const byte of bytes) value = value * 256n + BigInt(byte);
4039
+ let out = "";
4040
+ while (value > 0n) {
4041
+ out = BASE58_ALPHABET[Number(value % 58n)] + out;
4042
+ value /= 58n;
4043
+ }
4044
+ let zeros = 0;
4045
+ while (zeros < bytes.length && bytes[zeros] === 0) zeros += 1;
4046
+ return "1".repeat(zeros) + out;
4047
+ }
4048
+ function unb58(value) {
4049
+ if (value.length === 0) throw new Error("empty base58 value");
4050
+ let rest = 0n;
4051
+ for (const char of value) {
4052
+ const digit = BASE58_INDEX.get(char);
4053
+ if (digit === void 0) throw new Error("invalid base58 character");
4054
+ rest = rest * 58n + digit;
4055
+ }
4056
+ const body = [];
4057
+ while (rest > 0n) {
4058
+ body.unshift(Number(rest & 0xffn));
4059
+ rest >>= 8n;
4060
+ }
4061
+ let zeros = 0;
4062
+ while (zeros < value.length && value[zeros] === "1") zeros += 1;
4063
+ const out = new Uint8Array(zeros + body.length);
4064
+ out.set(body, zeros);
4065
+ return out;
4066
+ }
4067
+ function identityFromSeed(seed) {
4068
+ if (seed.length !== 32) throw new Error("an eXe seed is 32 bytes");
4069
+ return { seed: new Uint8Array(seed), public: ed25519.getPublicKey(seed) };
4070
+ }
4071
+ function decodeSecret(secret) {
4072
+ const raw = unb58(secret);
4073
+ if (raw.length !== 64) throw new Error("an eXe secret is 64 bytes: seed32 || pub32");
4074
+ const identity = identityFromSeed(raw.slice(0, 32));
4075
+ for (let i = 0; i < 32; i += 1) {
4076
+ if (identity.public[i] !== raw[32 + i]) throw new Error("the secret does not match its own public key");
4077
+ }
4078
+ return identity;
4079
+ }
4080
+ function addressOf(identity) {
4081
+ return b58(identity.public);
4082
+ }
4083
+ function parseAddress(text2) {
4084
+ if (typeof text2 !== "string" || text2.length < 32 || text2.length > 64) throw new Error("not an eXe address");
4085
+ const raw = unb58(text2);
4086
+ if (raw.length !== 32) throw new Error("an eXe address is 32 bytes");
4087
+ return raw;
4088
+ }
4089
+ function isAddress(text2) {
4090
+ if (typeof text2 !== "string") return false;
4091
+ try {
4092
+ parseAddress(text2);
4093
+ return true;
4094
+ } catch {
4095
+ return false;
4096
+ }
4097
+ }
4098
+ function sign(seed, message2) {
4099
+ return b58(ed25519.sign(message2, seed));
4100
+ }
4101
+ function verifySignature(publicKey, message2, signature) {
4102
+ try {
4103
+ return ed25519.verify(unb58(signature), message2, publicKey);
4104
+ } catch {
4105
+ return false;
4106
+ }
4107
+ }
4108
+ function agreementPublic(publicKey) {
4109
+ return ed25519.utils.toMontgomery(publicKey);
4110
+ }
4111
+ function agreementSecret(seed) {
4112
+ const clamped = new Uint8Array(sha512(seed).slice(0, 32));
4113
+ clamped[0] = clamped[0] & 248;
4114
+ clamped[31] = clamped[31] & 127 | 64;
4115
+ return clamped;
4116
+ }
4117
+ function associatedData(context) {
4118
+ return cat(
4119
+ lp(utf8(context.direction)),
4120
+ lp(utf8(context.caller)),
4121
+ lp(utf8(context.device)),
4122
+ lp(utf8(context.callId)),
4123
+ u64be(context.issuedAt),
4124
+ u64be(context.expiresAt)
4125
+ );
4126
+ }
4127
+ var ZERO_16 = new Uint8Array(16);
4128
+ var SIGMA = new Uint32Array([1634760805, 857760878, 2036477234, 1797285236]);
4129
+ function rotl2(value, shift) {
4130
+ return (value << shift | value >>> 32 - shift) >>> 0;
4131
+ }
4132
+ function quarterRound(x, a, b, c, d) {
4133
+ x[b] = x[b] ^ rotl2(x[a] + x[d] >>> 0, 7);
4134
+ x[c] = x[c] ^ rotl2(x[b] + x[a] >>> 0, 9);
4135
+ x[d] = x[d] ^ rotl2(x[c] + x[b] >>> 0, 13);
4136
+ x[a] = x[a] ^ rotl2(x[d] + x[c] >>> 0, 18);
4137
+ }
4138
+ function wordsLe(bytes) {
4139
+ const out = new Uint32Array(bytes.length / 4);
4140
+ for (let i = 0; i < out.length; i += 1) {
4141
+ out[i] = (bytes[i * 4] | bytes[i * 4 + 1] << 8 | bytes[i * 4 + 2] << 16 | bytes[i * 4 + 3] << 24) >>> 0;
4142
+ }
4143
+ return out;
4144
+ }
4145
+ function bytesLe(words) {
4146
+ const out = new Uint8Array(words.length * 4);
4147
+ for (let i = 0; i < words.length; i += 1) {
4148
+ const word = words[i];
4149
+ out[i * 4] = word & 255;
4150
+ out[i * 4 + 1] = word >>> 8 & 255;
4151
+ out[i * 4 + 2] = word >>> 16 & 255;
4152
+ out[i * 4 + 3] = word >>> 24 & 255;
4153
+ }
4154
+ return out;
4155
+ }
4156
+ function hsalsa20(key, input) {
4157
+ if (key.length !== 32 || input.length !== 16) throw new Error("hsalsa20 takes a 32-byte key and a 16-byte input");
4158
+ const k = wordsLe(key);
4159
+ const i = wordsLe(input);
4160
+ const x = new Uint32Array(16);
4161
+ x[0] = SIGMA[0];
4162
+ x[1] = k[0];
4163
+ x[2] = k[1];
4164
+ x[3] = k[2];
4165
+ x[4] = k[3];
4166
+ x[5] = SIGMA[1];
4167
+ x[6] = i[0];
4168
+ x[7] = i[1];
4169
+ x[8] = i[2];
4170
+ x[9] = i[3];
4171
+ x[10] = SIGMA[2];
4172
+ x[11] = k[4];
4173
+ x[12] = k[5];
4174
+ x[13] = k[6];
4175
+ x[14] = k[7];
4176
+ x[15] = SIGMA[3];
4177
+ for (let round = 0; round < 10; round += 1) {
4178
+ quarterRound(x, 0, 4, 8, 12);
4179
+ quarterRound(x, 5, 9, 13, 1);
4180
+ quarterRound(x, 10, 14, 2, 6);
4181
+ quarterRound(x, 15, 3, 7, 11);
4182
+ quarterRound(x, 0, 1, 2, 3);
4183
+ quarterRound(x, 5, 6, 7, 4);
4184
+ quarterRound(x, 10, 11, 8, 9);
4185
+ quarterRound(x, 15, 12, 13, 14);
4186
+ }
4187
+ return bytesLe(new Uint32Array([x[0], x[5], x[10], x[15], x[6], x[7], x[8], x[9]]));
4188
+ }
4189
+ var SEALED_PREFIX = 24 + 32 + 48 + 12;
4190
+ function seal(input) {
4191
+ const contentKey = input.contentKey ?? randomBytes4(32);
4192
+ const iv = input.iv ?? randomBytes4(12);
4193
+ const nonce = input.nonce ?? randomBytes4(24);
4194
+ const ephemeralSecret = input.ephemeralSecret ?? randomBytes4(32);
4195
+ if (contentKey.length !== 32 || iv.length !== 12 || nonce.length !== 24) throw new Error("bad seal parameters");
4196
+ const body = gcm(contentKey, iv, associatedData(input)).encrypt(utf8(input.plaintext));
4197
+ const ephemeral = x25519.getPublicKey(ephemeralSecret);
4198
+ const shared = x25519.getSharedSecret(ephemeralSecret, input.recipient);
4199
+ const box = xsalsa20poly1305(hsalsa20(shared, ZERO_16), nonce).encrypt(contentKey);
4200
+ return b64u(cat(nonce, ephemeral, box, iv, body));
4201
+ }
4202
+ function open(input) {
4203
+ return openParts(unb64u(input.sealed), input, input.recipientSecret);
4204
+ }
4205
+ function openBytes(input) {
4206
+ return openParts(input.sealed, input, input.recipientSecret);
4207
+ }
4208
+ function openParts(raw, context, recipientSecret) {
4209
+ if (raw.length < SEALED_PREFIX + 16) throw new Error("sealed payload is too short");
4210
+ const nonce = raw.slice(0, 24);
4211
+ const ephemeral = raw.slice(24, 56);
4212
+ const box = raw.slice(56, 104);
4213
+ const iv = raw.slice(104, 116);
4214
+ const body = raw.slice(116);
4215
+ const shared = x25519.getSharedSecret(recipientSecret, ephemeral);
4216
+ const contentKey = xsalsa20poly1305(hsalsa20(shared, ZERO_16), nonce).decrypt(box);
4217
+ return fromUtf8(gcm(contentKey, iv, associatedData(context)).decrypt(body));
4218
+ }
4219
+ function callTranscript(call) {
4220
+ return cat(
4221
+ utf8("eXe/call\0"),
4222
+ lp(utf8(call.call_id)),
4223
+ lp(utf8(call.caller)),
4224
+ lp(utf8(call.device)),
4225
+ u64be(call.issued_at),
4226
+ u64be(call.expires_at),
4227
+ lp(unb64u(call.sealed))
4228
+ );
4229
+ }
4230
+ function resultTranscript(result) {
4231
+ return cat(
4232
+ utf8("eXe/result\0"),
4233
+ lp(utf8(result.call_id)),
4234
+ lp(utf8(result.device)),
4235
+ new Uint8Array([result.ok ? 1 : 0]),
4236
+ u64be(result.issued_at),
4237
+ lp(unb64u(result.sealed))
4238
+ );
4239
+ }
4240
+ function signCall(seed, call) {
4241
+ return sign(seed, callTranscript(call));
4242
+ }
4243
+ function verifyResult(result) {
4244
+ try {
4245
+ return verifySignature(parseAddress(result.device), resultTranscript(result), result.sig);
4246
+ } catch {
4247
+ return false;
4248
+ }
4249
+ }
4250
+ function requestTranscript(auth) {
4251
+ return cat(
4252
+ utf8("eXe/request\0"),
4253
+ lp(utf8(auth.method.toUpperCase())),
4254
+ lp(utf8(auth.path)),
4255
+ lp(utf8(auth.address)),
4256
+ u64be(auth.timestamp)
4257
+ );
4258
+ }
4259
+ function signRequest(seed, auth) {
4260
+ return sign(seed, requestTranscript(auth));
4261
+ }
4262
+ function requestHeaders(identity, method, path) {
4263
+ const address = addressOf(identity);
4264
+ const timestamp = Math.floor(Date.now() / 1e3);
4265
+ return {
4266
+ "x-exe-address": address,
4267
+ "x-exe-timestamp": String(timestamp),
4268
+ "x-exe-signature": signRequest(identity.seed, { method, path, address, timestamp })
4269
+ };
4270
+ }
4271
+ function buildCall(input) {
4272
+ const sealed = seal({
4273
+ direction: "call",
4274
+ caller: input.caller,
4275
+ device: input.device,
4276
+ callId: input.callId,
4277
+ issuedAt: input.issuedAt,
4278
+ expiresAt: input.expiresAt,
4279
+ recipient: agreementPublic(parseAddress(input.device)),
4280
+ plaintext: JSON.stringify({ name: input.name, args: input.args }),
4281
+ nonce: input.nonce,
4282
+ contentKey: input.contentKey,
4283
+ iv: input.iv,
4284
+ ephemeralSecret: input.ephemeralSecret
4285
+ });
4286
+ const call = {
4287
+ call_id: input.callId,
4288
+ caller: input.caller,
4289
+ device: input.device,
4290
+ issued_at: input.issuedAt,
4291
+ expires_at: input.expiresAt,
4292
+ sealed,
4293
+ sig: ""
4294
+ };
4295
+ call.sig = signCall(input.seed, call);
4296
+ return call;
4297
+ }
4298
+ function openAttachment(input) {
4299
+ return openBytes({
4300
+ direction: "blob",
4301
+ caller: input.call.caller,
4302
+ device: input.call.device,
4303
+ callId: input.call.call_id,
4304
+ issuedAt: input.result.issued_at,
4305
+ expiresAt: input.call.expires_at,
4306
+ recipientSecret: agreementSecret(input.seed),
4307
+ sealed: input.sealed
4308
+ });
4309
+ }
4310
+ function openResult(input) {
4311
+ return open({
4312
+ direction: "result",
4313
+ caller: input.call.caller,
4314
+ device: input.call.device,
4315
+ callId: input.call.call_id,
4316
+ issuedAt: input.result.issued_at,
4317
+ expiresAt: input.call.expires_at,
4318
+ recipientSecret: agreementSecret(input.seed),
4319
+ sealed: input.result.sealed
4320
+ });
4321
+ }
4322
+
4323
+ // src/config.ts
4324
+ var DEFAULT_ENDPOINTS = ["https://exe.ntnl.io", "https://exe.ntnl.top"];
4325
+ function defaultConfigPath(env = process.env) {
4326
+ const override = env.EXE_CONFIG_DIR?.trim();
4327
+ if (override) return join(override, "mcp.toml");
4328
+ if (process.platform === "win32" && env.APPDATA?.trim()) return join(env.APPDATA.trim(), "exe", "mcp.toml");
4329
+ const home = env.HOME?.trim() || env.USERPROFILE?.trim() || homedir();
4330
+ return join(home, ".config", "exe", "mcp.toml");
4331
+ }
4332
+ function splitEndpoints(value) {
4333
+ const entries = Array.isArray(value) ? value : typeof value === "string" ? [value] : [];
4334
+ return entries.filter((entry) => typeof entry === "string").flatMap((entry) => entry.split(",")).map((entry) => entry.trim().replace(/\/+$/, "")).filter((entry) => entry.length > 0);
4335
+ }
4336
+ function readFileConfig(path) {
4337
+ if (!existsSync(path)) return void 0;
4338
+ let text2;
4339
+ try {
4340
+ text2 = readFileSync(path, "utf8");
4341
+ } catch (error) {
4342
+ throw new Error(`cannot read the eXe caller config at ${path}: ${message(error)}`);
4343
+ }
4344
+ try {
4345
+ return parse(text2);
4346
+ } catch (error) {
4347
+ throw new Error(`${path} is not valid TOML: ${message(error)}`);
4348
+ }
4349
+ }
4350
+ function message(error) {
4351
+ return error instanceof Error ? error.message : String(error);
4352
+ }
4353
+ function endpointsOf(file, options) {
4354
+ const inline = splitEndpoints(options.endpoints);
4355
+ if (inline.length > 0) return inline;
4356
+ const configured = splitEndpoints(file?.endpoints);
4357
+ if (configured.length > 0) return configured;
4358
+ const legacy = splitEndpoints(file?.cloud);
4359
+ if (legacy.length > 0) return legacy;
4360
+ return [...DEFAULT_ENDPOINTS];
4361
+ }
4362
+ function devicesOf(file, options) {
4363
+ const merged = /* @__PURE__ */ new Map();
4364
+ const table = file?.devices;
4365
+ if (table !== void 0 && (typeof table !== "object" || table === null || Array.isArray(table))) {
4366
+ throw new Error("`devices` in the eXe caller config must be a table of label = address");
4367
+ }
4368
+ for (const [label, address] of Object.entries(table ?? {})) {
4369
+ if (typeof address !== "string") throw new Error(`device \`${label}\` in the caller config is not a string address`);
4370
+ merged.set(label, address.trim());
4371
+ }
4372
+ for (const [label, address] of Object.entries(options.devices ?? {})) {
4373
+ merged.set(label, address.trim());
4374
+ }
4375
+ const invalid = [...merged].filter(([, address]) => !isAddress(address)).map(([label]) => label);
4376
+ if (invalid.length > 0) {
4377
+ throw new Error(
4378
+ `not an eXe address: ${invalid.map((label) => `\`${label}\``).join(", ")}. A device address is base58 of its 32-byte public key; \`exe status\` prints it on the device.`
4379
+ );
4380
+ }
4381
+ return merged;
4382
+ }
4383
+ function resolveCaller(options = {}, env = process.env) {
4384
+ const path = options.configPath?.trim() || defaultConfigPath(env);
4385
+ const file = readFileConfig(path);
4386
+ const inlineSecret = options.secret?.trim();
4387
+ const fileSecret = typeof file?.secret === "string" ? file.secret.trim() : void 0;
4388
+ const secret = inlineSecret || fileSecret;
4389
+ if (!secret) {
4390
+ throw new Error(
4391
+ `no eXe caller key: ${path} does not exist. Run \`exe mcp init\` on this machine and add the address it prints to every device with \`exe trust <address>\`, or set \`secret\` in this plugin's config.`
4392
+ );
4393
+ }
4394
+ let identity;
4395
+ try {
4396
+ identity = decodeSecret(secret);
4397
+ } catch (error) {
4398
+ throw new Error(
4399
+ `the eXe caller key in ${inlineSecret ? "this plugin's config" : path} is not base58(seed32 || pub32): ` + message(error)
4400
+ );
4401
+ }
4402
+ return {
4403
+ address: addressOf(identity),
4404
+ identity,
4405
+ endpoints: endpointsOf(file, options),
4406
+ devices: devicesOf(file, options),
4407
+ source: inlineSecret ? "plugin config" : path
4408
+ };
4409
+ }
4410
+ function addressForDevice(caller, requested) {
4411
+ const named = caller.devices.get(requested);
4412
+ if (named !== void 0) return named;
4413
+ if (isAddress(requested)) return requested;
4414
+ const known = [...caller.devices.keys()];
4415
+ throw new Error(
4416
+ `unknown device \`${requested}\`: ${known.length > 0 ? `configured: ${known.join(", ")}` : "no devices are configured"}. Call the devices tool for the labels, or add [devices] entries to the eXe caller config.`
4417
+ );
4418
+ }
4419
+
4420
+ // src/relay.ts
4421
+ import { randomUUID } from "node:crypto";
4422
+ var MAX_TTL_SECONDS = 3600;
4423
+ var POLL_START_MS = 150;
4424
+ var POLL_CEILING_MS = 600;
4425
+ var PROBE_TIMEOUT_MS = 3e3;
4426
+ function reason(error) {
4427
+ return error instanceof Error ? error.message : String(error);
4428
+ }
4429
+ function sleep(ms, signal) {
4430
+ return new Promise((resolve, reject) => {
4431
+ if (signal.aborted) {
4432
+ reject(signal.reason ?? new Error("cancelled"));
4433
+ return;
4434
+ }
4435
+ const timer = setTimeout(() => {
4436
+ signal.removeEventListener("abort", onAbort);
4437
+ resolve();
4438
+ }, ms);
4439
+ const onAbort = () => {
4440
+ clearTimeout(timer);
4441
+ reject(signal.reason ?? new Error("cancelled"));
4442
+ };
4443
+ signal.addEventListener("abort", onAbort, { once: true });
4444
+ });
4445
+ }
4446
+ function withDeadline(signal, ms) {
4447
+ const deadline = AbortSignal.timeout(ms);
4448
+ return signal === void 0 ? deadline : AbortSignal.any([signal, deadline]);
4449
+ }
4450
+ var Relay = class {
4451
+ /** base58 of this caller's public key — the address devices must trust. */
4452
+ address;
4453
+ endpoints;
4454
+ identity;
4455
+ fetchImpl;
4456
+ /** Resolved on first use: a briefly unreachable relay must not look like a broken plugin. */
4457
+ cloud;
4458
+ constructor(options) {
4459
+ this.endpoints = options.endpoints;
4460
+ this.identity = options.identity;
4461
+ this.address = addressOf(options.identity);
4462
+ this.fetchImpl = options.fetch ?? globalThis.fetch;
4463
+ }
4464
+ /** The first endpoint that answers as an eXe relay, remembered once found. */
4465
+ async base(signal) {
4466
+ if (this.cloud !== void 0) return this.cloud;
4467
+ for (const endpoint of this.endpoints) {
4468
+ try {
4469
+ const response = await this.fetchImpl(`${endpoint}/api/health`, {
4470
+ signal: withDeadline(signal, PROBE_TIMEOUT_MS)
4471
+ });
4472
+ const health = await response.json();
4473
+ if (health.service === "exe") {
4474
+ this.cloud = endpoint;
4475
+ return endpoint;
4476
+ }
4477
+ } catch {
4478
+ }
4479
+ }
4480
+ throw new Error(`no eXe relay answered at ${this.endpoints.join(", ")}`);
4481
+ }
4482
+ /** One request, self-signed: there is no token and no login anywhere in eXe. */
4483
+ async request(method, path, init = {}) {
4484
+ const base = await this.base(init.signal);
4485
+ const headers = { ...requestHeaders(this.identity, method, path) };
4486
+ if (init.body !== void 0) headers["content-type"] = "application/json";
4487
+ return await this.fetchImpl(`${base}${path}`, {
4488
+ method,
4489
+ headers,
4490
+ body: init.body,
4491
+ signal: init.signal
4492
+ });
4493
+ }
4494
+ async json(path, signal) {
4495
+ const response = await this.request("GET", path, { signal });
4496
+ if (!response.ok) throw new Error(`the relay answered ${response.status} for ${path}`);
4497
+ return await response.json();
4498
+ }
4499
+ /** Registered, online, platform — the relay's metadata about one device. */
4500
+ async device(address, signal) {
4501
+ const value = await this.json(`/api/devices/${address}`, signal);
4502
+ const text2 = (key) => {
4503
+ const entry = value[key];
4504
+ return typeof entry === "string" && entry.length > 0 ? entry : void 0;
4505
+ };
4506
+ const status = {
4507
+ address,
4508
+ registered: value.registered === true,
4509
+ online: value.online === true
4510
+ };
4511
+ const platform = text2("platform");
4512
+ const version = text2("version");
4513
+ const lastSeen = value.last_seen_at;
4514
+ if (platform !== void 0) status.platform = platform;
4515
+ if (version !== void 0) status.version = version;
4516
+ if (typeof lastSeen === "number") status.last_seen_at = lastSeen;
4517
+ return status;
4518
+ }
4519
+ /**
4520
+ * One call: seal, queue, wait, open. The waiting is the caller's problem,
4521
+ * which is why the relay can stay a queue and a poll.
4522
+ */
4523
+ async call(request) {
4524
+ const issuedAt = Math.floor(Date.now() / 1e3);
4525
+ const ttl = Math.min(Math.max(Math.trunc(request.ttlSeconds), 1), MAX_TTL_SECONDS);
4526
+ const expiresAt = issuedAt + ttl;
4527
+ const callId = randomUUID().replaceAll("-", "");
4528
+ const envelope = buildCall({
4529
+ seed: this.identity.seed,
4530
+ caller: this.address,
4531
+ device: request.device,
4532
+ callId,
4533
+ name: request.name,
4534
+ args: JSON.stringify(request.args),
4535
+ issuedAt,
4536
+ expiresAt
4537
+ });
4538
+ const response = await this.request("POST", `/api/devices/${request.device}/calls`, {
4539
+ body: JSON.stringify(envelope),
4540
+ signal: request.signal
4541
+ });
4542
+ if (!response.ok) {
4543
+ const detail = (await response.text()).trim();
4544
+ throw new Error(
4545
+ `the relay refused the call${detail.length > 0 ? `: ${detail}` : ` (${response.status})`}`
4546
+ );
4547
+ }
4548
+ try {
4549
+ return await this.wait(envelope, ttl, request.signal);
4550
+ } catch (error) {
4551
+ if (request.signal.aborted) await this.cancel(callId);
4552
+ throw error;
4553
+ }
4554
+ }
4555
+ async wait(envelope, ttl, signal) {
4556
+ const detailPath = `/api/calls/${envelope.call_id}`;
4557
+ const deadline = Date.now() + (ttl + 30) * 1e3;
4558
+ let wait = POLL_START_MS;
4559
+ for (; ; ) {
4560
+ if (signal.aborted) throw signal.reason ?? new Error("cancelled");
4561
+ if (Date.now() > deadline) throw new Error("no answer from the device before the call expired");
4562
+ const detail = await this.json(detailPath, signal);
4563
+ const status = detail.call?.status ?? "queued";
4564
+ switch (status) {
4565
+ case "queued":
4566
+ case "received":
4567
+ break;
4568
+ case "succeeded":
4569
+ case "failed":
4570
+ return await this.settle(envelope, detail, signal);
4571
+ case "cancelled":
4572
+ throw new Error("the call was cancelled before the device ran it");
4573
+ case "expired":
4574
+ throw new Error("the call expired before the device answered");
4575
+ case "lost":
4576
+ throw new Error(
4577
+ "the device process that took this call is gone and it never answered: the command may have run. Do not retry blindly \u2014 inspect the device state first."
4578
+ );
4579
+ default:
4580
+ throw new Error(`unexpected call status \`${status}\``);
4581
+ }
4582
+ await sleep(wait, signal);
4583
+ wait = Math.min(wait * 2, POLL_CEILING_MS);
4584
+ }
4585
+ }
4586
+ async settle(envelope, detail, signal) {
4587
+ const result = detail.result;
4588
+ if (result === void 0 || result === null) throw new Error("the relay has no result for a settled call");
4589
+ if (!verifyResult(result)) throw new Error("the device's signature on this result does not verify");
4590
+ let answer;
4591
+ try {
4592
+ answer = JSON.parse(openResult({ seed: this.identity.seed, call: envelope, result }));
4593
+ } catch (error) {
4594
+ throw new Error(`the device's answer did not open with this caller's key: ${reason(error)}`);
4595
+ }
4596
+ let attachment;
4597
+ if ((detail.call?.blob_bytes ?? 0) > 0) {
4598
+ const response = await this.request("GET", `/api/calls/${envelope.call_id}/blob`, { signal });
4599
+ if (response.ok) {
4600
+ const raw = new Uint8Array(await response.arrayBuffer());
4601
+ try {
4602
+ attachment = openAttachment({
4603
+ seed: this.identity.seed,
4604
+ call: envelope,
4605
+ result,
4606
+ sealed: raw
4607
+ });
4608
+ } catch (error) {
4609
+ throw new Error(`the device's attachment did not open: ${reason(error)}`);
4610
+ }
4611
+ }
4612
+ }
4613
+ await this.ack(envelope.call_id);
4614
+ return attachment === void 0 ? { answer } : { answer, attachment };
4615
+ }
4616
+ async cancel(callId) {
4617
+ try {
4618
+ await this.request("POST", `/api/calls/${callId}/cancel`);
4619
+ } catch {
4620
+ }
4621
+ }
4622
+ /** Taking the result ends the call's life: the relay drops the row and its blob. */
4623
+ async ack(callId) {
4624
+ try {
4625
+ await this.request("POST", `/api/calls/${callId}/ack`);
4626
+ } catch {
4627
+ }
4628
+ }
4629
+ };
4630
+
4631
+ // src/answers.ts
4632
+ function whole(outcome) {
4633
+ if (outcome.attachment !== void 0) {
4634
+ try {
4635
+ const parsed = JSON.parse(outcome.attachment);
4636
+ if (isRecord(parsed)) return parsed;
4637
+ } catch {
4638
+ }
4639
+ }
4640
+ return isRecord(outcome.answer) ? outcome.answer : {};
4641
+ }
4642
+ function isRecord(value) {
4643
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4644
+ }
4645
+ function text(value) {
4646
+ return typeof value === "string" ? value : "";
4647
+ }
4648
+ function shellAnswer(device, command, outcome) {
4649
+ const body = whole(outcome);
4650
+ const output = isRecord(body.output) ? body.output : {};
4651
+ const exitCode = output.exit_code;
4652
+ const answer = {
4653
+ device,
4654
+ command,
4655
+ exit_code: typeof exitCode === "number" ? exitCode : -1,
4656
+ stdout: text(output.stdout),
4657
+ stderr: text(output.stderr),
4658
+ truncated: output.truncated === true,
4659
+ timed_out: body.code === "timeout"
4660
+ };
4661
+ if (typeof body.error === "string") answer.error = body.error;
4662
+ return answer;
4663
+ }
4664
+ function imageBase64(device, path, outcome) {
4665
+ const body = whole(outcome);
4666
+ const output = isRecord(body.output) ? body.output : {};
4667
+ const base64 = text(output.stdout).split(/\s+/).join("");
4668
+ if (output.truncated === true) {
4669
+ const failure = isRecord(body.blob) ? text(body.blob.error) : "";
4670
+ throw new Error(
4671
+ `${device}: ${path} did not arrive whole \u2014 the device had to cut the answer to a preview${failure.length > 0 ? ` (${failure})` : ""}. Downscale it on the device first.`
4672
+ );
4673
+ }
4674
+ if (base64.length === 0) {
4675
+ throw new Error(`${device}: nothing came back for ${path} \u2014 not a file, or base64 is missing there`);
4676
+ }
4677
+ return base64;
4678
+ }
4679
+ function trimmed(value) {
4680
+ return value.endsWith("\n") ? value.slice(0, -1) : value;
4681
+ }
4682
+ function renderShell(answer) {
4683
+ const parts = [`[${answer.device}] $ ${answer.command}`, `exit ${answer.exit_code}`];
4684
+ if (answer.stdout.length > 0) parts.push(trimmed(answer.stdout));
4685
+ if (answer.stderr.length > 0) parts.push("--- stderr ---", trimmed(answer.stderr));
4686
+ if (answer.truncated) parts.push("[output truncated by the device]");
4687
+ if (answer.timed_out) parts.push("[the device killed the command at its timeout]");
4688
+ if (answer.error !== void 0) parts.push(`[device error: ${answer.error}]`);
4689
+ return parts.join("\n");
4690
+ }
4691
+ function renderDevices(caller, rows) {
4692
+ const lines = [`caller ${caller}`];
4693
+ if (rows.length === 0) {
4694
+ lines.push(
4695
+ "no devices configured: add [devices] entries to the eXe caller config (~/.config/exe/mcp.toml) or set `devices` in this plugin's config"
4696
+ );
4697
+ return lines.join("\n");
4698
+ }
4699
+ for (const row of rows) {
4700
+ if (row.error !== void 0) {
4701
+ lines.push(`${row.device} ${row.address} unreachable: ${row.error}`);
4702
+ continue;
4703
+ }
4704
+ const state = row.online === true ? "online" : "offline";
4705
+ const registered = row.registered === true ? "" : " (not registered yet)";
4706
+ const platform = [row.platform, row.version].filter((part) => part !== void 0).join(" ");
4707
+ lines.push(
4708
+ `${row.device} ${row.address} ${state}${registered}${platform.length > 0 ? ` ${platform}` : ""}`
4709
+ );
4710
+ }
4711
+ return lines.join("\n");
4712
+ }
4713
+
4714
+ // src/index.ts
4715
+ var name = "dsh-plugin-exe";
4716
+ var inject = ["tools"];
4717
+ var Config = Schema.object({
4718
+ endpoints: Schema.array(Schema.string()).description("Relay entry points, tried in order until one answers as an eXe relay.").default([...DEFAULT_ENDPOINTS]),
4719
+ secret: Schema.string().role("secret").description(
4720
+ "Caller key, base58(seed32 || pub32). Leave it unset to use the key `exe mcp` already keeps in configPath."
4721
+ ),
4722
+ configPath: Schema.string().description("Where to read the caller key and device list when not set inline. Defaults to ~/.config/exe/mcp.toml."),
4723
+ devices: Schema.dict(Schema.string()).description("Device label \u2192 address, merged over the caller config's [devices] table.").default({}),
4724
+ toolPrefix: Schema.string().pattern(/^[A-Za-z][A-Za-z0-9_-]{0,40}$/).description("Prefix for the three tool names. Keep it: a harness flattens every server's tools into one table.").default("exe"),
4725
+ defaultTimeoutSeconds: Schema.natural().min(1).max(3600).description("How long a command may run when the model does not say.").default(60),
4726
+ maxCallSeconds: Schema.natural().min(1).max(3600).description("Ceiling on one call's whole lifetime, including the wait for the device.").default(3600)
4727
+ });
4728
+ function shQuote(value) {
4729
+ return `'${value.replaceAll("'", `'\\''`)}'`;
4730
+ }
4731
+ function reason2(error) {
4732
+ return error instanceof Error ? error.message : String(error);
4733
+ }
4734
+ function mediaTypeOf(bytes, path, allowed) {
4735
+ const starts = (...signature) => signature.every((byte, index) => bytes[index] === byte);
4736
+ let mediaType;
4737
+ if (starts(137, 80, 78, 71)) mediaType = "image/png";
4738
+ else if (starts(255, 216, 255)) mediaType = "image/jpeg";
4739
+ else if (starts(71, 73, 70, 56)) mediaType = "image/gif";
4740
+ else if (starts(82, 73, 70, 70) && bytes[8] === 87 && bytes[9] === 69) mediaType = "image/webp";
4741
+ if (mediaType === void 0) {
4742
+ throw new Error(`${path} is not a png, jpeg, webp or gif; read it with the shell tool if its bytes matter`);
4743
+ }
4744
+ if (!allowed.includes(mediaType)) {
4745
+ throw new Error(`this harness accepts ${allowed.join(", ")}; ${path} is ${mediaType}`);
4746
+ }
4747
+ return mediaType;
4748
+ }
4749
+ function basename(path) {
4750
+ const parts = path.split(/[\\/]/);
4751
+ return parts[parts.length - 1] ?? path;
4752
+ }
4753
+ function apply(ctx, config) {
4754
+ const prefix = config.toolPrefix.trim();
4755
+ if (!/^[A-Za-z][A-Za-z0-9_-]{0,40}$/.test(prefix)) {
4756
+ throw new Error(`toolPrefix must be letters, digits, \`_\` or \`-\` and start with a letter: ${JSON.stringify(config.toolPrefix)}`);
4757
+ }
4758
+ let resolved;
4759
+ let relay;
4760
+ const callerOf = () => resolved ??= resolveCaller(config);
4761
+ const relayOf = () => {
4762
+ if (relay === void 0) {
4763
+ const caller = callerOf();
4764
+ relay = new Relay({ endpoints: caller.endpoints, identity: caller.identity });
4765
+ }
4766
+ return relay;
4767
+ };
4768
+ ctx.tools.register(
4769
+ defineTool({
4770
+ name: `${prefix}_devices`,
4771
+ description: `${prefix}_devices lists the devices this harness can reach through eXe, and whether each one is registered and online. Call it first: every other eXe tool takes a device label from here. These are the user's own machines; nothing here runs on the machine hosting the harness.`,
4772
+ parameters: {},
4773
+ output: {
4774
+ schema: {
4775
+ type: "object",
4776
+ additionalProperties: false,
4777
+ properties: {
4778
+ caller: {
4779
+ type: "string",
4780
+ required: true,
4781
+ description: "The address this harness signs as; every device's trust list must contain it."
4782
+ },
4783
+ devices: {
4784
+ type: "array",
4785
+ required: true,
4786
+ items: {
4787
+ type: "object",
4788
+ additionalProperties: false,
4789
+ properties: {
4790
+ device: { type: "string", required: true },
4791
+ address: { type: "string", required: true },
4792
+ registered: { type: "boolean" },
4793
+ online: { type: "boolean" },
4794
+ platform: { type: "string" },
4795
+ version: { type: "string" },
4796
+ last_seen_at: { type: "integer" },
4797
+ error: { type: "string" }
4798
+ }
4799
+ }
4800
+ }
4801
+ }
4802
+ },
4803
+ render: (_args, value) => [
4804
+ { type: "text", text: renderDevices(value.caller, value.devices) }
4805
+ ]
4806
+ },
4807
+ isConcurrencySafe: () => true,
4808
+ async execute(_args, exec) {
4809
+ const caller = callerOf();
4810
+ const client = relayOf();
4811
+ const rows = await Promise.all(
4812
+ [...caller.devices].map(async ([label, address]) => {
4813
+ try {
4814
+ const status = await client.device(address, exec.signal);
4815
+ const row = {
4816
+ device: label,
4817
+ address,
4818
+ registered: status.registered,
4819
+ online: status.online
4820
+ };
4821
+ if (status.platform !== void 0) row.platform = status.platform;
4822
+ if (status.version !== void 0) row.version = status.version;
4823
+ if (status.last_seen_at !== void 0) row.last_seen_at = status.last_seen_at;
4824
+ return row;
4825
+ } catch (error) {
4826
+ return { device: label, address, error: reason2(error) };
4827
+ }
4828
+ })
4829
+ );
4830
+ return { caller: caller.address, devices: rows };
4831
+ }
4832
+ })
4833
+ );
4834
+ ctx.tools.register(
4835
+ defineTool({
4836
+ name: `${prefix}_bash`,
4837
+ description: "Run a shell command on a REMOTE device through eXe \u2014 not on this machine and not in a sandbox. The command runs as that device's own user, with no confirmation and no undo. Prefer one command that does the whole job (`cd x && a && b`) over many small ones: every call is a round trip through the relay. Use `cwd` instead of `cd` when only the directory matters. A call that fails with `lost` may already have run on the device: check the device before retrying. This does not look at files here; read them on the device or ask for an image with the image tool.",
4838
+ parameters: {
4839
+ device: {
4840
+ type: "string",
4841
+ required: true,
4842
+ description: "Device label from the devices tool, or the device's address."
4843
+ },
4844
+ command: {
4845
+ type: "string",
4846
+ required: true,
4847
+ description: "The command line, run with `sh -c` on the device (`cmd /C` on Windows)."
4848
+ },
4849
+ cwd: { type: "string", description: "Working directory on the device." },
4850
+ timeout_seconds: {
4851
+ type: "integer",
4852
+ description: `How long the command may run before the device kills it. Defaults to ${config.defaultTimeoutSeconds}.`
4853
+ }
4854
+ },
4855
+ output: {
4856
+ schema: {
4857
+ type: "object",
4858
+ additionalProperties: false,
4859
+ properties: {
4860
+ device: { type: "string", required: true },
4861
+ command: { type: "string", required: true },
4862
+ exit_code: { type: "integer", required: true },
4863
+ stdout: { type: "string", required: true },
4864
+ stderr: { type: "string", required: true },
4865
+ truncated: { type: "boolean", required: true },
4866
+ timed_out: { type: "boolean", required: true },
4867
+ error: { type: "string" }
4868
+ }
4869
+ },
4870
+ render: (_args, value) => [{ type: "text", text: renderShell(value) }]
4871
+ },
4872
+ async execute(args, exec) {
4873
+ const caller = callerOf();
4874
+ const client = relayOf();
4875
+ const timeout = args.timeout_seconds ?? config.defaultTimeoutSeconds;
4876
+ if (!Number.isFinite(timeout) || timeout <= 0) {
4877
+ throw new Error(`timeout_seconds must be a positive number, got ${JSON.stringify(args.timeout_seconds)}`);
4878
+ }
4879
+ const call = { command: args.command };
4880
+ if (args.cwd !== void 0) call.cwd = args.cwd;
4881
+ if (args.timeout_seconds !== void 0) call.timeout_seconds = timeout;
4882
+ const outcome = await client.call({
4883
+ device: addressForDevice(caller, args.device),
4884
+ name: "shell",
4885
+ args: call,
4886
+ ttlSeconds: Math.min(timeout + 60, config.maxCallSeconds),
4887
+ signal: exec.signal
4888
+ });
4889
+ return shellAnswer(args.device, args.command, outcome);
4890
+ }
4891
+ })
4892
+ );
4893
+ ctx.tools.register(
4894
+ defineTool({
4895
+ name: `${prefix}_image`,
4896
+ description: "Read an image file on a REMOTE device through eXe and return it as an image the model can see. Useful for screenshots: take one with the shell tool, then read it here. Only png, jpeg, webp and gif arrive; a file too large for this harness must be downscaled on the device first.",
4897
+ parameters: {
4898
+ device: {
4899
+ type: "string",
4900
+ required: true,
4901
+ description: "Device label from the devices tool, or the device's address."
4902
+ },
4903
+ path: { type: "string", required: true, description: "Absolute path of a png, jpeg, webp or gif on the device." }
4904
+ },
4905
+ output: {
4906
+ schema: {
4907
+ type: "object",
4908
+ additionalProperties: false,
4909
+ properties: {
4910
+ device: { type: "string", required: true },
4911
+ path: { type: "string", required: true },
4912
+ media_type: { type: "string", required: true },
4913
+ bytes: { type: "integer", required: true },
4914
+ width: { type: "integer", required: true },
4915
+ height: { type: "integer", required: true },
4916
+ attachment: {
4917
+ type: "json",
4918
+ required: true,
4919
+ description: "The durable attachment this harness hands to the model as an image."
4920
+ }
4921
+ }
4922
+ },
4923
+ render: (_args, value) => [
4924
+ { type: "image", attachment: value.attachment },
4925
+ {
4926
+ type: "text",
4927
+ text: `[${value.device}] ${value.path} \u2014 ${value.width}\xD7${value.height}, ${value.bytes} bytes`
4928
+ }
4929
+ ]
4930
+ },
4931
+ isConcurrencySafe: () => true,
4932
+ async execute(args, exec) {
4933
+ const attachments = ctx.get("attachments");
4934
+ if (attachments === void 0) {
4935
+ throw new Error("this harness has no attachment service, so an image cannot be handed to the model");
4936
+ }
4937
+ const caller = callerOf();
4938
+ const client = relayOf();
4939
+ const outcome = await client.call({
4940
+ device: addressForDevice(caller, args.device),
4941
+ name: "shell",
4942
+ // One round trip: the device base64s the file, and a result too big for
4943
+ // one row travels whole as an attachment. `tr -d` keeps it on one line
4944
+ // so the JSON string stays valid whatever the platform's base64 does.
4945
+ args: { command: `base64 < ${shQuote(args.path)} | tr -d '\\n'`, timeout_seconds: 120 },
4946
+ ttlSeconds: Math.min(180, config.maxCallSeconds),
4947
+ signal: exec.signal
4948
+ });
4949
+ const base64 = imageBase64(args.device, args.path, outcome);
4950
+ const bytes = new Uint8Array(Buffer.from(base64, "base64"));
4951
+ const limits = attachments.imageLimits;
4952
+ if (bytes.length > limits.maxImageBytes) {
4953
+ throw new Error(
4954
+ `${args.path} is ${bytes.length} bytes, past this harness's ${limits.maxImageBytes}-byte image limit: downscale it on the device first.`
4955
+ );
4956
+ }
4957
+ const mediaType = mediaTypeOf(bytes, args.path, limits.mediaTypes);
4958
+ const ref = await attachments.saveImage({ data: bytes, mediaType, name: basename(args.path) });
4959
+ return {
4960
+ device: args.device,
4961
+ path: args.path,
4962
+ media_type: ref.mediaType,
4963
+ bytes: ref.bytes,
4964
+ width: ref.width,
4965
+ height: ref.height,
4966
+ attachment: {
4967
+ attachmentId: ref.attachmentId,
4968
+ mediaType: ref.mediaType,
4969
+ bytes: ref.bytes,
4970
+ width: ref.width,
4971
+ height: ref.height,
4972
+ ...ref.name === void 0 ? {} : { name: ref.name }
4973
+ }
4974
+ };
4975
+ }
4976
+ })
4977
+ );
4978
+ }
4979
+ export {
4980
+ Config,
4981
+ apply,
4982
+ inject,
4983
+ name
4984
+ };