blaizejs 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/chunk-337RPHG5.js +11 -0
  2. package/dist/{chunk-HB6MRTGD.js.map → chunk-337RPHG5.js.map} +1 -1
  3. package/dist/{unsupported-media-type-error-VVHRDTUH.js → chunk-HX7XLEO3.js} +3 -9
  4. package/dist/{chunk-7IM52S7P.js.map → chunk-HX7XLEO3.js.map} +1 -1
  5. package/dist/chunk-KE2IOPV4.js +11 -0
  6. package/dist/{chunk-IFP53BNM.js.map → chunk-KE2IOPV4.js.map} +1 -1
  7. package/dist/chunk-LY65OJH4.js +11 -0
  8. package/dist/{chunk-3VK325MM.js.map → chunk-LY65OJH4.js.map} +1 -1
  9. package/dist/chunk-VM3QGHVO.js +11 -0
  10. package/dist/{chunk-CQKM74J4.js.map → chunk-VM3QGHVO.js.map} +1 -1
  11. package/dist/index.cjs +38 -3486
  12. package/dist/index.cjs.map +1 -1
  13. package/dist/index.d.cts +2 -2
  14. package/dist/index.d.ts +2 -2
  15. package/dist/index.js +38 -3153
  16. package/dist/index.js.map +1 -1
  17. package/dist/{validation-error-TXMSFWZL.js → internal-server-error-JHHSKW5B.js} +3 -9
  18. package/dist/{internal-server-error-PVME2DGN.js → payload-too-large-error-SOQINKUL.js} +3 -9
  19. package/dist/{payload-too-large-error-QQG7MKGT.js → unsupported-media-type-error-KJMHH5CY.js} +3 -9
  20. package/dist/validation-error-Q6IOTN4C.js +11 -0
  21. package/package.json +6 -6
  22. package/dist/chunk-3VK325MM.js +0 -31
  23. package/dist/chunk-7IM52S7P.js +0 -31
  24. package/dist/chunk-CQKM74J4.js +0 -39
  25. package/dist/chunk-HB6MRTGD.js +0 -39
  26. package/dist/chunk-IFP53BNM.js +0 -149
  27. /package/dist/{internal-server-error-PVME2DGN.js.map → internal-server-error-JHHSKW5B.js.map} +0 -0
  28. /package/dist/{payload-too-large-error-QQG7MKGT.js.map → payload-too-large-error-SOQINKUL.js.map} +0 -0
  29. /package/dist/{unsupported-media-type-error-VVHRDTUH.js.map → unsupported-media-type-error-KJMHH5CY.js.map} +0 -0
  30. /package/dist/{validation-error-TXMSFWZL.js.map → validation-error-Q6IOTN4C.js.map} +0 -0
package/dist/index.js CHANGED
@@ -1,3172 +1,57 @@
1
1
 
2
2
  /**
3
- * blaizejs v0.3.2
3
+ * blaizejs v0.3.3
4
4
  * A blazing-fast, TypeScript-first Node.js framework with HTTP/2 support, file-based routing, powerful middleware system, and end-to-end type safety for building modern APIs.
5
5
  *
6
6
  * Copyright (c) 2025 BlaizeJS Contributors
7
7
  * @license MIT
8
8
  */
9
9
 
10
- import {
11
- InternalServerError
12
- } from "./chunk-CQKM74J4.js";
13
- import {
14
- ValidationError
15
- } from "./chunk-HB6MRTGD.js";
16
- import {
17
- PayloadTooLargeError
18
- } from "./chunk-3VK325MM.js";
19
- import {
20
- UnsupportedMediaTypeError
21
- } from "./chunk-7IM52S7P.js";
22
- import {
23
- BlaizeError,
24
- ErrorSeverity,
25
- ErrorType,
26
- __require,
27
- generateCorrelationId,
28
- getCurrentCorrelationId,
29
- isBodyParseError
30
- } from "./chunk-IFP53BNM.js";
31
-
32
- // src/middleware/execute.ts
33
- function execute(middleware, ctx, next) {
34
- if (!middleware) {
35
- return Promise.resolve(next());
36
- }
37
- if (middleware.skip && middleware.skip(ctx)) {
38
- return Promise.resolve(next());
39
- }
40
- try {
41
- const result = middleware.execute(ctx, next);
42
- if (result instanceof Promise) {
43
- return result;
44
- } else {
45
- return Promise.resolve(result);
46
- }
47
- } catch (error) {
48
- return Promise.reject(error);
49
- }
50
- }
51
-
52
- // src/middleware/compose.ts
53
- function compose(middlewareStack) {
54
- if (middlewareStack.length === 0) {
55
- return async (_, next) => {
56
- await Promise.resolve(next());
57
- };
58
- }
59
- return async function(ctx, finalHandler) {
60
- const called = /* @__PURE__ */ new Set();
61
- const dispatch = async (i) => {
62
- if (i >= middlewareStack.length) {
63
- return Promise.resolve(finalHandler());
64
- }
65
- const middleware = middlewareStack[i];
66
- const nextDispatch = () => {
67
- if (called.has(i)) {
68
- throw new Error("next() called multiple times");
69
- }
70
- called.add(i);
71
- return dispatch(i + 1);
72
- };
73
- return execute(middleware, ctx, nextDispatch);
74
- };
75
- return dispatch(0);
76
- };
77
- }
78
-
79
- // src/middleware/create.ts
80
- function create(handlerOrOptions) {
81
- if (typeof handlerOrOptions === "function") {
82
- return {
83
- name: "anonymous",
84
- // Default name for function middleware
85
- execute: handlerOrOptions,
86
- debug: false
87
- };
88
- }
89
- const { name = "anonymous", handler, skip, debug = false } = handlerOrOptions;
90
- const middleware = {
91
- name,
92
- execute: handler,
93
- debug
94
- };
95
- if (skip !== void 0) {
96
- return {
97
- ...middleware,
98
- skip
99
- };
100
- }
101
- return middleware;
102
- }
103
-
104
- // src/plugins/create.ts
105
- function create2(name, version, setup, defaultOptions = {}) {
106
- if (!name || typeof name !== "string") {
107
- throw new Error("Plugin name must be a non-empty string");
108
- }
109
- if (!version || typeof version !== "string") {
110
- throw new Error("Plugin version must be a non-empty string");
111
- }
112
- if (typeof setup !== "function") {
113
- throw new Error("Plugin setup must be a function");
114
- }
115
- return function pluginFactory(userOptions) {
116
- const mergedOptions = { ...defaultOptions, ...userOptions };
117
- const plugin = {
118
- name,
119
- version,
120
- // The register hook calls the user's setup function
121
- register: async (app) => {
122
- const result = await setup(app, mergedOptions);
123
- if (result && typeof result === "object") {
124
- Object.assign(plugin, result);
125
- }
126
- }
127
- };
128
- return plugin;
129
- };
130
- }
131
-
132
- // src/router/create.ts
133
- import { fileURLToPath } from "node:url";
134
-
135
- // src/config.ts
136
- var config = {};
137
- function setRuntimeConfig(newConfig) {
138
- config = { ...config, ...newConfig };
139
- }
140
- function getRoutesDir() {
141
- if (!config.routesDir) {
142
- throw new Error("Routes directory not configured. Make sure server is properly initialized.");
143
- }
144
- return config.routesDir;
145
- }
146
-
147
- // src/router/discovery/parser.ts
148
- import * as path from "node:path";
149
- function parseRoutePath(filePath, basePath) {
150
- if (filePath.startsWith("file://")) {
151
- filePath = filePath.replace("file://", "");
152
- }
153
- if (basePath.startsWith("file://")) {
154
- basePath = basePath.replace("file://", "");
155
- }
156
- const forwardSlashFilePath = filePath.replace(/\\/g, "/");
157
- const forwardSlashBasePath = basePath.replace(/\\/g, "/");
158
- const normalizedBasePath = forwardSlashBasePath.endsWith("/") ? forwardSlashBasePath : `${forwardSlashBasePath}/`;
159
- let relativePath = forwardSlashFilePath;
160
- if (forwardSlashFilePath.startsWith(normalizedBasePath)) {
161
- relativePath = forwardSlashFilePath.substring(normalizedBasePath.length);
162
- } else if (forwardSlashFilePath.startsWith(forwardSlashBasePath)) {
163
- relativePath = forwardSlashFilePath.substring(forwardSlashBasePath.length);
164
- if (relativePath.startsWith("/")) {
165
- relativePath = relativePath.substring(1);
166
- }
167
- } else {
168
- relativePath = path.relative(forwardSlashBasePath, forwardSlashFilePath).replace(/\\/g, "/");
169
- }
170
- relativePath = relativePath.replace(/\.[^.]+$/, "");
171
- const segments = relativePath.split("/").filter(Boolean);
172
- const params = [];
173
- const routeSegments = segments.map((segment) => {
174
- if (segment.startsWith("[") && segment.endsWith("]")) {
175
- const paramName = segment.slice(1, -1);
176
- params.push(paramName);
177
- return `:${paramName}`;
178
- }
179
- return segment;
180
- });
181
- let routePath = routeSegments.length > 0 ? `/${routeSegments.join("/")}` : "/";
182
- if (routePath.endsWith("/index")) {
183
- routePath = routePath.slice(0, -6) || "/";
184
- }
185
- return {
186
- filePath,
187
- routePath,
188
- params
189
- };
190
- }
191
-
192
- // src/router/create.ts
193
- function getCallerFilePath() {
194
- const originalPrepareStackTrace = Error.prepareStackTrace;
195
- try {
196
- Error.prepareStackTrace = (_, stack2) => stack2;
197
- const stack = new Error().stack;
198
- const callerFrame = stack[3];
199
- if (!callerFrame || typeof callerFrame.getFileName !== "function") {
200
- throw new Error("Unable to determine caller file frame");
201
- }
202
- const fileName = callerFrame.getFileName();
203
- if (!fileName) {
204
- throw new Error("Unable to determine caller file name");
205
- }
206
- if (fileName.startsWith("file://")) {
207
- return fileURLToPath(fileName);
208
- }
209
- return fileName;
210
- } finally {
211
- Error.prepareStackTrace = originalPrepareStackTrace;
212
- }
213
- }
214
- function getRoutePath() {
215
- const callerPath = getCallerFilePath();
216
- const routesDir = getRoutesDir();
217
- const parsedRoute = parseRoutePath(callerPath, routesDir);
218
- console.log(`\u{1F50E} Parsed route path: ${parsedRoute.routePath} from file: ${callerPath}`);
219
- return parsedRoute.routePath;
220
- }
221
- var createGetRoute = (config2) => {
222
- validateMethodConfig("GET", config2);
223
- const path6 = getRoutePath();
224
- return {
225
- GET: config2,
226
- // Let TypeScript infer the proper types
227
- path: path6
228
- };
229
- };
230
- var createPostRoute = (config2) => {
231
- validateMethodConfig("POST", config2);
232
- const path6 = getRoutePath();
233
- return {
234
- POST: config2,
235
- // Let TypeScript infer the proper types
236
- path: path6
237
- };
238
- };
239
- var createPutRoute = (config2) => {
240
- validateMethodConfig("PUT", config2);
241
- const path6 = getRoutePath();
242
- return {
243
- PUT: config2,
244
- // Let TypeScript infer the proper types
245
- path: path6
246
- };
247
- };
248
- var createDeleteRoute = (config2) => {
249
- validateMethodConfig("DELETE", config2);
250
- const path6 = getRoutePath();
251
- return {
252
- DELETE: config2,
253
- // Let TypeScript infer the proper types
254
- path: path6
255
- };
256
- };
257
- var createPatchRoute = (config2) => {
258
- validateMethodConfig("PATCH", config2);
259
- const path6 = getRoutePath();
260
- return {
261
- PATCH: config2,
262
- // Let TypeScript infer the proper types
263
- path: path6
264
- };
265
- };
266
- var createHeadRoute = (config2) => {
267
- validateMethodConfig("HEAD", config2);
268
- const path6 = getRoutePath();
269
- return {
270
- HEAD: config2,
271
- // Let TypeScript infer the proper types
272
- path: path6
273
- };
274
- };
275
- var createOptionsRoute = (config2) => {
276
- validateMethodConfig("OPTIONS", config2);
277
- const path6 = getRoutePath();
278
- return {
279
- OPTIONS: config2,
280
- // Let TypeScript infer the proper types
281
- path: path6
282
- };
283
- };
284
- function validateMethodConfig(method, config2) {
285
- if (!config2.handler || typeof config2.handler !== "function") {
286
- throw new Error(`Handler for method ${method} must be a function`);
287
- }
288
- if (config2.middleware && !Array.isArray(config2.middleware)) {
289
- throw new Error(`Middleware for method ${method} must be an array`);
290
- }
291
- if (config2.schema) {
292
- validateSchema(method, config2.schema);
293
- }
294
- switch (method) {
295
- case "GET":
296
- case "HEAD":
297
- case "DELETE":
298
- if (config2.schema?.body) {
299
- console.warn(`Warning: ${method} requests typically don't have request bodies`);
300
- }
301
- break;
302
- }
303
- }
304
- function validateSchema(method, schema) {
305
- const { params, query, body, response } = schema;
306
- if (params && (!params._def || typeof params.parse !== "function")) {
307
- throw new Error(`Params schema for ${method} must be a valid Zod schema`);
308
- }
309
- if (query && (!query._def || typeof query.parse !== "function")) {
310
- throw new Error(`Query schema for ${method} must be a valid Zod schema`);
311
- }
312
- if (body && (!body._def || typeof body.parse !== "function")) {
313
- throw new Error(`Body schema for ${method} must be a valid Zod schema`);
314
- }
315
- if (response && (!response._def || typeof response.parse !== "function")) {
316
- throw new Error(`Response schema for ${method} must be a valid Zod schema`);
317
- }
318
- }
319
-
320
- // src/server/create.ts
321
- import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
322
- import EventEmitter from "node:events";
323
-
324
- // src/server/start.ts
325
- import * as fs2 from "node:fs";
326
- import * as http from "node:http";
327
- import * as http2 from "node:http2";
328
-
329
- // src/server/dev-certificate.ts
330
- import * as fs from "node:fs";
331
- import * as path2 from "node:path";
332
- import * as selfsigned from "selfsigned";
333
- async function generateDevCertificates() {
334
- const certDir = path2.join(process.cwd(), ".blaizejs", "certs");
335
- const keyPath = path2.join(certDir, "dev.key");
336
- const certPath = path2.join(certDir, "dev.cert");
337
- if (fs.existsSync(keyPath) && fs.existsSync(certPath)) {
338
- return {
339
- keyFile: keyPath,
340
- certFile: certPath
341
- };
342
- }
343
- if (!fs.existsSync(certDir)) {
344
- fs.mkdirSync(certDir, { recursive: true });
345
- }
346
- const attrs = [{ name: "commonName", value: "localhost" }];
347
- const options = {
348
- days: 365,
349
- algorithm: "sha256",
350
- keySize: 2048,
351
- extensions: [
352
- { name: "basicConstraints", cA: true },
353
- {
354
- name: "keyUsage",
355
- keyCertSign: true,
356
- digitalSignature: true,
357
- nonRepudiation: true,
358
- keyEncipherment: true,
359
- dataEncipherment: true
360
- },
361
- {
362
- name: "extKeyUsage",
363
- serverAuth: true,
364
- clientAuth: true
365
- },
366
- {
367
- name: "subjectAltName",
368
- altNames: [
369
- { type: 2, value: "localhost" },
370
- { type: 7, ip: "127.0.0.1" }
371
- ]
372
- }
373
- ]
374
- };
375
- const pems = selfsigned.generate(attrs, options);
376
- fs.writeFileSync(keyPath, Buffer.from(pems.private, "utf-8"));
377
- fs.writeFileSync(certPath, Buffer.from(pems.cert, "utf-8"));
378
- console.log(`
379
- \u{1F512} Generated self-signed certificates for development at ${certDir}
380
- `);
381
- return {
382
- keyFile: keyPath,
383
- certFile: certPath
384
- };
385
- }
386
-
387
- // src/context/errors.ts
388
- var ResponseSentError = class extends Error {
389
- constructor(message = "\u274C Response has already been sent") {
390
- super(message);
391
- this.name = "ResponseSentError";
392
- }
393
- };
394
- var ResponseSentHeaderError = class extends ResponseSentError {
395
- constructor(message = "Cannot set header after response has been sent") {
396
- super(message);
397
- }
398
- };
399
- var ResponseSentContentError = class extends ResponseSentError {
400
- constructor(message = "Cannot set content type after response has been sent") {
401
- super(message);
402
- }
403
- };
404
- var ParseUrlError = class extends ResponseSentError {
405
- constructor(message = "Invalide URL") {
406
- super(message);
407
- }
408
- };
409
-
410
- // src/context/store.ts
411
- import { AsyncLocalStorage } from "node:async_hooks";
412
- var contextStorage = new AsyncLocalStorage();
413
- function runWithContext(context, callback) {
414
- return contextStorage.run(context, callback);
415
- }
416
-
417
- // src/upload/multipart-parser.ts
418
- import { randomUUID } from "node:crypto";
419
- import { createWriteStream } from "node:fs";
420
- import { tmpdir } from "node:os";
421
- import { join as join2 } from "node:path";
422
- import { Readable } from "node:stream";
423
-
424
- // src/upload/utils.ts
425
- var BOUNDARY_REGEX = /boundary=([^;]+)/i;
426
- var CONTENT_DISPOSITION_REGEX = /Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;[\s\r\n]*filename="([^"]*)")?/i;
427
- var CONTENT_TYPE_REGEX = /Content-Type:\s*([^\r\n]+)/i;
428
- var MULTIPART_REGEX = /multipart\/form-data/i;
429
- function extractBoundary(contentType) {
430
- const match = contentType.match(BOUNDARY_REGEX);
431
- if (!match || !match[1]) return null;
432
- let boundary = match[1].trim();
433
- if (boundary.startsWith('"') && boundary.endsWith('"')) {
434
- boundary = boundary.slice(1, -1);
435
- }
436
- return boundary || null;
437
- }
438
- function parseContentDisposition(headers) {
439
- const match = headers.match(CONTENT_DISPOSITION_REGEX);
440
- if (!match || !match[1]) return null;
441
- return {
442
- name: match[1],
443
- filename: match[2] !== void 0 ? match[2] : void 0
444
- };
445
- }
446
- function parseContentType(headers) {
447
- const match = headers.match(CONTENT_TYPE_REGEX);
448
- return match && match[1]?.trim() ? match[1].trim() : "application/octet-stream";
449
- }
450
- function isMultipartContent(contentType) {
451
- return MULTIPART_REGEX.test(contentType);
452
- }
453
-
454
- // src/upload/multipart-parser.ts
455
- var DEFAULT_OPTIONS = {
456
- maxFileSize: 10 * 1024 * 1024,
457
- // 10MB
458
- maxFiles: 10,
459
- maxFieldSize: 1 * 1024 * 1024,
460
- // 1MB
461
- allowedMimeTypes: [],
462
- allowedExtensions: [],
463
- strategy: "stream",
464
- tempDir: tmpdir(),
465
- computeHash: false
466
- };
467
- function createParserState(boundary, options = {}) {
468
- return {
469
- boundary: Buffer.from(`--${boundary}`),
470
- options: { ...DEFAULT_OPTIONS, ...options },
471
- fields: /* @__PURE__ */ new Map(),
472
- files: /* @__PURE__ */ new Map(),
473
- buffer: Buffer.alloc(0),
474
- stage: "boundary",
475
- currentHeaders: "",
476
- currentField: null,
477
- currentFilename: void 0,
478
- currentMimetype: "application/octet-stream",
479
- currentContentLength: 0,
480
- fileCount: 0,
481
- fieldCount: 0,
482
- currentBufferChunks: [],
483
- currentStream: null,
484
- currentTempPath: null,
485
- currentWriteStream: null,
486
- streamController: null,
487
- cleanupTasks: [],
488
- // Track validation state
489
- hasFoundValidBoundary: false,
490
- hasProcessedAnyPart: false,
491
- isFinished: false
492
- };
493
- }
494
- async function processChunk(state, chunk) {
495
- const newBuffer = Buffer.concat([state.buffer, chunk]);
496
- let currentState = { ...state, buffer: newBuffer };
497
- while (currentState.buffer.length > 0 && !currentState.isFinished) {
498
- const nextState = await processCurrentStage(currentState);
499
- if (nextState === currentState) break;
500
- currentState = nextState;
501
- }
502
- return currentState;
503
- }
504
- async function processCurrentStage(state) {
505
- switch (state.stage) {
506
- case "boundary":
507
- return processBoundary(state);
508
- case "headers":
509
- return processHeaders(state);
510
- case "content":
511
- return processContent(state);
512
- default: {
513
- const { InternalServerError: InternalServerError2 } = await import("./internal-server-error-PVME2DGN.js");
514
- throw new InternalServerError2(`Invalid parser stage`, {
515
- operation: state.stage
516
- });
517
- }
518
- }
519
- }
520
- function processBoundary(state) {
521
- const boundaryIndex = state.buffer.indexOf(state.boundary);
522
- if (boundaryIndex === -1) return state;
523
- const hasFoundValidBoundary = true;
524
- let buffer = state.buffer.subarray(boundaryIndex + state.boundary.length);
525
- if (buffer.length >= 2 && buffer.subarray(0, 2).equals(Buffer.from("--"))) {
526
- return {
527
- ...state,
528
- buffer,
529
- hasFoundValidBoundary,
530
- isFinished: true,
531
- stage: "boundary"
532
- };
533
- }
534
- if (buffer.length >= 2 && buffer.subarray(0, 2).equals(Buffer.from("\r\n"))) {
535
- buffer = buffer.subarray(2);
536
- }
537
- return {
538
- ...state,
539
- buffer,
540
- hasFoundValidBoundary,
541
- stage: "headers",
542
- currentHeaders: ""
543
- };
544
- }
545
- async function processHeaders(state) {
546
- const headerEnd = state.buffer.indexOf("\r\n\r\n");
547
- if (headerEnd === -1) return state;
548
- const headers = state.buffer.subarray(0, headerEnd).toString("utf8");
549
- const buffer = state.buffer.subarray(headerEnd + 4);
550
- const disposition = parseContentDisposition(headers);
551
- if (!disposition) {
552
- const { ValidationError: ValidationError2 } = await import("./validation-error-TXMSFWZL.js");
553
- throw new ValidationError2("Missing or invalid Content-Disposition header");
554
- }
555
- const mimetype = parseContentType(headers);
556
- const isFile = disposition.filename !== void 0;
557
- if (isFile && state.fileCount >= state.options.maxFiles) {
558
- const { PayloadTooLargeError: PayloadTooLargeError2 } = await import("./payload-too-large-error-QQG7MKGT.js");
559
- throw new PayloadTooLargeError2("Too many files in upload", {
560
- fileCount: state.fileCount + 1,
561
- maxFiles: state.options.maxFiles,
562
- filename: disposition.filename
563
- });
564
- }
565
- if (isFile && state.options.allowedMimeTypes.length > 0 && !state.options.allowedMimeTypes.includes(mimetype)) {
566
- const { UnsupportedMediaTypeError: UnsupportedMediaTypeError2 } = await import("./unsupported-media-type-error-VVHRDTUH.js");
567
- throw new UnsupportedMediaTypeError2("File type not allowed", {
568
- receivedMimeType: mimetype,
569
- allowedMimeTypes: state.options.allowedMimeTypes,
570
- filename: disposition.filename
571
- });
572
- }
573
- return {
574
- ...state,
575
- buffer,
576
- stage: "content",
577
- currentHeaders: headers,
578
- currentField: disposition.name,
579
- currentFilename: disposition.filename,
580
- currentMimetype: mimetype,
581
- currentContentLength: 0,
582
- fileCount: isFile ? state.fileCount + 1 : state.fileCount,
583
- fieldCount: isFile ? state.fieldCount : state.fieldCount + 1,
584
- currentBufferChunks: []
585
- };
586
- }
587
- async function processContent(state) {
588
- const nextBoundaryIndex = state.buffer.indexOf(state.boundary);
589
- let contentChunk;
590
- let isComplete = false;
591
- let buffer = state.buffer;
592
- if (nextBoundaryIndex === -1) {
593
- const safeLength = Math.max(0, state.buffer.length - state.boundary.length);
594
- if (safeLength === 0) return state;
595
- contentChunk = state.buffer.subarray(0, safeLength);
596
- buffer = state.buffer.subarray(safeLength);
597
- } else {
598
- const contentEnd = Math.max(0, nextBoundaryIndex - 2);
599
- contentChunk = state.buffer.subarray(0, contentEnd);
600
- buffer = state.buffer.subarray(nextBoundaryIndex);
601
- isComplete = true;
602
- }
603
- let updatedState = { ...state, buffer };
604
- if (contentChunk.length > 0) {
605
- updatedState = await processContentChunk(updatedState, contentChunk);
606
- }
607
- if (isComplete) {
608
- updatedState = await finalizeCurrentPart(updatedState);
609
- updatedState = {
610
- ...updatedState,
611
- stage: "boundary",
612
- hasProcessedAnyPart: true
613
- // Mark that we've processed at least one part
614
- };
615
- }
616
- return updatedState;
617
- }
618
- async function processContentChunk(state, chunk) {
619
- const newContentLength = state.currentContentLength + chunk.length;
620
- const maxSize = state.currentFilename !== void 0 ? state.options.maxFileSize : state.options.maxFieldSize;
621
- if (newContentLength > maxSize) {
622
- const isFile = state.currentFilename !== void 0;
623
- const { PayloadTooLargeError: PayloadTooLargeError2 } = await import("./payload-too-large-error-QQG7MKGT.js");
624
- const payloadErrorDetals = state.currentField ? {
625
- contentType: isFile ? "file" : "field",
626
- currentSize: newContentLength,
627
- maxSize,
628
- field: state.currentField,
629
- filename: state.currentFilename
630
- } : {
631
- contentType: isFile ? "file" : "field",
632
- currentSize: newContentLength,
633
- maxSize,
634
- filename: state.currentFilename
635
- };
636
- throw new PayloadTooLargeError2(
637
- `${isFile ? "File" : "Field"} size exceeds limit`,
638
- payloadErrorDetals
639
- );
640
- }
641
- if (state.currentFilename !== void 0) {
642
- return processFileChunk(state, chunk, newContentLength);
643
- } else {
644
- return {
645
- ...state,
646
- currentContentLength: newContentLength,
647
- currentBufferChunks: [...state.currentBufferChunks, chunk]
648
- };
649
- }
650
- }
651
- async function processFileChunk(state, chunk, newContentLength) {
652
- switch (state.options.strategy) {
653
- case "memory":
654
- return {
655
- ...state,
656
- currentContentLength: newContentLength,
657
- currentBufferChunks: [...state.currentBufferChunks, chunk]
658
- };
659
- case "stream":
660
- if (state.streamController) {
661
- state.streamController.enqueue(chunk);
662
- }
663
- return { ...state, currentContentLength: newContentLength };
664
- case "temp":
665
- if (state.currentWriteStream) {
666
- await writeToStream(state.currentWriteStream, chunk);
667
- }
668
- return { ...state, currentContentLength: newContentLength };
669
- default: {
670
- const { ValidationError: ValidationError2 } = await import("./validation-error-TXMSFWZL.js");
671
- throw new ValidationError2(`Invalid parsing strategy`);
672
- }
673
- }
674
- }
675
- async function initializeFileProcessing(state) {
676
- if (state.currentFilename === void 0) return state;
677
- switch (state.options.strategy) {
678
- case "memory":
679
- return { ...state, currentBufferChunks: [] };
680
- case "stream": {
681
- let streamController = null;
682
- const stream = new ReadableStream({
683
- start: (controller) => {
684
- streamController = controller;
685
- }
686
- });
687
- return {
688
- ...state,
689
- currentStream: stream,
690
- // Type cast for Node.js compatibility
691
- streamController
692
- };
693
- }
694
- case "temp": {
695
- const tempPath = join2(state.options.tempDir, `upload-${randomUUID()}`);
696
- const writeStream = createWriteStream(tempPath);
697
- const cleanupTask = async () => {
698
- try {
699
- const { unlink } = await import("node:fs/promises");
700
- await unlink(tempPath);
701
- } catch (error) {
702
- console.warn(`Failed to cleanup temp file: ${tempPath}`, error);
703
- }
704
- };
705
- return {
706
- ...state,
707
- currentTempPath: tempPath,
708
- currentWriteStream: writeStream,
709
- cleanupTasks: [...state.cleanupTasks, cleanupTask]
710
- };
711
- }
712
- default: {
713
- const { ValidationError: ValidationError2 } = await import("./validation-error-TXMSFWZL.js");
714
- throw new ValidationError2(`Invalid file processing strategy`);
715
- }
716
- }
717
- }
718
- async function finalizeCurrentPart(state) {
719
- if (!state.currentField) return resetCurrentPart(state);
720
- if (state.currentFilename !== void 0) {
721
- return finalizeFile(state);
722
- } else {
723
- return finalizeField(state);
724
- }
725
- }
726
- async function finalizeFile(state) {
727
- if (!state.currentField || state.currentFilename === void 0) {
728
- return resetCurrentPart(state);
729
- }
730
- let stream;
731
- let buffer;
732
- let tempPath;
733
- switch (state.options.strategy) {
734
- case "memory":
735
- buffer = Buffer.concat(state.currentBufferChunks);
736
- stream = Readable.from(buffer);
737
- break;
738
- case "stream":
739
- if (state.streamController) {
740
- state.streamController.close();
741
- }
742
- stream = state.currentStream;
743
- break;
744
- case "temp":
745
- if (state.currentWriteStream) {
746
- await closeStream(state.currentWriteStream);
747
- }
748
- tempPath = state.currentTempPath;
749
- stream = Readable.from(Buffer.alloc(0));
750
- break;
751
- default: {
752
- const { ValidationError: ValidationError2 } = await import("./validation-error-TXMSFWZL.js");
753
- throw new ValidationError2(`Invalid file finalization strategy`);
754
- }
755
- }
756
- const file = {
757
- filename: state.currentFilename,
758
- fieldname: state.currentField,
759
- mimetype: state.currentMimetype,
760
- size: state.currentContentLength,
761
- stream,
762
- buffer,
763
- tempPath
764
- };
765
- const updatedFiles = addToCollection(state.files, state.currentField, file);
766
- return {
767
- ...resetCurrentPart(state),
768
- files: updatedFiles
769
- };
770
- }
771
- function finalizeField(state) {
772
- if (!state.currentField) return resetCurrentPart(state);
773
- const value = Buffer.concat(state.currentBufferChunks).toString("utf8");
774
- const updatedFields = addToCollection(state.fields, state.currentField, value);
775
- return {
776
- ...resetCurrentPart(state),
777
- fields: updatedFields
778
- };
779
- }
780
- function resetCurrentPart(state) {
781
- return {
782
- ...state,
783
- currentField: null,
784
- currentFilename: void 0,
785
- currentContentLength: 0,
786
- currentBufferChunks: [],
787
- currentStream: null,
788
- streamController: null,
789
- currentTempPath: null,
790
- currentWriteStream: null
791
- };
792
- }
793
- function addToCollection(collection, key, value) {
794
- const newCollection = new Map(collection);
795
- const existing = newCollection.get(key) || [];
796
- newCollection.set(key, [...existing, value]);
797
- return newCollection;
798
- }
799
- async function finalize(state) {
800
- if (!state.hasFoundValidBoundary) {
801
- const { ValidationError: ValidationError2 } = await import("./validation-error-TXMSFWZL.js");
802
- throw new ValidationError2("No valid multipart boundary found");
803
- }
804
- if (state.hasFoundValidBoundary && !state.hasProcessedAnyPart) {
805
- const { ValidationError: ValidationError2 } = await import("./validation-error-TXMSFWZL.js");
806
- throw new ValidationError2("Empty multipart request");
807
- }
808
- const fields = {};
809
- for (const [key, values] of state.fields.entries()) {
810
- fields[key] = values.length === 1 ? values[0] : values;
811
- }
812
- const files = {};
813
- for (const [key, fileList] of state.files.entries()) {
814
- files[key] = fileList.length === 1 ? fileList[0] : fileList;
815
- }
816
- return { fields, files };
817
- }
818
- async function cleanup(state) {
819
- await Promise.allSettled(state.cleanupTasks.map((task) => task()));
820
- if (state.streamController) {
821
- state.streamController.close();
822
- }
823
- if (state.currentWriteStream) {
824
- await closeStream(state.currentWriteStream);
825
- }
826
- }
827
- async function writeToStream(stream, chunk) {
828
- return new Promise((resolve3, reject) => {
829
- stream.write(chunk, (error) => {
830
- if (error) reject(error);
831
- else resolve3();
832
- });
833
- });
834
- }
835
- async function closeStream(stream) {
836
- return new Promise((resolve3) => {
837
- stream.end(() => resolve3());
838
- });
839
- }
840
- async function parseMultipartRequest(request, options = {}) {
841
- const contentType = request.headers["content-type"] || "";
842
- const boundary = extractBoundary(contentType);
843
- if (!boundary) {
844
- const { UnsupportedMediaTypeError: UnsupportedMediaTypeError2 } = await import("./unsupported-media-type-error-VVHRDTUH.js");
845
- throw new UnsupportedMediaTypeError2("Missing boundary in multipart content-type", {
846
- receivedContentType: contentType,
847
- expectedFormat: "multipart/form-data; boundary=..."
848
- });
849
- }
850
- let state = createParserState(boundary, options);
851
- if (state.currentFilename !== void 0) {
852
- state = await initializeFileProcessing(state);
853
- }
854
- try {
855
- for await (const chunk of request) {
856
- state = await processChunk(state, chunk);
857
- }
858
- return finalize(state);
859
- } finally {
860
- await cleanup(state);
861
- }
862
- }
863
-
864
- // src/context/create.ts
865
- var CONTENT_TYPE_HEADER = "Content-Type";
866
- var DEFAULT_BODY_LIMITS = {
867
- json: 512 * 1024,
868
- // 512KB - Most APIs should be much smaller
869
- form: 1024 * 1024,
870
- // 1MB - Reasonable for form submissions
871
- text: 5 * 1024 * 1024,
872
- // 5MB - Documents, logs, code files
873
- multipart: {
874
- maxFileSize: 50 * 1024 * 1024,
875
- // 50MB per file
876
- maxTotalSize: 100 * 1024 * 1024,
877
- // 100MB total request
878
- maxFiles: 10,
879
- maxFieldSize: 1024 * 1024
880
- // 1MB for form fields
881
- },
882
- raw: 10 * 1024 * 1024
883
- // 10MB for unknown content types
884
- };
885
- function parseRequestUrl(req) {
886
- const originalUrl = req.url || "/";
887
- const host = req.headers.host || "localhost";
888
- const protocol = req.socket && req.socket.encrypted ? "https" : "http";
889
- const fullUrl = `${protocol}://${host}${originalUrl.startsWith("/") ? "" : "/"}${originalUrl}`;
890
- try {
891
- const url = new URL(fullUrl);
892
- const path6 = url.pathname;
893
- const query = {};
894
- url.searchParams.forEach((value, key) => {
895
- if (query[key] !== void 0) {
896
- if (Array.isArray(query[key])) {
897
- query[key].push(value);
898
- } else {
899
- query[key] = [query[key], value];
900
- }
901
- } else {
902
- query[key] = value;
903
- }
904
- });
905
- return { path: path6, url, query };
906
- } catch (error) {
907
- console.warn(`Invalid URL: ${fullUrl}`, error);
908
- throw new ParseUrlError(`Invalid URL: ${fullUrl}`);
909
- }
910
- }
911
- function isHttp2Request(req) {
912
- return "stream" in req || "httpVersionMajor" in req && req.httpVersionMajor === 2;
913
- }
914
- function getProtocol(req) {
915
- const encrypted = req.socket && req.socket.encrypted;
916
- const forwardedProto = req.headers["x-forwarded-proto"];
917
- if (forwardedProto) {
918
- if (Array.isArray(forwardedProto)) {
919
- return forwardedProto[0]?.split(",")[0]?.trim() || "http";
920
- } else {
921
- return forwardedProto.split(",")[0]?.trim() || "http";
922
- }
923
- }
924
- return encrypted ? "https" : "http";
925
- }
926
- async function createContext(req, res, options = {}) {
927
- const { path: path6, url, query } = parseRequestUrl(req);
928
- const method = req.method || "GET";
929
- const isHttp2 = isHttp2Request(req);
930
- const protocol = getProtocol(req);
931
- const params = {};
932
- const state = { ...options.initialState || {} };
933
- const responseState = { sent: false };
934
- const ctx = {
935
- request: createRequestObject(req, {
936
- path: path6,
937
- url,
938
- query,
939
- params,
940
- method,
941
- isHttp2,
942
- protocol
943
- }),
944
- response: {},
945
- state
946
- };
947
- ctx.response = createResponseObject(res, responseState, ctx);
948
- if (options.parseBody) {
949
- await parseBodyIfNeeded(req, ctx, options);
950
- }
951
- return ctx;
952
- }
953
- function createRequestObject(req, info) {
954
- return {
955
- raw: req,
956
- ...info,
957
- header: createRequestHeaderGetter(req),
958
- headers: createRequestHeadersGetter(req),
959
- body: void 0
960
- };
961
- }
962
- function createRequestHeaderGetter(req) {
963
- return (name) => {
964
- const value = req.headers[name.toLowerCase()];
965
- if (Array.isArray(value)) {
966
- return value.join(", ");
967
- }
968
- return value || void 0;
969
- };
970
- }
971
- function createRequestHeadersGetter(req) {
972
- const headerGetter = createRequestHeaderGetter(req);
973
- return (names) => {
974
- if (names && Array.isArray(names) && names.length > 0) {
975
- return names.reduce((acc, name) => {
976
- acc[name] = headerGetter(name);
977
- return acc;
978
- }, {});
979
- } else {
980
- return Object.entries(req.headers).reduce(
981
- (acc, [key, value]) => {
982
- acc[key] = Array.isArray(value) ? value.join(", ") : value || void 0;
983
- return acc;
984
- },
985
- {}
986
- );
987
- }
988
- };
989
- }
990
- function createResponseObject(res, responseState, ctx) {
991
- return {
992
- raw: res,
993
- get sent() {
994
- return responseState.sent;
995
- },
996
- status: createStatusSetter(res, responseState, ctx),
997
- header: createHeaderSetter(res, responseState, ctx),
998
- headers: createHeadersSetter(res, responseState, ctx),
999
- type: createContentTypeSetter(res, responseState, ctx),
1000
- json: createJsonResponder(res, responseState),
1001
- text: createTextResponder(res, responseState),
1002
- html: createHtmlResponder(res, responseState),
1003
- redirect: createRedirectResponder(res, responseState),
1004
- stream: createStreamResponder(res, responseState)
1005
- };
1006
- }
1007
- function createStatusSetter(res, responseState, ctx) {
1008
- return function statusSetter(code) {
1009
- if (responseState.sent) {
1010
- throw new ResponseSentError();
1011
- }
1012
- res.statusCode = code;
1013
- return ctx.response;
1014
- };
1015
- }
1016
- function createHeaderSetter(res, responseState, ctx) {
1017
- return function headerSetter(name, value) {
1018
- if (responseState.sent) {
1019
- throw new ResponseSentHeaderError();
1020
- }
1021
- res.setHeader(name, value);
1022
- return ctx.response;
1023
- };
1024
- }
1025
- function createHeadersSetter(res, responseState, ctx) {
1026
- return function headersSetter(headers) {
1027
- if (responseState.sent) {
1028
- throw new ResponseSentHeaderError();
1029
- }
1030
- for (const [name, value] of Object.entries(headers)) {
1031
- res.setHeader(name, value);
1032
- }
1033
- return ctx.response;
1034
- };
1035
- }
1036
- function createContentTypeSetter(res, responseState, ctx) {
1037
- return function typeSetter(type) {
1038
- if (responseState.sent) {
1039
- throw new ResponseSentContentError();
1040
- }
1041
- res.setHeader(CONTENT_TYPE_HEADER, type);
1042
- return ctx.response;
1043
- };
1044
- }
1045
- function createJsonResponder(res, responseState) {
1046
- return function jsonResponder(body, status) {
1047
- if (responseState.sent) {
1048
- throw new ResponseSentError();
1049
- }
1050
- if (status !== void 0) {
1051
- res.statusCode = status;
1052
- }
1053
- res.setHeader(CONTENT_TYPE_HEADER, "application/json");
1054
- res.end(JSON.stringify(body));
1055
- responseState.sent = true;
1056
- };
1057
- }
1058
- function createTextResponder(res, responseState) {
1059
- return function textResponder(body, status) {
1060
- if (responseState.sent) {
1061
- throw new ResponseSentError();
1062
- }
1063
- if (status !== void 0) {
1064
- res.statusCode = status;
1065
- }
1066
- res.setHeader(CONTENT_TYPE_HEADER, "text/plain");
1067
- res.end(body);
1068
- responseState.sent = true;
1069
- };
1070
- }
1071
- function createHtmlResponder(res, responseState) {
1072
- return function htmlResponder(body, status) {
1073
- if (responseState.sent) {
1074
- throw new ResponseSentError();
1075
- }
1076
- if (status !== void 0) {
1077
- res.statusCode = status;
1078
- }
1079
- res.setHeader(CONTENT_TYPE_HEADER, "text/html");
1080
- res.end(body);
1081
- responseState.sent = true;
1082
- };
1083
- }
1084
- function createRedirectResponder(res, responseState) {
1085
- return function redirectResponder(url, status = 302) {
1086
- if (responseState.sent) {
1087
- throw new ResponseSentError();
1088
- }
1089
- res.statusCode = status;
1090
- res.setHeader("Location", url);
1091
- res.end();
1092
- responseState.sent = true;
1093
- };
1094
- }
1095
- function createStreamResponder(res, responseState) {
1096
- return function streamResponder(readable, options = {}) {
1097
- if (responseState.sent) {
1098
- throw new ResponseSentError();
1099
- }
1100
- if (options.status !== void 0) {
1101
- res.statusCode = options.status;
1102
- }
1103
- if (options.contentType) {
1104
- res.setHeader(CONTENT_TYPE_HEADER, options.contentType);
1105
- }
1106
- if (options.headers) {
1107
- for (const [name, value] of Object.entries(options.headers)) {
1108
- res.setHeader(name, value);
1109
- }
1110
- }
1111
- readable.pipe(res);
1112
- readable.on("end", () => {
1113
- responseState.sent = true;
1114
- });
1115
- readable.on("error", (err) => {
1116
- console.error("Stream error:", err);
1117
- if (!responseState.sent) {
1118
- res.statusCode = 500;
1119
- res.end("Stream error");
1120
- responseState.sent = true;
1121
- }
1122
- });
1123
- };
1124
- }
1125
- async function parseBodyIfNeeded(req, ctx, options = {}) {
1126
- if (shouldSkipParsing(req.method)) {
1127
- return;
1128
- }
1129
- const contentType = req.headers["content-type"] || "";
1130
- const contentLength = parseInt(req.headers["content-length"] || "0", 10);
1131
- if (contentLength === 0) {
1132
- return;
1133
- }
1134
- const limits = {
1135
- json: options.bodyLimits?.json ?? DEFAULT_BODY_LIMITS.json,
1136
- form: options.bodyLimits?.form ?? DEFAULT_BODY_LIMITS.form,
1137
- text: options.bodyLimits?.text ?? DEFAULT_BODY_LIMITS.text,
1138
- raw: options.bodyLimits?.raw ?? DEFAULT_BODY_LIMITS.raw,
1139
- multipart: {
1140
- maxFileSize: options.bodyLimits?.multipart?.maxFileSize ?? DEFAULT_BODY_LIMITS.multipart.maxFileSize,
1141
- maxFiles: options.bodyLimits?.multipart?.maxFiles ?? DEFAULT_BODY_LIMITS.multipart.maxFiles,
1142
- maxFieldSize: options.bodyLimits?.multipart?.maxFieldSize ?? DEFAULT_BODY_LIMITS.multipart.maxFieldSize,
1143
- maxTotalSize: options.bodyLimits?.multipart?.maxTotalSize ?? DEFAULT_BODY_LIMITS.multipart.maxTotalSize
1144
- }
1145
- };
1146
- try {
1147
- if (contentType.includes("application/json")) {
1148
- if (contentLength > limits.json) {
1149
- throw new Error(`JSON body too large: ${contentLength} > ${limits.json} bytes`);
1150
- }
1151
- await parseJsonBody(req, ctx);
1152
- } else if (contentType.includes("application/x-www-form-urlencoded")) {
1153
- if (contentLength > limits.form) {
1154
- throw new Error(`Form body too large: ${contentLength} > ${limits.form} bytes`);
1155
- }
1156
- await parseFormUrlEncodedBody(req, ctx);
1157
- } else if (contentType.includes("text/")) {
1158
- if (contentLength > limits.text) {
1159
- throw new Error(`Text body too large: ${contentLength} > ${limits.text} bytes`);
1160
- }
1161
- await parseTextBody(req, ctx);
1162
- } else if (isMultipartContent(contentType)) {
1163
- await parseMultipartBody(req, ctx, limits.multipart);
1164
- } else {
1165
- if (contentLength > limits.raw) {
1166
- throw new Error(`Request body too large: ${contentLength} > ${limits.raw} bytes`);
1167
- }
1168
- return;
1169
- }
1170
- } catch (error) {
1171
- const errorType = contentType.includes("multipart") ? "multipart_parse_error" : "body_read_error";
1172
- setBodyError(ctx, errorType, "Error reading request body", error);
1173
- }
1174
- }
1175
- function shouldSkipParsing(method) {
1176
- const skipMethods = ["GET", "HEAD", "OPTIONS"];
1177
- return skipMethods.includes(method || "GET");
1178
- }
1179
- async function parseJsonBody(req, ctx) {
1180
- const body = await readRequestBody(req);
1181
- if (!body) {
1182
- console.warn("Empty body, skipping JSON parsing");
1183
- return;
1184
- }
1185
- if (body.trim() === "null") {
1186
- console.warn('Body is the string "null"');
1187
- ctx.request.body = null;
1188
- return;
1189
- }
1190
- try {
1191
- const json = JSON.parse(body);
1192
- ctx.request.body = json;
1193
- } catch (error) {
1194
- ctx.request.body = null;
1195
- setBodyError(ctx, "json_parse_error", "Invalid JSON in request body", error);
1196
- }
1197
- }
1198
- async function parseFormUrlEncodedBody(req, ctx) {
1199
- const body = await readRequestBody(req);
1200
- if (!body) return;
1201
- try {
1202
- ctx.request.body = parseUrlEncodedData(body);
1203
- } catch (error) {
1204
- ctx.request.body = null;
1205
- setBodyError(ctx, "form_parse_error", "Invalid form data in request body", error);
1206
- }
1207
- }
1208
- function parseUrlEncodedData(body) {
1209
- const params = new URLSearchParams(body);
1210
- const formData = {};
1211
- params.forEach((value, key) => {
1212
- if (formData[key] !== void 0) {
1213
- if (Array.isArray(formData[key])) {
1214
- formData[key].push(value);
1215
- } else {
1216
- formData[key] = [formData[key], value];
1217
- }
1218
- } else {
1219
- formData[key] = value;
1220
- }
1221
- });
1222
- return formData;
1223
- }
1224
- async function parseTextBody(req, ctx) {
1225
- const body = await readRequestBody(req);
1226
- if (body) {
1227
- ctx.request.body = body;
1228
- }
1229
- }
1230
- async function parseMultipartBody(req, ctx, multipartLimits) {
1231
- try {
1232
- const limits = multipartLimits || DEFAULT_BODY_LIMITS.multipart;
1233
- const multipartData = await parseMultipartRequest(req, {
1234
- strategy: "stream",
1235
- maxFileSize: limits.maxFileSize,
1236
- maxFiles: limits.maxFiles,
1237
- maxFieldSize: limits.maxFieldSize
1238
- // Could add total size validation here
1239
- });
1240
- ctx.request.multipart = multipartData;
1241
- ctx.request.files = multipartData.files;
1242
- ctx.request.body = multipartData.fields;
1243
- } catch (error) {
1244
- ctx.request.body = null;
1245
- setBodyError(ctx, "multipart_parse_error", "Failed to parse multipart data", error);
1246
- }
1247
- }
1248
- function setBodyError(ctx, type, message, error) {
1249
- const bodyError = { type, message, error };
1250
- ctx.state._bodyError = bodyError;
1251
- }
1252
- async function readRequestBody(req) {
1253
- return new Promise((resolve3, reject) => {
1254
- const chunks = [];
1255
- req.on("data", (chunk) => {
1256
- chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
1257
- });
1258
- req.on("end", () => {
1259
- resolve3(Buffer.concat(chunks).toString("utf8"));
1260
- });
1261
- req.on("error", (err) => {
1262
- reject(err);
1263
- });
1264
- });
1265
- }
1266
-
1267
- // src/errors/not-found-error.ts
1268
- var NotFoundError = class extends BlaizeError {
1269
- /**
1270
- * Creates a new NotFoundError instance
1271
- *
1272
- * @param title - Human-readable error message
1273
- * @param details - Optional context about the missing resource
1274
- * @param correlationId - Optional correlation ID (uses current context if not provided)
1275
- */
1276
- constructor(title, details = void 0, correlationId = void 0) {
1277
- super(
1278
- "NOT_FOUND" /* NOT_FOUND */,
1279
- title,
1280
- 404,
1281
- // HTTP 404 Not Found
1282
- correlationId ?? getCurrentCorrelationId(),
1283
- details
1284
- );
1285
- }
1286
- };
1287
-
1288
- // src/errors/boundary.ts
1289
- function isHandledError(error) {
1290
- return error instanceof BlaizeError;
1291
- }
1292
- function formatErrorResponse(error) {
1293
- if (isHandledError(error)) {
1294
- return {
1295
- type: error.type,
1296
- title: error.title,
1297
- status: error.status,
1298
- correlationId: error.correlationId,
1299
- timestamp: error.timestamp.toISOString(),
1300
- details: error.details
1301
- };
1302
- }
1303
- const correlationId = generateCorrelationId();
1304
- let originalMessage;
1305
- if (error instanceof Error) {
1306
- originalMessage = error.message;
1307
- } else if (error === null || error === void 0) {
1308
- originalMessage = "Unknown error occurred";
1309
- } else {
1310
- originalMessage = String(error);
1311
- }
1312
- const wrappedError = new InternalServerError(
1313
- "Internal Server Error",
1314
- { originalMessage },
1315
- correlationId
1316
- );
1317
- return {
1318
- type: wrappedError.type,
1319
- title: wrappedError.title,
1320
- status: wrappedError.status,
1321
- correlationId: wrappedError.correlationId,
1322
- timestamp: wrappedError.timestamp.toISOString(),
1323
- details: wrappedError.details
1324
- };
1325
- }
1326
- function extractOrGenerateCorrelationId(headerGetter) {
1327
- return headerGetter("x-correlation-id") ?? generateCorrelationId();
1328
- }
1329
- function setErrorResponseHeaders(headerSetter, correlationId) {
1330
- headerSetter("x-correlation-id", correlationId);
1331
- }
1332
-
1333
- // src/middleware/error-boundary.ts
1334
- function createErrorBoundary(options = {}) {
1335
- const { debug = false } = options;
1336
- const middlewareFn = async (ctx, next) => {
1337
- try {
1338
- await next();
1339
- } catch (error) {
1340
- if (ctx.response.sent) {
1341
- if (debug) {
1342
- console.error("Error occurred after response was sent:", error);
1343
- }
1344
- return;
1345
- }
1346
- if (debug) {
1347
- console.error("Error boundary caught error:", error);
1348
- }
1349
- const correlationId = extractOrGenerateCorrelationId(ctx.request.header);
1350
- const errorResponse = formatErrorResponse(error);
1351
- errorResponse.correlationId = correlationId;
1352
- setErrorResponseHeaders(ctx.response.header, correlationId);
1353
- ctx.response.status(errorResponse.status).json(errorResponse);
1354
- }
1355
- };
1356
- return {
1357
- name: "ErrorBoundary",
1358
- execute: middlewareFn,
1359
- debug
1360
- };
1361
- }
1362
-
1363
- // src/server/request-handler.ts
1364
- function createRequestHandler(serverInstance) {
1365
- return async (req, res) => {
1366
- try {
1367
- const context = await createContext(req, res, {
1368
- parseBody: true
1369
- // Enable automatic body parsing
1370
- });
1371
- const errorBoundary = createErrorBoundary();
1372
- const allMiddleware = [errorBoundary, ...serverInstance.middleware];
1373
- const handler = compose(allMiddleware);
1374
- await runWithContext(context, async () => {
1375
- await handler(context, async () => {
1376
- if (!context.response.sent) {
1377
- await serverInstance.router.handleRequest(context);
1378
- if (!context.response.sent) {
1379
- throw new NotFoundError(
1380
- `Route not found: ${context.request.method} ${context.request.path}`
1381
- );
1382
- }
1383
- }
1384
- });
1385
- });
1386
- } catch (error) {
1387
- console.error("Error creating context:", error);
1388
- res.writeHead(500, { "Content-Type": "application/json" });
1389
- res.end(
1390
- JSON.stringify({
1391
- error: "Internal Server Error",
1392
- message: "Failed to process request"
1393
- })
1394
- );
1395
- }
1396
- };
1397
- }
1398
-
1399
- // src/server/start.ts
1400
- async function prepareCertificates(http2Options) {
1401
- if (!http2Options.enabled) {
1402
- return {};
1403
- }
1404
- const { keyFile, certFile } = http2Options;
1405
- const isDevMode = process.env.NODE_ENV === "development";
1406
- const certificatesMissing = !keyFile || !certFile;
1407
- if (certificatesMissing && isDevMode) {
1408
- const devCerts = await generateDevCertificates();
1409
- return devCerts;
1410
- }
1411
- if (certificatesMissing) {
1412
- throw new Error(
1413
- "HTTP/2 requires SSL certificates. Provide keyFile and certFile in http2 options. In development, set NODE_ENV=development to generate them automatically."
1414
- );
1415
- }
1416
- return { keyFile, certFile };
1417
- }
1418
- function createServerInstance(isHttp2, certOptions) {
1419
- if (!isHttp2) {
1420
- return http.createServer();
1421
- }
1422
- const http2ServerOptions = {
1423
- allowHTTP1: true
1424
- // Allow fallback to HTTP/1.1
1425
- };
1426
- try {
1427
- if (certOptions.keyFile) {
1428
- http2ServerOptions.key = fs2.readFileSync(certOptions.keyFile);
1429
- }
1430
- if (certOptions.certFile) {
1431
- http2ServerOptions.cert = fs2.readFileSync(certOptions.certFile);
1432
- }
1433
- } catch (err) {
1434
- throw new Error(
1435
- `Failed to read certificate files: ${err instanceof Error ? err.message : String(err)}`
1436
- );
1437
- }
1438
- return http2.createSecureServer(http2ServerOptions);
1439
- }
1440
- function listenOnPort(server, port, host, isHttp2) {
1441
- return new Promise((resolve3, reject) => {
1442
- server.listen(port, host, () => {
1443
- const protocol = isHttp2 ? "https" : "http";
1444
- const url = `${protocol}://${host}:${port}`;
1445
- console.log(`
10
+ import{a as Ar}from"./chunk-VM3QGHVO.js";import{a as Br}from"./chunk-337RPHG5.js";import{a as El}from"./chunk-LY65OJH4.js";import{a as xl}from"./chunk-HX7XLEO3.js";import{a as Dt,b as H,c as Cl,d as jt,e as Fh,f as Ge,g as Oh,h as ja,i as Xe}from"./chunk-KE2IOPV4.js";var W=H((Yh,Wi)=>{"use strict";Wi.exports={options:{usePureJavaScript:!1}}});var Yi=H((Xh,$i)=>{"use strict";var Xa={};$i.exports=Xa;var ji={};Xa.encode=function(e,t,a){if(typeof t!="string")throw new TypeError('"alphabet" must be a string.');if(a!==void 0&&typeof a!="number")throw new TypeError('"maxline" must be a number.');var r="";if(!(e instanceof Uint8Array))r=Il(e,t);else{var n=0,i=t.length,s=t.charAt(0),o=[0];for(n=0;n<e.length;++n){for(var u=0,l=e[n];u<o.length;++u)l+=o[u]<<8,o[u]=l%i,l=l/i|0;for(;l>0;)o.push(l%i),l=l/i|0}for(n=0;e[n]===0&&n<e.length-1;++n)r+=s;for(n=o.length-1;n>=0;--n)r+=t[o[n]]}if(a){var f=new RegExp(".{1,"+a+"}","g");r=r.match(f).join(`\r
11
+ `)}return r};Xa.decode=function(e,t){if(typeof e!="string")throw new TypeError('"input" must be a string.');if(typeof t!="string")throw new TypeError('"alphabet" must be a string.');var a=ji[t];if(!a){a=ji[t]=[];for(var r=0;r<t.length;++r)a[t.charCodeAt(r)]=r}e=e.replace(/\s/g,"");for(var n=t.length,i=t.charAt(0),s=[0],r=0;r<e.length;r++){var o=a[e.charCodeAt(r)];if(o===void 0)return;for(var u=0,l=o;u<s.length;++u)l+=s[u]*n,s[u]=l&255,l>>=8;for(;l>0;)s.push(l&255),l>>=8}for(var f=0;e[f]===i&&f<e.length-1;++f)s.push(0);return typeof Buffer<"u"?Buffer.from(s.reverse()):new Uint8Array(s.reverse())};function Il(e,t){var a=0,r=t.length,n=t.charAt(0),i=[0];for(a=0;a<e.length();++a){for(var s=0,o=e.at(a);s<i.length;++s)o+=i[s]<<8,i[s]=o%r,o=o/r|0;for(;o>0;)i.push(o%r),o=o/r|0}var u="";for(a=0;e.at(a)===0&&a<e.length()-1;++a)u+=n;for(a=i.length-1;a>=0;--a)u+=t[i[a]];return u}});var re=H((Zh,es)=>{"use strict";var Xi=W(),Zi=Yi(),S=es.exports=Xi.util=Xi.util||{};(function(){if(typeof process<"u"&&process.nextTick&&!process.browser){S.nextTick=process.nextTick,typeof setImmediate=="function"?S.setImmediate=setImmediate:S.setImmediate=S.nextTick;return}if(typeof setImmediate=="function"){S.setImmediate=function(){return setImmediate.apply(void 0,arguments)},S.nextTick=function(o){return setImmediate(o)};return}if(S.setImmediate=function(o){setTimeout(o,0)},typeof window<"u"&&typeof window.postMessage=="function"){let o=function(u){if(u.source===window&&u.data===e){u.stopPropagation();var l=t.slice();t.length=0,l.forEach(function(f){f()})}};var s=o,e="forge.setImmediate",t=[];S.setImmediate=function(u){t.push(u),t.length===1&&window.postMessage(e,"*")},window.addEventListener("message",o,!0)}if(typeof MutationObserver<"u"){var a=Date.now(),r=!0,n=document.createElement("div"),t=[];new MutationObserver(function(){var u=t.slice();t.length=0,u.forEach(function(l){l()})}).observe(n,{attributes:!0});var i=S.setImmediate;S.setImmediate=function(u){Date.now()-a>15?(a=Date.now(),i(u)):(t.push(u),t.length===1&&n.setAttribute("a",r=!r))}}S.nextTick=S.setImmediate})();S.isNodejs=typeof process<"u"&&process.versions&&process.versions.node;S.globalScope=function(){return S.isNodejs?global:typeof self>"u"?window:self}();S.isArray=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};S.isArrayBuffer=function(e){return typeof ArrayBuffer<"u"&&e instanceof ArrayBuffer};S.isArrayBufferView=function(e){return e&&S.isArrayBuffer(e.buffer)&&e.byteLength!==void 0};function Rr(e){if(!(e===8||e===16||e===24||e===32))throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}S.ByteBuffer=Za;function Za(e){if(this.data="",this.read=0,typeof e=="string")this.data=e;else if(S.isArrayBuffer(e)||S.isArrayBufferView(e))if(typeof Buffer<"u"&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch{for(var a=0;a<t.length;++a)this.putByte(t[a])}}else(e instanceof Za||typeof e=="object"&&typeof e.data=="string"&&typeof e.read=="number")&&(this.data=e.data,this.read=e.read);this._constructedStringLength=0}S.ByteStringBuffer=Za;var wl=4096;S.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>wl&&(this.data.substr(0,1),this._constructedStringLength=0)};S.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read};S.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0};S.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))};S.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var a=this.data;t>0;)t&1&&(a+=e),t>>>=1,t>0&&(e+=e);return this.data=a,this._optimizeConstructedString(t),this};S.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this};S.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(S.encodeUtf8(e))};S.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};S.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};S.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255))};S.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255))};S.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))};S.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(e&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))};S.ByteStringBuffer.prototype.putInt=function(e,t){Rr(t);var a="";do t-=8,a+=String.fromCharCode(e>>t&255);while(t>0);return this.putBytes(a)};S.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<<t-1),this.putInt(e,t)};S.ByteStringBuffer.prototype.putBuffer=function(e){return this.putBytes(e.getBytes())};S.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)};S.ByteStringBuffer.prototype.getInt16=function(){var e=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,e};S.ByteStringBuffer.prototype.getInt24=function(){var e=this.data.charCodeAt(this.read)<<16^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2);return this.read+=3,e};S.ByteStringBuffer.prototype.getInt32=function(){var e=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,e};S.ByteStringBuffer.prototype.getInt16Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,e};S.ByteStringBuffer.prototype.getInt24Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16;return this.read+=3,e};S.ByteStringBuffer.prototype.getInt32Le=function(){var e=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16^this.data.charCodeAt(this.read+3)<<24;return this.read+=4,e};S.ByteStringBuffer.prototype.getInt=function(e){Rr(e);var t=0;do t=(t<<8)+this.data.charCodeAt(this.read++),e-=8;while(e>0);return t};S.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),a=2<<e-2;return t>=a&&(t-=a<<1),t};S.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):e===0?t="":(t=this.read===0?this.data:this.data.slice(this.read),this.clear()),t};S.ByteStringBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};S.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)};S.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this};S.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)};S.ByteStringBuffer.prototype.copy=function(){var e=S.createBuffer(this.data);return e.read=this.read,e};S.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this};S.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this};S.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this};S.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t<this.data.length;++t){var a=this.data.charCodeAt(t);a<16&&(e+="0"),e+=a.toString(16)}return e};S.ByteStringBuffer.prototype.toString=function(){return S.decodeUtf8(this.bytes())};function Al(e,t){t=t||{},this.read=t.readOffset||0,this.growSize=t.growSize||1024;var a=S.isArrayBuffer(e),r=S.isArrayBufferView(e);if(a||r){a?this.data=new DataView(e):this.data=new DataView(e.buffer,e.byteOffset,e.byteLength),this.write="writeOffset"in t?t.writeOffset:this.data.byteLength;return}this.data=new DataView(new ArrayBuffer(0)),this.write=0,e!=null&&this.putBytes(e),"writeOffset"in t&&(this.write=t.writeOffset)}S.DataBuffer=Al;S.DataBuffer.prototype.length=function(){return this.write-this.read};S.DataBuffer.prototype.isEmpty=function(){return this.length()<=0};S.DataBuffer.prototype.accommodate=function(e,t){if(this.length()>=e)return this;t=Math.max(t||this.growSize,e);var a=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),r=new Uint8Array(this.length()+t);return r.set(a),this.data=new DataView(r.buffer),this};S.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this};S.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var a=0;a<t;++a)this.data.setUint8(e);return this};S.DataBuffer.prototype.putBytes=function(e,t){if(S.isArrayBufferView(e)){var a=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=a.byteLength-a.byteOffset;this.accommodate(r);var n=new Uint8Array(this.data.buffer,this.write);return n.set(a),this.write+=r,this}if(S.isArrayBuffer(e)){var a=new Uint8Array(e);this.accommodate(a.byteLength);var n=new Uint8Array(this.data.buffer);return n.set(a,this.write),this.write+=a.byteLength,this}if(e instanceof S.DataBuffer||typeof e=="object"&&typeof e.read=="number"&&typeof e.write=="number"&&S.isArrayBufferView(e.data)){var a=new Uint8Array(e.data.byteLength,e.read,e.length());this.accommodate(a.byteLength);var n=new Uint8Array(e.data.byteLength,this.write);return n.set(a),this.write+=a.byteLength,this}if(e instanceof S.ByteStringBuffer&&(e=e.data,t="binary"),t=t||"binary",typeof e=="string"){var i;if(t==="hex")return this.accommodate(Math.ceil(e.length/2)),i=new Uint8Array(this.data.buffer,this.write),this.write+=S.binary.hex.decode(e,i,this.write),this;if(t==="base64")return this.accommodate(Math.ceil(e.length/4)*3),i=new Uint8Array(this.data.buffer,this.write),this.write+=S.binary.base64.decode(e,i,this.write),this;if(t==="utf8"&&(e=S.encodeUtf8(e),t="binary"),t==="binary"||t==="raw")return this.accommodate(e.length),i=new Uint8Array(this.data.buffer,this.write),this.write+=S.binary.raw.decode(i),this;if(t==="utf16")return this.accommodate(e.length*2),i=new Uint16Array(this.data.buffer,this.write),this.write+=S.text.utf16.encode(i),this;throw new Error("Invalid encoding: "+t)}throw Error("Invalid parameter: "+e)};S.DataBuffer.prototype.putBuffer=function(e){return this.putBytes(e),e.clear(),this};S.DataBuffer.prototype.putString=function(e){return this.putBytes(e,"utf16")};S.DataBuffer.prototype.putInt16=function(e){return this.accommodate(2),this.data.setInt16(this.write,e),this.write+=2,this};S.DataBuffer.prototype.putInt24=function(e){return this.accommodate(3),this.data.setInt16(this.write,e>>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this};S.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this};S.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this};S.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this};S.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this};S.DataBuffer.prototype.putInt=function(e,t){Rr(t),this.accommodate(t/8);do t-=8,this.data.setInt8(this.write++,e>>t&255);while(t>0);return this};S.DataBuffer.prototype.putSignedInt=function(e,t){return Rr(t),this.accommodate(t/8),e<0&&(e+=2<<t-1),this.putInt(e,t)};S.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)};S.DataBuffer.prototype.getInt16=function(){var e=this.data.getInt16(this.read);return this.read+=2,e};S.DataBuffer.prototype.getInt24=function(){var e=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,e};S.DataBuffer.prototype.getInt32=function(){var e=this.data.getInt32(this.read);return this.read+=4,e};S.DataBuffer.prototype.getInt16Le=function(){var e=this.data.getInt16(this.read,!0);return this.read+=2,e};S.DataBuffer.prototype.getInt24Le=function(){var e=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,e};S.DataBuffer.prototype.getInt32Le=function(){var e=this.data.getInt32(this.read,!0);return this.read+=4,e};S.DataBuffer.prototype.getInt=function(e){Rr(e);var t=0;do t=(t<<8)+this.data.getInt8(this.read++),e-=8;while(e>0);return t};S.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),a=2<<e-2;return t>=a&&(t-=a<<1),t};S.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):e===0?t="":(t=this.read===0?this.data:this.data.slice(this.read),this.clear()),t};S.DataBuffer.prototype.bytes=function(e){return typeof e>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+e)};S.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)};S.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this};S.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)};S.DataBuffer.prototype.copy=function(){return new S.DataBuffer(this)};S.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this};S.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this};S.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this};S.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t<this.data.byteLength;++t){var a=this.data.getUint8(t);a<16&&(e+="0"),e+=a.toString(16)}return e};S.DataBuffer.prototype.toString=function(e){var t=new Uint8Array(this.data,this.read,this.length());if(e=e||"utf8",e==="binary"||e==="raw")return S.binary.raw.encode(t);if(e==="hex")return S.binary.hex.encode(t);if(e==="base64")return S.binary.base64.encode(t);if(e==="utf8")return S.text.utf8.decode(t);if(e==="utf16")return S.text.utf16.decode(t);throw new Error("Invalid encoding: "+e)};S.createBuffer=function(e,t){return t=t||"raw",e!==void 0&&t==="utf8"&&(e=S.encodeUtf8(e)),new S.ByteBuffer(e)};S.fillString=function(e,t){for(var a="";t>0;)t&1&&(a+=e),t>>>=1,t>0&&(e+=e);return a};S.xorBytes=function(e,t,a){for(var r="",n="",i="",s=0,o=0;a>0;--a,++s)n=e.charCodeAt(s)^t.charCodeAt(s),o>=10&&(r+=i,i="",o=0),i+=String.fromCharCode(n),++o;return r+=i,r};S.hexToBytes=function(e){var t="",a=0;for(e.length&!0&&(a=1,t+=String.fromCharCode(parseInt(e[0],16)));a<e.length;a+=2)t+=String.fromCharCode(parseInt(e.substr(a,2),16));return t};S.bytesToHex=function(e){return S.createBuffer(e).toHex()};S.int32ToBytes=function(e){return String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(e&255)};var Lt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",kt=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],Ji="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";S.encode64=function(e,t){for(var a="",r="",n,i,s,o=0;o<e.length;)n=e.charCodeAt(o++),i=e.charCodeAt(o++),s=e.charCodeAt(o++),a+=Lt.charAt(n>>2),a+=Lt.charAt((n&3)<<4|i>>4),isNaN(i)?a+="==":(a+=Lt.charAt((i&15)<<2|s>>6),a+=isNaN(s)?"=":Lt.charAt(s&63)),t&&a.length>t&&(r+=a.substr(0,t)+`\r
12
+ `,a=a.substr(t));return r+=a,r};S.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t="",a,r,n,i,s=0;s<e.length;)a=kt[e.charCodeAt(s++)-43],r=kt[e.charCodeAt(s++)-43],n=kt[e.charCodeAt(s++)-43],i=kt[e.charCodeAt(s++)-43],t+=String.fromCharCode(a<<2|r>>4),n!==64&&(t+=String.fromCharCode((r&15)<<4|n>>2),i!==64&&(t+=String.fromCharCode((n&3)<<6|i)));return t};S.encodeUtf8=function(e){return unescape(encodeURIComponent(e))};S.decodeUtf8=function(e){return decodeURIComponent(escape(e))};S.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:Zi.encode,decode:Zi.decode}};S.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)};S.binary.raw.decode=function(e,t,a){var r=t;r||(r=new Uint8Array(e.length)),a=a||0;for(var n=a,i=0;i<e.length;++i)r[n++]=e.charCodeAt(i);return t?n-a:r};S.binary.hex.encode=S.bytesToHex;S.binary.hex.decode=function(e,t,a){var r=t;r||(r=new Uint8Array(Math.ceil(e.length/2))),a=a||0;var n=0,i=a;for(e.length&1&&(n=1,r[i++]=parseInt(e[0],16));n<e.length;n+=2)r[i++]=parseInt(e.substr(n,2),16);return t?i-a:r};S.binary.base64.encode=function(e,t){for(var a="",r="",n,i,s,o=0;o<e.byteLength;)n=e[o++],i=e[o++],s=e[o++],a+=Lt.charAt(n>>2),a+=Lt.charAt((n&3)<<4|i>>4),isNaN(i)?a+="==":(a+=Lt.charAt((i&15)<<2|s>>6),a+=isNaN(s)?"=":Lt.charAt(s&63)),t&&a.length>t&&(r+=a.substr(0,t)+`\r
13
+ `,a=a.substr(t));return r+=a,r};S.binary.base64.decode=function(e,t,a){var r=t;r||(r=new Uint8Array(Math.ceil(e.length/4)*3)),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,""),a=a||0;for(var n,i,s,o,u=0,l=a;u<e.length;)n=kt[e.charCodeAt(u++)-43],i=kt[e.charCodeAt(u++)-43],s=kt[e.charCodeAt(u++)-43],o=kt[e.charCodeAt(u++)-43],r[l++]=n<<2|i>>4,s!==64&&(r[l++]=(i&15)<<4|s>>2,o!==64&&(r[l++]=(s&3)<<6|o));return t?l-a:r.subarray(0,l)};S.binary.base58.encode=function(e,t){return S.binary.baseN.encode(e,Ji,t)};S.binary.base58.decode=function(e,t){return S.binary.baseN.decode(e,Ji,t)};S.text={utf8:{},utf16:{}};S.text.utf8.encode=function(e,t,a){e=S.encodeUtf8(e);var r=t;r||(r=new Uint8Array(e.length)),a=a||0;for(var n=a,i=0;i<e.length;++i)r[n++]=e.charCodeAt(i);return t?n-a:r};S.text.utf8.decode=function(e){return S.decodeUtf8(String.fromCharCode.apply(null,e))};S.text.utf16.encode=function(e,t,a){var r=t;r||(r=new Uint8Array(e.length*2));var n=new Uint16Array(r.buffer);a=a||0;for(var i=a,s=a,o=0;o<e.length;++o)n[s++]=e.charCodeAt(o),i+=2;return t?i-a:r};S.text.utf16.decode=function(e){return String.fromCharCode.apply(null,new Uint16Array(e.buffer))};S.deflate=function(e,t,a){if(t=S.decode64(e.deflate(S.encode64(t)).rval),a){var r=2,n=t.charCodeAt(1);n&32&&(r=6),t=t.substring(r,t.length-4)}return t};S.inflate=function(e,t,a){var r=e.inflate(S.encode64(t)).rval;return r===null?null:S.decode64(r)};var Ja=function(e,t,a){if(!e)throw new Error("WebStorage not available.");var r;if(a===null?r=e.removeItem(t):(a=S.encode64(JSON.stringify(a)),r=e.setItem(t,a)),typeof r<"u"&&r.rval!==!0){var n=new Error(r.error.message);throw n.id=r.error.id,n.name=r.error.name,n}},en=function(e,t){if(!e)throw new Error("WebStorage not available.");var a=e.getItem(t);if(e.init)if(a.rval===null){if(a.error){var r=new Error(a.error.message);throw r.id=a.error.id,r.name=a.error.name,r}a=null}else a=a.rval;return a!==null&&(a=JSON.parse(S.decode64(a))),a},Bl=function(e,t,a,r){var n=en(e,t);n===null&&(n={}),n[a]=r,Ja(e,t,n)},Rl=function(e,t,a){var r=en(e,t);return r!==null&&(r=a in r?r[a]:null),r},_l=function(e,t,a){var r=en(e,t);if(r!==null&&a in r){delete r[a];var n=!0;for(var i in r){n=!1;break}n&&(r=null),Ja(e,t,r)}},Nl=function(e,t){Ja(e,t,null)},ea=function(e,t,a){var r=null;typeof a>"u"&&(a=["web","flash"]);var n,i=!1,s=null;for(var o in a){n=a[o];try{if(n==="flash"||n==="both"){if(t[0]===null)throw new Error("Flash local storage not available.");r=e.apply(this,t),i=n==="flash"}(n==="web"||n==="both")&&(t[0]=localStorage,r=e.apply(this,t),i=!0)}catch(u){s=u}if(i)break}if(!i)throw s;return r};S.setItem=function(e,t,a,r,n){ea(Bl,arguments,n)};S.getItem=function(e,t,a,r){return ea(Rl,arguments,r)};S.removeItem=function(e,t,a,r){ea(_l,arguments,r)};S.clearItems=function(e,t,a){ea(Nl,arguments,a)};S.isEmpty=function(e){for(var t in e)if(e.hasOwnProperty(t))return!1;return!0};S.format=function(e){for(var t=/%./g,a,r,n=0,i=[],s=0;a=t.exec(e);){r=e.substring(s,t.lastIndex-2),r.length>0&&i.push(r),s=t.lastIndex;var o=a[0][1];switch(o){case"s":case"o":n<arguments.length?i.push(arguments[n+++1]):i.push("<?>");break;case"%":i.push("%");break;default:i.push("<%"+o+"?>")}}return i.push(e.substring(s)),i.join("")};S.formatNumber=function(e,t,a,r){var n=e,i=isNaN(t=Math.abs(t))?2:t,s=a===void 0?",":a,o=r===void 0?".":r,u=n<0?"-":"",l=parseInt(n=Math.abs(+n||0).toFixed(i),10)+"",f=l.length>3?l.length%3:0;return u+(f?l.substr(0,f)+o:"")+l.substr(f).replace(/(\d{3})(?=\d)/g,"$1"+o)+(i?s+Math.abs(n-l).toFixed(i).slice(2):"")};S.formatSize=function(e){return e>=1073741824?e=S.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?e=S.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?e=S.formatNumber(e/1024,0)+" KiB":e=S.formatNumber(e,0)+" bytes",e};S.bytesFromIP=function(e){return e.indexOf(".")!==-1?S.bytesFromIPv4(e):e.indexOf(":")!==-1?S.bytesFromIPv6(e):null};S.bytesFromIPv4=function(e){if(e=e.split("."),e.length!==4)return null;for(var t=S.createBuffer(),a=0;a<e.length;++a){var r=parseInt(e[a],10);if(isNaN(r))return null;t.putByte(r)}return t.getBytes()};S.bytesFromIPv6=function(e){var t=0;e=e.split(":").filter(function(s){return s.length===0&&++t,!0});for(var a=(8-e.length+t)*2,r=S.createBuffer(),n=0;n<8;++n){if(!e[n]||e[n].length===0){r.fillWithByte(0,a),a=0;continue}var i=S.hexToBytes(e[n]);i.length<2&&r.putByte(0),r.putBytes(i)}return r.getBytes()};S.bytesToIP=function(e){return e.length===4?S.bytesToIPv4(e):e.length===16?S.bytesToIPv6(e):null};S.bytesToIPv4=function(e){if(e.length!==4)return null;for(var t=[],a=0;a<e.length;++a)t.push(e.charCodeAt(a));return t.join(".")};S.bytesToIPv6=function(e){if(e.length!==16)return null;for(var t=[],a=[],r=0,n=0;n<e.length;n+=2){for(var i=S.bytesToHex(e[n]+e[n+1]);i[0]==="0"&&i!=="0";)i=i.substr(1);if(i==="0"){var s=a[a.length-1],o=t.length;!s||o!==s.end+1?a.push({start:o,end:o}):(s.end=o,s.end-s.start>a[r].end-a[r].start&&(r=a.length-1))}t.push(i)}if(a.length>0){var u=a[r];u.end-u.start>0&&(t.splice(u.start,u.end-u.start+1,""),u.start===0&&t.unshift(""),u.end===7&&t.push(""))}return t.join(":")};S.estimateCores=function(e,t){if(typeof e=="function"&&(t=e,e={}),e=e||{},"cores"in S&&!e.update)return t(null,S.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return S.cores=navigator.hardwareConcurrency,t(null,S.cores);if(typeof Worker>"u")return S.cores=1,t(null,S.cores);if(typeof Blob>"u")return S.cores=2,t(null,S.cores);var a=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(s){for(var o=Date.now(),u=o+4;Date.now()<u;);self.postMessage({st:o,et:u})})}.toString(),")()"],{type:"application/javascript"}));r([],5,16);function r(s,o,u){if(o===0){var l=Math.floor(s.reduce(function(f,c){return f+c},0)/s.length);return S.cores=Math.max(1,l),URL.revokeObjectURL(a),t(null,S.cores)}n(u,function(f,c){s.push(i(u,c)),r(s,o-1,u)})}function n(s,o){for(var u=[],l=[],f=0;f<s;++f){var c=new Worker(a);c.addEventListener("message",function(g){if(l.push(g.data),l.length===s){for(var m=0;m<s;++m)u[m].terminate();o(null,l)}}),u.push(c)}for(var f=0;f<s;++f)u[f].postMessage(f)}function i(s,o){for(var u=[],l=0;l<s;++l)for(var f=o[l],c=u[l]=[],g=0;g<s;++g)if(l!==g){var m=o[g];(f.st>m.st&&f.st<m.et||m.st>f.st&&m.st<f.et)&&c.push(g)}return u.reduce(function(h,v){return Math.max(h,v.length)},0)}}});var ta=H((Jh,ts)=>{"use strict";var Ie=W();re();ts.exports=Ie.cipher=Ie.cipher||{};Ie.cipher.algorithms=Ie.cipher.algorithms||{};Ie.cipher.createCipher=function(e,t){var a=e;if(typeof a=="string"&&(a=Ie.cipher.getAlgorithm(a),a&&(a=a())),!a)throw new Error("Unsupported algorithm: "+e);return new Ie.cipher.BlockCipher({algorithm:a,key:t,decrypt:!1})};Ie.cipher.createDecipher=function(e,t){var a=e;if(typeof a=="string"&&(a=Ie.cipher.getAlgorithm(a),a&&(a=a())),!a)throw new Error("Unsupported algorithm: "+e);return new Ie.cipher.BlockCipher({algorithm:a,key:t,decrypt:!0})};Ie.cipher.registerAlgorithm=function(e,t){e=e.toUpperCase(),Ie.cipher.algorithms[e]=t};Ie.cipher.getAlgorithm=function(e){return e=e.toUpperCase(),e in Ie.cipher.algorithms?Ie.cipher.algorithms[e]:null};var tn=Ie.cipher.BlockCipher=function(e){this.algorithm=e.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=e.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=e.decrypt,this.algorithm.initialize(e)};tn.prototype.start=function(e){e=e||{};var t={};for(var a in e)t[a]=e[a];t.decrypt=this._decrypt,this._finish=!1,this._input=Ie.util.createBuffer(),this.output=e.output||Ie.util.createBuffer(),this.mode.start(t)};tn.prototype.update=function(e){for(e&&this._input.putBuffer(e);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()};tn.prototype.finish=function(e){e&&(this.mode.name==="ECB"||this.mode.name==="CBC")&&(this.mode.pad=function(a){return e(this.blockSize,a,!1)},this.mode.unpad=function(a){return e(this.blockSize,a,!0)});var t={};return t.decrypt=this._decrypt,t.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,t)||(this._finish=!0,this.update(),this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,t))||this.mode.afterFinish&&!this.mode.afterFinish(this.output,t))}});var an=H((ey,rs)=>{"use strict";var we=W();re();we.cipher=we.cipher||{};var $=rs.exports=we.cipher.modes=we.cipher.modes||{};$.ecb=function(e){e=e||{},this.name="ECB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)};$.ecb.prototype.start=function(e){};$.ecb.prototype.encrypt=function(e,t,a){if(e.length()<this.blockSize&&!(a&&e.length()>0))return!0;for(var r=0;r<this._ints;++r)this._inBlock[r]=e.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var r=0;r<this._ints;++r)t.putInt32(this._outBlock[r])};$.ecb.prototype.decrypt=function(e,t,a){if(e.length()<this.blockSize&&!(a&&e.length()>0))return!0;for(var r=0;r<this._ints;++r)this._inBlock[r]=e.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var r=0;r<this._ints;++r)t.putInt32(this._outBlock[r])};$.ecb.prototype.pad=function(e,t){var a=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(a,a),!0};$.ecb.prototype.unpad=function(e,t){if(t.overflow>0)return!1;var a=e.length(),r=e.at(a-1);return r>this.blockSize<<2?!1:(e.truncate(r),!0)};$.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)};$.cbc.prototype.start=function(e){if(e.iv===null){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else if("iv"in e)this._iv=ra(e.iv,this.blockSize),this._prev=this._iv.slice(0);else throw new Error("Invalid IV parameter.")};$.cbc.prototype.encrypt=function(e,t,a){if(e.length()<this.blockSize&&!(a&&e.length()>0))return!0;for(var r=0;r<this._ints;++r)this._inBlock[r]=this._prev[r]^e.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var r=0;r<this._ints;++r)t.putInt32(this._outBlock[r]);this._prev=this._outBlock};$.cbc.prototype.decrypt=function(e,t,a){if(e.length()<this.blockSize&&!(a&&e.length()>0))return!0;for(var r=0;r<this._ints;++r)this._inBlock[r]=e.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var r=0;r<this._ints;++r)t.putInt32(this._prev[r]^this._outBlock[r]);this._prev=this._inBlock.slice(0)};$.cbc.prototype.pad=function(e,t){var a=e.length()===this.blockSize?this.blockSize:this.blockSize-e.length();return e.fillWithByte(a,a),!0};$.cbc.prototype.unpad=function(e,t){if(t.overflow>0)return!1;var a=e.length(),r=e.at(a-1);return r>this.blockSize<<2?!1:(e.truncate(r),!0)};$.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=we.util.createBuffer(),this._partialBytes=0};$.cfb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=ra(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};$.cfb.prototype.encrypt=function(e,t,a){var r=e.length();if(r===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&r>=this.blockSize){for(var n=0;n<this._ints;++n)this._inBlock[n]=e.getInt32()^this._outBlock[n],t.putInt32(this._inBlock[n]);return}var i=(this.blockSize-r)%this.blockSize;i>0&&(i=this.blockSize-i),this._partialOutput.clear();for(var n=0;n<this._ints;++n)this._partialBlock[n]=e.getInt32()^this._outBlock[n],this._partialOutput.putInt32(this._partialBlock[n]);if(i>0)e.read-=this.blockSize;else for(var n=0;n<this._ints;++n)this._inBlock[n]=this._partialBlock[n];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!a)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};$.cfb.prototype.decrypt=function(e,t,a){var r=e.length();if(r===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&r>=this.blockSize){for(var n=0;n<this._ints;++n)this._inBlock[n]=e.getInt32(),t.putInt32(this._inBlock[n]^this._outBlock[n]);return}var i=(this.blockSize-r)%this.blockSize;i>0&&(i=this.blockSize-i),this._partialOutput.clear();for(var n=0;n<this._ints;++n)this._partialBlock[n]=e.getInt32(),this._partialOutput.putInt32(this._partialBlock[n]^this._outBlock[n]);if(i>0)e.read-=this.blockSize;else for(var n=0;n<this._ints;++n)this._inBlock[n]=this._partialBlock[n];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!a)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};$.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=we.util.createBuffer(),this._partialBytes=0};$.ofb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=ra(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};$.ofb.prototype.encrypt=function(e,t,a){var r=e.length();if(e.length()===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&r>=this.blockSize){for(var n=0;n<this._ints;++n)t.putInt32(e.getInt32()^this._outBlock[n]),this._inBlock[n]=this._outBlock[n];return}var i=(this.blockSize-r)%this.blockSize;i>0&&(i=this.blockSize-i),this._partialOutput.clear();for(var n=0;n<this._ints;++n)this._partialOutput.putInt32(e.getInt32()^this._outBlock[n]);if(i>0)e.read-=this.blockSize;else for(var n=0;n<this._ints;++n)this._inBlock[n]=this._outBlock[n];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!a)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0};$.ofb.prototype.decrypt=$.ofb.prototype.encrypt;$.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=we.util.createBuffer(),this._partialBytes=0};$.ctr.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=ra(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0};$.ctr.prototype.encrypt=function(e,t,a){var r=e.length();if(r===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&r>=this.blockSize)for(var n=0;n<this._ints;++n)t.putInt32(e.getInt32()^this._outBlock[n]);else{var i=(this.blockSize-r)%this.blockSize;i>0&&(i=this.blockSize-i),this._partialOutput.clear();for(var n=0;n<this._ints;++n)this._partialOutput.putInt32(e.getInt32()^this._outBlock[n]);if(i>0&&(e.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!a)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}aa(this._inBlock)};$.ctr.prototype.decrypt=$.ctr.prototype.encrypt;$.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=we.util.createBuffer(),this._partialBytes=0,this._R=3774873600};$.gcm.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");var t=we.util.createBuffer(e.iv);this._cipherLength=0;var a;if("additionalData"in e?a=we.util.createBuffer(e.additionalData):a=we.util.createBuffer(),"tagLength"in e?this._tagLength=e.tagLength:this._tagLength=128,this._tag=null,e.decrypt&&(this._tag=we.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var r=t.length();if(r===12)this._j0=[t.getInt32(),t.getInt32(),t.getInt32(),1];else{for(this._j0=[0,0,0,0];t.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(rn(r*8)))}this._inBlock=this._j0.slice(0),aa(this._inBlock),this._partialBytes=0,a=we.util.createBuffer(a),this._aDataLength=rn(a.length()*8);var n=a.length()%this.blockSize;for(n&&a.fillWithByte(0,this.blockSize-n),this._s=[0,0,0,0];a.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[a.getInt32(),a.getInt32(),a.getInt32(),a.getInt32()])};$.gcm.prototype.encrypt=function(e,t,a){var r=e.length();if(r===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&r>=this.blockSize){for(var n=0;n<this._ints;++n)t.putInt32(this._outBlock[n]^=e.getInt32());this._cipherLength+=this.blockSize}else{var i=(this.blockSize-r)%this.blockSize;i>0&&(i=this.blockSize-i),this._partialOutput.clear();for(var n=0;n<this._ints;++n)this._partialOutput.putInt32(e.getInt32()^this._outBlock[n]);if(i<=0||a){if(a){var s=r%this.blockSize;this._cipherLength+=s,this._partialOutput.truncate(this.blockSize-s)}else this._cipherLength+=this.blockSize;for(var n=0;n<this._ints;++n)this._outBlock[n]=this._partialOutput.getInt32();this._partialOutput.read-=this.blockSize}if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!a)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),aa(this._inBlock)};$.gcm.prototype.decrypt=function(e,t,a){var r=e.length();if(r<this.blockSize&&!(a&&r>0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),aa(this._inBlock),this._hashBlock[0]=e.getInt32(),this._hashBlock[1]=e.getInt32(),this._hashBlock[2]=e.getInt32(),this._hashBlock[3]=e.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var n=0;n<this._ints;++n)t.putInt32(this._outBlock[n]^this._hashBlock[n]);r<this.blockSize?this._cipherLength+=r%this.blockSize:this._cipherLength+=this.blockSize};$.gcm.prototype.afterFinish=function(e,t){var a=!0;t.decrypt&&t.overflow&&e.truncate(this.blockSize-t.overflow),this.tag=we.util.createBuffer();var r=this._aDataLength.concat(rn(this._cipherLength*8));this._s=this.ghash(this._hashSubkey,this._s,r);var n=[];this.cipher.encrypt(this._j0,n);for(var i=0;i<this._ints;++i)this.tag.putInt32(this._s[i]^n[i]);return this.tag.truncate(this.tag.length()%(this._tagLength/8)),t.decrypt&&this.tag.bytes()!==this._tag&&(a=!1),a};$.gcm.prototype.multiply=function(e,t){for(var a=[0,0,0,0],r=t.slice(0),n=0;n<128;++n){var i=e[n/32|0]&1<<31-n%32;i&&(a[0]^=r[0],a[1]^=r[1],a[2]^=r[2],a[3]^=r[3]),this.pow(r,r)}return a};$.gcm.prototype.pow=function(e,t){for(var a=e[3]&1,r=3;r>0;--r)t[r]=e[r]>>>1|(e[r-1]&1)<<31;t[0]=e[0]>>>1,a&&(t[0]^=this._R)};$.gcm.prototype.tableMultiply=function(e){for(var t=[0,0,0,0],a=0;a<32;++a){var r=a/8|0,n=e[r]>>>(7-a%8)*4&15,i=this._m[a][n];t[0]^=i[0],t[1]^=i[1],t[2]^=i[2],t[3]^=i[3]}return t};$.gcm.prototype.ghash=function(e,t,a){return t[0]^=a[0],t[1]^=a[1],t[2]^=a[2],t[3]^=a[3],this.tableMultiply(t)};$.gcm.prototype.generateHashTable=function(e,t){for(var a=8/t,r=4*a,n=16*a,i=new Array(n),s=0;s<n;++s){var o=[0,0,0,0],u=s/r|0,l=(r-1-s%r)*t;o[u]=1<<t-1<<l,i[s]=this.generateSubHashTable(this.multiply(o,e),t)}return i};$.gcm.prototype.generateSubHashTable=function(e,t){var a=1<<t,r=a>>>1,n=new Array(a);n[r]=e.slice(0);for(var i=r>>>1;i>0;)this.pow(n[2*i],n[i]=[]),i>>=1;for(i=2;i<r;){for(var s=1;s<i;++s){var o=n[i],u=n[s];n[i+s]=[o[0]^u[0],o[1]^u[1],o[2]^u[2],o[3]^u[3]]}i*=2}for(n[0]=[0,0,0,0],i=r+1;i<a;++i){var l=n[i^r];n[i]=[e[0]^l[0],e[1]^l[1],e[2]^l[2],e[3]^l[3]]}return n};function ra(e,t){if(typeof e=="string"&&(e=we.util.createBuffer(e)),we.util.isArray(e)&&e.length>4){var a=e;e=we.util.createBuffer();for(var r=0;r<a.length;++r)e.putByte(a[r])}if(e.length()<t)throw new Error("Invalid IV length; got "+e.length()+" bytes and expected "+t+" bytes.");if(!we.util.isArray(e)){for(var n=[],i=t/4,r=0;r<i;++r)n.push(e.getInt32());e=n}return e}function aa(e){e[e.length-1]=e[e.length-1]+1&4294967295}function rn(e){return[e/4294967296|0,e&4294967295]}});var Ut=H((ty,ss)=>{"use strict";var ce=W();ta();an();re();ss.exports=ce.aes=ce.aes||{};ce.aes.startEncrypting=function(e,t,a,r){var n=na({key:e,output:a,decrypt:!1,mode:r});return n.start(t),n};ce.aes.createEncryptionCipher=function(e,t){return na({key:e,output:null,decrypt:!1,mode:t})};ce.aes.startDecrypting=function(e,t,a,r){var n=na({key:e,output:a,decrypt:!0,mode:r});return n.start(t),n};ce.aes.createDecryptionCipher=function(e,t){return na({key:e,output:null,decrypt:!0,mode:t})};ce.aes.Algorithm=function(e,t){on||ns();var a=this;a.name=e,a.mode=new t({blockSize:16,cipher:{encrypt:function(r,n){return sn(a._w,r,n,!1)},decrypt:function(r,n){return sn(a._w,r,n,!0)}}}),a._init=!1};ce.aes.Algorithm.prototype.initialize=function(e){if(!this._init){var t=e.key,a;if(typeof t=="string"&&(t.length===16||t.length===24||t.length===32))t=ce.util.createBuffer(t);else if(ce.util.isArray(t)&&(t.length===16||t.length===24||t.length===32)){a=t,t=ce.util.createBuffer();for(var r=0;r<a.length;++r)t.putByte(a[r])}if(!ce.util.isArray(t)){a=t,t=[];var n=a.length();if(n===16||n===24||n===32){n=n>>>2;for(var r=0;r<n;++r)t.push(a.getInt32())}}if(!ce.util.isArray(t)||!(t.length===4||t.length===6||t.length===8))throw new Error("Invalid key parameter.");var i=this.mode.name,s=["CFB","OFB","CTR","GCM"].indexOf(i)!==-1;this._w=is(t,e.decrypt&&!s),this._init=!0}};ce.aes._expandKey=function(e,t){return on||ns(),is(e,t)};ce.aes._updateBlock=sn;cr("AES-ECB",ce.cipher.modes.ecb);cr("AES-CBC",ce.cipher.modes.cbc);cr("AES-CFB",ce.cipher.modes.cfb);cr("AES-OFB",ce.cipher.modes.ofb);cr("AES-CTR",ce.cipher.modes.ctr);cr("AES-GCM",ce.cipher.modes.gcm);function cr(e,t){var a=function(){return new ce.aes.Algorithm(e,t)};ce.cipher.registerAlgorithm(e,a)}var on=!1,fr=4,We,nn,as,Xt,dt;function ns(){on=!0,as=[0,1,2,4,8,16,32,64,128,27,54];for(var e=new Array(256),t=0;t<128;++t)e[t]=t<<1,e[t+128]=t+128<<1^283;We=new Array(256),nn=new Array(256),Xt=new Array(4),dt=new Array(4);for(var t=0;t<4;++t)Xt[t]=new Array(256),dt[t]=new Array(256);for(var a=0,r=0,n,i,s,o,u,l,f,t=0;t<256;++t){o=r^r<<1^r<<2^r<<3^r<<4,o=o>>8^o&255^99,We[a]=o,nn[o]=a,u=e[o],n=e[a],i=e[n],s=e[i],l=u<<24^o<<16^o<<8^(o^u),f=(n^i^s)<<24^(a^s)<<16^(a^i^s)<<8^(a^n^s);for(var c=0;c<4;++c)Xt[c][a]=l,dt[c][o]=f,l=l<<24|l>>>8,f=f<<24|f>>>8;a===0?a=r=1:(a=n^e[e[e[n^s]]],r^=e[e[r]])}}function is(e,t){for(var a=e.slice(0),r,n=1,i=a.length,s=i+6+1,o=fr*s,u=i;u<o;++u)r=a[u-1],u%i===0?(r=We[r>>>16&255]<<24^We[r>>>8&255]<<16^We[r&255]<<8^We[r>>>24]^as[n]<<24,n++):i>6&&u%i===4&&(r=We[r>>>24]<<24^We[r>>>16&255]<<16^We[r>>>8&255]<<8^We[r&255]),a[u]=a[u-i]^r;if(t){var l,f=dt[0],c=dt[1],g=dt[2],m=dt[3],h=a.slice(0);o=a.length;for(var u=0,v=o-fr;u<o;u+=fr,v-=fr)if(u===0||u===o-fr)h[u]=a[v],h[u+1]=a[v+3],h[u+2]=a[v+2],h[u+3]=a[v+1];else for(var E=0;E<fr;++E)l=a[v+E],h[u+(3&-E)]=f[We[l>>>24]]^c[We[l>>>16&255]]^g[We[l>>>8&255]]^m[We[l&255]];a=h}return a}function sn(e,t,a,r){var n=e.length/4-1,i,s,o,u,l;r?(i=dt[0],s=dt[1],o=dt[2],u=dt[3],l=nn):(i=Xt[0],s=Xt[1],o=Xt[2],u=Xt[3],l=We);var f,c,g,m,h,v,E;f=t[0]^e[0],c=t[r?3:1]^e[1],g=t[2]^e[2],m=t[r?1:3]^e[3];for(var T=3,I=1;I<n;++I)h=i[f>>>24]^s[c>>>16&255]^o[g>>>8&255]^u[m&255]^e[++T],v=i[c>>>24]^s[g>>>16&255]^o[m>>>8&255]^u[f&255]^e[++T],E=i[g>>>24]^s[m>>>16&255]^o[f>>>8&255]^u[c&255]^e[++T],m=i[m>>>24]^s[f>>>16&255]^o[c>>>8&255]^u[g&255]^e[++T],f=h,c=v,g=E;a[0]=l[f>>>24]<<24^l[c>>>16&255]<<16^l[g>>>8&255]<<8^l[m&255]^e[++T],a[r?3:1]=l[c>>>24]<<24^l[g>>>16&255]<<16^l[m>>>8&255]<<8^l[f&255]^e[++T],a[2]=l[g>>>24]<<24^l[m>>>16&255]<<16^l[f>>>8&255]<<8^l[c&255]^e[++T],a[r?1:3]=l[m>>>24]<<24^l[f>>>16&255]<<16^l[c>>>8&255]<<8^l[g&255]^e[++T]}function na(e){e=e||{};var t=(e.mode||"CBC").toUpperCase(),a="AES-"+t,r;e.decrypt?r=ce.cipher.createDecipher(a,e.key):r=ce.cipher.createCipher(a,e.key);var n=r.start;return r.start=function(i,s){var o=null;s instanceof ce.util.ByteBuffer&&(o=s,s={}),s=s||{},s.output=o,s.iv=i,n.call(r,s)},r}});var Ft=H((ry,os)=>{"use strict";var _r=W();_r.pki=_r.pki||{};var un=os.exports=_r.pki.oids=_r.oids=_r.oids||{};function _(e,t){un[e]=t,un[t]=e}function ne(e,t){un[e]=t}_("1.2.840.113549.1.1.1","rsaEncryption");_("1.2.840.113549.1.1.4","md5WithRSAEncryption");_("1.2.840.113549.1.1.5","sha1WithRSAEncryption");_("1.2.840.113549.1.1.7","RSAES-OAEP");_("1.2.840.113549.1.1.8","mgf1");_("1.2.840.113549.1.1.9","pSpecified");_("1.2.840.113549.1.1.10","RSASSA-PSS");_("1.2.840.113549.1.1.11","sha256WithRSAEncryption");_("1.2.840.113549.1.1.12","sha384WithRSAEncryption");_("1.2.840.113549.1.1.13","sha512WithRSAEncryption");_("1.3.101.112","EdDSA25519");_("1.2.840.10040.4.3","dsa-with-sha1");_("1.3.14.3.2.7","desCBC");_("1.3.14.3.2.26","sha1");_("1.3.14.3.2.29","sha1WithRSASignature");_("2.16.840.1.101.3.4.2.1","sha256");_("2.16.840.1.101.3.4.2.2","sha384");_("2.16.840.1.101.3.4.2.3","sha512");_("2.16.840.1.101.3.4.2.4","sha224");_("2.16.840.1.101.3.4.2.5","sha512-224");_("2.16.840.1.101.3.4.2.6","sha512-256");_("1.2.840.113549.2.2","md2");_("1.2.840.113549.2.5","md5");_("1.2.840.113549.1.7.1","data");_("1.2.840.113549.1.7.2","signedData");_("1.2.840.113549.1.7.3","envelopedData");_("1.2.840.113549.1.7.4","signedAndEnvelopedData");_("1.2.840.113549.1.7.5","digestedData");_("1.2.840.113549.1.7.6","encryptedData");_("1.2.840.113549.1.9.1","emailAddress");_("1.2.840.113549.1.9.2","unstructuredName");_("1.2.840.113549.1.9.3","contentType");_("1.2.840.113549.1.9.4","messageDigest");_("1.2.840.113549.1.9.5","signingTime");_("1.2.840.113549.1.9.6","counterSignature");_("1.2.840.113549.1.9.7","challengePassword");_("1.2.840.113549.1.9.8","unstructuredAddress");_("1.2.840.113549.1.9.14","extensionRequest");_("1.2.840.113549.1.9.20","friendlyName");_("1.2.840.113549.1.9.21","localKeyId");_("1.2.840.113549.1.9.22.1","x509Certificate");_("1.2.840.113549.1.12.10.1.1","keyBag");_("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag");_("1.2.840.113549.1.12.10.1.3","certBag");_("1.2.840.113549.1.12.10.1.4","crlBag");_("1.2.840.113549.1.12.10.1.5","secretBag");_("1.2.840.113549.1.12.10.1.6","safeContentsBag");_("1.2.840.113549.1.5.13","pkcs5PBES2");_("1.2.840.113549.1.5.12","pkcs5PBKDF2");_("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4");_("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4");_("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC");_("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC");_("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC");_("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC");_("1.2.840.113549.2.7","hmacWithSHA1");_("1.2.840.113549.2.8","hmacWithSHA224");_("1.2.840.113549.2.9","hmacWithSHA256");_("1.2.840.113549.2.10","hmacWithSHA384");_("1.2.840.113549.2.11","hmacWithSHA512");_("1.2.840.113549.3.7","des-EDE3-CBC");_("2.16.840.1.101.3.4.1.2","aes128-CBC");_("2.16.840.1.101.3.4.1.22","aes192-CBC");_("2.16.840.1.101.3.4.1.42","aes256-CBC");_("2.5.4.3","commonName");_("2.5.4.4","surname");_("2.5.4.5","serialNumber");_("2.5.4.6","countryName");_("2.5.4.7","localityName");_("2.5.4.8","stateOrProvinceName");_("2.5.4.9","streetAddress");_("2.5.4.10","organizationName");_("2.5.4.11","organizationalUnitName");_("2.5.4.12","title");_("2.5.4.13","description");_("2.5.4.15","businessCategory");_("2.5.4.17","postalCode");_("2.5.4.42","givenName");_("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName");_("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName");_("2.16.840.1.113730.1.1","nsCertType");_("2.16.840.1.113730.1.13","nsComment");ne("2.5.29.1","authorityKeyIdentifier");ne("2.5.29.2","keyAttributes");ne("2.5.29.3","certificatePolicies");ne("2.5.29.4","keyUsageRestriction");ne("2.5.29.5","policyMapping");ne("2.5.29.6","subtreesConstraint");ne("2.5.29.7","subjectAltName");ne("2.5.29.8","issuerAltName");ne("2.5.29.9","subjectDirectoryAttributes");ne("2.5.29.10","basicConstraints");ne("2.5.29.11","nameConstraints");ne("2.5.29.12","policyConstraints");ne("2.5.29.13","basicConstraints");_("2.5.29.14","subjectKeyIdentifier");_("2.5.29.15","keyUsage");ne("2.5.29.16","privateKeyUsagePeriod");_("2.5.29.17","subjectAltName");_("2.5.29.18","issuerAltName");_("2.5.29.19","basicConstraints");ne("2.5.29.20","cRLNumber");ne("2.5.29.21","cRLReason");ne("2.5.29.22","expirationDate");ne("2.5.29.23","instructionCode");ne("2.5.29.24","invalidityDate");ne("2.5.29.25","cRLDistributionPoints");ne("2.5.29.26","issuingDistributionPoint");ne("2.5.29.27","deltaCRLIndicator");ne("2.5.29.28","issuingDistributionPoint");ne("2.5.29.29","certificateIssuer");ne("2.5.29.30","nameConstraints");_("2.5.29.31","cRLDistributionPoints");_("2.5.29.32","certificatePolicies");ne("2.5.29.33","policyMappings");ne("2.5.29.34","policyConstraints");_("2.5.29.35","authorityKeyIdentifier");ne("2.5.29.36","policyConstraints");_("2.5.29.37","extKeyUsage");ne("2.5.29.46","freshestCRL");ne("2.5.29.54","inhibitAnyPolicy");_("1.3.6.1.4.1.11129.2.4.2","timestampList");_("1.3.6.1.5.5.7.1.1","authorityInfoAccess");_("1.3.6.1.5.5.7.3.1","serverAuth");_("1.3.6.1.5.5.7.3.2","clientAuth");_("1.3.6.1.5.5.7.3.3","codeSigning");_("1.3.6.1.5.5.7.3.4","emailProtection");_("1.3.6.1.5.5.7.3.8","timeStamping")});var pt=H((ay,ls)=>{"use strict";var he=W();re();Ft();var U=ls.exports=he.asn1=he.asn1||{};U.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192};U.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30};U.create=function(e,t,a,r,n){if(he.util.isArray(r)){for(var i=[],s=0;s<r.length;++s)r[s]!==void 0&&i.push(r[s]);r=i}var o={tagClass:e,type:t,constructed:a,composed:a||he.util.isArray(r),value:r};return n&&"bitStringContents"in n&&(o.bitStringContents=n.bitStringContents,o.original=U.copy(o)),o};U.copy=function(e,t){var a;if(he.util.isArray(e)){a=[];for(var r=0;r<e.length;++r)a.push(U.copy(e[r],t));return a}return typeof e=="string"?e:(a={tagClass:e.tagClass,type:e.type,constructed:e.constructed,composed:e.composed,value:U.copy(e.value,t)},t&&!t.excludeBitStringContents&&(a.bitStringContents=e.bitStringContents),a)};U.equals=function(e,t,a){if(he.util.isArray(e)){if(!he.util.isArray(t)||e.length!==t.length)return!1;for(var r=0;r<e.length;++r)if(!U.equals(e[r],t[r]))return!1;return!0}if(typeof e!=typeof t)return!1;if(typeof e=="string")return e===t;var n=e.tagClass===t.tagClass&&e.type===t.type&&e.constructed===t.constructed&&e.composed===t.composed&&U.equals(e.value,t.value);return a&&a.includeBitStringContents&&(n=n&&e.bitStringContents===t.bitStringContents),n};U.getBerValueLength=function(e){var t=e.getByte();if(t!==128){var a,r=t&128;return r?a=e.getInt((t&127)<<3):a=t,a}};function Nr(e,t,a){if(a>t){var r=new Error("Too few bytes to parse DER.");throw r.available=e.length(),r.remaining=t,r.requested=a,r}}var Pl=function(e,t){var a=e.getByte();if(t--,a!==128){var r,n=a&128;if(!n)r=a;else{var i=a&127;Nr(e,t,i),r=e.getInt(i<<3)}if(r<0)throw new Error("Negative length: "+r);return r}};U.fromDer=function(e,t){t===void 0&&(t={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),typeof t=="boolean"&&(t={strict:t,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in t||(t.strict=!0),"parseAllBytes"in t||(t.parseAllBytes=!0),"decodeBitStrings"in t||(t.decodeBitStrings=!0),typeof e=="string"&&(e=he.util.createBuffer(e));var a=e.length(),r=ia(e,e.length(),0,t);if(t.parseAllBytes&&e.length()!==0){var n=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw n.byteCount=a,n.remaining=e.length(),n}return r};function ia(e,t,a,r){var n;Nr(e,t,2);var i=e.getByte();t--;var s=i&192,o=i&31;n=e.length();var u=Pl(e,t);if(t-=n-e.length(),u!==void 0&&u>t){if(r.strict){var l=new Error("Too few bytes to read ASN.1 value.");throw l.available=e.length(),l.remaining=t,l.requested=u,l}u=t}var f,c,g=(i&32)===32;if(g)if(f=[],u===void 0)for(;;){if(Nr(e,t,2),e.bytes(2)==="\0\0"){e.getBytes(2),t-=2;break}n=e.length(),f.push(ia(e,t,a+1,r)),t-=n-e.length()}else for(;u>0;)n=e.length(),f.push(ia(e,u,a+1,r)),t-=n-e.length(),u-=n-e.length();if(f===void 0&&s===U.Class.UNIVERSAL&&o===U.Type.BITSTRING&&(c=e.bytes(u)),f===void 0&&r.decodeBitStrings&&s===U.Class.UNIVERSAL&&o===U.Type.BITSTRING&&u>1){var m=e.read,h=t,v=0;if(o===U.Type.BITSTRING&&(Nr(e,t,1),v=e.getByte(),t--),v===0)try{n=e.length();var E={strict:!0,decodeBitStrings:!0},T=ia(e,t,a+1,E),I=n-e.length();t-=I,o==U.Type.BITSTRING&&I++;var A=T.tagClass;I===u&&(A===U.Class.UNIVERSAL||A===U.Class.CONTEXT_SPECIFIC)&&(f=[T])}catch{}f===void 0&&(e.read=m,t=h)}if(f===void 0){if(u===void 0){if(r.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");u=t}if(o===U.Type.BMPSTRING)for(f="";u>0;u-=2)Nr(e,t,2),f+=String.fromCharCode(e.getInt16()),t-=2;else f=e.getBytes(u),t-=u}var L=c===void 0?null:{bitStringContents:c};return U.create(s,o,g,f,L)}U.toDer=function(e){var t=he.util.createBuffer(),a=e.tagClass|e.type,r=he.util.createBuffer(),n=!1;if("bitStringContents"in e&&(n=!0,e.original&&(n=U.equals(e,e.original))),n)r.putBytes(e.bitStringContents);else if(e.composed){e.constructed?a|=32:r.putByte(0);for(var i=0;i<e.value.length;++i)e.value[i]!==void 0&&r.putBuffer(U.toDer(e.value[i]))}else if(e.type===U.Type.BMPSTRING)for(var i=0;i<e.value.length;++i)r.putInt16(e.value.charCodeAt(i));else e.type===U.Type.INTEGER&&e.value.length>1&&(e.value.charCodeAt(0)===0&&(e.value.charCodeAt(1)&128)===0||e.value.charCodeAt(0)===255&&(e.value.charCodeAt(1)&128)===128)?r.putBytes(e.value.substr(1)):r.putBytes(e.value);if(t.putByte(a),r.length()<=127)t.putByte(r.length()&127);else{var s=r.length(),o="";do o+=String.fromCharCode(s&255),s=s>>>8;while(s>0);t.putByte(o.length|128);for(var i=o.length-1;i>=0;--i)t.putByte(o.charCodeAt(i))}return t.putBuffer(r),t};U.oidToDer=function(e){var t=e.split("."),a=he.util.createBuffer();a.putByte(40*parseInt(t[0],10)+parseInt(t[1],10));for(var r,n,i,s,o=2;o<t.length;++o){r=!0,n=[],i=parseInt(t[o],10);do s=i&127,i=i>>>7,r||(s|=128),n.push(s),r=!1;while(i>0);for(var u=n.length-1;u>=0;--u)a.putByte(n[u])}return a};U.derToOid=function(e){var t;typeof e=="string"&&(e=he.util.createBuffer(e));var a=e.getByte();t=Math.floor(a/40)+"."+a%40;for(var r=0;e.length()>0;)a=e.getByte(),r=r<<7,a&128?r+=a&127:(t+="."+(r+a),r=0);return t};U.utcTimeToDate=function(e){var t=new Date,a=parseInt(e.substr(0,2),10);a=a>=50?1900+a:2e3+a;var r=parseInt(e.substr(2,2),10)-1,n=parseInt(e.substr(4,2),10),i=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),o=0;if(e.length>11){var u=e.charAt(10),l=10;u!=="+"&&u!=="-"&&(o=parseInt(e.substr(10,2),10),l+=2)}if(t.setUTCFullYear(a,r,n),t.setUTCHours(i,s,o,0),l&&(u=e.charAt(l),u==="+"||u==="-")){var f=parseInt(e.substr(l+1,2),10),c=parseInt(e.substr(l+4,2),10),g=f*60+c;g*=6e4,u==="+"?t.setTime(+t-g):t.setTime(+t+g)}return t};U.generalizedTimeToDate=function(e){var t=new Date,a=parseInt(e.substr(0,4),10),r=parseInt(e.substr(4,2),10)-1,n=parseInt(e.substr(6,2),10),i=parseInt(e.substr(8,2),10),s=parseInt(e.substr(10,2),10),o=parseInt(e.substr(12,2),10),u=0,l=0,f=!1;e.charAt(e.length-1)==="Z"&&(f=!0);var c=e.length-5,g=e.charAt(c);if(g==="+"||g==="-"){var m=parseInt(e.substr(c+1,2),10),h=parseInt(e.substr(c+4,2),10);l=m*60+h,l*=6e4,g==="+"&&(l*=-1),f=!0}return e.charAt(14)==="."&&(u=parseFloat(e.substr(14),10)*1e3),f?(t.setUTCFullYear(a,r,n),t.setUTCHours(i,s,o,u),t.setTime(+t+l)):(t.setFullYear(a,r,n),t.setHours(i,s,o,u)),t};U.dateToUtcTime=function(e){if(typeof e=="string")return e;var t="",a=[];a.push((""+e.getUTCFullYear()).substr(2)),a.push(""+(e.getUTCMonth()+1)),a.push(""+e.getUTCDate()),a.push(""+e.getUTCHours()),a.push(""+e.getUTCMinutes()),a.push(""+e.getUTCSeconds());for(var r=0;r<a.length;++r)a[r].length<2&&(t+="0"),t+=a[r];return t+="Z",t};U.dateToGeneralizedTime=function(e){if(typeof e=="string")return e;var t="",a=[];a.push(""+e.getUTCFullYear()),a.push(""+(e.getUTCMonth()+1)),a.push(""+e.getUTCDate()),a.push(""+e.getUTCHours()),a.push(""+e.getUTCMinutes()),a.push(""+e.getUTCSeconds());for(var r=0;r<a.length;++r)a[r].length<2&&(t+="0"),t+=a[r];return t+="Z",t};U.integerToDer=function(e){var t=he.util.createBuffer();if(e>=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putSignedInt(e,24);if(e>=-2147483648&&e<2147483648)return t.putSignedInt(e,32);var a=new Error("Integer too large; max is 32-bits.");throw a.integer=e,a};U.derToInteger=function(e){typeof e=="string"&&(e=he.util.createBuffer(e));var t=e.length()*8;if(t>32)throw new Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)};U.validate=function(e,t,a,r){var n=!1;if((e.tagClass===t.tagClass||typeof t.tagClass>"u")&&(e.type===t.type||typeof t.type>"u"))if(e.constructed===t.constructed||typeof t.constructed>"u"){if(n=!0,t.value&&he.util.isArray(t.value))for(var i=0,s=0;n&&s<t.value.length;++s)n=t.value[s].optional||!1,e.value[i]&&(n=U.validate(e.value[i],t.value[s],a,r),n?++i:t.value[s].optional&&(n=!0)),!n&&r&&r.push("["+t.name+'] Tag class "'+t.tagClass+'", type "'+t.type+'" expected value length "'+t.value.length+'", got "'+e.value.length+'"');if(n&&a&&(t.capture&&(a[t.capture]=e.value),t.captureAsn1&&(a[t.captureAsn1]=e),t.captureBitStringContents&&"bitStringContents"in e&&(a[t.captureBitStringContents]=e.bitStringContents),t.captureBitStringValue&&"bitStringContents"in e)){var o;if(e.bitStringContents.length<2)a[t.captureBitStringValue]="";else{var u=e.bitStringContents.charCodeAt(0);if(u!==0)throw new Error("captureBitStringValue only supported for zero unused bits");a[t.captureBitStringValue]=e.bitStringContents.slice(1)}}}else r&&r.push("["+t.name+'] Expected constructed "'+t.constructed+'", got "'+e.constructed+'"');else r&&(e.tagClass!==t.tagClass&&r.push("["+t.name+'] Expected tag class "'+t.tagClass+'", got "'+e.tagClass+'"'),e.type!==t.type&&r.push("["+t.name+'] Expected type "'+t.type+'", got "'+e.type+'"'));return n};var us=/[^\\u0000-\\u00ff]/;U.prettyPrint=function(e,t,a){var r="";t=t||0,a=a||2,t>0&&(r+=`
14
+ `);for(var n="",i=0;i<t*a;++i)n+=" ";switch(r+=n+"Tag: ",e.tagClass){case U.Class.UNIVERSAL:r+="Universal:";break;case U.Class.APPLICATION:r+="Application:";break;case U.Class.CONTEXT_SPECIFIC:r+="Context-Specific:";break;case U.Class.PRIVATE:r+="Private:";break}if(e.tagClass===U.Class.UNIVERSAL)switch(r+=e.type,e.type){case U.Type.NONE:r+=" (None)";break;case U.Type.BOOLEAN:r+=" (Boolean)";break;case U.Type.INTEGER:r+=" (Integer)";break;case U.Type.BITSTRING:r+=" (Bit string)";break;case U.Type.OCTETSTRING:r+=" (Octet string)";break;case U.Type.NULL:r+=" (Null)";break;case U.Type.OID:r+=" (Object Identifier)";break;case U.Type.ODESC:r+=" (Object Descriptor)";break;case U.Type.EXTERNAL:r+=" (External or Instance of)";break;case U.Type.REAL:r+=" (Real)";break;case U.Type.ENUMERATED:r+=" (Enumerated)";break;case U.Type.EMBEDDED:r+=" (Embedded PDV)";break;case U.Type.UTF8:r+=" (UTF8)";break;case U.Type.ROID:r+=" (Relative Object Identifier)";break;case U.Type.SEQUENCE:r+=" (Sequence)";break;case U.Type.SET:r+=" (Set)";break;case U.Type.PRINTABLESTRING:r+=" (Printable String)";break;case U.Type.IA5String:r+=" (IA5String (ASCII))";break;case U.Type.UTCTIME:r+=" (UTC time)";break;case U.Type.GENERALIZEDTIME:r+=" (Generalized time)";break;case U.Type.BMPSTRING:r+=" (BMP String)";break}else r+=e.type;if(r+=`
15
+ `,r+=n+"Constructed: "+e.constructed+`
16
+ `,e.composed){for(var s=0,o="",i=0;i<e.value.length;++i)e.value[i]!==void 0&&(s+=1,o+=U.prettyPrint(e.value[i],t+1,a),i+1<e.value.length&&(o+=","));r+=n+"Sub values: "+s+o}else{if(r+=n+"Value: ",e.type===U.Type.OID){var u=U.derToOid(e.value);r+=u,he.pki&&he.pki.oids&&u in he.pki.oids&&(r+=" ("+he.pki.oids[u]+") ")}if(e.type===U.Type.INTEGER)try{r+=U.derToInteger(e.value)}catch{r+="0x"+he.util.bytesToHex(e.value)}else if(e.type===U.Type.BITSTRING){if(e.value.length>1?r+="0x"+he.util.bytesToHex(e.value.slice(1)):r+="(none)",e.value.length>0){var l=e.value.charCodeAt(0);l==1?r+=" (1 unused bit shown)":l>1&&(r+=" ("+l+" unused bits shown)")}}else if(e.type===U.Type.OCTETSTRING)us.test(e.value)||(r+="("+e.value+") "),r+="0x"+he.util.bytesToHex(e.value);else if(e.type===U.Type.UTF8)try{r+=he.util.decodeUtf8(e.value)}catch(f){if(f.message==="URI malformed")r+="0x"+he.util.bytesToHex(e.value)+" (malformed UTF8)";else throw f}else e.type===U.Type.PRINTABLESTRING||e.type===U.Type.IA5String?r+=e.value:us.test(e.value)?r+="0x"+he.util.bytesToHex(e.value):e.value.length===0?r+="[null]":r+=e.value}return r}});var mt=H((ny,fs)=>{"use strict";var sa=W();fs.exports=sa.md=sa.md||{};sa.md.algorithms=sa.md.algorithms||{}});var dr=H((iy,cs)=>{"use strict";var At=W();mt();re();var Dl=cs.exports=At.hmac=At.hmac||{};Dl.create=function(){var e=null,t=null,a=null,r=null,n={};return n.start=function(i,s){if(i!==null)if(typeof i=="string")if(i=i.toLowerCase(),i in At.md.algorithms)t=At.md.algorithms[i].create();else throw new Error('Unknown hash algorithm "'+i+'"');else t=i;if(s===null)s=e;else{if(typeof s=="string")s=At.util.createBuffer(s);else if(At.util.isArray(s)){var o=s;s=At.util.createBuffer();for(var u=0;u<o.length;++u)s.putByte(o[u])}var l=s.length();l>t.blockLength&&(t.start(),t.update(s.bytes()),s=t.digest()),a=At.util.createBuffer(),r=At.util.createBuffer(),l=s.length();for(var u=0;u<l;++u){var o=s.at(u);a.putByte(54^o),r.putByte(92^o)}if(l<t.blockLength)for(var o=t.blockLength-l,u=0;u<o;++u)a.putByte(54),r.putByte(92);e=s,a=a.bytes(),r=r.bytes()}t.start(),t.update(a)},n.update=function(i){t.update(i)},n.getMac=function(){var i=t.digest().bytes();return t.start(),t.update(r),t.update(i),t.digest()},n.digest=n.getMac,n}});var ua=H((sy,ys)=>{"use strict";var vt=W();mt();re();var ps=ys.exports=vt.md5=vt.md5||{};vt.md.md5=vt.md.algorithms.md5=ps;ps.create=function(){hs||Ll();var e=null,t=vt.util.createBuffer(),a=new Array(16),r={algorithm:"md5",blockLength:64,digestLength:16,messageLength:0,fullMessageLength:null,messageLengthSize:8};return r.start=function(){r.messageLength=0,r.fullMessageLength=r.messageLength64=[];for(var n=r.messageLengthSize/4,i=0;i<n;++i)r.fullMessageLength.push(0);return t=vt.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878},r},r.start(),r.update=function(n,i){i==="utf8"&&(n=vt.util.encodeUtf8(n));var s=n.length;r.messageLength+=s,s=[s/4294967296>>>0,s>>>0];for(var o=r.fullMessageLength.length-1;o>=0;--o)r.fullMessageLength[o]+=s[1],s[1]=s[0]+(r.fullMessageLength[o]/4294967296>>>0),r.fullMessageLength[o]=r.fullMessageLength[o]>>>0,s[0]=s[1]/4294967296>>>0;return t.putBytes(n),ds(e,a,t),(t.read>2048||t.length()===0)&&t.compact(),r},r.digest=function(){var n=vt.util.createBuffer();n.putBytes(t.bytes());var i=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,s=i&r.blockLength-1;n.putBytes(ln.substr(0,r.blockLength-s));for(var o,u=0,l=r.fullMessageLength.length-1;l>=0;--l)o=r.fullMessageLength[l]*8+u,u=o/4294967296>>>0,n.putInt32Le(o>>>0);var f={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3};ds(f,a,n);var c=vt.util.createBuffer();return c.putInt32Le(f.h0),c.putInt32Le(f.h1),c.putInt32Le(f.h2),c.putInt32Le(f.h3),c},r};var ln=null,oa=null,Pr=null,pr=null,hs=!1;function Ll(){ln="\x80",ln+=vt.util.fillString("\0",64),oa=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,1,6,11,0,5,10,15,4,9,14,3,8,13,2,7,12,5,8,11,14,1,4,7,10,13,0,3,6,9,12,15,2,0,7,14,5,12,3,10,1,8,15,6,13,4,11,2,9],Pr=[7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21],pr=new Array(64);for(var e=0;e<64;++e)pr[e]=Math.floor(Math.abs(Math.sin(e+1))*4294967296);hs=!0}function ds(e,t,a){for(var r,n,i,s,o,u,l,f,c=a.length();c>=64;){for(n=e.h0,i=e.h1,s=e.h2,o=e.h3,f=0;f<16;++f)t[f]=a.getInt32Le(),u=o^i&(s^o),r=n+u+pr[f]+t[f],l=Pr[f],n=o,o=s,s=i,i+=r<<l|r>>>32-l;for(;f<32;++f)u=s^o&(i^s),r=n+u+pr[f]+t[oa[f]],l=Pr[f],n=o,o=s,s=i,i+=r<<l|r>>>32-l;for(;f<48;++f)u=i^s^o,r=n+u+pr[f]+t[oa[f]],l=Pr[f],n=o,o=s,s=i,i+=r<<l|r>>>32-l;for(;f<64;++f)u=s^(i|~o),r=n+u+pr[f]+t[oa[f]],l=Pr[f],n=o,o=s,s=i,i+=r<<l|r>>>32-l;e.h0=e.h0+n|0,e.h1=e.h1+i|0,e.h2=e.h2+s|0,e.h3=e.h3+o|0,c-=64}}});var Zt=H((oy,ms)=>{"use strict";var fa=W();re();var gs=ms.exports=fa.pem=fa.pem||{};gs.encode=function(e,t){t=t||{};var a="-----BEGIN "+e.type+`-----\r
17
+ `,r;if(e.procType&&(r={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]},a+=la(r)),e.contentDomain&&(r={name:"Content-Domain",values:[e.contentDomain]},a+=la(r)),e.dekInfo&&(r={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters&&r.values.push(e.dekInfo.parameters),a+=la(r)),e.headers)for(var n=0;n<e.headers.length;++n)a+=la(e.headers[n]);return e.procType&&(a+=`\r
18
+ `),a+=fa.util.encode64(e.body,t.maxline||64)+`\r
19
+ `,a+="-----END "+e.type+`-----\r
20
+ `,a};gs.decode=function(e){for(var t=[],a=/\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g,r=/([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/,n=/\r?\n/,i;i=a.exec(e),!!i;){var s=i[1];s==="NEW CERTIFICATE REQUEST"&&(s="CERTIFICATE REQUEST");var o={type:s,procType:null,contentDomain:null,dekInfo:null,headers:[],body:fa.util.decode64(i[3])};if(t.push(o),!!i[2]){for(var u=i[2].split(n),l=0;i&&l<u.length;){for(var f=u[l].replace(/\s+$/,""),c=l+1;c<u.length;++c){var g=u[c];if(!/\s/.test(g[0]))break;f+=g,l=c}if(i=f.match(r),i){for(var m={name:i[1],values:[]},h=i[2].split(","),v=0;v<h.length;++v)m.values.push(kl(h[v]));if(o.procType)if(!o.contentDomain&&m.name==="Content-Domain")o.contentDomain=h[0]||"";else if(!o.dekInfo&&m.name==="DEK-Info"){if(m.values.length===0)throw new Error('Invalid PEM formatted message. The "DEK-Info" header must have at least one subfield.');o.dekInfo={algorithm:h[0],parameters:h[1]||null}}else o.headers.push(m);else{if(m.name!=="Proc-Type")throw new Error('Invalid PEM formatted message. The first encapsulated header must be "Proc-Type".');if(m.values.length!==2)throw new Error('Invalid PEM formatted message. The "Proc-Type" header must have two subfields.');o.procType={version:h[0],type:h[1]}}}++l}if(o.procType==="ENCRYPTED"&&!o.dekInfo)throw new Error('Invalid PEM formatted message. The "DEK-Info" header must be present if "Proc-Type" is "ENCRYPTED".')}}if(t.length===0)throw new Error("Invalid PEM formatted message.");return t};function la(e){for(var t=e.name+": ",a=[],r=function(u,l){return" "+l},n=0;n<e.values.length;++n)a.push(e.values[n].replace(/^(\S+\r\n)/,r));t+=a.join(",")+`\r
21
+ `;for(var i=0,s=-1,n=0;n<t.length;++n,++i)if(i>65&&s!==-1){var o=t[s];o===","?(++s,t=t.substr(0,s)+`\r
22
+ `+t.substr(s)):t=t.substr(0,s)+`\r
23
+ `+o+t.substr(s+1),i=n-s-1,s=-1,++n}else(t[n]===" "||t[n]===" "||t[n]===",")&&(s=n);return t}function kl(e){return e.replace(/^\s+/,"")}});var Dr=H((uy,Cs)=>{"use strict";var ge=W();ta();an();re();Cs.exports=ge.des=ge.des||{};ge.des.startEncrypting=function(e,t,a,r){var n=ca({key:e,output:a,decrypt:!1,mode:r||(t===null?"ECB":"CBC")});return n.start(t),n};ge.des.createEncryptionCipher=function(e,t){return ca({key:e,output:null,decrypt:!1,mode:t})};ge.des.startDecrypting=function(e,t,a,r){var n=ca({key:e,output:a,decrypt:!0,mode:r||(t===null?"ECB":"CBC")});return n.start(t),n};ge.des.createDecryptionCipher=function(e,t){return ca({key:e,output:null,decrypt:!0,mode:t})};ge.des.Algorithm=function(e,t){var a=this;a.name=e,a.mode=new t({blockSize:8,cipher:{encrypt:function(r,n){return vs(a._keys,r,n,!1)},decrypt:function(r,n){return vs(a._keys,r,n,!0)}}}),a._init=!1};ge.des.Algorithm.prototype.initialize=function(e){if(!this._init){var t=ge.util.createBuffer(e.key);if(this.name.indexOf("3DES")===0&&t.length()!==24)throw new Error("Invalid Triple-DES key size: "+t.length()*8);this._keys=zl(t),this._init=!0}};Ct("DES-ECB",ge.cipher.modes.ecb);Ct("DES-CBC",ge.cipher.modes.cbc);Ct("DES-CFB",ge.cipher.modes.cfb);Ct("DES-OFB",ge.cipher.modes.ofb);Ct("DES-CTR",ge.cipher.modes.ctr);Ct("3DES-ECB",ge.cipher.modes.ecb);Ct("3DES-CBC",ge.cipher.modes.cbc);Ct("3DES-CFB",ge.cipher.modes.cfb);Ct("3DES-OFB",ge.cipher.modes.ofb);Ct("3DES-CTR",ge.cipher.modes.ctr);function Ct(e,t){var a=function(){return new ge.des.Algorithm(e,t)};ge.cipher.registerAlgorithm(e,a)}var Ul=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],Fl=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],Ol=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],Vl=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],Ml=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],Kl=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],ql=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],Hl=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function zl(e){for(var t=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],a=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],r=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],n=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],i=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],s=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],o=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],u=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],l=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],f=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],c=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],g=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],m=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],h=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],v=e.length()>8?3:1,E=[],T=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],I=0,A,L=0;L<v;L++){var N=e.getInt32(),P=e.getInt32();A=(N>>>4^P)&252645135,P^=A,N^=A<<4,A=(P>>>-16^N)&65535,N^=A,P^=A<<-16,A=(N>>>2^P)&858993459,P^=A,N^=A<<2,A=(P>>>-16^N)&65535,N^=A,P^=A<<-16,A=(N>>>1^P)&1431655765,P^=A,N^=A<<1,A=(P>>>8^N)&16711935,N^=A,P^=A<<8,A=(N>>>1^P)&1431655765,P^=A,N^=A<<1,A=N<<8|P>>>20&240,N=P<<24|P<<8&16711680|P>>>8&65280|P>>>24&240,P=A;for(var G=0;G<T.length;++G){T[G]?(N=N<<2|N>>>26,P=P<<2|P>>>26):(N=N<<1|N>>>27,P=P<<1|P>>>27),N&=-15,P&=-15;var j=t[N>>>28]|a[N>>>24&15]|r[N>>>20&15]|n[N>>>16&15]|i[N>>>12&15]|s[N>>>8&15]|o[N>>>4&15],ie=u[P>>>28]|l[P>>>24&15]|f[P>>>20&15]|c[P>>>16&15]|g[P>>>12&15]|m[P>>>8&15]|h[P>>>4&15];A=(ie>>>16^j)&65535,E[I++]=j^A,E[I++]=ie^A<<16}}return E}function vs(e,t,a,r){var n=e.length===32?3:9,i;n===3?i=r?[30,-2,-2]:[0,32,2]:i=r?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var s,o=t[0],u=t[1];s=(o>>>4^u)&252645135,u^=s,o^=s<<4,s=(o>>>16^u)&65535,u^=s,o^=s<<16,s=(u>>>2^o)&858993459,o^=s,u^=s<<2,s=(u>>>8^o)&16711935,o^=s,u^=s<<8,s=(o>>>1^u)&1431655765,u^=s,o^=s<<1,o=o<<1|o>>>31,u=u<<1|u>>>31;for(var l=0;l<n;l+=3){for(var f=i[l+1],c=i[l+2],g=i[l];g!=f;g+=c){var m=u^e[g],h=(u>>>4|u<<28)^e[g+1];s=o,o=u,u=s^(Fl[m>>>24&63]|Vl[m>>>16&63]|Kl[m>>>8&63]|Hl[m&63]|Ul[h>>>24&63]|Ol[h>>>16&63]|Ml[h>>>8&63]|ql[h&63])}s=o,o=u,u=s}o=o>>>1|o<<31,u=u>>>1|u<<31,s=(o>>>1^u)&1431655765,u^=s,o^=s<<1,s=(u>>>8^o)&16711935,o^=s,u^=s<<8,s=(u>>>2^o)&858993459,o^=s,u^=s<<2,s=(o>>>16^u)&65535,u^=s,o^=s<<16,s=(o>>>4^u)&252645135,u^=s,o^=s<<4,a[0]=o,a[1]=u}function ca(e){e=e||{};var t=(e.mode||"CBC").toUpperCase(),a="DES-"+t,r;e.decrypt?r=ge.cipher.createDecipher(a,e.key):r=ge.cipher.createCipher(a,e.key);var n=r.start;return r.start=function(i,s){var o=null;s instanceof ge.util.ByteBuffer&&(o=s,s={}),s=s||{},s.output=o,s.iv=i,n.call(r,s)},r}});var da=H((ly,Es)=>{"use strict";var je=W();dr();mt();re();var Gl=je.pkcs5=je.pkcs5||{},Bt;je.util.isNodejs&&!je.options.usePureJavaScript&&(Bt=Dt("crypto"));Es.exports=je.pbkdf2=Gl.pbkdf2=function(e,t,a,r,n,i){if(typeof n=="function"&&(i=n,n=null),je.util.isNodejs&&!je.options.usePureJavaScript&&Bt.pbkdf2&&(n===null||typeof n!="object")&&(Bt.pbkdf2Sync.length>4||!n||n==="sha1"))return typeof n!="string"&&(n="sha1"),e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),i?Bt.pbkdf2Sync.length===4?Bt.pbkdf2(e,t,a,r,function(A,L){if(A)return i(A);i(null,L.toString("binary"))}):Bt.pbkdf2(e,t,a,r,n,function(A,L){if(A)return i(A);i(null,L.toString("binary"))}):Bt.pbkdf2Sync.length===4?Bt.pbkdf2Sync(e,t,a,r).toString("binary"):Bt.pbkdf2Sync(e,t,a,r,n).toString("binary");if((typeof n>"u"||n===null)&&(n="sha1"),typeof n=="string"){if(!(n in je.md.algorithms))throw new Error("Unknown hash algorithm: "+n);n=je.md[n].create()}var s=n.digestLength;if(r>4294967295*s){var o=new Error("Derived key is too long.");if(i)return i(o);throw o}var u=Math.ceil(r/s),l=r-(u-1)*s,f=je.hmac.create();f.start(n,e);var c="",g,m,h;if(!i){for(var v=1;v<=u;++v){f.start(null,null),f.update(t),f.update(je.util.int32ToBytes(v)),g=h=f.digest().getBytes();for(var E=2;E<=a;++E)f.start(null,null),f.update(h),m=f.digest().getBytes(),g=je.util.xorBytes(g,m,s),h=m;c+=v<u?g:g.substr(0,l)}return c}var v=1,E;function T(){if(v>u)return i(null,c);f.start(null,null),f.update(t),f.update(je.util.int32ToBytes(v)),g=h=f.digest().getBytes(),E=2,I()}function I(){if(E<=a)return f.start(null,null),f.update(h),m=f.digest().getBytes(),g=je.util.xorBytes(g,m,s),h=m,++E,je.util.setImmediate(I);c+=v<u?g:g.substr(0,l),++v,T()}T()}});var cn=H((fy,Is)=>{"use strict";var Et=W();mt();re();var Ss=Is.exports=Et.sha256=Et.sha256||{};Et.md.sha256=Et.md.algorithms.sha256=Ss;Ss.create=function(){Ts||Ql();var e=null,t=Et.util.createBuffer(),a=new Array(64),r={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};return r.start=function(){r.messageLength=0,r.fullMessageLength=r.messageLength64=[];for(var n=r.messageLengthSize/4,i=0;i<n;++i)r.fullMessageLength.push(0);return t=Et.util.createBuffer(),e={h0:1779033703,h1:3144134277,h2:1013904242,h3:2773480762,h4:1359893119,h5:2600822924,h6:528734635,h7:1541459225},r},r.start(),r.update=function(n,i){i==="utf8"&&(n=Et.util.encodeUtf8(n));var s=n.length;r.messageLength+=s,s=[s/4294967296>>>0,s>>>0];for(var o=r.fullMessageLength.length-1;o>=0;--o)r.fullMessageLength[o]+=s[1],s[1]=s[0]+(r.fullMessageLength[o]/4294967296>>>0),r.fullMessageLength[o]=r.fullMessageLength[o]>>>0,s[0]=s[1]/4294967296>>>0;return t.putBytes(n),xs(e,a,t),(t.read>2048||t.length()===0)&&t.compact(),r},r.digest=function(){var n=Et.util.createBuffer();n.putBytes(t.bytes());var i=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,s=i&r.blockLength-1;n.putBytes(fn.substr(0,r.blockLength-s));for(var o,u,l=r.fullMessageLength[0]*8,f=0;f<r.fullMessageLength.length-1;++f)o=r.fullMessageLength[f+1]*8,u=o/4294967296>>>0,l+=u,n.putInt32(l>>>0),l=o>>>0;n.putInt32(l);var c={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};xs(c,a,n);var g=Et.util.createBuffer();return g.putInt32(c.h0),g.putInt32(c.h1),g.putInt32(c.h2),g.putInt32(c.h3),g.putInt32(c.h4),g.putInt32(c.h5),g.putInt32(c.h6),g.putInt32(c.h7),g},r};var fn=null,Ts=!1,bs=null;function Ql(){fn="\x80",fn+=Et.util.fillString("\0",64),bs=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],Ts=!0}function xs(e,t,a){for(var r,n,i,s,o,u,l,f,c,g,m,h,v,E,T,I=a.length();I>=64;){for(l=0;l<16;++l)t[l]=a.getInt32();for(;l<64;++l)r=t[l-2],r=(r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10,n=t[l-15],n=(n>>>7|n<<25)^(n>>>18|n<<14)^n>>>3,t[l]=r+t[l-7]+n+t[l-16]|0;for(f=e.h0,c=e.h1,g=e.h2,m=e.h3,h=e.h4,v=e.h5,E=e.h6,T=e.h7,l=0;l<64;++l)s=(h>>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7),o=E^h&(v^E),i=(f>>>2|f<<30)^(f>>>13|f<<19)^(f>>>22|f<<10),u=f&c|g&(f^c),r=T+s+o+bs[l]+t[l],n=i+u,T=E,E=v,v=h,h=m+r>>>0,m=g,g=c,c=f,f=r+n>>>0;e.h0=e.h0+f|0,e.h1=e.h1+c|0,e.h2=e.h2+g|0,e.h3=e.h3+m|0,e.h4=e.h4+h|0,e.h5=e.h5+v|0,e.h6=e.h6+E|0,e.h7=e.h7+T|0,I-=64}}});var dn=H((cy,ws)=>{"use strict";var xt=W();re();var pa=null;xt.util.isNodejs&&!xt.options.usePureJavaScript&&!process.versions["node-webkit"]&&(pa=Dt("crypto"));var Wl=ws.exports=xt.prng=xt.prng||{};Wl.create=function(e){for(var t={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},a=e.md,r=new Array(32),n=0;n<32;++n)r[n]=a.create();t.pools=r,t.pool=0,t.generate=function(l,f){if(!f)return t.generateSync(l);var c=t.plugin.cipher,g=t.plugin.increment,m=t.plugin.formatKey,h=t.plugin.formatSeed,v=xt.util.createBuffer();t.key=null,E();function E(T){if(T)return f(T);if(v.length()>=l)return f(null,v.getBytes(l));if(t.generated>1048575&&(t.key=null),t.key===null)return xt.util.nextTick(function(){i(E)});var I=c(t.key,t.seed);t.generated+=I.length,v.putBytes(I),t.key=m(c(t.key,g(t.seed))),t.seed=h(c(t.key,t.seed)),xt.util.setImmediate(E)}},t.generateSync=function(l){var f=t.plugin.cipher,c=t.plugin.increment,g=t.plugin.formatKey,m=t.plugin.formatSeed;t.key=null;for(var h=xt.util.createBuffer();h.length()<l;){t.generated>1048575&&(t.key=null),t.key===null&&s();var v=f(t.key,t.seed);t.generated+=v.length,h.putBytes(v),t.key=g(f(t.key,c(t.seed))),t.seed=m(f(t.key,t.seed))}return h.getBytes(l)};function i(l){if(t.pools[0].messageLength>=32)return o(),l();var f=32-t.pools[0].messageLength<<5;t.seedFile(f,function(c,g){if(c)return l(c);t.collect(g),o(),l()})}function s(){if(t.pools[0].messageLength>=32)return o();var l=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(l)),o()}function o(){t.reseeds=t.reseeds===4294967295?0:t.reseeds+1;var l=t.plugin.md.create();l.update(t.keyBytes);for(var f=1,c=0;c<32;++c)t.reseeds%f===0&&(l.update(t.pools[c].digest().getBytes()),t.pools[c].start()),f=f<<1;t.keyBytes=l.digest().getBytes(),l.start(),l.update(t.keyBytes);var g=l.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(g),t.generated=0}function u(l){var f=null,c=xt.util.globalScope,g=c.crypto||c.msCrypto;g&&g.getRandomValues&&(f=function(N){return g.getRandomValues(N)});var m=xt.util.createBuffer();if(f)for(;m.length()<l;){var h=Math.max(1,Math.min(l-m.length(),65536)/4),v=new Uint32Array(Math.floor(h));try{f(v);for(var E=0;E<v.length;++E)m.putInt32(v[E])}catch(N){if(!(typeof QuotaExceededError<"u"&&N instanceof QuotaExceededError))throw N}}if(m.length()<l)for(var T,I,A,L=Math.floor(Math.random()*65536);m.length()<l;){I=16807*(L&65535),T=16807*(L>>16),I+=(T&32767)<<16,I+=T>>15,I=(I&2147483647)+(I>>31),L=I&4294967295;for(var E=0;E<3;++E)A=L>>>(E<<3),A^=Math.floor(Math.random()*256),m.putByte(A&255)}return m.getBytes(l)}return pa?(t.seedFile=function(l,f){pa.randomBytes(l,function(c,g){if(c)return f(c);f(null,g.toString())})},t.seedFileSync=function(l){return pa.randomBytes(l).toString()}):(t.seedFile=function(l,f){try{f(null,u(l))}catch(c){f(c)}},t.seedFileSync=u),t.collect=function(l){for(var f=l.length,c=0;c<f;++c)t.pools[t.pool].update(l.substr(c,1)),t.pool=t.pool===31?0:t.pool+1},t.collectInt=function(l,f){for(var c="",g=0;g<f;g+=8)c+=String.fromCharCode(l>>g&255);t.collect(c)},t.registerWorker=function(l){if(l===self)t.seedFile=function(c,g){function m(h){var v=h.data;v.forge&&v.forge.prng&&(self.removeEventListener("message",m),g(v.forge.prng.err,v.forge.prng.bytes))}self.addEventListener("message",m),self.postMessage({forge:{prng:{needed:c}}})};else{var f=function(c){var g=c.data;g.forge&&g.forge.prng&&t.seedFile(g.forge.prng.needed,function(m,h){l.postMessage({forge:{prng:{err:m,bytes:h}}})})};l.addEventListener("message",f)}},t}});var it=H((dy,pn)=>{"use strict";var Ae=W();Ut();cn();dn();re();(function(){if(Ae.random&&Ae.random.getBytes){pn.exports=Ae.random;return}(function(e){var t={},a=new Array(4),r=Ae.util.createBuffer();t.formatKey=function(c){var g=Ae.util.createBuffer(c);return c=new Array(4),c[0]=g.getInt32(),c[1]=g.getInt32(),c[2]=g.getInt32(),c[3]=g.getInt32(),Ae.aes._expandKey(c,!1)},t.formatSeed=function(c){var g=Ae.util.createBuffer(c);return c=new Array(4),c[0]=g.getInt32(),c[1]=g.getInt32(),c[2]=g.getInt32(),c[3]=g.getInt32(),c},t.cipher=function(c,g){return Ae.aes._updateBlock(c,g,a,!1),r.putInt32(a[0]),r.putInt32(a[1]),r.putInt32(a[2]),r.putInt32(a[3]),r.getBytes()},t.increment=function(c){return++c[3],c},t.md=Ae.md.sha256;function n(){var c=Ae.prng.create(t);return c.getBytes=function(g,m){return c.generate(g,m)},c.getBytesSync=function(g){return c.generate(g)},c}var i=n(),s=null,o=Ae.util.globalScope,u=o.crypto||o.msCrypto;if(u&&u.getRandomValues&&(s=function(c){return u.getRandomValues(c)}),Ae.options.usePureJavaScript||!Ae.util.isNodejs&&!s){if(typeof window>"u"||window.document,i.collectInt(+new Date,32),typeof navigator<"u"){var l="";for(var f in navigator)try{typeof navigator[f]=="string"&&(l+=navigator[f])}catch{}i.collect(l),l=null}e&&(e().mousemove(function(c){i.collectInt(c.clientX,16),i.collectInt(c.clientY,16)}),e().keypress(function(c){i.collectInt(c.charCode,8)}))}if(!Ae.random)Ae.random=i;else for(var f in i)Ae.random[f]=i[f];Ae.random.createInstance=n,pn.exports=Ae.random})(typeof jQuery<"u"?jQuery:null)})()});var yn=H((py,Rs)=>{"use strict";var Ze=W();re();var hn=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],As=[1,2,3,5],jl=function(e,t){return e<<t&65535|(e&65535)>>16-t},$l=function(e,t){return(e&65535)>>t|e<<16-t&65535};Rs.exports=Ze.rc2=Ze.rc2||{};Ze.rc2.expandKey=function(e,t){typeof e=="string"&&(e=Ze.util.createBuffer(e)),t=t||128;var a=e,r=e.length(),n=t,i=Math.ceil(n/8),s=255>>(n&7),o;for(o=r;o<128;o++)a.putByte(hn[a.at(o-1)+a.at(o-r)&255]);for(a.setAt(128-i,hn[a.at(128-i)&s]),o=127-i;o>=0;o--)a.setAt(o,hn[a.at(o+1)^a.at(o+i)]);return a};var Bs=function(e,t,a){var r=!1,n=null,i=null,s=null,o,u,l,f,c=[];for(e=Ze.rc2.expandKey(e,t),l=0;l<64;l++)c.push(e.getInt16Le());a?(o=function(h){for(l=0;l<4;l++)h[l]+=c[f]+(h[(l+3)%4]&h[(l+2)%4])+(~h[(l+3)%4]&h[(l+1)%4]),h[l]=jl(h[l],As[l]),f++},u=function(h){for(l=0;l<4;l++)h[l]+=c[h[(l+3)%4]&63]}):(o=function(h){for(l=3;l>=0;l--)h[l]=$l(h[l],As[l]),h[l]-=c[f]+(h[(l+3)%4]&h[(l+2)%4])+(~h[(l+3)%4]&h[(l+1)%4]),f--},u=function(h){for(l=3;l>=0;l--)h[l]-=c[h[(l+3)%4]&63]});var g=function(h){var v=[];for(l=0;l<4;l++){var E=n.getInt16Le();s!==null&&(a?E^=s.getInt16Le():s.putInt16Le(E)),v.push(E&65535)}f=a?0:63;for(var T=0;T<h.length;T++)for(var I=0;I<h[T][0];I++)h[T][1](v);for(l=0;l<4;l++)s!==null&&(a?s.putInt16Le(v[l]):v[l]^=s.getInt16Le()),i.putInt16Le(v[l])},m=null;return m={start:function(h,v){h&&typeof h=="string"&&(h=Ze.util.createBuffer(h)),r=!1,n=Ze.util.createBuffer(),i=v||new Ze.util.createBuffer,s=h,m.output=i},update:function(h){for(r||n.putBuffer(h);n.length()>=8;)g([[5,o],[1,u],[6,o],[1,u],[5,o]])},finish:function(h){var v=!0;if(a)if(h)v=h(8,n,!a);else{var E=n.length()===8?8:8-n.length();n.fillWithByte(E,E)}if(v&&(r=!0,m.update()),!a&&(v=n.length()===0,v))if(h)v=h(8,i,!a);else{var T=i.length(),I=i.at(T-1);I>T?v=!1:i.truncate(I)}return v}},m};Ze.rc2.startEncrypting=function(e,t,a){var r=Ze.rc2.createEncryptionCipher(e,128);return r.start(t,a),r};Ze.rc2.createEncryptionCipher=function(e,t){return Bs(e,t,!0)};Ze.rc2.startDecrypting=function(e,t,a){var r=Ze.rc2.createDecryptionCipher(e,128);return r.start(t,a),r};Ze.rc2.createDecryptionCipher=function(e,t){return Bs(e,t,!1)}});var kr=H((hy,Fs)=>{"use strict";var gn=W();Fs.exports=gn.jsbn=gn.jsbn||{};var Rt,Yl=0xdeadbeefcafe,_s=(Yl&16777215)==15715070;function B(e,t,a){this.data=[],e!=null&&(typeof e=="number"?this.fromNumber(e,t,a):t==null&&typeof e!="string"?this.fromString(e,256):this.fromString(e,t))}gn.jsbn.BigInteger=B;function ae(){return new B(null)}function Xl(e,t,a,r,n,i){for(;--i>=0;){var s=t*this.data[e++]+a.data[r]+n;n=Math.floor(s/67108864),a.data[r++]=s&67108863}return n}function Zl(e,t,a,r,n,i){for(var s=t&32767,o=t>>15;--i>=0;){var u=this.data[e]&32767,l=this.data[e++]>>15,f=o*u+l*s;u=s*u+((f&32767)<<15)+a.data[r]+(n&1073741823),n=(u>>>30)+(f>>>15)+o*l+(n>>>30),a.data[r++]=u&1073741823}return n}function Ns(e,t,a,r,n,i){for(var s=t&16383,o=t>>14;--i>=0;){var u=this.data[e]&16383,l=this.data[e++]>>14,f=o*u+l*s;u=s*u+((f&16383)<<14)+a.data[r]+n,n=(u>>28)+(f>>14)+o*l,a.data[r++]=u&268435455}return n}typeof navigator>"u"?(B.prototype.am=Ns,Rt=28):_s&&navigator.appName=="Microsoft Internet Explorer"?(B.prototype.am=Zl,Rt=30):_s&&navigator.appName!="Netscape"?(B.prototype.am=Xl,Rt=26):(B.prototype.am=Ns,Rt=28);B.prototype.DB=Rt;B.prototype.DM=(1<<Rt)-1;B.prototype.DV=1<<Rt;var mn=52;B.prototype.FV=Math.pow(2,mn);B.prototype.F1=mn-Rt;B.prototype.F2=2*Rt-mn;var Jl="0123456789abcdefghijklmnopqrstuvwxyz",ha=new Array,hr,st;hr=48;for(st=0;st<=9;++st)ha[hr++]=st;hr=97;for(st=10;st<36;++st)ha[hr++]=st;hr=65;for(st=10;st<36;++st)ha[hr++]=st;function Ps(e){return Jl.charAt(e)}function Ds(e,t){var a=ha[e.charCodeAt(t)];return a??-1}function ef(e){for(var t=this.t-1;t>=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s}function tf(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+this.DV:this.t=0}function Ot(e){var t=ae();return t.fromInt(e),t}function rf(e,t){var a;if(t==16)a=4;else if(t==8)a=3;else if(t==256)a=8;else if(t==2)a=1;else if(t==32)a=5;else if(t==4)a=2;else{this.fromRadix(e,t);return}this.t=0,this.s=0;for(var r=e.length,n=!1,i=0;--r>=0;){var s=a==8?e[r]&255:Ds(e,r);if(s<0){e.charAt(r)=="-"&&(n=!0);continue}n=!1,i==0?this.data[this.t++]=s:i+a>this.DB?(this.data[this.t-1]|=(s&(1<<this.DB-i)-1)<<i,this.data[this.t++]=s>>this.DB-i):this.data[this.t-1]|=s<<i,i+=a,i>=this.DB&&(i-=this.DB)}a==8&&(e[0]&128)!=0&&(this.s=-1,i>0&&(this.data[this.t-1]|=(1<<this.DB-i)-1<<i)),this.clamp(),n&&B.ZERO.subTo(this,this)}function af(){for(var e=this.s&this.DM;this.t>0&&this.data[this.t-1]==e;)--this.t}function nf(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(e==16)t=4;else if(e==8)t=3;else if(e==2)t=1;else if(e==32)t=5;else if(e==4)t=2;else return this.toRadix(e);var a=(1<<t)-1,r,n=!1,i="",s=this.t,o=this.DB-s*this.DB%t;if(s-- >0)for(o<this.DB&&(r=this.data[s]>>o)>0&&(n=!0,i=Ps(r));s>=0;)o<t?(r=(this.data[s]&(1<<o)-1)<<t-o,r|=this.data[--s]>>(o+=this.DB-t)):(r=this.data[s]>>(o-=t)&a,o<=0&&(o+=this.DB,--s)),r>0&&(n=!0),n&&(i+=Ps(r));return n?i:"0"}function sf(){var e=ae();return B.ZERO.subTo(this,e),e}function of(){return this.s<0?this.negate():this}function uf(e){var t=this.s-e.s;if(t!=0)return t;var a=this.t;if(t=a-e.t,t!=0)return this.s<0?-t:t;for(;--a>=0;)if((t=this.data[a]-e.data[a])!=0)return t;return 0}function ya(e){var t=1,a;return(a=e>>>16)!=0&&(e=a,t+=16),(a=e>>8)!=0&&(e=a,t+=8),(a=e>>4)!=0&&(e=a,t+=4),(a=e>>2)!=0&&(e=a,t+=2),(a=e>>1)!=0&&(e=a,t+=1),t}function lf(){return this.t<=0?0:this.DB*(this.t-1)+ya(this.data[this.t-1]^this.s&this.DM)}function ff(e,t){var a;for(a=this.t-1;a>=0;--a)t.data[a+e]=this.data[a];for(a=e-1;a>=0;--a)t.data[a]=0;t.t=this.t+e,t.s=this.s}function cf(e,t){for(var a=e;a<this.t;++a)t.data[a-e]=this.data[a];t.t=Math.max(this.t-e,0),t.s=this.s}function df(e,t){var a=e%this.DB,r=this.DB-a,n=(1<<r)-1,i=Math.floor(e/this.DB),s=this.s<<a&this.DM,o;for(o=this.t-1;o>=0;--o)t.data[o+i+1]=this.data[o]>>r|s,s=(this.data[o]&n)<<a;for(o=i-1;o>=0;--o)t.data[o]=0;t.data[i]=s,t.t=this.t+i+1,t.s=this.s,t.clamp()}function pf(e,t){t.s=this.s;var a=Math.floor(e/this.DB);if(a>=this.t){t.t=0;return}var r=e%this.DB,n=this.DB-r,i=(1<<r)-1;t.data[0]=this.data[a]>>r;for(var s=a+1;s<this.t;++s)t.data[s-a-1]|=(this.data[s]&i)<<n,t.data[s-a]=this.data[s]>>r;r>0&&(t.data[this.t-a-1]|=(this.s&i)<<n),t.t=this.t-a,t.clamp()}function hf(e,t){for(var a=0,r=0,n=Math.min(e.t,this.t);a<n;)r+=this.data[a]-e.data[a],t.data[a++]=r&this.DM,r>>=this.DB;if(e.t<this.t){for(r-=e.s;a<this.t;)r+=this.data[a],t.data[a++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;a<e.t;)r-=e.data[a],t.data[a++]=r&this.DM,r>>=this.DB;r-=e.s}t.s=r<0?-1:0,r<-1?t.data[a++]=this.DV+r:r>0&&(t.data[a++]=r),t.t=a,t.clamp()}function yf(e,t){var a=this.abs(),r=e.abs(),n=a.t;for(t.t=n+r.t;--n>=0;)t.data[n]=0;for(n=0;n<r.t;++n)t.data[n+a.t]=a.am(0,r.data[n],t,n,0,a.t);t.s=0,t.clamp(),this.s!=e.s&&B.ZERO.subTo(t,t)}function gf(e){for(var t=this.abs(),a=e.t=2*t.t;--a>=0;)e.data[a]=0;for(a=0;a<t.t-1;++a){var r=t.am(a,t.data[a],e,2*a,0,1);(e.data[a+t.t]+=t.am(a+1,2*t.data[a],e,2*a+1,r,t.t-a-1))>=t.DV&&(e.data[a+t.t]-=t.DV,e.data[a+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(a,t.data[a],e,2*a,0,1)),e.s=0,e.clamp()}function mf(e,t,a){var r=e.abs();if(!(r.t<=0)){var n=this.abs();if(n.t<r.t){t?.fromInt(0),a!=null&&this.copyTo(a);return}a==null&&(a=ae());var i=ae(),s=this.s,o=e.s,u=this.DB-ya(r.data[r.t-1]);u>0?(r.lShiftTo(u,i),n.lShiftTo(u,a)):(r.copyTo(i),n.copyTo(a));var l=i.t,f=i.data[l-1];if(f!=0){var c=f*(1<<this.F1)+(l>1?i.data[l-2]>>this.F2:0),g=this.FV/c,m=(1<<this.F1)/c,h=1<<this.F2,v=a.t,E=v-l,T=t??ae();for(i.dlShiftTo(E,T),a.compareTo(T)>=0&&(a.data[a.t++]=1,a.subTo(T,a)),B.ONE.dlShiftTo(l,T),T.subTo(i,i);i.t<l;)i.data[i.t++]=0;for(;--E>=0;){var I=a.data[--v]==f?this.DM:Math.floor(a.data[v]*g+(a.data[v-1]+h)*m);if((a.data[v]+=i.am(0,I,a,E,0,l))<I)for(i.dlShiftTo(E,T),a.subTo(T,a);a.data[v]<--I;)a.subTo(T,a)}t!=null&&(a.drShiftTo(l,t),s!=o&&B.ZERO.subTo(t,t)),a.t=l,a.clamp(),u>0&&a.rShiftTo(u,a),s<0&&B.ZERO.subTo(a,a)}}}function vf(e){var t=ae();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(B.ZERO)>0&&e.subTo(t,t),t}function Jt(e){this.m=e}function Cf(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e}function Ef(e){return e}function xf(e){e.divRemTo(this.m,null,e)}function Sf(e,t,a){e.multiplyTo(t,a),this.reduce(a)}function Tf(e,t){e.squareTo(t),this.reduce(t)}Jt.prototype.convert=Cf;Jt.prototype.revert=Ef;Jt.prototype.reduce=xf;Jt.prototype.mulTo=Sf;Jt.prototype.sqrTo=Tf;function bf(){if(this.t<1)return 0;var e=this.data[0];if((e&1)==0)return 0;var t=e&3;return t=t*(2-(e&15)*t)&15,t=t*(2-(e&255)*t)&255,t=t*(2-((e&65535)*t&65535))&65535,t=t*(2-e*t%this.DV)%this.DV,t>0?this.DV-t:-t}function er(e){this.m=e,this.mp=e.invDigit(),this.mpl=this.mp&32767,this.mph=this.mp>>15,this.um=(1<<e.DB-15)-1,this.mt2=2*e.t}function If(e){var t=ae();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(B.ZERO)>0&&this.m.subTo(t,t),t}function wf(e){var t=ae();return e.copyTo(t),this.reduce(t),t}function Af(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t<this.m.t;++t){var a=e.data[t]&32767,r=a*this.mpl+((a*this.mph+(e.data[t]>>15)*this.mpl&this.um)<<15)&e.DM;for(a=t+this.m.t,e.data[a]+=this.m.am(0,r,e,t,0,this.m.t);e.data[a]>=e.DV;)e.data[a]-=e.DV,e.data[++a]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)}function Bf(e,t){e.squareTo(t),this.reduce(t)}function Rf(e,t,a){e.multiplyTo(t,a),this.reduce(a)}er.prototype.convert=If;er.prototype.revert=wf;er.prototype.reduce=Af;er.prototype.mulTo=Rf;er.prototype.sqrTo=Bf;function _f(){return(this.t>0?this.data[0]&1:this.s)==0}function Nf(e,t){if(e>4294967295||e<1)return B.ONE;var a=ae(),r=ae(),n=t.convert(this),i=ya(e)-1;for(n.copyTo(a);--i>=0;)if(t.sqrTo(a,r),(e&1<<i)>0)t.mulTo(r,n,a);else{var s=a;a=r,r=s}return t.revert(a)}function Pf(e,t){var a;return e<256||t.isEven()?a=new Jt(t):a=new er(t),this.exp(e,a)}B.prototype.copyTo=ef;B.prototype.fromInt=tf;B.prototype.fromString=rf;B.prototype.clamp=af;B.prototype.dlShiftTo=ff;B.prototype.drShiftTo=cf;B.prototype.lShiftTo=df;B.prototype.rShiftTo=pf;B.prototype.subTo=hf;B.prototype.multiplyTo=yf;B.prototype.squareTo=gf;B.prototype.divRemTo=mf;B.prototype.invDigit=bf;B.prototype.isEven=_f;B.prototype.exp=Nf;B.prototype.toString=nf;B.prototype.negate=sf;B.prototype.abs=of;B.prototype.compareTo=uf;B.prototype.bitLength=lf;B.prototype.mod=vf;B.prototype.modPowInt=Pf;B.ZERO=Ot(0);B.ONE=Ot(1);function Df(){var e=ae();return this.copyTo(e),e}function Lf(){if(this.s<0){if(this.t==1)return this.data[0]-this.DV;if(this.t==0)return-1}else{if(this.t==1)return this.data[0];if(this.t==0)return 0}return(this.data[1]&(1<<32-this.DB)-1)<<this.DB|this.data[0]}function kf(){return this.t==0?this.s:this.data[0]<<24>>24}function Uf(){return this.t==0?this.s:this.data[0]<<16>>16}function Ff(e){return Math.floor(Math.LN2*this.DB/Math.log(e))}function Of(){return this.s<0?-1:this.t<=0||this.t==1&&this.data[0]<=0?0:1}function Vf(e){if(e==null&&(e=10),this.signum()==0||e<2||e>36)return"0";var t=this.chunkSize(e),a=Math.pow(e,t),r=Ot(a),n=ae(),i=ae(),s="";for(this.divRemTo(r,n,i);n.signum()>0;)s=(a+i.intValue()).toString(e).substr(1)+s,n.divRemTo(r,n,i);return i.intValue().toString(e)+s}function Mf(e,t){this.fromInt(0),t==null&&(t=10);for(var a=this.chunkSize(t),r=Math.pow(t,a),n=!1,i=0,s=0,o=0;o<e.length;++o){var u=Ds(e,o);if(u<0){e.charAt(o)=="-"&&this.signum()==0&&(n=!0);continue}s=t*s+u,++i>=a&&(this.dMultiply(r),this.dAddOffset(s,0),i=0,s=0)}i>0&&(this.dMultiply(Math.pow(t,i)),this.dAddOffset(s,0)),n&&B.ZERO.subTo(this,this)}function Kf(e,t,a){if(typeof t=="number")if(e<2)this.fromInt(1);else for(this.fromNumber(e,a),this.testBit(e-1)||this.bitwiseTo(B.ONE.shiftLeft(e-1),vn,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(B.ONE.shiftLeft(e-1),this);else{var r=new Array,n=e&7;r.length=(e>>3)+1,t.nextBytes(r),n>0?r[0]&=(1<<n)-1:r[0]=0,this.fromString(r,256)}}function qf(){var e=this.t,t=new Array;t[0]=this.s;var a=this.DB-e*this.DB%8,r,n=0;if(e-- >0)for(a<this.DB&&(r=this.data[e]>>a)!=(this.s&this.DM)>>a&&(t[n++]=r|this.s<<this.DB-a);e>=0;)a<8?(r=(this.data[e]&(1<<a)-1)<<8-a,r|=this.data[--e]>>(a+=this.DB-8)):(r=this.data[e]>>(a-=8)&255,a<=0&&(a+=this.DB,--e)),(r&128)!=0&&(r|=-256),n==0&&(this.s&128)!=(r&128)&&++n,(n>0||r!=this.s)&&(t[n++]=r);return t}function Hf(e){return this.compareTo(e)==0}function zf(e){return this.compareTo(e)<0?this:e}function Gf(e){return this.compareTo(e)>0?this:e}function Qf(e,t,a){var r,n,i=Math.min(e.t,this.t);for(r=0;r<i;++r)a.data[r]=t(this.data[r],e.data[r]);if(e.t<this.t){for(n=e.s&this.DM,r=i;r<this.t;++r)a.data[r]=t(this.data[r],n);a.t=this.t}else{for(n=this.s&this.DM,r=i;r<e.t;++r)a.data[r]=t(n,e.data[r]);a.t=e.t}a.s=t(this.s,e.s),a.clamp()}function Wf(e,t){return e&t}function jf(e){var t=ae();return this.bitwiseTo(e,Wf,t),t}function vn(e,t){return e|t}function $f(e){var t=ae();return this.bitwiseTo(e,vn,t),t}function Ls(e,t){return e^t}function Yf(e){var t=ae();return this.bitwiseTo(e,Ls,t),t}function ks(e,t){return e&~t}function Xf(e){var t=ae();return this.bitwiseTo(e,ks,t),t}function Zf(){for(var e=ae(),t=0;t<this.t;++t)e.data[t]=this.DM&~this.data[t];return e.t=this.t,e.s=~this.s,e}function Jf(e){var t=ae();return e<0?this.rShiftTo(-e,t):this.lShiftTo(e,t),t}function ec(e){var t=ae();return e<0?this.lShiftTo(-e,t):this.rShiftTo(e,t),t}function tc(e){if(e==0)return-1;var t=0;return(e&65535)==0&&(e>>=16,t+=16),(e&255)==0&&(e>>=8,t+=8),(e&15)==0&&(e>>=4,t+=4),(e&3)==0&&(e>>=2,t+=2),(e&1)==0&&++t,t}function rc(){for(var e=0;e<this.t;++e)if(this.data[e]!=0)return e*this.DB+tc(this.data[e]);return this.s<0?this.t*this.DB:-1}function ac(e){for(var t=0;e!=0;)e&=e-1,++t;return t}function nc(){for(var e=0,t=this.s&this.DM,a=0;a<this.t;++a)e+=ac(this.data[a]^t);return e}function ic(e){var t=Math.floor(e/this.DB);return t>=this.t?this.s!=0:(this.data[t]&1<<e%this.DB)!=0}function sc(e,t){var a=B.ONE.shiftLeft(e);return this.bitwiseTo(a,t,a),a}function oc(e){return this.changeBit(e,vn)}function uc(e){return this.changeBit(e,ks)}function lc(e){return this.changeBit(e,Ls)}function fc(e,t){for(var a=0,r=0,n=Math.min(e.t,this.t);a<n;)r+=this.data[a]+e.data[a],t.data[a++]=r&this.DM,r>>=this.DB;if(e.t<this.t){for(r+=e.s;a<this.t;)r+=this.data[a],t.data[a++]=r&this.DM,r>>=this.DB;r+=this.s}else{for(r+=this.s;a<e.t;)r+=e.data[a],t.data[a++]=r&this.DM,r>>=this.DB;r+=e.s}t.s=r<0?-1:0,r>0?t.data[a++]=r:r<-1&&(t.data[a++]=this.DV+r),t.t=a,t.clamp()}function cc(e){var t=ae();return this.addTo(e,t),t}function dc(e){var t=ae();return this.subTo(e,t),t}function pc(e){var t=ae();return this.multiplyTo(e,t),t}function hc(e){var t=ae();return this.divRemTo(e,t,null),t}function yc(e){var t=ae();return this.divRemTo(e,null,t),t}function gc(e){var t=ae(),a=ae();return this.divRemTo(e,t,a),new Array(t,a)}function mc(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()}function vc(e,t){if(e!=0){for(;this.t<=t;)this.data[this.t++]=0;for(this.data[t]+=e;this.data[t]>=this.DV;)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}}function Lr(){}function Us(e){return e}function Cc(e,t,a){e.multiplyTo(t,a)}function Ec(e,t){e.squareTo(t)}Lr.prototype.convert=Us;Lr.prototype.revert=Us;Lr.prototype.mulTo=Cc;Lr.prototype.sqrTo=Ec;function xc(e){return this.exp(e,new Lr)}function Sc(e,t,a){var r=Math.min(this.t+e.t,t);for(a.s=0,a.t=r;r>0;)a.data[--r]=0;var n;for(n=a.t-this.t;r<n;++r)a.data[r+this.t]=this.am(0,e.data[r],a,r,0,this.t);for(n=Math.min(e.t,t);r<n;++r)this.am(0,e.data[r],a,r,0,t-r);a.clamp()}function Tc(e,t,a){--t;var r=a.t=this.t+e.t-t;for(a.s=0;--r>=0;)a.data[r]=0;for(r=Math.max(t-this.t,0);r<e.t;++r)a.data[this.t+r-t]=this.am(t-r,e.data[r],a,0,0,this.t+r-t);a.clamp(),a.drShiftTo(1,a)}function yr(e){this.r2=ae(),this.q3=ae(),B.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}function bc(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=ae();return e.copyTo(t),this.reduce(t),t}function Ic(e){return e}function wc(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)}function Ac(e,t){e.squareTo(t),this.reduce(t)}function Bc(e,t,a){e.multiplyTo(t,a),this.reduce(a)}yr.prototype.convert=bc;yr.prototype.revert=Ic;yr.prototype.reduce=wc;yr.prototype.mulTo=Bc;yr.prototype.sqrTo=Ac;function Rc(e,t){var a=e.bitLength(),r,n=Ot(1),i;if(a<=0)return n;a<18?r=1:a<48?r=3:a<144?r=4:a<768?r=5:r=6,a<8?i=new Jt(t):t.isEven()?i=new yr(t):i=new er(t);var s=new Array,o=3,u=r-1,l=(1<<r)-1;if(s[1]=i.convert(this),r>1){var f=ae();for(i.sqrTo(s[1],f);o<=l;)s[o]=ae(),i.mulTo(f,s[o-2],s[o]),o+=2}var c=e.t-1,g,m=!0,h=ae(),v;for(a=ya(e.data[c])-1;c>=0;){for(a>=u?g=e.data[c]>>a-u&l:(g=(e.data[c]&(1<<a+1)-1)<<u-a,c>0&&(g|=e.data[c-1]>>this.DB+a-u)),o=r;(g&1)==0;)g>>=1,--o;if((a-=o)<0&&(a+=this.DB,--c),m)s[g].copyTo(n),m=!1;else{for(;o>1;)i.sqrTo(n,h),i.sqrTo(h,n),o-=2;o>0?i.sqrTo(n,h):(v=n,n=h,h=v),i.mulTo(h,s[g],n)}for(;c>=0&&(e.data[c]&1<<a)==0;)i.sqrTo(n,h),v=n,n=h,h=v,--a<0&&(a=this.DB-1,--c)}return i.revert(n)}function _c(e){var t=this.s<0?this.negate():this.clone(),a=e.s<0?e.negate():e.clone();if(t.compareTo(a)<0){var r=t;t=a,a=r}var n=t.getLowestSetBit(),i=a.getLowestSetBit();if(i<0)return t;for(n<i&&(i=n),i>0&&(t.rShiftTo(i,t),a.rShiftTo(i,a));t.signum()>0;)(n=t.getLowestSetBit())>0&&t.rShiftTo(n,t),(n=a.getLowestSetBit())>0&&a.rShiftTo(n,a),t.compareTo(a)>=0?(t.subTo(a,t),t.rShiftTo(1,t)):(a.subTo(t,a),a.rShiftTo(1,a));return i>0&&a.lShiftTo(i,a),a}function Nc(e){if(e<=0)return 0;var t=this.DV%e,a=this.s<0?e-1:0;if(this.t>0)if(t==0)a=this.data[0]%e;else for(var r=this.t-1;r>=0;--r)a=(t*a+this.data[r])%e;return a}function Pc(e){var t=e.isEven();if(this.isEven()&&t||e.signum()==0)return B.ZERO;for(var a=e.clone(),r=this.clone(),n=Ot(1),i=Ot(0),s=Ot(0),o=Ot(1);a.signum()!=0;){for(;a.isEven();)a.rShiftTo(1,a),t?((!n.isEven()||!i.isEven())&&(n.addTo(this,n),i.subTo(e,i)),n.rShiftTo(1,n)):i.isEven()||i.subTo(e,i),i.rShiftTo(1,i);for(;r.isEven();)r.rShiftTo(1,r),t?((!s.isEven()||!o.isEven())&&(s.addTo(this,s),o.subTo(e,o)),s.rShiftTo(1,s)):o.isEven()||o.subTo(e,o),o.rShiftTo(1,o);a.compareTo(r)>=0?(a.subTo(r,a),t&&n.subTo(s,n),i.subTo(o,i)):(r.subTo(a,r),t&&s.subTo(n,s),o.subTo(i,o))}if(r.compareTo(B.ONE)!=0)return B.ZERO;if(o.compareTo(e)>=0)return o.subtract(e);if(o.signum()<0)o.addTo(e,o);else return o;return o.signum()<0?o.add(e):o}var ht=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],Dc=(1<<26)/ht[ht.length-1];function Lc(e){var t,a=this.abs();if(a.t==1&&a.data[0]<=ht[ht.length-1]){for(t=0;t<ht.length;++t)if(a.data[0]==ht[t])return!0;return!1}if(a.isEven())return!1;for(t=1;t<ht.length;){for(var r=ht[t],n=t+1;n<ht.length&&r<Dc;)r*=ht[n++];for(r=a.modInt(r);t<n;)if(r%ht[t++]==0)return!1}return a.millerRabin(e)}function kc(e){var t=this.subtract(B.ONE),a=t.getLowestSetBit();if(a<=0)return!1;for(var r=t.shiftRight(a),n=Uc(),i,s=0;s<e;++s){do i=new B(this.bitLength(),n);while(i.compareTo(B.ONE)<=0||i.compareTo(t)>=0);var o=i.modPow(r,this);if(o.compareTo(B.ONE)!=0&&o.compareTo(t)!=0){for(var u=1;u++<a&&o.compareTo(t)!=0;)if(o=o.modPowInt(2,this),o.compareTo(B.ONE)==0)return!1;if(o.compareTo(t)!=0)return!1}}return!0}function Uc(){return{nextBytes:function(e){for(var t=0;t<e.length;++t)e[t]=Math.floor(Math.random()*256)}}}B.prototype.chunkSize=Ff;B.prototype.toRadix=Vf;B.prototype.fromRadix=Mf;B.prototype.fromNumber=Kf;B.prototype.bitwiseTo=Qf;B.prototype.changeBit=sc;B.prototype.addTo=fc;B.prototype.dMultiply=mc;B.prototype.dAddOffset=vc;B.prototype.multiplyLowerTo=Sc;B.prototype.multiplyUpperTo=Tc;B.prototype.modInt=Nc;B.prototype.millerRabin=kc;B.prototype.clone=Df;B.prototype.intValue=Lf;B.prototype.byteValue=kf;B.prototype.shortValue=Uf;B.prototype.signum=Of;B.prototype.toByteArray=qf;B.prototype.equals=Hf;B.prototype.min=zf;B.prototype.max=Gf;B.prototype.and=jf;B.prototype.or=$f;B.prototype.xor=Yf;B.prototype.andNot=Xf;B.prototype.not=Zf;B.prototype.shiftLeft=Jf;B.prototype.shiftRight=ec;B.prototype.getLowestSetBit=rc;B.prototype.bitCount=nc;B.prototype.testBit=ic;B.prototype.setBit=oc;B.prototype.clearBit=uc;B.prototype.flipBit=lc;B.prototype.add=cc;B.prototype.subtract=dc;B.prototype.multiply=pc;B.prototype.divide=hc;B.prototype.remainder=yc;B.prototype.divideAndRemainder=gc;B.prototype.modPow=Rc;B.prototype.modInverse=Pc;B.prototype.pow=xc;B.prototype.gcd=_c;B.prototype.isProbablePrime=Lc});var gr=H((yy,Ks)=>{"use strict";var St=W();mt();re();var Vs=Ks.exports=St.sha1=St.sha1||{};St.md.sha1=St.md.algorithms.sha1=Vs;Vs.create=function(){Ms||Fc();var e=null,t=St.util.createBuffer(),a=new Array(80),r={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};return r.start=function(){r.messageLength=0,r.fullMessageLength=r.messageLength64=[];for(var n=r.messageLengthSize/4,i=0;i<n;++i)r.fullMessageLength.push(0);return t=St.util.createBuffer(),e={h0:1732584193,h1:4023233417,h2:2562383102,h3:271733878,h4:3285377520},r},r.start(),r.update=function(n,i){i==="utf8"&&(n=St.util.encodeUtf8(n));var s=n.length;r.messageLength+=s,s=[s/4294967296>>>0,s>>>0];for(var o=r.fullMessageLength.length-1;o>=0;--o)r.fullMessageLength[o]+=s[1],s[1]=s[0]+(r.fullMessageLength[o]/4294967296>>>0),r.fullMessageLength[o]=r.fullMessageLength[o]>>>0,s[0]=s[1]/4294967296>>>0;return t.putBytes(n),Os(e,a,t),(t.read>2048||t.length()===0)&&t.compact(),r},r.digest=function(){var n=St.util.createBuffer();n.putBytes(t.bytes());var i=r.fullMessageLength[r.fullMessageLength.length-1]+r.messageLengthSize,s=i&r.blockLength-1;n.putBytes(Cn.substr(0,r.blockLength-s));for(var o,u,l=r.fullMessageLength[0]*8,f=0;f<r.fullMessageLength.length-1;++f)o=r.fullMessageLength[f+1]*8,u=o/4294967296>>>0,l+=u,n.putInt32(l>>>0),l=o>>>0;n.putInt32(l);var c={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};Os(c,a,n);var g=St.util.createBuffer();return g.putInt32(c.h0),g.putInt32(c.h1),g.putInt32(c.h2),g.putInt32(c.h3),g.putInt32(c.h4),g},r};var Cn=null,Ms=!1;function Fc(){Cn="\x80",Cn+=St.util.fillString("\0",64),Ms=!0}function Os(e,t,a){for(var r,n,i,s,o,u,l,f,c=a.length();c>=64;){for(n=e.h0,i=e.h1,s=e.h2,o=e.h3,u=e.h4,f=0;f<16;++f)r=a.getInt32(),t[f]=r,l=o^i&(s^o),r=(n<<5|n>>>27)+l+u+1518500249+r,u=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=r;for(;f<20;++f)r=t[f-3]^t[f-8]^t[f-14]^t[f-16],r=r<<1|r>>>31,t[f]=r,l=o^i&(s^o),r=(n<<5|n>>>27)+l+u+1518500249+r,u=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=r;for(;f<32;++f)r=t[f-3]^t[f-8]^t[f-14]^t[f-16],r=r<<1|r>>>31,t[f]=r,l=i^s^o,r=(n<<5|n>>>27)+l+u+1859775393+r,u=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=r;for(;f<40;++f)r=t[f-6]^t[f-16]^t[f-28]^t[f-32],r=r<<2|r>>>30,t[f]=r,l=i^s^o,r=(n<<5|n>>>27)+l+u+1859775393+r,u=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=r;for(;f<60;++f)r=t[f-6]^t[f-16]^t[f-28]^t[f-32],r=r<<2|r>>>30,t[f]=r,l=i&s|o&(i^s),r=(n<<5|n>>>27)+l+u+2400959708+r,u=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=r;for(;f<80;++f)r=t[f-6]^t[f-16]^t[f-28]^t[f-32],r=r<<2|r>>>30,t[f]=r,l=i^s^o,r=(n<<5|n>>>27)+l+u+3395469782+r,u=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=r;e.h0=e.h0+n|0,e.h1=e.h1+i|0,e.h2=e.h2+s|0,e.h3=e.h3+o|0,e.h4=e.h4+u|0,c-=64}}});var En=H((gy,Hs)=>{"use strict";var Tt=W();re();it();gr();var qs=Hs.exports=Tt.pkcs1=Tt.pkcs1||{};qs.encode_rsa_oaep=function(e,t,a){var r,n,i,s;typeof a=="string"?(r=a,n=arguments[3]||void 0,i=arguments[4]||void 0):a&&(r=a.label||void 0,n=a.seed||void 0,i=a.md||void 0,a.mgf1&&a.mgf1.md&&(s=a.mgf1.md)),i?i.start():i=Tt.md.sha1.create(),s||(s=i);var o=Math.ceil(e.n.bitLength()/8),u=o-2*i.digestLength-2;if(t.length>u){var l=new Error("RSAES-OAEP input message length is too long.");throw l.length=t.length,l.maxLength=u,l}r||(r=""),i.update(r,"raw");for(var f=i.digest(),c="",g=u-t.length,m=0;m<g;m++)c+="\0";var h=f.getBytes()+c+""+t;if(!n)n=Tt.random.getBytes(i.digestLength);else if(n.length!==i.digestLength){var l=new Error("Invalid RSAES-OAEP seed. The seed length must match the digest length.");throw l.seedLength=n.length,l.digestLength=i.digestLength,l}var v=ga(n,o-i.digestLength-1,s),E=Tt.util.xorBytes(h,v,h.length),T=ga(E,i.digestLength,s),I=Tt.util.xorBytes(n,T,n.length);return"\0"+I+E};qs.decode_rsa_oaep=function(e,t,a){var r,n,i;typeof a=="string"?(r=a,n=arguments[3]||void 0):a&&(r=a.label||void 0,n=a.md||void 0,a.mgf1&&a.mgf1.md&&(i=a.mgf1.md));var s=Math.ceil(e.n.bitLength()/8);if(t.length!==s){var E=new Error("RSAES-OAEP encoded message length is invalid.");throw E.length=t.length,E.expectedLength=s,E}if(n===void 0?n=Tt.md.sha1.create():n.start(),i||(i=n),s<2*n.digestLength+2)throw new Error("RSAES-OAEP key is too short for the hash function.");r||(r=""),n.update(r,"raw");for(var o=n.digest().getBytes(),u=t.charAt(0),l=t.substring(1,n.digestLength+1),f=t.substring(1+n.digestLength),c=ga(f,n.digestLength,i),g=Tt.util.xorBytes(l,c,l.length),m=ga(g,s-n.digestLength-1,i),h=Tt.util.xorBytes(f,m,f.length),v=h.substring(0,n.digestLength),E=u!=="\0",T=0;T<n.digestLength;++T)E|=o.charAt(T)!==v.charAt(T);for(var I=1,A=n.digestLength,L=n.digestLength;L<h.length;L++){var N=h.charCodeAt(L),P=N&1^1,G=I?65534:0;E|=N&G,I=I&P,A+=I}if(E||h.charCodeAt(A)!==1)throw new Error("Invalid RSAES-OAEP padding.");return h.substring(A+1)};function ga(e,t,a){a||(a=Tt.md.sha1.create());for(var r="",n=Math.ceil(t/a.digestLength),i=0;i<n;++i){var s=String.fromCharCode(i>>24&255,i>>16&255,i>>8&255,i&255);a.start(),a.update(e+s),r+=a.digest().getBytes()}return r.substring(0,t)}});var Sn=H((my,xn)=>{"use strict";var Vt=W();re();kr();it();(function(){if(Vt.prime){xn.exports=Vt.prime;return}var e=xn.exports=Vt.prime=Vt.prime||{},t=Vt.jsbn.BigInteger,a=[6,4,2,4,2,4,6,2],r=new t(null);r.fromInt(30);var n=function(c,g){return c|g};e.generateProbablePrime=function(c,g,m){typeof g=="function"&&(m=g,g={}),g=g||{};var h=g.algorithm||"PRIMEINC";typeof h=="string"&&(h={name:h}),h.options=h.options||{};var v=g.prng||Vt.random,E={nextBytes:function(T){for(var I=v.getBytesSync(T.length),A=0;A<T.length;++A)T[A]=I.charCodeAt(A)}};if(h.name==="PRIMEINC")return i(c,E,h.options,m);throw new Error("Invalid prime generation algorithm: "+h.name)};function i(c,g,m,h){return"workers"in m?u(c,g,m,h):s(c,g,m,h)}function s(c,g,m,h){var v=l(c,g),E=0,T=f(v.bitLength());"millerRabinTests"in m&&(T=m.millerRabinTests);var I=10;"maxBlockTime"in m&&(I=m.maxBlockTime),o(v,c,g,E,T,I,h)}function o(c,g,m,h,v,E,T){var I=+new Date;do{if(c.bitLength()>g&&(c=l(g,m)),c.isProbablePrime(v))return T(null,c);c.dAddOffset(a[h++%8],0)}while(E<0||+new Date-I<E);Vt.util.setImmediate(function(){o(c,g,m,h,v,E,T)})}function u(c,g,m,h){if(typeof Worker>"u")return s(c,g,m,h);var v=l(c,g),E=m.workers,T=m.workLoad||100,I=T*30/8,A=m.workerScript||"forge/prime.worker.js";if(E===-1)return Vt.util.estimateCores(function(N,P){N&&(P=2),E=P-1,L()});L();function L(){E=Math.max(1,E);for(var N=[],P=0;P<E;++P)N[P]=new Worker(A);for(var G=E,P=0;P<E;++P)N[P].addEventListener("message",ie);var j=!1;function ie(oe){if(!j){--G;var fe=oe.data;if(fe.found){for(var pe=0;pe<N.length;++pe)N[pe].terminate();return j=!0,h(null,new t(fe.prime,16))}v.bitLength()>c&&(v=l(c,g));var Qe=v.toString(16);oe.target.postMessage({hex:Qe,workLoad:T}),v.dAddOffset(I,0)}}}}function l(c,g){var m=new t(c,g),h=c-1;return m.testBit(h)||m.bitwiseTo(t.ONE.shiftLeft(h),n,m),m.dAddOffset(31-m.mod(r).byteValue(),0),m}function f(c){return c<=100?27:c<=150?18:c<=200?15:c<=250?12:c<=300?9:c<=350?8:c<=400?7:c<=500?6:c<=600?5:c<=800?4:c<=1250?3:2}})()});var Ur=H((vy,Ys)=>{"use strict";var M=W();pt();kr();Ft();En();Sn();it();re();typeof ee>"u"&&(ee=M.jsbn.BigInteger);var ee,Tn=M.util.isNodejs?Dt("crypto"):null,b=M.asn1,ot=M.util;M.pki=M.pki||{};Ys.exports=M.pki.rsa=M.rsa=M.rsa||{};var z=M.pki,Oc=[6,4,2,4,2,4,6,2],Vc={name:"PrivateKeyInfo",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:b.Class.UNIVERSAL,type:b.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:b.Class.UNIVERSAL,type:b.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},Mc={name:"RSAPrivateKey",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},Kc={name:"RSAPublicKey",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:b.Class.UNIVERSAL,type:b.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},qc=M.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:b.Class.UNIVERSAL,type:b.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:b.Class.UNIVERSAL,type:b.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},Hc={name:"DigestInfo",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:b.Class.UNIVERSAL,type:b.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:b.Class.UNIVERSAL,type:b.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:b.Class.UNIVERSAL,type:b.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:b.Class.UNIVERSAL,type:b.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},zc=function(e){var t;if(e.algorithm in z.oids)t=z.oids[e.algorithm];else{var a=new Error("Unknown message digest algorithm.");throw a.algorithm=e.algorithm,a}var r=b.oidToDer(t).getBytes(),n=b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[]),i=b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[]);i.value.push(b.create(b.Class.UNIVERSAL,b.Type.OID,!1,r)),i.value.push(b.create(b.Class.UNIVERSAL,b.Type.NULL,!1,""));var s=b.create(b.Class.UNIVERSAL,b.Type.OCTETSTRING,!1,e.digest().getBytes());return n.value.push(i),n.value.push(s),b.toDer(n).getBytes()},js=function(e,t,a){if(a)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);t.dP||(t.dP=t.d.mod(t.p.subtract(ee.ONE))),t.dQ||(t.dQ=t.d.mod(t.q.subtract(ee.ONE))),t.qInv||(t.qInv=t.q.modInverse(t.p));var r;do r=new ee(M.util.bytesToHex(M.random.getBytes(t.n.bitLength()/8)),16);while(r.compareTo(t.n)>=0||!r.gcd(t.n).equals(ee.ONE));e=e.multiply(r.modPow(t.e,t.n)).mod(t.n);for(var n=e.mod(t.p).modPow(t.dP,t.p),i=e.mod(t.q).modPow(t.dQ,t.q);n.compareTo(i)<0;)n=n.add(t.p);var s=n.subtract(i).multiply(t.qInv).mod(t.p).multiply(t.q).add(i);return s=s.multiply(r.modInverse(t.n)).mod(t.n),s};z.rsa.encrypt=function(e,t,a){var r=a,n,i=Math.ceil(t.n.bitLength()/8);a!==!1&&a!==!0?(r=a===2,n=$s(e,t,a)):(n=M.util.createBuffer(),n.putBytes(e));for(var s=new ee(n.toHex(),16),o=js(s,t,r),u=o.toString(16),l=M.util.createBuffer(),f=i-Math.ceil(u.length/2);f>0;)l.putByte(0),--f;return l.putBytes(M.util.hexToBytes(u)),l.getBytes()};z.rsa.decrypt=function(e,t,a,r){var n=Math.ceil(t.n.bitLength()/8);if(e.length!==n){var i=new Error("Encrypted message length is invalid.");throw i.length=e.length,i.expected=n,i}var s=new ee(M.util.createBuffer(e).toHex(),16);if(s.compareTo(t.n)>=0)throw new Error("Encrypted message is invalid.");for(var o=js(s,t,a),u=o.toString(16),l=M.util.createBuffer(),f=n-Math.ceil(u.length/2);f>0;)l.putByte(0),--f;return l.putBytes(M.util.hexToBytes(u)),r!==!1?ma(l.getBytes(),t,a):l.getBytes()};z.rsa.createKeyPairGenerationState=function(e,t,a){typeof e=="string"&&(e=parseInt(e,10)),e=e||2048,a=a||{};var r=a.prng||M.random,n={nextBytes:function(o){for(var u=r.getBytesSync(o.length),l=0;l<o.length;++l)o[l]=u.charCodeAt(l)}},i=a.algorithm||"PRIMEINC",s;if(i==="PRIMEINC")s={algorithm:i,state:0,bits:e,rng:n,eInt:t||65537,e:new ee(null),p:null,q:null,qBits:e>>1,pBits:e-(e>>1),pqState:0,num:null,keys:null},s.e.fromInt(s.eInt);else throw new Error("Invalid key generation algorithm: "+i);return s};z.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var a=new ee(null);a.fromInt(30);for(var r=0,n=function(c,g){return c|g},i=+new Date,s,o=0;e.keys===null&&(t<=0||o<t);){if(e.state===0){var u=e.p===null?e.pBits:e.qBits,l=u-1;e.pqState===0?(e.num=new ee(u,e.rng),e.num.testBit(l)||e.num.bitwiseTo(ee.ONE.shiftLeft(l),n,e.num),e.num.dAddOffset(31-e.num.mod(a).byteValue(),0),r=0,++e.pqState):e.pqState===1?e.num.bitLength()>u?e.pqState=0:e.num.isProbablePrime(Qc(e.num.bitLength()))?++e.pqState:e.num.dAddOffset(Oc[r++%8],0):e.pqState===2?e.pqState=e.num.subtract(ee.ONE).gcd(e.e).compareTo(ee.ONE)===0?3:0:e.pqState===3&&(e.pqState=0,e.p===null?e.p=e.num:e.q=e.num,e.p!==null&&e.q!==null&&++e.state,e.num=null)}else if(e.state===1)e.p.compareTo(e.q)<0&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(e.state===2)e.p1=e.p.subtract(ee.ONE),e.q1=e.q.subtract(ee.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(e.state===3)e.phi.gcd(e.e).compareTo(ee.ONE)===0?++e.state:(e.p=null,e.q=null,e.state=0);else if(e.state===4)e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits?++e.state:(e.q=null,e.state=0);else if(e.state===5){var f=e.e.modInverse(e.phi);e.keys={privateKey:z.rsa.setPrivateKey(e.n,e.e,f,e.p,e.q,f.mod(e.p1),f.mod(e.q1),e.q.modInverse(e.p)),publicKey:z.rsa.setPublicKey(e.n,e.e)}}s=+new Date,o+=s-i,i=s}return e.keys!==null};z.rsa.generateKeyPair=function(e,t,a,r){if(arguments.length===1?typeof e=="object"?(a=e,e=void 0):typeof e=="function"&&(r=e,e=void 0):arguments.length===2?typeof e=="number"?typeof t=="function"?(r=t,t=void 0):typeof t!="number"&&(a=t,t=void 0):(a=e,r=t,e=void 0,t=void 0):arguments.length===3&&(typeof t=="number"?typeof a=="function"&&(r=a,a=void 0):(r=a,a=t,t=void 0)),a=a||{},e===void 0&&(e=a.bits||2048),t===void 0&&(t=a.e||65537),!M.options.usePureJavaScript&&!a.prng&&e>=256&&e<=16384&&(t===65537||t===3)){if(r){if(zs("generateKeyPair"))return Tn.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(o,u,l){if(o)return r(o);r(null,{privateKey:z.privateKeyFromPem(l),publicKey:z.publicKeyFromPem(u)})});if(Gs("generateKey")&&Gs("exportKey"))return ot.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:Ws(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(o){return ot.globalScope.crypto.subtle.exportKey("pkcs8",o.privateKey)}).then(void 0,function(o){r(o)}).then(function(o){if(o){var u=z.privateKeyFromAsn1(b.fromDer(M.util.createBuffer(o)));r(null,{privateKey:u,publicKey:z.setRsaPublicKey(u.n,u.e)})}});if(Qs("generateKey")&&Qs("exportKey")){var n=ot.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:Ws(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);n.oncomplete=function(o){var u=o.target.result,l=ot.globalScope.msCrypto.subtle.exportKey("pkcs8",u.privateKey);l.oncomplete=function(f){var c=f.target.result,g=z.privateKeyFromAsn1(b.fromDer(M.util.createBuffer(c)));r(null,{privateKey:g,publicKey:z.setRsaPublicKey(g.n,g.e)})},l.onerror=function(f){r(f)}},n.onerror=function(o){r(o)};return}}else if(zs("generateKeyPairSync")){var i=Tn.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:z.privateKeyFromPem(i.privateKey),publicKey:z.publicKeyFromPem(i.publicKey)}}}var s=z.rsa.createKeyPairGenerationState(e,t,a);if(!r)return z.rsa.stepKeyPairGenerationState(s,0),s.keys;Gc(s,a,r)};z.setRsaPublicKey=z.rsa.setPublicKey=function(e,t){var a={n:e,e:t};return a.encrypt=function(r,n,i){if(typeof n=="string"?n=n.toUpperCase():n===void 0&&(n="RSAES-PKCS1-V1_5"),n==="RSAES-PKCS1-V1_5")n={encode:function(o,u,l){return $s(o,u,2).getBytes()}};else if(n==="RSA-OAEP"||n==="RSAES-OAEP")n={encode:function(o,u){return M.pkcs1.encode_rsa_oaep(u,o,i)}};else if(["RAW","NONE","NULL",null].indexOf(n)!==-1)n={encode:function(o){return o}};else if(typeof n=="string")throw new Error('Unsupported encryption scheme: "'+n+'".');var s=n.encode(r,a,!0);return z.rsa.encrypt(s,a,!0)},a.verify=function(r,n,i,s){typeof i=="string"?i=i.toUpperCase():i===void 0&&(i="RSASSA-PKCS1-V1_5"),s===void 0&&(s={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in s||(s._parseAllDigestBytes=!0),i==="RSASSA-PKCS1-V1_5"?i={verify:function(u,l){l=ma(l,a,!0);var f=b.fromDer(l,{parseAllBytes:s._parseAllDigestBytes}),c={},g=[];if(!b.validate(f,Hc,c,g)){var m=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.");throw m.errors=g,m}var h=b.derToOid(c.algorithmIdentifier);if(!(h===M.oids.md2||h===M.oids.md5||h===M.oids.sha1||h===M.oids.sha224||h===M.oids.sha256||h===M.oids.sha384||h===M.oids.sha512||h===M.oids["sha512-224"]||h===M.oids["sha512-256"])){var m=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.");throw m.oid=h,m}if((h===M.oids.md2||h===M.oids.md5)&&!("parameters"in c))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifer NULL parameters.");return u===c.digest}}:(i==="NONE"||i==="NULL"||i===null)&&(i={verify:function(u,l){return l=ma(l,a,!0),u===l}});var o=z.rsa.decrypt(n,a,!0,!1);return i.verify(r,o,a.n.bitLength())},a};z.setRsaPrivateKey=z.rsa.setPrivateKey=function(e,t,a,r,n,i,s,o){var u={n:e,e:t,d:a,p:r,q:n,dP:i,dQ:s,qInv:o};return u.decrypt=function(l,f,c){typeof f=="string"?f=f.toUpperCase():f===void 0&&(f="RSAES-PKCS1-V1_5");var g=z.rsa.decrypt(l,u,!1,!1);if(f==="RSAES-PKCS1-V1_5")f={decode:ma};else if(f==="RSA-OAEP"||f==="RSAES-OAEP")f={decode:function(m,h){return M.pkcs1.decode_rsa_oaep(h,m,c)}};else if(["RAW","NONE","NULL",null].indexOf(f)!==-1)f={decode:function(m){return m}};else throw new Error('Unsupported encryption scheme: "'+f+'".');return f.decode(g,u,!1)},u.sign=function(l,f){var c=!1;typeof f=="string"&&(f=f.toUpperCase()),f===void 0||f==="RSASSA-PKCS1-V1_5"?(f={encode:zc},c=1):(f==="NONE"||f==="NULL"||f===null)&&(f={encode:function(){return l}},c=1);var g=f.encode(l,u.n.bitLength());return z.rsa.encrypt(g,u,c)},u};z.wrapRsaPrivateKey=function(e){return b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,b.integerToDer(0).getBytes()),b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.OID,!1,b.oidToDer(z.oids.rsaEncryption).getBytes()),b.create(b.Class.UNIVERSAL,b.Type.NULL,!1,"")]),b.create(b.Class.UNIVERSAL,b.Type.OCTETSTRING,!1,b.toDer(e).getBytes())])};z.privateKeyFromAsn1=function(e){var t={},a=[];if(b.validate(e,Vc,t,a)&&(e=b.fromDer(M.util.createBuffer(t.privateKey))),t={},a=[],!b.validate(e,Mc,t,a)){var r=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw r.errors=a,r}var n,i,s,o,u,l,f,c;return n=M.util.createBuffer(t.privateKeyModulus).toHex(),i=M.util.createBuffer(t.privateKeyPublicExponent).toHex(),s=M.util.createBuffer(t.privateKeyPrivateExponent).toHex(),o=M.util.createBuffer(t.privateKeyPrime1).toHex(),u=M.util.createBuffer(t.privateKeyPrime2).toHex(),l=M.util.createBuffer(t.privateKeyExponent1).toHex(),f=M.util.createBuffer(t.privateKeyExponent2).toHex(),c=M.util.createBuffer(t.privateKeyCoefficient).toHex(),z.setRsaPrivateKey(new ee(n,16),new ee(i,16),new ee(s,16),new ee(o,16),new ee(u,16),new ee(l,16),new ee(f,16),new ee(c,16))};z.privateKeyToAsn1=z.privateKeyToRSAPrivateKey=function(e){return b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,b.integerToDer(0).getBytes()),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,bt(e.n)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,bt(e.e)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,bt(e.d)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,bt(e.p)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,bt(e.q)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,bt(e.dP)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,bt(e.dQ)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,bt(e.qInv))])};z.publicKeyFromAsn1=function(e){var t={},a=[];if(b.validate(e,qc,t,a)){var r=b.derToOid(t.publicKeyOid);if(r!==z.oids.rsaEncryption){var n=new Error("Cannot read public key. Unknown OID.");throw n.oid=r,n}e=t.rsaPublicKey}if(a=[],!b.validate(e,Kc,t,a)){var n=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw n.errors=a,n}var i=M.util.createBuffer(t.publicKeyModulus).toHex(),s=M.util.createBuffer(t.publicKeyExponent).toHex();return z.setRsaPublicKey(new ee(i,16),new ee(s,16))};z.publicKeyToAsn1=z.publicKeyToSubjectPublicKeyInfo=function(e){return b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.OID,!1,b.oidToDer(z.oids.rsaEncryption).getBytes()),b.create(b.Class.UNIVERSAL,b.Type.NULL,!1,"")]),b.create(b.Class.UNIVERSAL,b.Type.BITSTRING,!1,[z.publicKeyToRSAPublicKey(e)])])};z.publicKeyToRSAPublicKey=function(e){return b.create(b.Class.UNIVERSAL,b.Type.SEQUENCE,!0,[b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,bt(e.n)),b.create(b.Class.UNIVERSAL,b.Type.INTEGER,!1,bt(e.e))])};function $s(e,t,a){var r=M.util.createBuffer(),n=Math.ceil(t.n.bitLength()/8);if(e.length>n-11){var i=new Error("Message is too long for PKCS#1 v1.5 padding.");throw i.length=e.length,i.max=n-11,i}r.putByte(0),r.putByte(a);var s=n-3-e.length,o;if(a===0||a===1){o=a===0?0:255;for(var u=0;u<s;++u)r.putByte(o)}else for(;s>0;){for(var l=0,f=M.random.getBytes(s),u=0;u<s;++u)o=f.charCodeAt(u),o===0?++l:r.putByte(o);s=l}return r.putByte(0),r.putBytes(e),r}function ma(e,t,a,r){var n=Math.ceil(t.n.bitLength()/8),i=M.util.createBuffer(e),s=i.getByte(),o=i.getByte();if(s!==0||a&&o!==0&&o!==1||!a&&o!=2||a&&o===0&&typeof r>"u")throw new Error("Encryption block is invalid.");var u=0;if(o===0){u=n-3-r;for(var l=0;l<u;++l)if(i.getByte()!==0)throw new Error("Encryption block is invalid.")}else if(o===1)for(u=0;i.length()>1;){if(i.getByte()!==255){--i.read;break}++u}else if(o===2)for(u=0;i.length()>1;){if(i.getByte()===0){--i.read;break}++u}var f=i.getByte();if(f!==0||u!==n-3-i.length())throw new Error("Encryption block is invalid.");return i.getBytes()}function Gc(e,t,a){typeof t=="function"&&(a=t,t={}),t=t||{};var r={algorithm:{name:t.algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};"prng"in t&&(r.prng=t.prng),n();function n(){i(e.pBits,function(o,u){if(o)return a(o);if(e.p=u,e.q!==null)return s(o,e.q);i(e.qBits,s)})}function i(o,u){M.prime.generateProbablePrime(o,r,u)}function s(o,u){if(o)return a(o);if(e.q=u,e.p.compareTo(e.q)<0){var l=e.p;e.p=e.q,e.q=l}if(e.p.subtract(ee.ONE).gcd(e.e).compareTo(ee.ONE)!==0){e.p=null,n();return}if(e.q.subtract(ee.ONE).gcd(e.e).compareTo(ee.ONE)!==0){e.q=null,i(e.qBits,s);return}if(e.p1=e.p.subtract(ee.ONE),e.q1=e.q.subtract(ee.ONE),e.phi=e.p1.multiply(e.q1),e.phi.gcd(e.e).compareTo(ee.ONE)!==0){e.p=e.q=null,n();return}if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits){e.q=null,i(e.qBits,s);return}var f=e.e.modInverse(e.phi);e.keys={privateKey:z.rsa.setPrivateKey(e.n,e.e,f,e.p,e.q,f.mod(e.p1),f.mod(e.q1),e.q.modInverse(e.p)),publicKey:z.rsa.setPublicKey(e.n,e.e)},a(null,e.keys)}}function bt(e){var t=e.toString(16);t[0]>="8"&&(t="00"+t);var a=M.util.hexToBytes(t);return a.length>1&&(a.charCodeAt(0)===0&&(a.charCodeAt(1)&128)===0||a.charCodeAt(0)===255&&(a.charCodeAt(1)&128)===128)?a.substr(1):a}function Qc(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}function zs(e){return M.util.isNodejs&&typeof Tn[e]=="function"}function Gs(e){return typeof ot.globalScope<"u"&&typeof ot.globalScope.crypto=="object"&&typeof ot.globalScope.crypto.subtle=="object"&&typeof ot.globalScope.crypto.subtle[e]=="function"}function Qs(e){return typeof ot.globalScope<"u"&&typeof ot.globalScope.msCrypto=="object"&&typeof ot.globalScope.msCrypto.subtle=="object"&&typeof ot.globalScope.msCrypto.subtle[e]=="function"}function Ws(e){for(var t=M.util.hexToBytes(e.toString(16)),a=new Uint8Array(t.length),r=0;r<t.length;++r)a[r]=t.charCodeAt(r);return a}});var bn=H((Cy,to)=>{"use strict";var O=W();Ut();pt();Dr();mt();Ft();da();Zt();it();yn();Ur();re();typeof Xs>"u"&&(Xs=O.jsbn.BigInteger);var Xs,w=O.asn1,Q=O.pki=O.pki||{};to.exports=Q.pbe=O.pbe=O.pbe||{};var tr=Q.oids,Wc={name:"EncryptedPrivateKeyInfo",tagClass:w.Class.UNIVERSAL,type:w.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:w.Class.UNIVERSAL,type:w.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:w.Class.UNIVERSAL,type:w.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:w.Class.UNIVERSAL,type:w.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:w.Class.UNIVERSAL,type:w.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},jc={name:"PBES2Algorithms",tagClass:w.Class.UNIVERSAL,type:w.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:w.Class.UNIVERSAL,type:w.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:w.Class.UNIVERSAL,type:w.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:w.Class.UNIVERSAL,type:w.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:w.Class.UNIVERSAL,type:w.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:w.Class.UNIVERSAL,type:w.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:w.Class.UNIVERSAL,type:w.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:w.Class.UNIVERSAL,type:w.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:w.Class.UNIVERSAL,type:w.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:w.Class.UNIVERSAL,type:w.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:w.Class.UNIVERSAL,type:w.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:w.Class.UNIVERSAL,type:w.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},$c={name:"pkcs-12PbeParams",tagClass:w.Class.UNIVERSAL,type:w.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:w.Class.UNIVERSAL,type:w.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:w.Class.UNIVERSAL,type:w.Type.INTEGER,constructed:!1,capture:"iterations"}]};Q.encryptPrivateKeyInfo=function(e,t,a){a=a||{},a.saltSize=a.saltSize||8,a.count=a.count||2048,a.algorithm=a.algorithm||"aes128",a.prfAlgorithm=a.prfAlgorithm||"sha1";var r=O.random.getBytesSync(a.saltSize),n=a.count,i=w.integerToDer(n),s,o,u;if(a.algorithm.indexOf("aes")===0||a.algorithm==="des"){var l,f,c;switch(a.algorithm){case"aes128":s=16,l=16,f=tr["aes128-CBC"],c=O.aes.createEncryptionCipher;break;case"aes192":s=24,l=16,f=tr["aes192-CBC"],c=O.aes.createEncryptionCipher;break;case"aes256":s=32,l=16,f=tr["aes256-CBC"],c=O.aes.createEncryptionCipher;break;case"des":s=8,l=8,f=tr.desCBC,c=O.des.createEncryptionCipher;break;default:var g=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw g.algorithm=a.algorithm,g}var m="hmacWith"+a.prfAlgorithm.toUpperCase(),h=eo(m),v=O.pkcs5.pbkdf2(t,r,n,s,h),E=O.random.getBytesSync(l),T=c(v);T.start(E),T.update(w.toDer(e)),T.finish(),u=T.output.getBytes();var I=Yc(r,i,s,m);o=w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(tr.pkcs5PBES2).getBytes()),w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(tr.pkcs5PBKDF2).getBytes()),I]),w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(f).getBytes()),w.create(w.Class.UNIVERSAL,w.Type.OCTETSTRING,!1,E)])])])}else if(a.algorithm==="3des"){s=24;var A=new O.util.ByteBuffer(r),v=Q.pbe.generatePkcs12Key(t,A,1,n,s),E=Q.pbe.generatePkcs12Key(t,A,2,n,s),T=O.des.createEncryptionCipher(v);T.start(E),T.update(w.toDer(e)),T.finish(),u=T.output.getBytes(),o=w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(tr["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OCTETSTRING,!1,r),w.create(w.Class.UNIVERSAL,w.Type.INTEGER,!1,i.getBytes())])])}else{var g=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw g.algorithm=a.algorithm,g}var L=w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[o,w.create(w.Class.UNIVERSAL,w.Type.OCTETSTRING,!1,u)]);return L};Q.decryptPrivateKeyInfo=function(e,t){var a=null,r={},n=[];if(!w.validate(e,Wc,r,n)){var i=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw i.errors=n,i}var s=w.derToOid(r.encryptionOid),o=Q.pbe.getCipher(s,r.encryptionParams,t),u=O.util.createBuffer(r.encryptedData);return o.update(u),o.finish()&&(a=w.fromDer(o.output)),a};Q.encryptedPrivateKeyToPem=function(e,t){var a={type:"ENCRYPTED PRIVATE KEY",body:w.toDer(e).getBytes()};return O.pem.encode(a,{maxline:t})};Q.encryptedPrivateKeyFromPem=function(e){var t=O.pem.decode(e)[0];if(t.type!=="ENCRYPTED PRIVATE KEY"){var a=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw a.headerType=t.type,a}if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return w.fromDer(t.body)};Q.encryptRsaPrivateKey=function(e,t,a){if(a=a||{},!a.legacy){var r=Q.wrapRsaPrivateKey(Q.privateKeyToAsn1(e));return r=Q.encryptPrivateKeyInfo(r,t,a),Q.encryptedPrivateKeyToPem(r)}var n,i,s,o;switch(a.algorithm){case"aes128":n="AES-128-CBC",s=16,i=O.random.getBytesSync(16),o=O.aes.createEncryptionCipher;break;case"aes192":n="AES-192-CBC",s=24,i=O.random.getBytesSync(16),o=O.aes.createEncryptionCipher;break;case"aes256":n="AES-256-CBC",s=32,i=O.random.getBytesSync(16),o=O.aes.createEncryptionCipher;break;case"3des":n="DES-EDE3-CBC",s=24,i=O.random.getBytesSync(8),o=O.des.createEncryptionCipher;break;case"des":n="DES-CBC",s=8,i=O.random.getBytesSync(8),o=O.des.createEncryptionCipher;break;default:var u=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+a.algorithm+'".');throw u.algorithm=a.algorithm,u}var l=O.pbe.opensslDeriveBytes(t,i.substr(0,8),s),f=o(l);f.start(i),f.update(w.toDer(Q.privateKeyToAsn1(e))),f.finish();var c={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:n,parameters:O.util.bytesToHex(i).toUpperCase()},body:f.output.getBytes()};return O.pem.encode(c)};Q.decryptRsaPrivateKey=function(e,t){var a=null,r=O.pem.decode(e)[0];if(r.type!=="ENCRYPTED PRIVATE KEY"&&r.type!=="PRIVATE KEY"&&r.type!=="RSA PRIVATE KEY"){var n=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');throw n.headerType=n,n}if(r.procType&&r.procType.type==="ENCRYPTED"){var i,s;switch(r.dekInfo.algorithm){case"DES-CBC":i=8,s=O.des.createDecryptionCipher;break;case"DES-EDE3-CBC":i=24,s=O.des.createDecryptionCipher;break;case"AES-128-CBC":i=16,s=O.aes.createDecryptionCipher;break;case"AES-192-CBC":i=24,s=O.aes.createDecryptionCipher;break;case"AES-256-CBC":i=32,s=O.aes.createDecryptionCipher;break;case"RC2-40-CBC":i=5,s=function(c){return O.rc2.createDecryptionCipher(c,40)};break;case"RC2-64-CBC":i=8,s=function(c){return O.rc2.createDecryptionCipher(c,64)};break;case"RC2-128-CBC":i=16,s=function(c){return O.rc2.createDecryptionCipher(c,128)};break;default:var n=new Error('Could not decrypt private key; unsupported encryption algorithm "'+r.dekInfo.algorithm+'".');throw n.algorithm=r.dekInfo.algorithm,n}var o=O.util.hexToBytes(r.dekInfo.parameters),u=O.pbe.opensslDeriveBytes(t,o.substr(0,8),i),l=s(u);if(l.start(o),l.update(O.util.createBuffer(r.body)),l.finish())a=l.output.getBytes();else return a}else a=r.body;return r.type==="ENCRYPTED PRIVATE KEY"?a=Q.decryptPrivateKeyInfo(w.fromDer(a),t):a=w.fromDer(a),a!==null&&(a=Q.privateKeyFromAsn1(a)),a};Q.pbe.generatePkcs12Key=function(e,t,a,r,n,i){var s,o;if(typeof i>"u"||i===null){if(!("sha1"in O.md))throw new Error('"sha1" hash algorithm unavailable.');i=O.md.sha1.create()}var u=i.digestLength,l=i.blockLength,f=new O.util.ByteBuffer,c=new O.util.ByteBuffer;if(e!=null){for(o=0;o<e.length;o++)c.putInt16(e.charCodeAt(o));c.putInt16(0)}var g=c.length(),m=t.length(),h=new O.util.ByteBuffer;h.fillWithByte(a,l);var v=l*Math.ceil(m/l),E=new O.util.ByteBuffer;for(o=0;o<v;o++)E.putByte(t.at(o%m));var T=l*Math.ceil(g/l),I=new O.util.ByteBuffer;for(o=0;o<T;o++)I.putByte(c.at(o%g));var A=E;A.putBuffer(I);for(var L=Math.ceil(n/u),N=1;N<=L;N++){var P=new O.util.ByteBuffer;P.putBytes(h.bytes()),P.putBytes(A.bytes());for(var G=0;G<r;G++)i.start(),i.update(P.getBytes()),P=i.digest();var j=new O.util.ByteBuffer;for(o=0;o<l;o++)j.putByte(P.at(o%u));var ie=Math.ceil(m/l)+Math.ceil(g/l),oe=new O.util.ByteBuffer;for(s=0;s<ie;s++){var fe=new O.util.ByteBuffer(A.getBytes(l)),pe=511;for(o=j.length()-1;o>=0;o--)pe=pe>>8,pe+=j.at(o)+fe.at(o),fe.setAt(o,pe&255);oe.putBuffer(fe)}A=oe,f.putBuffer(P)}return f.truncate(f.length()-n),f};Q.pbe.getCipher=function(e,t,a){switch(e){case Q.oids.pkcs5PBES2:return Q.pbe.getCipherForPBES2(e,t,a);case Q.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case Q.oids["pbewithSHAAnd40BitRC2-CBC"]:return Q.pbe.getCipherForPKCS12PBE(e,t,a);default:var r=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw r.oid=e,r.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],r}};Q.pbe.getCipherForPBES2=function(e,t,a){var r={},n=[];if(!w.validate(t,jc,r,n)){var i=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw i.errors=n,i}if(e=w.derToOid(r.kdfOid),e!==Q.oids.pkcs5PBKDF2){var i=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw i.oid=e,i.supportedOids=["pkcs5PBKDF2"],i}if(e=w.derToOid(r.encOid),e!==Q.oids["aes128-CBC"]&&e!==Q.oids["aes192-CBC"]&&e!==Q.oids["aes256-CBC"]&&e!==Q.oids["des-EDE3-CBC"]&&e!==Q.oids.desCBC){var i=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw i.oid=e,i.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],i}var s=r.kdfSalt,o=O.util.createBuffer(r.kdfIterationCount);o=o.getInt(o.length()<<3);var u,l;switch(Q.oids[e]){case"aes128-CBC":u=16,l=O.aes.createDecryptionCipher;break;case"aes192-CBC":u=24,l=O.aes.createDecryptionCipher;break;case"aes256-CBC":u=32,l=O.aes.createDecryptionCipher;break;case"des-EDE3-CBC":u=24,l=O.des.createDecryptionCipher;break;case"desCBC":u=8,l=O.des.createDecryptionCipher;break}var f=Js(r.prfOid),c=O.pkcs5.pbkdf2(a,s,o,u,f),g=r.encIv,m=l(c);return m.start(g),m};Q.pbe.getCipherForPKCS12PBE=function(e,t,a){var r={},n=[];if(!w.validate(t,$c,r,n)){var i=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw i.errors=n,i}var s=O.util.createBuffer(r.salt),o=O.util.createBuffer(r.iterations);o=o.getInt(o.length()<<3);var u,l,f;switch(e){case Q.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:u=24,l=8,f=O.des.startDecrypting;break;case Q.oids["pbewithSHAAnd40BitRC2-CBC"]:u=5,l=8,f=function(v,E){var T=O.rc2.createDecryptionCipher(v,40);return T.start(E,null),T};break;default:var i=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw i.oid=e,i}var c=Js(r.prfOid),g=Q.pbe.generatePkcs12Key(a,s,1,o,u,c);c.start();var m=Q.pbe.generatePkcs12Key(a,s,2,o,l,c);return f(g,m)};Q.pbe.opensslDeriveBytes=function(e,t,a,r){if(typeof r>"u"||r===null){if(!("md5"in O.md))throw new Error('"md5" hash algorithm unavailable.');r=O.md.md5.create()}t===null&&(t="");for(var n=[Zs(r,e+t)],i=16,s=1;i<a;++s,i+=16)n.push(Zs(r,n[s-1]+e+t));return n.join("").substr(0,a)};function Zs(e,t){return e.start().update(t).digest().getBytes()}function Js(e){var t;if(!e)t="hmacWithSHA1";else if(t=Q.oids[w.derToOid(e)],!t){var a=new Error("Unsupported PRF OID.");throw a.oid=e,a.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],a}return eo(t)}function eo(e){var t=O.md;switch(e){case"hmacWithSHA224":t=O.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":e=e.substr(8).toLowerCase();break;default:var a=new Error("Unsupported PRF algorithm.");throw a.algorithm=e,a.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],a}if(!t||!(e in t))throw new Error("Unknown hash algorithm: "+e);return t[e].create()}function Yc(e,t,a,r){var n=w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OCTETSTRING,!1,e),w.create(w.Class.UNIVERSAL,w.Type.INTEGER,!1,t.getBytes())]);return r!=="hmacWithSHA1"&&n.value.push(w.create(w.Class.UNIVERSAL,w.Type.INTEGER,!1,O.util.hexToBytes(a.toString(16))),w.create(w.Class.UNIVERSAL,w.Type.SEQUENCE,!0,[w.create(w.Class.UNIVERSAL,w.Type.OID,!1,w.oidToDer(Q.oids[r]).getBytes()),w.create(w.Class.UNIVERSAL,w.Type.NULL,!1,"")])),n}});var In=H((Ey,no)=>{"use strict";var mr=W();pt();re();var F=mr.asn1,vr=no.exports=mr.pkcs7asn1=mr.pkcs7asn1||{};mr.pkcs7=mr.pkcs7||{};mr.pkcs7.asn1=vr;var ro={name:"ContentInfo",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:F.Class.UNIVERSAL,type:F.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:F.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};vr.contentInfoValidator=ro;var ao={name:"EncryptedContentInfo",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:F.Class.UNIVERSAL,type:F.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:F.Class.UNIVERSAL,type:F.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:F.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:F.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};vr.envelopedDataValidator={name:"EnvelopedData",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:F.Class.UNIVERSAL,type:F.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:F.Class.UNIVERSAL,type:F.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(ao)};vr.encryptedDataValidator={name:"EncryptedData",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:F.Class.UNIVERSAL,type:F.Type.INTEGER,constructed:!1,capture:"version"}].concat(ao)};var Xc={name:"SignerInfo",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:F.Class.UNIVERSAL,type:F.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:F.Class.UNIVERSAL,type:F.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:F.Class.UNIVERSAL,type:F.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:F.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:F.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:F.Class.UNIVERSAL,type:F.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:F.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};vr.signedDataValidator={name:"SignedData",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:F.Class.UNIVERSAL,type:F.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:F.Class.UNIVERSAL,type:F.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},ro,{name:"SignedData.Certificates",tagClass:F.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:F.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:F.Class.UNIVERSAL,type:F.Type.SET,capture:"signerInfos",optional:!0,value:[Xc]}]};vr.recipientInfoValidator={name:"RecipientInfo",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:F.Class.UNIVERSAL,type:F.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:F.Class.UNIVERSAL,type:F.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:F.Class.UNIVERSAL,type:F.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:F.Class.UNIVERSAL,type:F.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:F.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:F.Class.UNIVERSAL,type:F.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}});var wn=H((xy,io)=>{"use strict";var rr=W();re();rr.mgf=rr.mgf||{};var Zc=io.exports=rr.mgf.mgf1=rr.mgf1=rr.mgf1||{};Zc.create=function(e){var t={generate:function(a,r){for(var n=new rr.util.ByteBuffer,i=Math.ceil(r/e.digestLength),s=0;s<i;s++){var o=new rr.util.ByteBuffer;o.putInt32(s),e.start(),e.update(a+o.getBytes()),n.putBuffer(e.digest())}return n.truncate(n.length()-r),n.getBytes()}};return t}});var oo=H((Sy,so)=>{"use strict";var va=W();wn();so.exports=va.mgf=va.mgf||{};va.mgf.mgf1=va.mgf1});var Ca=H((Ty,uo)=>{"use strict";var ar=W();it();re();var Jc=uo.exports=ar.pss=ar.pss||{};Jc.create=function(e){arguments.length===3&&(e={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]});var t=e.md,a=e.mgf,r=t.digestLength,n=e.salt||null;typeof n=="string"&&(n=ar.util.createBuffer(n));var i;if("saltLength"in e)i=e.saltLength;else if(n!==null)i=n.length();else throw new Error("Salt length not specified or specific salt not given.");if(n!==null&&n.length()!==i)throw new Error("Given salt length does not match length of given salt.");var s=e.prng||ar.random,o={};return o.encode=function(u,l){var f,c=l-1,g=Math.ceil(c/8),m=u.digest().getBytes();if(g<r+i+2)throw new Error("Message is too long to encrypt.");var h;n===null?h=s.getBytesSync(i):h=n.bytes();var v=new ar.util.ByteBuffer;v.fillWithByte(0,8),v.putBytes(m),v.putBytes(h),t.start(),t.update(v.getBytes());var E=t.digest().getBytes(),T=new ar.util.ByteBuffer;T.fillWithByte(0,g-i-r-2),T.putByte(1),T.putBytes(h);var I=T.getBytes(),A=g-r-1,L=a.generate(E,A),N="";for(f=0;f<A;f++)N+=String.fromCharCode(I.charCodeAt(f)^L.charCodeAt(f));var P=65280>>8*g-c&255;return N=String.fromCharCode(N.charCodeAt(0)&~P)+N.substr(1),N+E+"\xBC"},o.verify=function(u,l,f){var c,g=f-1,m=Math.ceil(g/8);if(l=l.substr(-m),m<r+i+2)throw new Error("Inconsistent parameters to PSS signature verification.");if(l.charCodeAt(m-1)!==188)throw new Error("Encoded message does not end in 0xBC.");var h=m-r-1,v=l.substr(0,h),E=l.substr(h,r),T=65280>>8*m-g&255;if((v.charCodeAt(0)&T)!==0)throw new Error("Bits beyond keysize not zero as expected.");var I=a.generate(E,h),A="";for(c=0;c<h;c++)A+=String.fromCharCode(v.charCodeAt(c)^I.charCodeAt(c));A=String.fromCharCode(A.charCodeAt(0)&~T)+A.substr(1);var L=m-r-i-2;for(c=0;c<L;c++)if(A.charCodeAt(c)!==0)throw new Error("Leftmost octets not zero as expected");if(A.charCodeAt(L)!==1)throw new Error("Inconsistent PSS signature, 0x01 marker not found");var N=A.substr(-i),P=new ar.util.ByteBuffer;P.fillWithByte(0,8),P.putBytes(u),P.putBytes(N),t.start(),t.update(P.getBytes());var G=t.digest().getBytes();return E===G},o}});var Sa=H((by,ho)=>{"use strict";var K=W();Ut();pt();Dr();mt();oo();Ft();Zt();Ca();Ur();re();var d=K.asn1,D=ho.exports=K.pki=K.pki||{},te=D.oids,Ce={};Ce.CN=te.commonName;Ce.commonName="CN";Ce.C=te.countryName;Ce.countryName="C";Ce.L=te.localityName;Ce.localityName="L";Ce.ST=te.stateOrProvinceName;Ce.stateOrProvinceName="ST";Ce.O=te.organizationName;Ce.organizationName="O";Ce.OU=te.organizationalUnitName;Ce.organizationalUnitName="OU";Ce.E=te.emailAddress;Ce.emailAddress="E";var fo=K.pki.rsa.publicKeyValidator,e0={name:"Certificate",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,captureAsn1:"tbsCertificate",value:[{name:"Certificate.TBSCertificate.version",tagClass:d.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.version.integer",tagClass:d.Class.UNIVERSAL,type:d.Type.INTEGER,constructed:!1,capture:"certVersion"}]},{name:"Certificate.TBSCertificate.serialNumber",tagClass:d.Class.UNIVERSAL,type:d.Type.INTEGER,constructed:!1,capture:"certSerialNumber"},{name:"Certificate.TBSCertificate.signature",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.signature.algorithm",tagClass:d.Class.UNIVERSAL,type:d.Type.OID,constructed:!1,capture:"certinfoSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:d.Class.UNIVERSAL,optional:!0,captureAsn1:"certinfoSignatureParams"}]},{name:"Certificate.TBSCertificate.issuer",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,captureAsn1:"certIssuer"},{name:"Certificate.TBSCertificate.validity",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.TBSCertificate.validity.notBefore (utc)",tagClass:d.Class.UNIVERSAL,type:d.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity1UTCTime"},{name:"Certificate.TBSCertificate.validity.notBefore (generalized)",tagClass:d.Class.UNIVERSAL,type:d.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity2GeneralizedTime"},{name:"Certificate.TBSCertificate.validity.notAfter (utc)",tagClass:d.Class.UNIVERSAL,type:d.Type.UTCTIME,constructed:!1,optional:!0,capture:"certValidity3UTCTime"},{name:"Certificate.TBSCertificate.validity.notAfter (generalized)",tagClass:d.Class.UNIVERSAL,type:d.Type.GENERALIZEDTIME,constructed:!1,optional:!0,capture:"certValidity4GeneralizedTime"}]},{name:"Certificate.TBSCertificate.subject",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,captureAsn1:"certSubject"},fo,{name:"Certificate.TBSCertificate.issuerUniqueID",tagClass:d.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.issuerUniqueID.id",tagClass:d.Class.UNIVERSAL,type:d.Type.BITSTRING,constructed:!1,captureBitStringValue:"certIssuerUniqueId"}]},{name:"Certificate.TBSCertificate.subjectUniqueID",tagClass:d.Class.CONTEXT_SPECIFIC,type:2,constructed:!0,optional:!0,value:[{name:"Certificate.TBSCertificate.subjectUniqueID.id",tagClass:d.Class.UNIVERSAL,type:d.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSubjectUniqueId"}]},{name:"Certificate.TBSCertificate.extensions",tagClass:d.Class.CONTEXT_SPECIFIC,type:3,constructed:!0,captureAsn1:"certExtensions",optional:!0}]},{name:"Certificate.signatureAlgorithm",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,value:[{name:"Certificate.signatureAlgorithm.algorithm",tagClass:d.Class.UNIVERSAL,type:d.Type.OID,constructed:!1,capture:"certSignatureOid"},{name:"Certificate.TBSCertificate.signature.parameters",tagClass:d.Class.UNIVERSAL,optional:!0,captureAsn1:"certSignatureParams"}]},{name:"Certificate.signatureValue",tagClass:d.Class.UNIVERSAL,type:d.Type.BITSTRING,constructed:!1,captureBitStringValue:"certSignature"}]},t0={name:"rsapss",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.hashAlgorithm",tagClass:d.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier",tagClass:d.Class.UNIVERSAL,type:d.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm",tagClass:d.Class.UNIVERSAL,type:d.Type.OID,constructed:!1,capture:"hashOid"}]}]},{name:"rsapss.maskGenAlgorithm",tagClass:d.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier",tagClass:d.Class.UNIVERSAL,type:d.Class.SEQUENCE,constructed:!0,optional:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm",tagClass:d.Class.UNIVERSAL,type:d.Type.OID,constructed:!1,capture:"maskGenOid"},{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,value:[{name:"rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm",tagClass:d.Class.UNIVERSAL,type:d.Type.OID,constructed:!1,capture:"maskGenHashOid"}]}]}]},{name:"rsapss.saltLength",tagClass:d.Class.CONTEXT_SPECIFIC,type:2,optional:!0,value:[{name:"rsapss.saltLength.saltLength",tagClass:d.Class.UNIVERSAL,type:d.Class.INTEGER,constructed:!1,capture:"saltLength"}]},{name:"rsapss.trailerField",tagClass:d.Class.CONTEXT_SPECIFIC,type:3,optional:!0,value:[{name:"rsapss.trailer.trailer",tagClass:d.Class.UNIVERSAL,type:d.Class.INTEGER,constructed:!1,capture:"trailer"}]}]},r0={name:"CertificationRequestInfo",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfo",value:[{name:"CertificationRequestInfo.integer",tagClass:d.Class.UNIVERSAL,type:d.Type.INTEGER,constructed:!1,capture:"certificationRequestInfoVersion"},{name:"CertificationRequestInfo.subject",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,captureAsn1:"certificationRequestInfoSubject"},fo,{name:"CertificationRequestInfo.attributes",tagClass:d.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"certificationRequestInfoAttributes",value:[{name:"CertificationRequestInfo.attributes",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequestInfo.attributes.type",tagClass:d.Class.UNIVERSAL,type:d.Type.OID,constructed:!1},{name:"CertificationRequestInfo.attributes.value",tagClass:d.Class.UNIVERSAL,type:d.Type.SET,constructed:!0}]}]}]},a0={name:"CertificationRequest",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,captureAsn1:"csr",value:[r0,{name:"CertificationRequest.signatureAlgorithm",tagClass:d.Class.UNIVERSAL,type:d.Type.SEQUENCE,constructed:!0,value:[{name:"CertificationRequest.signatureAlgorithm.algorithm",tagClass:d.Class.UNIVERSAL,type:d.Type.OID,constructed:!1,capture:"csrSignatureOid"},{name:"CertificationRequest.signatureAlgorithm.parameters",tagClass:d.Class.UNIVERSAL,optional:!0,captureAsn1:"csrSignatureParams"}]},{name:"CertificationRequest.signature",tagClass:d.Class.UNIVERSAL,type:d.Type.BITSTRING,constructed:!1,captureBitStringValue:"csrSignature"}]};D.RDNAttributesAsArray=function(e,t){for(var a=[],r,n,i,s=0;s<e.value.length;++s){r=e.value[s];for(var o=0;o<r.value.length;++o)i={},n=r.value[o],i.type=d.derToOid(n.value[0].value),i.value=n.value[1].value,i.valueTagClass=n.value[1].type,i.type in te&&(i.name=te[i.type],i.name in Ce&&(i.shortName=Ce[i.name])),t&&(t.update(i.type),t.update(i.value)),a.push(i)}return a};D.CRIAttributesAsArray=function(e){for(var t=[],a=0;a<e.length;++a)for(var r=e[a],n=d.derToOid(r.value[0].value),i=r.value[1].value,s=0;s<i.length;++s){var o={};if(o.type=n,o.value=i[s].value,o.valueTagClass=i[s].type,o.type in te&&(o.name=te[o.type],o.name in Ce&&(o.shortName=Ce[o.name])),o.type===te.extensionRequest){o.extensions=[];for(var u=0;u<o.value.length;++u)o.extensions.push(D.certificateExtensionFromAsn1(o.value[u]))}t.push(o)}return t};function Mt(e,t){typeof t=="string"&&(t={shortName:t});for(var a=null,r,n=0;a===null&&n<e.attributes.length;++n)r=e.attributes[n],(t.type&&t.type===r.type||t.name&&t.name===r.name||t.shortName&&t.shortName===r.shortName)&&(a=r);return a}var Ea=function(e,t,a){var r={};if(e!==te["RSASSA-PSS"])return r;a&&(r={hash:{algorithmOid:te.sha1},mgf:{algorithmOid:te.mgf1,hash:{algorithmOid:te.sha1}},saltLength:20});var n={},i=[];if(!d.validate(t,t0,n,i)){var s=new Error("Cannot read RSASSA-PSS parameter block.");throw s.errors=i,s}return n.hashOid!==void 0&&(r.hash=r.hash||{},r.hash.algorithmOid=d.derToOid(n.hashOid)),n.maskGenOid!==void 0&&(r.mgf=r.mgf||{},r.mgf.algorithmOid=d.derToOid(n.maskGenOid),r.mgf.hash=r.mgf.hash||{},r.mgf.hash.algorithmOid=d.derToOid(n.maskGenHashOid)),n.saltLength!==void 0&&(r.saltLength=n.saltLength.charCodeAt(0)),r},xa=function(e){switch(te[e.signatureOid]){case"sha1WithRSAEncryption":case"sha1WithRSASignature":return K.md.sha1.create();case"md5WithRSAEncryption":return K.md.md5.create();case"sha256WithRSAEncryption":return K.md.sha256.create();case"sha384WithRSAEncryption":return K.md.sha384.create();case"sha512WithRSAEncryption":return K.md.sha512.create();case"RSASSA-PSS":return K.md.sha256.create();default:var t=new Error("Could not compute "+e.type+" digest. Unknown signature OID.");throw t.signatureOid=e.signatureOid,t}},co=function(e){var t=e.certificate,a;switch(t.signatureOid){case te.sha1WithRSAEncryption:case te.sha1WithRSASignature:break;case te["RSASSA-PSS"]:var r,n;if(r=te[t.signatureParameters.mgf.hash.algorithmOid],r===void 0||K.md[r]===void 0){var i=new Error("Unsupported MGF hash function.");throw i.oid=t.signatureParameters.mgf.hash.algorithmOid,i.name=r,i}if(n=te[t.signatureParameters.mgf.algorithmOid],n===void 0||K.mgf[n]===void 0){var i=new Error("Unsupported MGF function.");throw i.oid=t.signatureParameters.mgf.algorithmOid,i.name=n,i}if(n=K.mgf[n].create(K.md[r].create()),r=te[t.signatureParameters.hash.algorithmOid],r===void 0||K.md[r]===void 0){var i=new Error("Unsupported RSASSA-PSS hash function.");throw i.oid=t.signatureParameters.hash.algorithmOid,i.name=r,i}a=K.pss.create(K.md[r].create(),n,t.signatureParameters.saltLength);break}return t.publicKey.verify(e.md.digest().getBytes(),e.signature,a)};D.certificateFromPem=function(e,t,a){var r=K.pem.decode(e)[0];if(r.type!=="CERTIFICATE"&&r.type!=="X509 CERTIFICATE"&&r.type!=="TRUSTED CERTIFICATE"){var n=new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw n.headerType=r.type,n}if(r.procType&&r.procType.type==="ENCRYPTED")throw new Error("Could not convert certificate from PEM; PEM is encrypted.");var i=d.fromDer(r.body,a);return D.certificateFromAsn1(i,t)};D.certificateToPem=function(e,t){var a={type:"CERTIFICATE",body:d.toDer(D.certificateToAsn1(e)).getBytes()};return K.pem.encode(a,{maxline:t})};D.publicKeyFromPem=function(e){var t=K.pem.decode(e)[0];if(t.type!=="PUBLIC KEY"&&t.type!=="RSA PUBLIC KEY"){var a=new Error('Could not convert public key from PEM; PEM header type is not "PUBLIC KEY" or "RSA PUBLIC KEY".');throw a.headerType=t.type,a}if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert public key from PEM; PEM is encrypted.");var r=d.fromDer(t.body);return D.publicKeyFromAsn1(r)};D.publicKeyToPem=function(e,t){var a={type:"PUBLIC KEY",body:d.toDer(D.publicKeyToAsn1(e)).getBytes()};return K.pem.encode(a,{maxline:t})};D.publicKeyToRSAPublicKeyPem=function(e,t){var a={type:"RSA PUBLIC KEY",body:d.toDer(D.publicKeyToRSAPublicKey(e)).getBytes()};return K.pem.encode(a,{maxline:t})};D.getPublicKeyFingerprint=function(e,t){t=t||{};var a=t.md||K.md.sha1.create(),r=t.type||"RSAPublicKey",n;switch(r){case"RSAPublicKey":n=d.toDer(D.publicKeyToRSAPublicKey(e)).getBytes();break;case"SubjectPublicKeyInfo":n=d.toDer(D.publicKeyToAsn1(e)).getBytes();break;default:throw new Error('Unknown fingerprint type "'+t.type+'".')}a.start(),a.update(n);var i=a.digest();if(t.encoding==="hex"){var s=i.toHex();return t.delimiter?s.match(/.{2}/g).join(t.delimiter):s}else{if(t.encoding==="binary")return i.getBytes();if(t.encoding)throw new Error('Unknown encoding "'+t.encoding+'".')}return i};D.certificationRequestFromPem=function(e,t,a){var r=K.pem.decode(e)[0];if(r.type!=="CERTIFICATE REQUEST"){var n=new Error('Could not convert certification request from PEM; PEM header type is not "CERTIFICATE REQUEST".');throw n.headerType=r.type,n}if(r.procType&&r.procType.type==="ENCRYPTED")throw new Error("Could not convert certification request from PEM; PEM is encrypted.");var i=d.fromDer(r.body,a);return D.certificationRequestFromAsn1(i,t)};D.certificationRequestToPem=function(e,t){var a={type:"CERTIFICATE REQUEST",body:d.toDer(D.certificationRequestToAsn1(e)).getBytes()};return K.pem.encode(a,{maxline:t})};D.createCertificate=function(){var e={};return e.version=2,e.serialNumber="00",e.signatureOid=null,e.signature=null,e.siginfo={},e.siginfo.algorithmOid=null,e.validity={},e.validity.notBefore=new Date,e.validity.notAfter=new Date,e.issuer={},e.issuer.getField=function(t){return Mt(e.issuer,t)},e.issuer.addField=function(t){ut([t]),e.issuer.attributes.push(t)},e.issuer.attributes=[],e.issuer.hash=null,e.subject={},e.subject.getField=function(t){return Mt(e.subject,t)},e.subject.addField=function(t){ut([t]),e.subject.attributes.push(t)},e.subject.attributes=[],e.subject.hash=null,e.extensions=[],e.publicKey=null,e.md=null,e.setSubject=function(t,a){ut(t),e.subject.attributes=t,delete e.subject.uniqueId,a&&(e.subject.uniqueId=a),e.subject.hash=null},e.setIssuer=function(t,a){ut(t),e.issuer.attributes=t,delete e.issuer.uniqueId,a&&(e.issuer.uniqueId=a),e.issuer.hash=null},e.setExtensions=function(t){for(var a=0;a<t.length;++a)po(t[a],{cert:e});e.extensions=t},e.getExtension=function(t){typeof t=="string"&&(t={name:t});for(var a=null,r,n=0;a===null&&n<e.extensions.length;++n)r=e.extensions[n],(t.id&&r.id===t.id||t.name&&r.name===t.name)&&(a=r);return a},e.sign=function(t,a){e.md=a||K.md.sha1.create();var r=te[e.md.algorithm+"WithRSAEncryption"];if(!r){var n=new Error("Could not compute certificate digest. Unknown message digest algorithm OID.");throw n.algorithm=e.md.algorithm,n}e.signatureOid=e.siginfo.algorithmOid=r,e.tbsCertificate=D.getTBSCertificate(e);var i=d.toDer(e.tbsCertificate);e.md.update(i.getBytes()),e.signature=t.sign(e.md)},e.verify=function(t){var a=!1;if(!e.issued(t)){var r=t.issuer,n=e.subject,i=new Error("The parent certificate did not issue the given child certificate; the child certificate's issuer does not match the parent's subject.");throw i.expectedIssuer=n.attributes,i.actualIssuer=r.attributes,i}var s=t.md;if(s===null){s=xa({signatureOid:t.signatureOid,type:"certificate"});var o=t.tbsCertificate||D.getTBSCertificate(t),u=d.toDer(o);s.update(u.getBytes())}return s!==null&&(a=co({certificate:e,md:s,signature:t.signature})),a},e.isIssuer=function(t){var a=!1,r=e.issuer,n=t.subject;if(r.hash&&n.hash)a=r.hash===n.hash;else if(r.attributes.length===n.attributes.length){a=!0;for(var i,s,o=0;a&&o<r.attributes.length;++o)i=r.attributes[o],s=n.attributes[o],(i.type!==s.type||i.value!==s.value)&&(a=!1)}return a},e.issued=function(t){return t.isIssuer(e)},e.generateSubjectKeyIdentifier=function(){return D.getPublicKeyFingerprint(e.publicKey,{type:"RSAPublicKey"})},e.verifySubjectKeyIdentifier=function(){for(var t=te.subjectKeyIdentifier,a=0;a<e.extensions.length;++a){var r=e.extensions[a];if(r.id===t){var n=e.generateSubjectKeyIdentifier().getBytes();return K.util.hexToBytes(r.subjectKeyIdentifier)===n}}return!1},e};D.certificateFromAsn1=function(e,t){var a={},r=[];if(!d.validate(e,e0,a,r)){var n=new Error("Cannot read X.509 certificate. ASN.1 object is not an X509v3 Certificate.");throw n.errors=r,n}var i=d.derToOid(a.publicKeyOid);if(i!==D.oids.rsaEncryption)throw new Error("Cannot read public key. OID is not RSA.");var s=D.createCertificate();s.version=a.certVersion?a.certVersion.charCodeAt(0):0;var o=K.util.createBuffer(a.certSerialNumber);s.serialNumber=o.toHex(),s.signatureOid=K.asn1.derToOid(a.certSignatureOid),s.signatureParameters=Ea(s.signatureOid,a.certSignatureParams,!0),s.siginfo.algorithmOid=K.asn1.derToOid(a.certinfoSignatureOid),s.siginfo.parameters=Ea(s.siginfo.algorithmOid,a.certinfoSignatureParams,!1),s.signature=a.certSignature;var u=[];if(a.certValidity1UTCTime!==void 0&&u.push(d.utcTimeToDate(a.certValidity1UTCTime)),a.certValidity2GeneralizedTime!==void 0&&u.push(d.generalizedTimeToDate(a.certValidity2GeneralizedTime)),a.certValidity3UTCTime!==void 0&&u.push(d.utcTimeToDate(a.certValidity3UTCTime)),a.certValidity4GeneralizedTime!==void 0&&u.push(d.generalizedTimeToDate(a.certValidity4GeneralizedTime)),u.length>2)throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(u.length<2)throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(s.validity.notBefore=u[0],s.validity.notAfter=u[1],s.tbsCertificate=a.tbsCertificate,t){s.md=xa({signatureOid:s.signatureOid,type:"certificate"});var l=d.toDer(s.tbsCertificate);s.md.update(l.getBytes())}var f=K.md.sha1.create(),c=d.toDer(a.certIssuer);f.update(c.getBytes()),s.issuer.getField=function(h){return Mt(s.issuer,h)},s.issuer.addField=function(h){ut([h]),s.issuer.attributes.push(h)},s.issuer.attributes=D.RDNAttributesAsArray(a.certIssuer),a.certIssuerUniqueId&&(s.issuer.uniqueId=a.certIssuerUniqueId),s.issuer.hash=f.digest().toHex();var g=K.md.sha1.create(),m=d.toDer(a.certSubject);return g.update(m.getBytes()),s.subject.getField=function(h){return Mt(s.subject,h)},s.subject.addField=function(h){ut([h]),s.subject.attributes.push(h)},s.subject.attributes=D.RDNAttributesAsArray(a.certSubject),a.certSubjectUniqueId&&(s.subject.uniqueId=a.certSubjectUniqueId),s.subject.hash=g.digest().toHex(),a.certExtensions?s.extensions=D.certificateExtensionsFromAsn1(a.certExtensions):s.extensions=[],s.publicKey=D.publicKeyFromAsn1(a.subjectPublicKeyInfo),s};D.certificateExtensionsFromAsn1=function(e){for(var t=[],a=0;a<e.value.length;++a)for(var r=e.value[a],n=0;n<r.value.length;++n)t.push(D.certificateExtensionFromAsn1(r.value[n]));return t};D.certificateExtensionFromAsn1=function(e){var t={};if(t.id=d.derToOid(e.value[0].value),t.critical=!1,e.value[1].type===d.Type.BOOLEAN?(t.critical=e.value[1].value.charCodeAt(0)!==0,t.value=e.value[2].value):t.value=e.value[1].value,t.id in te){if(t.name=te[t.id],t.name==="keyUsage"){var a=d.fromDer(t.value),r=0,n=0;a.value.length>1&&(r=a.value.charCodeAt(1),n=a.value.length>2?a.value.charCodeAt(2):0),t.digitalSignature=(r&128)===128,t.nonRepudiation=(r&64)===64,t.keyEncipherment=(r&32)===32,t.dataEncipherment=(r&16)===16,t.keyAgreement=(r&8)===8,t.keyCertSign=(r&4)===4,t.cRLSign=(r&2)===2,t.encipherOnly=(r&1)===1,t.decipherOnly=(n&128)===128}else if(t.name==="basicConstraints"){var a=d.fromDer(t.value);a.value.length>0&&a.value[0].type===d.Type.BOOLEAN?t.cA=a.value[0].value.charCodeAt(0)!==0:t.cA=!1;var i=null;a.value.length>0&&a.value[0].type===d.Type.INTEGER?i=a.value[0].value:a.value.length>1&&(i=a.value[1].value),i!==null&&(t.pathLenConstraint=d.derToInteger(i))}else if(t.name==="extKeyUsage")for(var a=d.fromDer(t.value),s=0;s<a.value.length;++s){var o=d.derToOid(a.value[s].value);o in te?t[te[o]]=!0:t[o]=!0}else if(t.name==="nsCertType"){var a=d.fromDer(t.value),r=0;a.value.length>1&&(r=a.value.charCodeAt(1)),t.client=(r&128)===128,t.server=(r&64)===64,t.email=(r&32)===32,t.objsign=(r&16)===16,t.reserved=(r&8)===8,t.sslCA=(r&4)===4,t.emailCA=(r&2)===2,t.objCA=(r&1)===1}else if(t.name==="subjectAltName"||t.name==="issuerAltName"){t.altNames=[];for(var u,a=d.fromDer(t.value),l=0;l<a.value.length;++l){u=a.value[l];var f={type:u.type,value:u.value};switch(t.altNames.push(f),u.type){case 1:case 2:case 6:break;case 7:f.ip=K.util.bytesToIP(u.value);break;case 8:f.oid=d.derToOid(u.value);break;default:}}}else if(t.name==="subjectKeyIdentifier"){var a=d.fromDer(t.value);t.subjectKeyIdentifier=K.util.bytesToHex(a.value)}}return t};D.certificationRequestFromAsn1=function(e,t){var a={},r=[];if(!d.validate(e,a0,a,r)){var n=new Error("Cannot read PKCS#10 certificate request. ASN.1 object is not a PKCS#10 CertificationRequest.");throw n.errors=r,n}var i=d.derToOid(a.publicKeyOid);if(i!==D.oids.rsaEncryption)throw new Error("Cannot read public key. OID is not RSA.");var s=D.createCertificationRequest();if(s.version=a.csrVersion?a.csrVersion.charCodeAt(0):0,s.signatureOid=K.asn1.derToOid(a.csrSignatureOid),s.signatureParameters=Ea(s.signatureOid,a.csrSignatureParams,!0),s.siginfo.algorithmOid=K.asn1.derToOid(a.csrSignatureOid),s.siginfo.parameters=Ea(s.siginfo.algorithmOid,a.csrSignatureParams,!1),s.signature=a.csrSignature,s.certificationRequestInfo=a.certificationRequestInfo,t){s.md=xa({signatureOid:s.signatureOid,type:"certification request"});var o=d.toDer(s.certificationRequestInfo);s.md.update(o.getBytes())}var u=K.md.sha1.create();return s.subject.getField=function(l){return Mt(s.subject,l)},s.subject.addField=function(l){ut([l]),s.subject.attributes.push(l)},s.subject.attributes=D.RDNAttributesAsArray(a.certificationRequestInfoSubject,u),s.subject.hash=u.digest().toHex(),s.publicKey=D.publicKeyFromAsn1(a.subjectPublicKeyInfo),s.getAttribute=function(l){return Mt(s,l)},s.addAttribute=function(l){ut([l]),s.attributes.push(l)},s.attributes=D.CRIAttributesAsArray(a.certificationRequestInfoAttributes||[]),s};D.createCertificationRequest=function(){var e={};return e.version=0,e.signatureOid=null,e.signature=null,e.siginfo={},e.siginfo.algorithmOid=null,e.subject={},e.subject.getField=function(t){return Mt(e.subject,t)},e.subject.addField=function(t){ut([t]),e.subject.attributes.push(t)},e.subject.attributes=[],e.subject.hash=null,e.publicKey=null,e.attributes=[],e.getAttribute=function(t){return Mt(e,t)},e.addAttribute=function(t){ut([t]),e.attributes.push(t)},e.md=null,e.setSubject=function(t){ut(t),e.subject.attributes=t,e.subject.hash=null},e.setAttributes=function(t){ut(t),e.attributes=t},e.sign=function(t,a){e.md=a||K.md.sha1.create();var r=te[e.md.algorithm+"WithRSAEncryption"];if(!r){var n=new Error("Could not compute certification request digest. Unknown message digest algorithm OID.");throw n.algorithm=e.md.algorithm,n}e.signatureOid=e.siginfo.algorithmOid=r,e.certificationRequestInfo=D.getCertificationRequestInfo(e);var i=d.toDer(e.certificationRequestInfo);e.md.update(i.getBytes()),e.signature=t.sign(e.md)},e.verify=function(){var t=!1,a=e.md;if(a===null){a=xa({signatureOid:e.signatureOid,type:"certification request"});var r=e.certificationRequestInfo||D.getCertificationRequestInfo(e),n=d.toDer(r);a.update(n.getBytes())}return a!==null&&(t=co({certificate:e,md:a,signature:e.signature})),t},e};function Cr(e){for(var t=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[]),a,r,n=e.attributes,i=0;i<n.length;++i){a=n[i];var s=a.value,o=d.Type.PRINTABLESTRING;"valueTagClass"in a&&(o=a.valueTagClass,o===d.Type.UTF8&&(s=K.util.encodeUtf8(s))),r=d.create(d.Class.UNIVERSAL,d.Type.SET,!0,[d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(a.type).getBytes()),d.create(d.Class.UNIVERSAL,o,!1,s)])]),t.value.push(r)}return t}function ut(e){for(var t,a=0;a<e.length;++a){if(t=e[a],typeof t.name>"u"&&(t.type&&t.type in D.oids?t.name=D.oids[t.type]:t.shortName&&t.shortName in Ce&&(t.name=D.oids[Ce[t.shortName]])),typeof t.type>"u")if(t.name&&t.name in D.oids)t.type=D.oids[t.name];else{var r=new Error("Attribute type not specified.");throw r.attribute=t,r}if(typeof t.shortName>"u"&&t.name&&t.name in Ce&&(t.shortName=Ce[t.name]),t.type===te.extensionRequest&&(t.valueConstructed=!0,t.valueTagClass=d.Type.SEQUENCE,!t.value&&t.extensions)){t.value=[];for(var n=0;n<t.extensions.length;++n)t.value.push(D.certificateExtensionToAsn1(po(t.extensions[n])))}if(typeof t.value>"u"){var r=new Error("Attribute value not specified.");throw r.attribute=t,r}}}function po(e,t){if(t=t||{},typeof e.name>"u"&&e.id&&e.id in D.oids&&(e.name=D.oids[e.id]),typeof e.id>"u")if(e.name&&e.name in D.oids)e.id=D.oids[e.name];else{var a=new Error("Extension ID not specified.");throw a.extension=e,a}if(typeof e.value<"u")return e;if(e.name==="keyUsage"){var r=0,n=0,i=0;e.digitalSignature&&(n|=128,r=7),e.nonRepudiation&&(n|=64,r=6),e.keyEncipherment&&(n|=32,r=5),e.dataEncipherment&&(n|=16,r=4),e.keyAgreement&&(n|=8,r=3),e.keyCertSign&&(n|=4,r=2),e.cRLSign&&(n|=2,r=1),e.encipherOnly&&(n|=1,r=0),e.decipherOnly&&(i|=128,r=7);var s=String.fromCharCode(r);i!==0?s+=String.fromCharCode(n)+String.fromCharCode(i):n!==0&&(s+=String.fromCharCode(n)),e.value=d.create(d.Class.UNIVERSAL,d.Type.BITSTRING,!1,s)}else if(e.name==="basicConstraints")e.value=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[]),e.cA&&e.value.value.push(d.create(d.Class.UNIVERSAL,d.Type.BOOLEAN,!1,"\xFF")),"pathLenConstraint"in e&&e.value.value.push(d.create(d.Class.UNIVERSAL,d.Type.INTEGER,!1,d.integerToDer(e.pathLenConstraint).getBytes()));else if(e.name==="extKeyUsage"){e.value=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[]);var o=e.value.value;for(var u in e)e[u]===!0&&(u in te?o.push(d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(te[u]).getBytes())):u.indexOf(".")!==-1&&o.push(d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(u).getBytes())))}else if(e.name==="nsCertType"){var r=0,n=0;e.client&&(n|=128,r=7),e.server&&(n|=64,r=6),e.email&&(n|=32,r=5),e.objsign&&(n|=16,r=4),e.reserved&&(n|=8,r=3),e.sslCA&&(n|=4,r=2),e.emailCA&&(n|=2,r=1),e.objCA&&(n|=1,r=0);var s=String.fromCharCode(r);n!==0&&(s+=String.fromCharCode(n)),e.value=d.create(d.Class.UNIVERSAL,d.Type.BITSTRING,!1,s)}else if(e.name==="subjectAltName"||e.name==="issuerAltName"){e.value=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[]);for(var l,f=0;f<e.altNames.length;++f){l=e.altNames[f];var s=l.value;if(l.type===7&&l.ip){if(s=K.util.bytesFromIP(l.ip),s===null){var a=new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw a.extension=e,a}}else l.type===8&&(l.oid?s=d.oidToDer(d.oidToDer(l.oid)):s=d.oidToDer(s));e.value.value.push(d.create(d.Class.CONTEXT_SPECIFIC,l.type,!1,s))}}else if(e.name==="nsComment"&&t.cert){if(!/^[\x00-\x7F]*$/.test(e.comment)||e.comment.length<1||e.comment.length>128)throw new Error('Invalid "nsComment" content.');e.value=d.create(d.Class.UNIVERSAL,d.Type.IA5STRING,!1,e.comment)}else if(e.name==="subjectKeyIdentifier"&&t.cert){var c=t.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=c.toHex(),e.value=d.create(d.Class.UNIVERSAL,d.Type.OCTETSTRING,!1,c.getBytes())}else if(e.name==="authorityKeyIdentifier"&&t.cert){e.value=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[]);var o=e.value.value;if(e.keyIdentifier){var g=e.keyIdentifier===!0?t.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;o.push(d.create(d.Class.CONTEXT_SPECIFIC,0,!1,g))}if(e.authorityCertIssuer){var m=[d.create(d.Class.CONTEXT_SPECIFIC,4,!0,[Cr(e.authorityCertIssuer===!0?t.cert.issuer:e.authorityCertIssuer)])];o.push(d.create(d.Class.CONTEXT_SPECIFIC,1,!0,m))}if(e.serialNumber){var h=K.util.hexToBytes(e.serialNumber===!0?t.cert.serialNumber:e.serialNumber);o.push(d.create(d.Class.CONTEXT_SPECIFIC,2,!1,h))}}else if(e.name==="cRLDistributionPoints"){e.value=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[]);for(var o=e.value.value,v=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[]),E=d.create(d.Class.CONTEXT_SPECIFIC,0,!0,[]),l,f=0;f<e.altNames.length;++f){l=e.altNames[f];var s=l.value;if(l.type===7&&l.ip){if(s=K.util.bytesFromIP(l.ip),s===null){var a=new Error('Extension "ip" value is not a valid IPv4 or IPv6 address.');throw a.extension=e,a}}else l.type===8&&(l.oid?s=d.oidToDer(d.oidToDer(l.oid)):s=d.oidToDer(s));E.value.push(d.create(d.Class.CONTEXT_SPECIFIC,l.type,!1,s))}v.value.push(d.create(d.Class.CONTEXT_SPECIFIC,0,!0,[E])),o.push(v)}if(typeof e.value>"u"){var a=new Error("Extension value not specified.");throw a.extension=e,a}return e}function An(e,t){switch(e){case te["RSASSA-PSS"]:var a=[];return t.hash.algorithmOid!==void 0&&a.push(d.create(d.Class.CONTEXT_SPECIFIC,0,!0,[d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(t.hash.algorithmOid).getBytes()),d.create(d.Class.UNIVERSAL,d.Type.NULL,!1,"")])])),t.mgf.algorithmOid!==void 0&&a.push(d.create(d.Class.CONTEXT_SPECIFIC,1,!0,[d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(t.mgf.algorithmOid).getBytes()),d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(t.mgf.hash.algorithmOid).getBytes()),d.create(d.Class.UNIVERSAL,d.Type.NULL,!1,"")])])])),t.saltLength!==void 0&&a.push(d.create(d.Class.CONTEXT_SPECIFIC,2,!0,[d.create(d.Class.UNIVERSAL,d.Type.INTEGER,!1,d.integerToDer(t.saltLength).getBytes())])),d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,a);default:return d.create(d.Class.UNIVERSAL,d.Type.NULL,!1,"")}}function n0(e){var t=d.create(d.Class.CONTEXT_SPECIFIC,0,!0,[]);if(e.attributes.length===0)return t;for(var a=e.attributes,r=0;r<a.length;++r){var n=a[r],i=n.value,s=d.Type.UTF8;"valueTagClass"in n&&(s=n.valueTagClass),s===d.Type.UTF8&&(i=K.util.encodeUtf8(i));var o=!1;"valueConstructed"in n&&(o=n.valueConstructed);var u=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(n.type).getBytes()),d.create(d.Class.UNIVERSAL,d.Type.SET,!0,[d.create(d.Class.UNIVERSAL,s,o,i)])]);t.value.push(u)}return t}var i0=new Date("1950-01-01T00:00:00Z"),s0=new Date("2050-01-01T00:00:00Z");function lo(e){return e>=i0&&e<s0?d.create(d.Class.UNIVERSAL,d.Type.UTCTIME,!1,d.dateToUtcTime(e)):d.create(d.Class.UNIVERSAL,d.Type.GENERALIZEDTIME,!1,d.dateToGeneralizedTime(e))}D.getTBSCertificate=function(e){var t=lo(e.validity.notBefore),a=lo(e.validity.notAfter),r=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.CONTEXT_SPECIFIC,0,!0,[d.create(d.Class.UNIVERSAL,d.Type.INTEGER,!1,d.integerToDer(e.version).getBytes())]),d.create(d.Class.UNIVERSAL,d.Type.INTEGER,!1,K.util.hexToBytes(e.serialNumber)),d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(e.siginfo.algorithmOid).getBytes()),An(e.siginfo.algorithmOid,e.siginfo.parameters)]),Cr(e.issuer),d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[t,a]),Cr(e.subject),D.publicKeyToAsn1(e.publicKey)]);return e.issuer.uniqueId&&r.value.push(d.create(d.Class.CONTEXT_SPECIFIC,1,!0,[d.create(d.Class.UNIVERSAL,d.Type.BITSTRING,!1,"\0"+e.issuer.uniqueId)])),e.subject.uniqueId&&r.value.push(d.create(d.Class.CONTEXT_SPECIFIC,2,!0,[d.create(d.Class.UNIVERSAL,d.Type.BITSTRING,!1,"\0"+e.subject.uniqueId)])),e.extensions.length>0&&r.value.push(D.certificateExtensionsToAsn1(e.extensions)),r};D.getCertificationRequestInfo=function(e){var t=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.INTEGER,!1,d.integerToDer(e.version).getBytes()),Cr(e.subject),D.publicKeyToAsn1(e.publicKey),n0(e)]);return t};D.distinguishedNameToAsn1=function(e){return Cr(e)};D.certificateToAsn1=function(e){var t=e.tbsCertificate||D.getTBSCertificate(e);return d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[t,d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(e.signatureOid).getBytes()),An(e.signatureOid,e.signatureParameters)]),d.create(d.Class.UNIVERSAL,d.Type.BITSTRING,!1,"\0"+e.signature)])};D.certificateExtensionsToAsn1=function(e){var t=d.create(d.Class.CONTEXT_SPECIFIC,3,!0,[]),a=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[]);t.value.push(a);for(var r=0;r<e.length;++r)a.value.push(D.certificateExtensionToAsn1(e[r]));return t};D.certificateExtensionToAsn1=function(e){var t=d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[]);t.value.push(d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(e.id).getBytes())),e.critical&&t.value.push(d.create(d.Class.UNIVERSAL,d.Type.BOOLEAN,!1,"\xFF"));var a=e.value;return typeof e.value!="string"&&(a=d.toDer(a).getBytes()),t.value.push(d.create(d.Class.UNIVERSAL,d.Type.OCTETSTRING,!1,a)),t};D.certificationRequestToAsn1=function(e){var t=e.certificationRequestInfo||D.getCertificationRequestInfo(e);return d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[t,d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(e.signatureOid).getBytes()),An(e.signatureOid,e.signatureParameters)]),d.create(d.Class.UNIVERSAL,d.Type.BITSTRING,!1,"\0"+e.signature)])};D.createCaStore=function(e){var t={certs:{}};t.getIssuer=function(s){var o=a(s.issuer);return o},t.addCertificate=function(s){if(typeof s=="string"&&(s=K.pki.certificateFromPem(s)),r(s.subject),!t.hasCertificate(s))if(s.subject.hash in t.certs){var o=t.certs[s.subject.hash];K.util.isArray(o)||(o=[o]),o.push(s),t.certs[s.subject.hash]=o}else t.certs[s.subject.hash]=s},t.hasCertificate=function(s){typeof s=="string"&&(s=K.pki.certificateFromPem(s));var o=a(s.subject);if(!o)return!1;K.util.isArray(o)||(o=[o]);for(var u=d.toDer(D.certificateToAsn1(s)).getBytes(),l=0;l<o.length;++l){var f=d.toDer(D.certificateToAsn1(o[l])).getBytes();if(u===f)return!0}return!1},t.listAllCertificates=function(){var s=[];for(var o in t.certs)if(t.certs.hasOwnProperty(o)){var u=t.certs[o];if(!K.util.isArray(u))s.push(u);else for(var l=0;l<u.length;++l)s.push(u[l])}return s},t.removeCertificate=function(s){var o;if(typeof s=="string"&&(s=K.pki.certificateFromPem(s)),r(s.subject),!t.hasCertificate(s))return null;var u=a(s.subject);if(!K.util.isArray(u))return o=t.certs[s.subject.hash],delete t.certs[s.subject.hash],o;for(var l=d.toDer(D.certificateToAsn1(s)).getBytes(),f=0;f<u.length;++f){var c=d.toDer(D.certificateToAsn1(u[f])).getBytes();l===c&&(o=u[f],u.splice(f,1))}return u.length===0&&delete t.certs[s.subject.hash],o};function a(s){return r(s),t.certs[s.hash]||null}function r(s){if(!s.hash){var o=K.md.sha1.create();s.attributes=D.RDNAttributesAsArray(Cr(s),o),s.hash=o.digest().toHex()}}if(e)for(var n=0;n<e.length;++n){var i=e[n];t.addCertificate(i)}return t};D.certificateError={bad_certificate:"forge.pki.BadCertificate",unsupported_certificate:"forge.pki.UnsupportedCertificate",certificate_revoked:"forge.pki.CertificateRevoked",certificate_expired:"forge.pki.CertificateExpired",certificate_unknown:"forge.pki.CertificateUnknown",unknown_ca:"forge.pki.UnknownCertificateAuthority"};D.verifyCertificateChain=function(e,t,a){typeof a=="function"&&(a={verify:a}),a=a||{},t=t.slice(0);var r=t.slice(0),n=a.validityCheckDate;typeof n>"u"&&(n=new Date);var i=!0,s=null,o=0;do{var u=t.shift(),l=null,f=!1;if(n&&(n<u.validity.notBefore||n>u.validity.notAfter)&&(s={message:"Certificate is not valid yet or has expired.",error:D.certificateError.certificate_expired,notBefore:u.validity.notBefore,notAfter:u.validity.notAfter,now:n}),s===null){if(l=t[0]||e.getIssuer(u),l===null&&u.isIssuer(u)&&(f=!0,l=u),l){var c=l;K.util.isArray(c)||(c=[c]);for(var g=!1;!g&&c.length>0;){l=c.shift();try{g=l.verify(u)}catch{}}g||(s={message:"Certificate signature is invalid.",error:D.certificateError.bad_certificate})}s===null&&(!l||f)&&!e.hasCertificate(u)&&(s={message:"Certificate is not trusted.",error:D.certificateError.unknown_ca})}if(s===null&&l&&!u.isIssuer(l)&&(s={message:"Certificate issuer is invalid.",error:D.certificateError.bad_certificate}),s===null)for(var m={keyUsage:!0,basicConstraints:!0},h=0;s===null&&h<u.extensions.length;++h){var v=u.extensions[h];v.critical&&!(v.name in m)&&(s={message:"Certificate has an unsupported critical extension.",error:D.certificateError.unsupported_certificate})}if(s===null&&(!i||t.length===0&&(!l||f))){var E=u.getExtension("basicConstraints"),T=u.getExtension("keyUsage");if(T!==null&&(!T.keyCertSign||E===null)&&(s={message:"Certificate keyUsage or basicConstraints conflict or indicate that the certificate is not a CA. If the certificate is the only one in the chain or isn't the first then the certificate must be a valid CA.",error:D.certificateError.bad_certificate}),s===null&&E!==null&&!E.cA&&(s={message:"Certificate basicConstraints indicates the certificate is not a CA.",error:D.certificateError.bad_certificate}),s===null&&T!==null&&"pathLenConstraint"in E){var I=o-1;I>E.pathLenConstraint&&(s={message:"Certificate basicConstraints pathLenConstraint violated.",error:D.certificateError.bad_certificate})}}var A=s===null?!0:s.error,L=a.verify?a.verify(A,o,r):A;if(L===!0)s=null;else throw A===!0&&(s={message:"The application rejected the certificate.",error:D.certificateError.bad_certificate}),(L||L===0)&&(typeof L=="object"&&!K.util.isArray(L)?(L.message&&(s.message=L.message),L.error&&(s.error=L.error)):typeof L=="string"&&(s.error=L)),s;i=!1,++o}while(t.length>0);return!0}});var Rn=H((Iy,go)=>{"use strict";var de=W();pt();dr();Ft();In();bn();it();Ur();gr();re();Sa();var C=de.asn1,Y=de.pki,Or=go.exports=de.pkcs12=de.pkcs12||{},yo={name:"ContentInfo",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.contentType",tagClass:C.Class.UNIVERSAL,type:C.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:C.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"content"}]},o0={name:"PFX",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.version",tagClass:C.Class.UNIVERSAL,type:C.Type.INTEGER,constructed:!1,capture:"version"},yo,{name:"PFX.macData",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"mac",value:[{name:"PFX.macData.mac",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm.algorithm",tagClass:C.Class.UNIVERSAL,type:C.Type.OID,constructed:!1,capture:"macAlgorithm"},{name:"PFX.macData.mac.digestAlgorithm.parameters",tagClass:C.Class.UNIVERSAL,captureAsn1:"macAlgorithmParameters"}]},{name:"PFX.macData.mac.digest",tagClass:C.Class.UNIVERSAL,type:C.Type.OCTETSTRING,constructed:!1,capture:"macDigest"}]},{name:"PFX.macData.macSalt",tagClass:C.Class.UNIVERSAL,type:C.Type.OCTETSTRING,constructed:!1,capture:"macSalt"},{name:"PFX.macData.iterations",tagClass:C.Class.UNIVERSAL,type:C.Type.INTEGER,constructed:!1,optional:!0,capture:"macIterations"}]}]},u0={name:"SafeBag",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"SafeBag.bagId",tagClass:C.Class.UNIVERSAL,type:C.Type.OID,constructed:!1,capture:"bagId"},{name:"SafeBag.bagValue",tagClass:C.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"bagValue"},{name:"SafeBag.bagAttributes",tagClass:C.Class.UNIVERSAL,type:C.Type.SET,constructed:!0,optional:!0,capture:"bagAttributes"}]},l0={name:"Attribute",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"Attribute.attrId",tagClass:C.Class.UNIVERSAL,type:C.Type.OID,constructed:!1,capture:"oid"},{name:"Attribute.attrValues",tagClass:C.Class.UNIVERSAL,type:C.Type.SET,constructed:!0,capture:"values"}]},f0={name:"CertBag",tagClass:C.Class.UNIVERSAL,type:C.Type.SEQUENCE,constructed:!0,value:[{name:"CertBag.certId",tagClass:C.Class.UNIVERSAL,type:C.Type.OID,constructed:!1,capture:"certId"},{name:"CertBag.certValue",tagClass:C.Class.CONTEXT_SPECIFIC,constructed:!0,value:[{name:"CertBag.certValue[0]",tagClass:C.Class.UNIVERSAL,type:C.Class.OCTETSTRING,constructed:!1,capture:"cert"}]}]};function Fr(e,t,a,r){for(var n=[],i=0;i<e.length;i++)for(var s=0;s<e[i].safeBags.length;s++){var o=e[i].safeBags[s];if(!(r!==void 0&&o.type!==r)){if(t===null){n.push(o);continue}o.attributes[t]!==void 0&&o.attributes[t].indexOf(a)>=0&&n.push(o)}}return n}Or.pkcs12FromAsn1=function(e,t,a){typeof t=="string"?(a=t,t=!0):t===void 0&&(t=!0);var r={},n=[];if(!C.validate(e,o0,r,n)){var i=new Error("Cannot read PKCS#12 PFX. ASN.1 object is not an PKCS#12 PFX.");throw i.errors=i,i}var s={version:r.version.charCodeAt(0),safeContents:[],getBags:function(E){var T={},I;return"localKeyId"in E?I=E.localKeyId:"localKeyIdHex"in E&&(I=de.util.hexToBytes(E.localKeyIdHex)),I===void 0&&!("friendlyName"in E)&&"bagType"in E&&(T[E.bagType]=Fr(s.safeContents,null,null,E.bagType)),I!==void 0&&(T.localKeyId=Fr(s.safeContents,"localKeyId",I,E.bagType)),"friendlyName"in E&&(T.friendlyName=Fr(s.safeContents,"friendlyName",E.friendlyName,E.bagType)),T},getBagsByFriendlyName:function(E,T){return Fr(s.safeContents,"friendlyName",E,T)},getBagsByLocalKeyId:function(E,T){return Fr(s.safeContents,"localKeyId",E,T)}};if(r.version.charCodeAt(0)!==3){var i=new Error("PKCS#12 PFX of version other than 3 not supported.");throw i.version=r.version.charCodeAt(0),i}if(C.derToOid(r.contentType)!==Y.oids.data){var i=new Error("Only PKCS#12 PFX in password integrity mode supported.");throw i.oid=C.derToOid(r.contentType),i}var o=r.content.value[0];if(o.tagClass!==C.Class.UNIVERSAL||o.type!==C.Type.OCTETSTRING)throw new Error("PKCS#12 authSafe content data is not an OCTET STRING.");if(o=Bn(o),r.mac){var u=null,l=0,f=C.derToOid(r.macAlgorithm);switch(f){case Y.oids.sha1:u=de.md.sha1.create(),l=20;break;case Y.oids.sha256:u=de.md.sha256.create(),l=32;break;case Y.oids.sha384:u=de.md.sha384.create(),l=48;break;case Y.oids.sha512:u=de.md.sha512.create(),l=64;break;case Y.oids.md5:u=de.md.md5.create(),l=16;break}if(u===null)throw new Error("PKCS#12 uses unsupported MAC algorithm: "+f);var c=new de.util.ByteBuffer(r.macSalt),g="macIterations"in r?parseInt(de.util.bytesToHex(r.macIterations),16):1,m=Or.generateKey(a,c,3,g,l,u),h=de.hmac.create();h.start(u,m),h.update(o.value);var v=h.getMac();if(v.getBytes()!==r.macDigest)throw new Error("PKCS#12 MAC could not be verified. Invalid password?")}return c0(s,o.value,t,a),s};function Bn(e){if(e.composed||e.constructed){for(var t=de.util.createBuffer(),a=0;a<e.value.length;++a)t.putBytes(e.value[a].value);e.composed=e.constructed=!1,e.value=t.getBytes()}return e}function c0(e,t,a,r){if(t=C.fromDer(t,a),t.tagClass!==C.Class.UNIVERSAL||t.type!==C.Type.SEQUENCE||t.constructed!==!0)throw new Error("PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo");for(var n=0;n<t.value.length;n++){var i=t.value[n],s={},o=[];if(!C.validate(i,yo,s,o)){var u=new Error("Cannot read ContentInfo.");throw u.errors=o,u}var l={encrypted:!1},f=null,c=s.content.value[0];switch(C.derToOid(s.contentType)){case Y.oids.data:if(c.tagClass!==C.Class.UNIVERSAL||c.type!==C.Type.OCTETSTRING)throw new Error("PKCS#12 SafeContents Data is not an OCTET STRING.");f=Bn(c).value;break;case Y.oids.encryptedData:f=d0(c,r),l.encrypted=!0;break;default:var u=new Error("Unsupported PKCS#12 contentType.");throw u.contentType=C.derToOid(s.contentType),u}l.safeBags=p0(f,a,r),e.safeContents.push(l)}}function d0(e,t){var a={},r=[];if(!C.validate(e,de.pkcs7.asn1.encryptedDataValidator,a,r)){var n=new Error("Cannot read EncryptedContentInfo.");throw n.errors=r,n}var i=C.derToOid(a.contentType);if(i!==Y.oids.data){var n=new Error("PKCS#12 EncryptedContentInfo ContentType is not Data.");throw n.oid=i,n}i=C.derToOid(a.encAlgorithm);var s=Y.pbe.getCipher(i,a.encParameter,t),o=Bn(a.encryptedContentAsn1),u=de.util.createBuffer(o.value);if(s.update(u),!s.finish())throw new Error("Failed to decrypt PKCS#12 SafeContents.");return s.output.getBytes()}function p0(e,t,a){if(!t&&e.length===0)return[];if(e=C.fromDer(e,t),e.tagClass!==C.Class.UNIVERSAL||e.type!==C.Type.SEQUENCE||e.constructed!==!0)throw new Error("PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.");for(var r=[],n=0;n<e.value.length;n++){var i=e.value[n],s={},o=[];if(!C.validate(i,u0,s,o)){var u=new Error("Cannot read SafeBag.");throw u.errors=o,u}var l={type:C.derToOid(s.bagId),attributes:h0(s.bagAttributes)};r.push(l);var f,c,g=s.bagValue.value[0];switch(l.type){case Y.oids.pkcs8ShroudedKeyBag:if(g=Y.decryptPrivateKeyInfo(g,a),g===null)throw new Error("Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?");case Y.oids.keyBag:try{l.key=Y.privateKeyFromAsn1(g)}catch{l.key=null,l.asn1=g}continue;case Y.oids.certBag:f=f0,c=function(){if(C.derToOid(s.certId)!==Y.oids.x509Certificate){var h=new Error("Unsupported certificate type, only X.509 supported.");throw h.oid=C.derToOid(s.certId),h}var v=C.fromDer(s.cert,t);try{l.cert=Y.certificateFromAsn1(v,!0)}catch{l.cert=null,l.asn1=v}};break;default:var u=new Error("Unsupported PKCS#12 SafeBag type.");throw u.oid=l.type,u}if(f!==void 0&&!C.validate(g,f,s,o)){var u=new Error("Cannot read PKCS#12 "+f.name);throw u.errors=o,u}c()}return r}function h0(e){var t={};if(e!==void 0)for(var a=0;a<e.length;++a){var r={},n=[];if(!C.validate(e[a],l0,r,n)){var i=new Error("Cannot read PKCS#12 BagAttribute.");throw i.errors=n,i}var s=C.derToOid(r.oid);if(Y.oids[s]!==void 0){t[Y.oids[s]]=[];for(var o=0;o<r.values.length;++o)t[Y.oids[s]].push(r.values[o].value)}}return t}Or.toPkcs12Asn1=function(e,t,a,r){r=r||{},r.saltSize=r.saltSize||8,r.count=r.count||2048,r.algorithm=r.algorithm||r.encAlgorithm||"aes128","useMac"in r||(r.useMac=!0),"localKeyId"in r||(r.localKeyId=null),"generateLocalKeyId"in r||(r.generateLocalKeyId=!0);var n=r.localKeyId,i;if(n!==null)n=de.util.hexToBytes(n);else if(r.generateLocalKeyId)if(t){var s=de.util.isArray(t)?t[0]:t;typeof s=="string"&&(s=Y.certificateFromPem(s));var o=de.md.sha1.create();o.update(C.toDer(Y.certificateToAsn1(s)).getBytes()),n=o.digest().getBytes()}else n=de.random.getBytes(20);var u=[];n!==null&&u.push(C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Y.oids.localKeyId).getBytes()),C.create(C.Class.UNIVERSAL,C.Type.SET,!0,[C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,n)])])),"friendlyName"in r&&u.push(C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Y.oids.friendlyName).getBytes()),C.create(C.Class.UNIVERSAL,C.Type.SET,!0,[C.create(C.Class.UNIVERSAL,C.Type.BMPSTRING,!1,r.friendlyName)])])),u.length>0&&(i=C.create(C.Class.UNIVERSAL,C.Type.SET,!0,u));var l=[],f=[];t!==null&&(de.util.isArray(t)?f=t:f=[t]);for(var c=[],g=0;g<f.length;++g){t=f[g],typeof t=="string"&&(t=Y.certificateFromPem(t));var m=g===0?i:void 0,h=Y.certificateToAsn1(t),v=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Y.oids.certBag).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Y.oids.x509Certificate).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,C.toDer(h).getBytes())])])]),m]);c.push(v)}if(c.length>0){var E=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,c),T=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Y.oids.data).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,C.toDer(E).getBytes())])]);l.push(T)}var I=null;if(e!==null){var A=Y.wrapRsaPrivateKey(Y.privateKeyToAsn1(e));a===null?I=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Y.oids.keyBag).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[A]),i]):I=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Y.oids.pkcs8ShroudedKeyBag).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[Y.encryptPrivateKeyInfo(A,a,r)]),i]);var L=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[I]),N=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Y.oids.data).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,C.toDer(L).getBytes())])]);l.push(N)}var P=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,l),G;if(r.useMac){var o=de.md.sha1.create(),j=new de.util.ByteBuffer(de.random.getBytes(r.saltSize)),ie=r.count,e=Or.generateKey(a,j,3,ie,20),oe=de.hmac.create();oe.start(o,e),oe.update(C.toDer(P).getBytes());var fe=oe.getMac();G=C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Y.oids.sha1).getBytes()),C.create(C.Class.UNIVERSAL,C.Type.NULL,!1,"")]),C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,fe.getBytes())]),C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,j.getBytes()),C.create(C.Class.UNIVERSAL,C.Type.INTEGER,!1,C.integerToDer(ie).getBytes())])}return C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.INTEGER,!1,C.integerToDer(3).getBytes()),C.create(C.Class.UNIVERSAL,C.Type.SEQUENCE,!0,[C.create(C.Class.UNIVERSAL,C.Type.OID,!1,C.oidToDer(Y.oids.data).getBytes()),C.create(C.Class.CONTEXT_SPECIFIC,0,!0,[C.create(C.Class.UNIVERSAL,C.Type.OCTETSTRING,!1,C.toDer(P).getBytes())])]),G])};Or.generateKey=de.pbe.generatePkcs12Key});var Nn=H((wy,mo)=>{"use strict";var Kt=W();pt();Ft();bn();Zt();da();Rn();Ca();Ur();re();Sa();var _n=Kt.asn1,Er=mo.exports=Kt.pki=Kt.pki||{};Er.pemToDer=function(e){var t=Kt.pem.decode(e)[0];if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert PEM to DER; PEM is encrypted.");return Kt.util.createBuffer(t.body)};Er.privateKeyFromPem=function(e){var t=Kt.pem.decode(e)[0];if(t.type!=="PRIVATE KEY"&&t.type!=="RSA PRIVATE KEY"){var a=new Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');throw a.headerType=t.type,a}if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert private key from PEM; PEM is encrypted.");var r=_n.fromDer(t.body);return Er.privateKeyFromAsn1(r)};Er.privateKeyToPem=function(e,t){var a={type:"RSA PRIVATE KEY",body:_n.toDer(Er.privateKeyToAsn1(e)).getBytes()};return Kt.pem.encode(a,{maxline:t})};Er.privateKeyInfoToPem=function(e,t){var a={type:"PRIVATE KEY",body:_n.toDer(e).getBytes()};return Kt.pem.encode(a,{maxline:t})}});var Fn=H((Ay,Io)=>{"use strict";var R=W();pt();dr();ua();Zt();Nn();it();gr();re();var wa=function(e,t,a,r){var n=R.util.createBuffer(),i=e.length>>1,s=i+(e.length&1),o=e.substr(0,s),u=e.substr(i,s),l=R.util.createBuffer(),f=R.hmac.create();a=t+a;var c=Math.ceil(r/16),g=Math.ceil(r/20);f.start("MD5",o);var m=R.util.createBuffer();l.putBytes(a);for(var h=0;h<c;++h)f.start(null,null),f.update(l.getBytes()),l.putBuffer(f.digest()),f.start(null,null),f.update(l.bytes()+a),m.putBuffer(f.digest());f.start("SHA1",u);var v=R.util.createBuffer();l.clear(),l.putBytes(a);for(var h=0;h<g;++h)f.start(null,null),f.update(l.getBytes()),l.putBuffer(f.digest()),f.start(null,null),f.update(l.bytes()+a),v.putBuffer(f.digest());return n.putBytes(R.util.xorBytes(m.getBytes(),v.getBytes(),r)),n},y0=function(e,t,a){var r=R.hmac.create();r.start("SHA1",e);var n=R.util.createBuffer();return n.putInt32(t[0]),n.putInt32(t[1]),n.putByte(a.type),n.putByte(a.version.major),n.putByte(a.version.minor),n.putInt16(a.length),n.putBytes(a.fragment.bytes()),r.update(n.getBytes()),r.digest().getBytes()},g0=function(e,t,a){var r=!1;try{var n=e.deflate(t.fragment.getBytes());t.fragment=R.util.createBuffer(n),t.length=n.length,r=!0}catch{}return r},m0=function(e,t,a){var r=!1;try{var n=e.inflate(t.fragment.getBytes());t.fragment=R.util.createBuffer(n),t.length=n.length,r=!0}catch{}return r},et=function(e,t){var a=0;switch(t){case 1:a=e.getByte();break;case 2:a=e.getInt16();break;case 3:a=e.getInt24();break;case 4:a=e.getInt32();break}return R.util.createBuffer(e.getBytes(a))},lt=function(e,t,a){e.putInt(a.length(),t<<3),e.putBuffer(a)},y={};y.Versions={TLS_1_0:{major:3,minor:1},TLS_1_1:{major:3,minor:2},TLS_1_2:{major:3,minor:3}};y.SupportedVersions=[y.Versions.TLS_1_1,y.Versions.TLS_1_0];y.Version=y.SupportedVersions[0];y.MaxFragment=15360;y.ConnectionEnd={server:0,client:1};y.PRFAlgorithm={tls_prf_sha256:0};y.BulkCipherAlgorithm={none:null,rc4:0,des3:1,aes:2};y.CipherType={stream:0,block:1,aead:2};y.MACAlgorithm={none:null,hmac_md5:0,hmac_sha1:1,hmac_sha256:2,hmac_sha384:3,hmac_sha512:4};y.CompressionMethod={none:0,deflate:1};y.ContentType={change_cipher_spec:20,alert:21,handshake:22,application_data:23,heartbeat:24};y.HandshakeType={hello_request:0,client_hello:1,server_hello:2,certificate:11,server_key_exchange:12,certificate_request:13,server_hello_done:14,certificate_verify:15,client_key_exchange:16,finished:20};y.Alert={};y.Alert.Level={warning:1,fatal:2};y.Alert.Description={close_notify:0,unexpected_message:10,bad_record_mac:20,decryption_failed:21,record_overflow:22,decompression_failure:30,handshake_failure:40,bad_certificate:42,unsupported_certificate:43,certificate_revoked:44,certificate_expired:45,certificate_unknown:46,illegal_parameter:47,unknown_ca:48,access_denied:49,decode_error:50,decrypt_error:51,export_restriction:60,protocol_version:70,insufficient_security:71,internal_error:80,user_canceled:90,no_renegotiation:100};y.HeartbeatMessageType={heartbeat_request:1,heartbeat_response:2};y.CipherSuites={};y.getCipherSuite=function(e){var t=null;for(var a in y.CipherSuites){var r=y.CipherSuites[a];if(r.id[0]===e.charCodeAt(0)&&r.id[1]===e.charCodeAt(1)){t=r;break}}return t};y.handleUnexpected=function(e,t){var a=!e.open&&e.entity===y.ConnectionEnd.client;a||e.error(e,{message:"Unexpected message. Received TLS record out of order.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.unexpected_message}})};y.handleHelloRequest=function(e,t,a){!e.handshaking&&e.handshakes>0&&(y.queue(e,y.createAlert(e,{level:y.Alert.Level.warning,description:y.Alert.Description.no_renegotiation})),y.flush(e)),e.process()};y.parseHelloMessage=function(e,t,a){var r=null,n=e.entity===y.ConnectionEnd.client;if(a<38)e.error(e,{message:n?"Invalid ServerHello message. Message too short.":"Invalid ClientHello message. Message too short.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.illegal_parameter}});else{var i=t.fragment,s=i.length();if(r={version:{major:i.getByte(),minor:i.getByte()},random:R.util.createBuffer(i.getBytes(32)),session_id:et(i,1),extensions:[]},n?(r.cipher_suite=i.getBytes(2),r.compression_method=i.getByte()):(r.cipher_suites=et(i,2),r.compression_methods=et(i,1)),s=a-(s-i.length()),s>0){for(var o=et(i,2);o.length()>0;)r.extensions.push({type:[o.getByte(),o.getByte()],data:et(o,2)});if(!n)for(var u=0;u<r.extensions.length;++u){var l=r.extensions[u];if(l.type[0]===0&&l.type[1]===0)for(var f=et(l.data,2);f.length()>0;){var c=f.getByte();if(c!==0)break;e.session.extensions.server_name.serverNameList.push(et(f,2).getBytes())}}}if(e.session.version&&(r.version.major!==e.session.version.major||r.version.minor!==e.session.version.minor))return e.error(e,{message:"TLS version change is disallowed during renegotiation.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.protocol_version}});if(n)e.session.cipherSuite=y.getCipherSuite(r.cipher_suite);else for(var g=R.util.createBuffer(r.cipher_suites.bytes());g.length()>0&&(e.session.cipherSuite=y.getCipherSuite(g.getBytes(2)),e.session.cipherSuite===null););if(e.session.cipherSuite===null)return e.error(e,{message:"No cipher suites in common.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.handshake_failure},cipherSuite:R.util.bytesToHex(r.cipher_suite)});n?e.session.compressionMethod=r.compression_method:e.session.compressionMethod=y.CompressionMethod.none}return r};y.createSecurityParameters=function(e,t){var a=e.entity===y.ConnectionEnd.client,r=t.random.bytes(),n=a?e.session.sp.client_random:r,i=a?r:y.createRandom().getBytes();e.session.sp={entity:e.entity,prf_algorithm:y.PRFAlgorithm.tls_prf_sha256,bulk_cipher_algorithm:null,cipher_type:null,enc_key_length:null,block_length:null,fixed_iv_length:null,record_iv_length:null,mac_algorithm:null,mac_length:null,mac_key_length:null,compression_algorithm:e.session.compressionMethod,pre_master_secret:null,master_secret:null,client_random:n,server_random:i}};y.handleServerHello=function(e,t,a){var r=y.parseHelloMessage(e,t,a);if(!e.fail){if(r.version.minor<=e.version.minor)e.version.minor=r.version.minor;else return e.error(e,{message:"Incompatible TLS version.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.protocol_version}});e.session.version=e.version;var n=r.session_id.bytes();n.length>0&&n===e.session.id?(e.expect=Eo,e.session.resuming=!0,e.session.sp.server_random=r.random.bytes()):(e.expect=C0,e.session.resuming=!1,y.createSecurityParameters(e,r)),e.session.id=n,e.process()}};y.handleClientHello=function(e,t,a){var r=y.parseHelloMessage(e,t,a);if(!e.fail){var n=r.session_id.bytes(),i=null;if(e.sessionCache&&(i=e.sessionCache.getSession(n),i===null?n="":(i.version.major!==r.version.major||i.version.minor>r.version.minor)&&(i=null,n="")),n.length===0&&(n=R.random.getBytes(32)),e.session.id=n,e.session.clientHelloVersion=r.version,e.session.sp={},i)e.version=e.session.version=i.version,e.session.sp=i.sp;else{for(var s,o=1;o<y.SupportedVersions.length&&(s=y.SupportedVersions[o],!(s.minor<=r.version.minor));++o);e.version={major:s.major,minor:s.minor},e.session.version=e.version}i!==null?(e.expect=kn,e.session.resuming=!0,e.session.sp.client_random=r.random.bytes()):(e.expect=e.verifyClient!==!1?w0:Ln,e.session.resuming=!1,y.createSecurityParameters(e,r)),e.open=!0,y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createServerHello(e)})),e.session.resuming?(y.queue(e,y.createRecord(e,{type:y.ContentType.change_cipher_spec,data:y.createChangeCipherSpec()})),e.state.pending=y.createConnectionState(e),e.state.current.write=e.state.pending.write,y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createFinished(e)}))):(y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createCertificate(e)})),e.fail||(y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createServerKeyExchange(e)})),e.verifyClient!==!1&&y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createCertificateRequest(e)})),y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createServerHelloDone(e)})))),y.flush(e),e.process()}};y.handleCertificate=function(e,t,a){if(a<3)return e.error(e,{message:"Invalid Certificate message. Message too short.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.illegal_parameter}});var r=t.fragment,n={certificate_list:et(r,3)},i,s,o=[];try{for(;n.certificate_list.length()>0;)i=et(n.certificate_list,3),s=R.asn1.fromDer(i),i=R.pki.certificateFromAsn1(s,!0),o.push(i)}catch(l){return e.error(e,{message:"Could not parse certificate list.",cause:l,send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.bad_certificate}})}var u=e.entity===y.ConnectionEnd.client;(u||e.verifyClient===!0)&&o.length===0?e.error(e,{message:u?"No server certificate provided.":"No client certificate provided.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.illegal_parameter}}):o.length===0?e.expect=u?vo:Ln:(u?e.session.serverCertificate=o[0]:e.session.clientCertificate=o[0],y.verifyCertificateChain(e,o)&&(e.expect=u?vo:Ln)),e.process()};y.handleServerKeyExchange=function(e,t,a){if(a>0)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.unsupported_certificate}});e.expect=E0,e.process()};y.handleClientKeyExchange=function(e,t,a){if(a<48)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.unsupported_certificate}});var r=t.fragment,n={enc_pre_master_secret:et(r,2).getBytes()},i=null;if(e.getPrivateKey)try{i=e.getPrivateKey(e,e.session.serverCertificate),i=R.pki.privateKeyFromPem(i)}catch(u){e.error(e,{message:"Could not get private key.",cause:u,send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.internal_error}})}if(i===null)return e.error(e,{message:"No private key set.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.internal_error}});try{var s=e.session.sp;s.pre_master_secret=i.decrypt(n.enc_pre_master_secret);var o=e.session.clientHelloVersion;if(o.major!==s.pre_master_secret.charCodeAt(0)||o.minor!==s.pre_master_secret.charCodeAt(1))throw new Error("TLS version rollback attack detected.")}catch{s.pre_master_secret=R.random.getBytes(48)}e.expect=kn,e.session.clientCertificate!==null&&(e.expect=A0),e.process()};y.handleCertificateRequest=function(e,t,a){if(a<3)return e.error(e,{message:"Invalid CertificateRequest. Message too short.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.illegal_parameter}});var r=t.fragment,n={certificate_types:et(r,1),certificate_authorities:et(r,2)};e.session.certificateRequest=n,e.expect=x0,e.process()};y.handleCertificateVerify=function(e,t,a){if(a<2)return e.error(e,{message:"Invalid CertificateVerify. Message too short.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.illegal_parameter}});var r=t.fragment;r.read-=4;var n=r.bytes();r.read+=4;var i={signature:et(r,2).getBytes()},s=R.util.createBuffer();s.putBuffer(e.session.md5.digest()),s.putBuffer(e.session.sha1.digest()),s=s.getBytes();try{var o=e.session.clientCertificate;if(!o.publicKey.verify(s,i.signature,"NONE"))throw new Error("CertificateVerify signature does not match.");e.session.md5.update(n),e.session.sha1.update(n)}catch{return e.error(e,{message:"Bad signature in CertificateVerify.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.handshake_failure}})}e.expect=kn,e.process()};y.handleServerHelloDone=function(e,t,a){if(a>0)return e.error(e,{message:"Invalid ServerHelloDone message. Invalid length.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.record_overflow}});if(e.serverCertificate===null){var r={message:"No server certificate provided. Not enough security.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.insufficient_security}},n=0,i=e.verify(e,r.alert.description,n,[]);if(i!==!0)return(i||i===0)&&(typeof i=="object"&&!R.util.isArray(i)?(i.message&&(r.message=i.message),i.alert&&(r.alert.description=i.alert)):typeof i=="number"&&(r.alert.description=i)),e.error(e,r)}e.session.certificateRequest!==null&&(t=y.createRecord(e,{type:y.ContentType.handshake,data:y.createCertificate(e)}),y.queue(e,t)),t=y.createRecord(e,{type:y.ContentType.handshake,data:y.createClientKeyExchange(e)}),y.queue(e,t),e.expect=b0;var s=function(o,u){o.session.certificateRequest!==null&&o.session.clientCertificate!==null&&y.queue(o,y.createRecord(o,{type:y.ContentType.handshake,data:y.createCertificateVerify(o,u)})),y.queue(o,y.createRecord(o,{type:y.ContentType.change_cipher_spec,data:y.createChangeCipherSpec()})),o.state.pending=y.createConnectionState(o),o.state.current.write=o.state.pending.write,y.queue(o,y.createRecord(o,{type:y.ContentType.handshake,data:y.createFinished(o)})),o.expect=Eo,y.flush(o),o.process()};if(e.session.certificateRequest===null||e.session.clientCertificate===null)return s(e,null);y.getClientSignature(e,s)};y.handleChangeCipherSpec=function(e,t){if(t.fragment.getByte()!==1)return e.error(e,{message:"Invalid ChangeCipherSpec message received.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.illegal_parameter}});var a=e.entity===y.ConnectionEnd.client;(e.session.resuming&&a||!e.session.resuming&&!a)&&(e.state.pending=y.createConnectionState(e)),e.state.current.read=e.state.pending.read,(!e.session.resuming&&a||e.session.resuming&&!a)&&(e.state.pending=null),e.expect=a?S0:B0,e.process()};y.handleFinished=function(e,t,a){var r=t.fragment;r.read-=4;var n=r.bytes();r.read+=4;var i=t.fragment.getBytes();r=R.util.createBuffer(),r.putBuffer(e.session.md5.digest()),r.putBuffer(e.session.sha1.digest());var s=e.entity===y.ConnectionEnd.client,o=s?"server finished":"client finished",u=e.session.sp,l=12,f=wa;if(r=f(u.master_secret,o,r.getBytes(),l),r.getBytes()!==i)return e.error(e,{message:"Invalid verify_data in Finished message.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.decrypt_error}});e.session.md5.update(n),e.session.sha1.update(n),(e.session.resuming&&s||!e.session.resuming&&!s)&&(y.queue(e,y.createRecord(e,{type:y.ContentType.change_cipher_spec,data:y.createChangeCipherSpec()})),e.state.current.write=e.state.pending.write,e.state.pending=null,y.queue(e,y.createRecord(e,{type:y.ContentType.handshake,data:y.createFinished(e)}))),e.expect=s?T0:R0,e.handshaking=!1,++e.handshakes,e.peerCertificate=s?e.session.serverCertificate:e.session.clientCertificate,y.flush(e),e.isConnected=!0,e.connected(e),e.process()};y.handleAlert=function(e,t){var a=t.fragment,r={level:a.getByte(),description:a.getByte()},n;switch(r.description){case y.Alert.Description.close_notify:n="Connection closed.";break;case y.Alert.Description.unexpected_message:n="Unexpected message.";break;case y.Alert.Description.bad_record_mac:n="Bad record MAC.";break;case y.Alert.Description.decryption_failed:n="Decryption failed.";break;case y.Alert.Description.record_overflow:n="Record overflow.";break;case y.Alert.Description.decompression_failure:n="Decompression failed.";break;case y.Alert.Description.handshake_failure:n="Handshake failure.";break;case y.Alert.Description.bad_certificate:n="Bad certificate.";break;case y.Alert.Description.unsupported_certificate:n="Unsupported certificate.";break;case y.Alert.Description.certificate_revoked:n="Certificate revoked.";break;case y.Alert.Description.certificate_expired:n="Certificate expired.";break;case y.Alert.Description.certificate_unknown:n="Certificate unknown.";break;case y.Alert.Description.illegal_parameter:n="Illegal parameter.";break;case y.Alert.Description.unknown_ca:n="Unknown certificate authority.";break;case y.Alert.Description.access_denied:n="Access denied.";break;case y.Alert.Description.decode_error:n="Decode error.";break;case y.Alert.Description.decrypt_error:n="Decrypt error.";break;case y.Alert.Description.export_restriction:n="Export restriction.";break;case y.Alert.Description.protocol_version:n="Unsupported protocol version.";break;case y.Alert.Description.insufficient_security:n="Insufficient security.";break;case y.Alert.Description.internal_error:n="Internal error.";break;case y.Alert.Description.user_canceled:n="User canceled.";break;case y.Alert.Description.no_renegotiation:n="Renegotiation not supported.";break;default:n="Unknown error.";break}if(r.description===y.Alert.Description.close_notify)return e.close();e.error(e,{message:n,send:!1,origin:e.entity===y.ConnectionEnd.client?"server":"client",alert:r}),e.process()};y.handleHandshake=function(e,t){var a=t.fragment,r=a.getByte(),n=a.getInt24();if(n>a.length())return e.fragmented=t,t.fragment=R.util.createBuffer(),a.read-=4,e.process();e.fragmented=null,a.read-=4;var i=a.bytes(n+4);a.read+=4,r in Ia[e.entity][e.expect]?(e.entity===y.ConnectionEnd.server&&!e.open&&!e.fail&&(e.handshaking=!0,e.session={version:null,extensions:{server_name:{serverNameList:[]}},cipherSuite:null,compressionMethod:null,serverCertificate:null,clientCertificate:null,md5:R.md.md5.create(),sha1:R.md.sha1.create()}),r!==y.HandshakeType.hello_request&&r!==y.HandshakeType.certificate_verify&&r!==y.HandshakeType.finished&&(e.session.md5.update(i),e.session.sha1.update(i)),Ia[e.entity][e.expect][r](e,t,n)):y.handleUnexpected(e,t)};y.handleApplicationData=function(e,t){e.data.putBuffer(t.fragment),e.dataReady(e),e.process()};y.handleHeartbeat=function(e,t){var a=t.fragment,r=a.getByte(),n=a.getInt16(),i=a.getBytes(n);if(r===y.HeartbeatMessageType.heartbeat_request){if(e.handshaking||n>i.length)return e.process();y.queue(e,y.createRecord(e,{type:y.ContentType.heartbeat,data:y.createHeartbeat(y.HeartbeatMessageType.heartbeat_response,i)})),y.flush(e)}else if(r===y.HeartbeatMessageType.heartbeat_response){if(i!==e.expectedHeartbeatPayload)return e.process();e.heartbeatReceived&&e.heartbeatReceived(e,R.util.createBuffer(i))}e.process()};var v0=0,C0=1,vo=2,E0=3,x0=4,Eo=5,S0=6,T0=7,b0=8,I0=0,w0=1,Ln=2,A0=3,kn=4,B0=5,R0=6,p=y.handleUnexpected,xo=y.handleChangeCipherSpec,Re=y.handleAlert,$e=y.handleHandshake,So=y.handleApplicationData,_e=y.handleHeartbeat,Un=[];Un[y.ConnectionEnd.client]=[[p,Re,$e,p,_e],[p,Re,$e,p,_e],[p,Re,$e,p,_e],[p,Re,$e,p,_e],[p,Re,$e,p,_e],[xo,Re,p,p,_e],[p,Re,$e,p,_e],[p,Re,$e,So,_e],[p,Re,$e,p,_e]];Un[y.ConnectionEnd.server]=[[p,Re,$e,p,_e],[p,Re,$e,p,_e],[p,Re,$e,p,_e],[p,Re,$e,p,_e],[xo,Re,p,p,_e],[p,Re,$e,p,_e],[p,Re,$e,So,_e],[p,Re,$e,p,_e]];var qt=y.handleHelloRequest,_0=y.handleServerHello,To=y.handleCertificate,Co=y.handleServerKeyExchange,Pn=y.handleCertificateRequest,Ta=y.handleServerHelloDone,bo=y.handleFinished,Ia=[];Ia[y.ConnectionEnd.client]=[[p,p,_0,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p],[qt,p,p,p,p,p,p,p,p,p,p,To,Co,Pn,Ta,p,p,p,p,p,p],[qt,p,p,p,p,p,p,p,p,p,p,p,Co,Pn,Ta,p,p,p,p,p,p],[qt,p,p,p,p,p,p,p,p,p,p,p,p,Pn,Ta,p,p,p,p,p,p],[qt,p,p,p,p,p,p,p,p,p,p,p,p,p,Ta,p,p,p,p,p,p],[qt,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p],[qt,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,bo],[qt,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p],[qt,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p]];var N0=y.handleClientHello,P0=y.handleClientKeyExchange,D0=y.handleCertificateVerify;Ia[y.ConnectionEnd.server]=[[p,N0,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p],[p,p,p,p,p,p,p,p,p,p,p,To,p,p,p,p,p,p,p,p,p],[p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,P0,p,p,p,p],[p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,D0,p,p,p,p,p],[p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p],[p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,bo],[p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p],[p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p,p]];y.generateKeys=function(e,t){var a=wa,r=t.client_random+t.server_random;e.session.resuming||(t.master_secret=a(t.pre_master_secret,"master secret",r,48).bytes(),t.pre_master_secret=null),r=t.server_random+t.client_random;var n=2*t.mac_key_length+2*t.enc_key_length,i=e.version.major===y.Versions.TLS_1_0.major&&e.version.minor===y.Versions.TLS_1_0.minor;i&&(n+=2*t.fixed_iv_length);var s=a(t.master_secret,"key expansion",r,n),o={client_write_MAC_key:s.getBytes(t.mac_key_length),server_write_MAC_key:s.getBytes(t.mac_key_length),client_write_key:s.getBytes(t.enc_key_length),server_write_key:s.getBytes(t.enc_key_length)};return i&&(o.client_write_IV=s.getBytes(t.fixed_iv_length),o.server_write_IV=s.getBytes(t.fixed_iv_length)),o};y.createConnectionState=function(e){var t=e.entity===y.ConnectionEnd.client,a=function(){var i={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(s){return!0},compressionState:null,compressFunction:function(s){return!0},updateSequenceNumber:function(){i.sequenceNumber[1]===4294967295?(i.sequenceNumber[1]=0,++i.sequenceNumber[0]):++i.sequenceNumber[1]}};return i},r={read:a(),write:a()};if(r.read.update=function(i,s){return r.read.cipherFunction(s,r.read)?r.read.compressFunction(i,s,r.read)||i.error(i,{message:"Could not decompress record.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.decompression_failure}}):i.error(i,{message:"Could not decrypt record or bad MAC.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.bad_record_mac}}),!i.fail},r.write.update=function(i,s){return r.write.compressFunction(i,s,r.write)?r.write.cipherFunction(s,r.write)||i.error(i,{message:"Could not encrypt record.",send:!1,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.internal_error}}):i.error(i,{message:"Could not compress record.",send:!1,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.internal_error}}),!i.fail},e.session){var n=e.session.sp;switch(e.session.cipherSuite.initSecurityParameters(n),n.keys=y.generateKeys(e,n),r.read.macKey=t?n.keys.server_write_MAC_key:n.keys.client_write_MAC_key,r.write.macKey=t?n.keys.client_write_MAC_key:n.keys.server_write_MAC_key,e.session.cipherSuite.initConnectionState(r,e,n),n.compression_algorithm){case y.CompressionMethod.none:break;case y.CompressionMethod.deflate:r.read.compressFunction=m0,r.write.compressFunction=g0;break;default:throw new Error("Unsupported compression algorithm.")}}return r};y.createRandom=function(){var e=new Date,t=+e+e.getTimezoneOffset()*6e4,a=R.util.createBuffer();return a.putInt32(t),a.putBytes(R.random.getBytes(28)),a};y.createRecord=function(e,t){if(!t.data)return null;var a={type:t.type,version:{major:e.version.major,minor:e.version.minor},length:t.data.length(),fragment:t.data};return a};y.createAlert=function(e,t){var a=R.util.createBuffer();return a.putByte(t.level),a.putByte(t.description),y.createRecord(e,{type:y.ContentType.alert,data:a})};y.createClientHello=function(e){e.session.clientHelloVersion={major:e.version.major,minor:e.version.minor};for(var t=R.util.createBuffer(),a=0;a<e.cipherSuites.length;++a){var r=e.cipherSuites[a];t.putByte(r.id[0]),t.putByte(r.id[1])}var n=t.length(),i=R.util.createBuffer();i.putByte(y.CompressionMethod.none);var s=i.length(),o=R.util.createBuffer();if(e.virtualHost){var u=R.util.createBuffer();u.putByte(0),u.putByte(0);var l=R.util.createBuffer();l.putByte(0),lt(l,2,R.util.createBuffer(e.virtualHost));var f=R.util.createBuffer();lt(f,2,l),lt(u,2,f),o.putBuffer(u)}var c=o.length();c>0&&(c+=2);var g=e.session.id,m=g.length+1+2+4+28+2+n+1+s+c,h=R.util.createBuffer();return h.putByte(y.HandshakeType.client_hello),h.putInt24(m),h.putByte(e.version.major),h.putByte(e.version.minor),h.putBytes(e.session.sp.client_random),lt(h,1,R.util.createBuffer(g)),lt(h,2,t),lt(h,1,i),c>0&&lt(h,2,o),h};y.createServerHello=function(e){var t=e.session.id,a=t.length+1+2+4+28+2+1,r=R.util.createBuffer();return r.putByte(y.HandshakeType.server_hello),r.putInt24(a),r.putByte(e.version.major),r.putByte(e.version.minor),r.putBytes(e.session.sp.server_random),lt(r,1,R.util.createBuffer(t)),r.putByte(e.session.cipherSuite.id[0]),r.putByte(e.session.cipherSuite.id[1]),r.putByte(e.session.compressionMethod),r};y.createCertificate=function(e){var t=e.entity===y.ConnectionEnd.client,a=null;if(e.getCertificate){var r;t?r=e.session.certificateRequest:r=e.session.extensions.server_name.serverNameList,a=e.getCertificate(e,r)}var n=R.util.createBuffer();if(a!==null)try{R.util.isArray(a)||(a=[a]);for(var i=null,s=0;s<a.length;++s){var o=R.pem.decode(a[s])[0];if(o.type!=="CERTIFICATE"&&o.type!=="X509 CERTIFICATE"&&o.type!=="TRUSTED CERTIFICATE"){var u=new Error('Could not convert certificate from PEM; PEM header type is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".');throw u.headerType=o.type,u}if(o.procType&&o.procType.type==="ENCRYPTED")throw new Error("Could not convert certificate from PEM; PEM is encrypted.");var l=R.util.createBuffer(o.body);i===null&&(i=R.asn1.fromDer(l.bytes(),!1));var f=R.util.createBuffer();lt(f,3,l),n.putBuffer(f)}a=R.pki.certificateFromAsn1(i),t?e.session.clientCertificate=a:e.session.serverCertificate=a}catch(m){return e.error(e,{message:"Could not send certificate list.",cause:m,send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.bad_certificate}})}var c=3+n.length(),g=R.util.createBuffer();return g.putByte(y.HandshakeType.certificate),g.putInt24(c),lt(g,3,n),g};y.createClientKeyExchange=function(e){var t=R.util.createBuffer();t.putByte(e.session.clientHelloVersion.major),t.putByte(e.session.clientHelloVersion.minor),t.putBytes(R.random.getBytes(46));var a=e.session.sp;a.pre_master_secret=t.getBytes();var r=e.session.serverCertificate.publicKey;t=r.encrypt(a.pre_master_secret);var n=t.length+2,i=R.util.createBuffer();return i.putByte(y.HandshakeType.client_key_exchange),i.putInt24(n),i.putInt16(t.length),i.putBytes(t),i};y.createServerKeyExchange=function(e){var t=0,a=R.util.createBuffer();return t>0&&(a.putByte(y.HandshakeType.server_key_exchange),a.putInt24(t)),a};y.getClientSignature=function(e,t){var a=R.util.createBuffer();a.putBuffer(e.session.md5.digest()),a.putBuffer(e.session.sha1.digest()),a=a.getBytes(),e.getSignature=e.getSignature||function(r,n,i){var s=null;if(r.getPrivateKey)try{s=r.getPrivateKey(r,r.session.clientCertificate),s=R.pki.privateKeyFromPem(s)}catch(o){r.error(r,{message:"Could not get private key.",cause:o,send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.internal_error}})}s===null?r.error(r,{message:"No private key set.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.internal_error}}):n=s.sign(n,null),i(r,n)},e.getSignature(e,a,t)};y.createCertificateVerify=function(e,t){var a=t.length+2,r=R.util.createBuffer();return r.putByte(y.HandshakeType.certificate_verify),r.putInt24(a),r.putInt16(t.length),r.putBytes(t),r};y.createCertificateRequest=function(e){var t=R.util.createBuffer();t.putByte(1);var a=R.util.createBuffer();for(var r in e.caStore.certs){var n=e.caStore.certs[r],i=R.pki.distinguishedNameToAsn1(n.subject),s=R.asn1.toDer(i);a.putInt16(s.length()),a.putBuffer(s)}var o=1+t.length()+2+a.length(),u=R.util.createBuffer();return u.putByte(y.HandshakeType.certificate_request),u.putInt24(o),lt(u,1,t),lt(u,2,a),u};y.createServerHelloDone=function(e){var t=R.util.createBuffer();return t.putByte(y.HandshakeType.server_hello_done),t.putInt24(0),t};y.createChangeCipherSpec=function(){var e=R.util.createBuffer();return e.putByte(1),e};y.createFinished=function(e){var t=R.util.createBuffer();t.putBuffer(e.session.md5.digest()),t.putBuffer(e.session.sha1.digest());var a=e.entity===y.ConnectionEnd.client,r=e.session.sp,n=12,i=wa,s=a?"client finished":"server finished";t=i(r.master_secret,s,t.getBytes(),n);var o=R.util.createBuffer();return o.putByte(y.HandshakeType.finished),o.putInt24(t.length()),o.putBuffer(t),o};y.createHeartbeat=function(e,t,a){typeof a>"u"&&(a=t.length);var r=R.util.createBuffer();r.putByte(e),r.putInt16(a),r.putBytes(t);var n=r.length(),i=Math.max(16,n-a-3);return r.putBytes(R.random.getBytes(i)),r};y.queue=function(e,t){if(t&&!(t.fragment.length()===0&&(t.type===y.ContentType.handshake||t.type===y.ContentType.alert||t.type===y.ContentType.change_cipher_spec))){if(t.type===y.ContentType.handshake){var a=t.fragment.bytes();e.session.md5.update(a),e.session.sha1.update(a),a=null}var r;if(t.fragment.length()<=y.MaxFragment)r=[t];else{r=[];for(var n=t.fragment.bytes();n.length>y.MaxFragment;)r.push(y.createRecord(e,{type:t.type,data:R.util.createBuffer(n.slice(0,y.MaxFragment))})),n=n.slice(y.MaxFragment);n.length>0&&r.push(y.createRecord(e,{type:t.type,data:R.util.createBuffer(n)}))}for(var i=0;i<r.length&&!e.fail;++i){var s=r[i],o=e.state.current.write;o.update(e,s)&&e.records.push(s)}}};y.flush=function(e){for(var t=0;t<e.records.length;++t){var a=e.records[t];e.tlsData.putByte(a.type),e.tlsData.putByte(a.version.major),e.tlsData.putByte(a.version.minor),e.tlsData.putInt16(a.fragment.length()),e.tlsData.putBuffer(e.records[t].fragment)}return e.records=[],e.tlsDataReady(e)};var Dn=function(e){switch(e){case!0:return!0;case R.pki.certificateError.bad_certificate:return y.Alert.Description.bad_certificate;case R.pki.certificateError.unsupported_certificate:return y.Alert.Description.unsupported_certificate;case R.pki.certificateError.certificate_revoked:return y.Alert.Description.certificate_revoked;case R.pki.certificateError.certificate_expired:return y.Alert.Description.certificate_expired;case R.pki.certificateError.certificate_unknown:return y.Alert.Description.certificate_unknown;case R.pki.certificateError.unknown_ca:return y.Alert.Description.unknown_ca;default:return y.Alert.Description.bad_certificate}},L0=function(e){switch(e){case!0:return!0;case y.Alert.Description.bad_certificate:return R.pki.certificateError.bad_certificate;case y.Alert.Description.unsupported_certificate:return R.pki.certificateError.unsupported_certificate;case y.Alert.Description.certificate_revoked:return R.pki.certificateError.certificate_revoked;case y.Alert.Description.certificate_expired:return R.pki.certificateError.certificate_expired;case y.Alert.Description.certificate_unknown:return R.pki.certificateError.certificate_unknown;case y.Alert.Description.unknown_ca:return R.pki.certificateError.unknown_ca;default:return R.pki.certificateError.bad_certificate}};y.verifyCertificateChain=function(e,t){try{var a={};for(var r in e.verifyOptions)a[r]=e.verifyOptions[r];a.verify=function(i,s,o){var u=Dn(i),l=e.verify(e,i,s,o);if(l!==!0){if(typeof l=="object"&&!R.util.isArray(l)){var f=new Error("The application rejected the certificate.");throw f.send=!0,f.alert={level:y.Alert.Level.fatal,description:y.Alert.Description.bad_certificate},l.message&&(f.message=l.message),l.alert&&(f.alert.description=l.alert),f}l!==i&&(l=L0(l))}return l},R.pki.verifyCertificateChain(e.caStore,t,a)}catch(i){var n=i;(typeof n!="object"||R.util.isArray(n))&&(n={send:!0,alert:{level:y.Alert.Level.fatal,description:Dn(i)}}),"send"in n||(n.send=!0),"alert"in n||(n.alert={level:y.Alert.Level.fatal,description:Dn(n.error)}),e.error(e,n)}return!e.fail};y.createSessionCache=function(e,t){var a=null;if(e&&e.getSession&&e.setSession&&e.order)a=e;else{a={},a.cache=e||{},a.capacity=Math.max(t||100,1),a.order=[];for(var r in e)a.order.length<=t?a.order.push(r):delete e[r];a.getSession=function(n){var i=null,s=null;if(n?s=R.util.bytesToHex(n):a.order.length>0&&(s=a.order[0]),s!==null&&s in a.cache){i=a.cache[s],delete a.cache[s];for(var o in a.order)if(a.order[o]===s){a.order.splice(o,1);break}}return i},a.setSession=function(n,i){if(a.order.length===a.capacity){var s=a.order.shift();delete a.cache[s]}var s=R.util.bytesToHex(n);a.order.push(s),a.cache[s]=i}}return a};y.createConnection=function(e){var t=null;e.caStore?R.util.isArray(e.caStore)?t=R.pki.createCaStore(e.caStore):t=e.caStore:t=R.pki.createCaStore();var a=e.cipherSuites||null;if(a===null){a=[];for(var r in y.CipherSuites)a.push(y.CipherSuites[r])}var n=e.server?y.ConnectionEnd.server:y.ConnectionEnd.client,i=e.sessionCache?y.createSessionCache(e.sessionCache):null,s={version:{major:y.Version.major,minor:y.Version.minor},entity:n,sessionId:e.sessionId,caStore:t,sessionCache:i,cipherSuites:a,connected:e.connected,virtualHost:e.virtualHost||null,verifyClient:e.verifyClient||!1,verify:e.verify||function(f,c,g,m){return c},verifyOptions:e.verifyOptions||{},getCertificate:e.getCertificate||null,getPrivateKey:e.getPrivateKey||null,getSignature:e.getSignature||null,input:R.util.createBuffer(),tlsData:R.util.createBuffer(),data:R.util.createBuffer(),tlsDataReady:e.tlsDataReady,dataReady:e.dataReady,heartbeatReceived:e.heartbeatReceived,closed:e.closed,error:function(f,c){c.origin=c.origin||(f.entity===y.ConnectionEnd.client?"client":"server"),c.send&&(y.queue(f,y.createAlert(f,c.alert)),y.flush(f));var g=c.fatal!==!1;g&&(f.fail=!0),e.error(f,c),g&&f.close(!1)},deflate:e.deflate||null,inflate:e.inflate||null};s.reset=function(f){s.version={major:y.Version.major,minor:y.Version.minor},s.record=null,s.session=null,s.peerCertificate=null,s.state={pending:null,current:null},s.expect=s.entity===y.ConnectionEnd.client?v0:I0,s.fragmented=null,s.records=[],s.open=!1,s.handshakes=0,s.handshaking=!1,s.isConnected=!1,s.fail=!(f||typeof f>"u"),s.input.clear(),s.tlsData.clear(),s.data.clear(),s.state.current=y.createConnectionState(s)},s.reset();var o=function(f,c){var g=c.type-y.ContentType.change_cipher_spec,m=Un[f.entity][f.expect];g in m?m[g](f,c):y.handleUnexpected(f,c)},u=function(f){var c=0,g=f.input,m=g.length();if(m<5)c=5-m;else{f.record={type:g.getByte(),version:{major:g.getByte(),minor:g.getByte()},length:g.getInt16(),fragment:R.util.createBuffer(),ready:!1};var h=f.record.version.major===f.version.major;h&&f.session&&f.session.version&&(h=f.record.version.minor===f.version.minor),h||f.error(f,{message:"Incompatible TLS version.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.protocol_version}})}return c},l=function(f){var c=0,g=f.input,m=g.length();if(m<f.record.length)c=f.record.length-m;else{f.record.fragment.putBytes(g.getBytes(f.record.length)),g.compact();var h=f.state.current.read;h.update(f,f.record)&&(f.fragmented!==null&&(f.fragmented.type===f.record.type?(f.fragmented.fragment.putBuffer(f.record.fragment),f.record=f.fragmented):f.error(f,{message:"Invalid fragmented record.",send:!0,alert:{level:y.Alert.Level.fatal,description:y.Alert.Description.unexpected_message}})),f.record.ready=!0)}return c};return s.handshake=function(f){if(s.entity!==y.ConnectionEnd.client)s.error(s,{message:"Cannot initiate handshake as a server.",fatal:!1});else if(s.handshaking)s.error(s,{message:"Handshake already in progress.",fatal:!1});else{s.fail&&!s.open&&s.handshakes===0&&(s.fail=!1),s.handshaking=!0,f=f||"";var c=null;f.length>0&&(s.sessionCache&&(c=s.sessionCache.getSession(f)),c===null&&(f="")),f.length===0&&s.sessionCache&&(c=s.sessionCache.getSession(),c!==null&&(f=c.id)),s.session={id:f,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:R.md.md5.create(),sha1:R.md.sha1.create()},c&&(s.version=c.version,s.session.sp=c.sp),s.session.sp.client_random=y.createRandom().getBytes(),s.open=!0,y.queue(s,y.createRecord(s,{type:y.ContentType.handshake,data:y.createClientHello(s)})),y.flush(s)}},s.process=function(f){var c=0;return f&&s.input.putBytes(f),s.fail||(s.record!==null&&s.record.ready&&s.record.fragment.isEmpty()&&(s.record=null),s.record===null&&(c=u(s)),!s.fail&&s.record!==null&&!s.record.ready&&(c=l(s)),!s.fail&&s.record!==null&&s.record.ready&&o(s,s.record)),c},s.prepare=function(f){return y.queue(s,y.createRecord(s,{type:y.ContentType.application_data,data:R.util.createBuffer(f)})),y.flush(s)},s.prepareHeartbeatRequest=function(f,c){return f instanceof R.util.ByteBuffer&&(f=f.bytes()),typeof c>"u"&&(c=f.length),s.expectedHeartbeatPayload=f,y.queue(s,y.createRecord(s,{type:y.ContentType.heartbeat,data:y.createHeartbeat(y.HeartbeatMessageType.heartbeat_request,f,c)})),y.flush(s)},s.close=function(f){if(!s.fail&&s.sessionCache&&s.session){var c={id:s.session.id,version:s.session.version,sp:s.session.sp};c.sp.keys=null,s.sessionCache.setSession(c.id,c)}s.open&&(s.open=!1,s.input.clear(),(s.isConnected||s.handshaking)&&(s.isConnected=s.handshaking=!1,y.queue(s,y.createAlert(s,{level:y.Alert.Level.warning,description:y.Alert.Description.close_notify})),y.flush(s)),s.closed(s)),s.reset(f)},s};Io.exports=R.tls=R.tls||{};for(ba in y)typeof y[ba]!="function"&&(R.tls[ba]=y[ba]);var ba;R.tls.prf_tls1=wa;R.tls.hmac_sha1=y0;R.tls.createSessionCache=y.createSessionCache;R.tls.createConnection=y.createConnection});var Bo=H((By,Ao)=>{"use strict";var Ht=W();Ut();Fn();var ft=Ao.exports=Ht.tls;ft.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA={id:[0,47],name:"TLS_RSA_WITH_AES_128_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=ft.BulkCipherAlgorithm.aes,e.cipher_type=ft.CipherType.block,e.enc_key_length=16,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=ft.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:wo};ft.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA={id:[0,53],name:"TLS_RSA_WITH_AES_256_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=ft.BulkCipherAlgorithm.aes,e.cipher_type=ft.CipherType.block,e.enc_key_length=32,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=ft.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:wo};function wo(e,t,a){var r=t.entity===Ht.tls.ConnectionEnd.client;e.read.cipherState={init:!1,cipher:Ht.cipher.createDecipher("AES-CBC",r?a.keys.server_write_key:a.keys.client_write_key),iv:r?a.keys.server_write_IV:a.keys.client_write_IV},e.write.cipherState={init:!1,cipher:Ht.cipher.createCipher("AES-CBC",r?a.keys.client_write_key:a.keys.server_write_key),iv:r?a.keys.client_write_IV:a.keys.server_write_IV},e.read.cipherFunction=O0,e.write.cipherFunction=k0,e.read.macLength=e.write.macLength=a.mac_length,e.read.macFunction=e.write.macFunction=ft.hmac_sha1}function k0(e,t){var a=!1,r=t.macFunction(t.macKey,t.sequenceNumber,e);e.fragment.putBytes(r),t.updateSequenceNumber();var n;e.version.minor===ft.Versions.TLS_1_0.minor?n=t.cipherState.init?null:t.cipherState.iv:n=Ht.random.getBytesSync(16),t.cipherState.init=!0;var i=t.cipherState.cipher;return i.start({iv:n}),e.version.minor>=ft.Versions.TLS_1_1.minor&&i.output.putBytes(n),i.update(e.fragment),i.finish(U0)&&(e.fragment=i.output,e.length=e.fragment.length(),a=!0),a}function U0(e,t,a){if(!a){var r=e-t.length()%e;t.fillWithByte(r-1,r)}return!0}function F0(e,t,a){var r=!0;if(a){for(var n=t.length(),i=t.last(),s=n-1-i;s<n-1;++s)r=r&&t.at(s)==i;r&&t.truncate(i+1)}return r}function O0(e,t){var a=!1,r;e.version.minor===ft.Versions.TLS_1_0.minor?r=t.cipherState.init?null:t.cipherState.iv:r=e.fragment.getBytes(16),t.cipherState.init=!0;var n=t.cipherState.cipher;n.start({iv:r}),n.update(e.fragment),a=n.finish(F0);var i=t.macLength,s=Ht.random.getBytesSync(i),o=n.output.length();o>=i?(e.fragment=n.output.getBytes(o-i),s=n.output.getBytes(i)):e.fragment=n.output.getBytes(),e.fragment=Ht.util.createBuffer(e.fragment),e.length=e.fragment.length();var u=t.macFunction(t.macKey,t.sequenceNumber,e);return t.updateSequenceNumber(),a=V0(t.macKey,s,u)&&a,a}function V0(e,t,a){var r=Ht.hmac.create();return r.start("SHA1",e),r.update(t),t=r.digest().getBytes(),r.start(null,null),r.update(a),a=r.digest().getBytes(),t===a}});var Mn=H((Ry,Po)=>{"use strict";var ye=W();mt();re();var Vr=Po.exports=ye.sha512=ye.sha512||{};ye.md.sha512=ye.md.algorithms.sha512=Vr;var _o=ye.sha384=ye.sha512.sha384=ye.sha512.sha384||{};_o.create=function(){return Vr.create("SHA-384")};ye.md.sha384=ye.md.algorithms.sha384=_o;ye.sha512.sha256=ye.sha512.sha256||{create:function(){return Vr.create("SHA-512/256")}};ye.md["sha512/256"]=ye.md.algorithms["sha512/256"]=ye.sha512.sha256;ye.sha512.sha224=ye.sha512.sha224||{create:function(){return Vr.create("SHA-512/224")}};ye.md["sha512/224"]=ye.md.algorithms["sha512/224"]=ye.sha512.sha224;Vr.create=function(e){if(No||M0(),typeof e>"u"&&(e="SHA-512"),!(e in nr))throw new Error("Invalid SHA-512 algorithm: "+e);for(var t=nr[e],a=null,r=ye.util.createBuffer(),n=new Array(80),i=0;i<80;++i)n[i]=new Array(2);var s=64;switch(e){case"SHA-384":s=48;break;case"SHA-512/256":s=32;break;case"SHA-512/224":s=28;break}var o={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:s,messageLength:0,fullMessageLength:null,messageLengthSize:16};return o.start=function(){o.messageLength=0,o.fullMessageLength=o.messageLength128=[];for(var u=o.messageLengthSize/4,l=0;l<u;++l)o.fullMessageLength.push(0);r=ye.util.createBuffer(),a=new Array(t.length);for(var l=0;l<t.length;++l)a[l]=t[l].slice(0);return o},o.start(),o.update=function(u,l){l==="utf8"&&(u=ye.util.encodeUtf8(u));var f=u.length;o.messageLength+=f,f=[f/4294967296>>>0,f>>>0];for(var c=o.fullMessageLength.length-1;c>=0;--c)o.fullMessageLength[c]+=f[1],f[1]=f[0]+(o.fullMessageLength[c]/4294967296>>>0),o.fullMessageLength[c]=o.fullMessageLength[c]>>>0,f[0]=f[1]/4294967296>>>0;return r.putBytes(u),Ro(a,n,r),(r.read>2048||r.length()===0)&&r.compact(),o},o.digest=function(){var u=ye.util.createBuffer();u.putBytes(r.bytes());var l=o.fullMessageLength[o.fullMessageLength.length-1]+o.messageLengthSize,f=l&o.blockLength-1;u.putBytes(On.substr(0,o.blockLength-f));for(var c,g,m=o.fullMessageLength[0]*8,h=0;h<o.fullMessageLength.length-1;++h)c=o.fullMessageLength[h+1]*8,g=c/4294967296>>>0,m+=g,u.putInt32(m>>>0),m=c>>>0;u.putInt32(m);for(var v=new Array(a.length),h=0;h<a.length;++h)v[h]=a[h].slice(0);Ro(v,n,u);var E=ye.util.createBuffer(),T;e==="SHA-512"?T=v.length:e==="SHA-384"?T=v.length-2:T=v.length-4;for(var h=0;h<T;++h)E.putInt32(v[h][0]),(h!==T-1||e!=="SHA-512/224")&&E.putInt32(v[h][1]);return E},o};var On=null,No=!1,Vn=null,nr=null;function M0(){On="\x80",On+=ye.util.fillString("\0",128),Vn=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],nr={},nr["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],nr["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],nr["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],nr["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],No=!0}function Ro(e,t,a){for(var r,n,i,s,o,u,l,f,c,g,m,h,v,E,T,I,A,L,N,P,G,j,ie,oe,fe,pe,Qe,nt,ue,Ee,V,Wt,ur,xe,Se,be=a.length();be>=128;){for(ue=0;ue<16;++ue)t[ue][0]=a.getInt32()>>>0,t[ue][1]=a.getInt32()>>>0;for(;ue<80;++ue)Wt=t[ue-2],Ee=Wt[0],V=Wt[1],r=((Ee>>>19|V<<13)^(V>>>29|Ee<<3)^Ee>>>6)>>>0,n=((Ee<<13|V>>>19)^(V<<3|Ee>>>29)^(Ee<<26|V>>>6))>>>0,xe=t[ue-15],Ee=xe[0],V=xe[1],i=((Ee>>>1|V<<31)^(Ee>>>8|V<<24)^Ee>>>7)>>>0,s=((Ee<<31|V>>>1)^(Ee<<24|V>>>8)^(Ee<<25|V>>>7))>>>0,ur=t[ue-7],Se=t[ue-16],V=n+ur[1]+s+Se[1],t[ue][0]=r+ur[0]+i+Se[0]+(V/4294967296>>>0)>>>0,t[ue][1]=V>>>0;for(v=e[0][0],E=e[0][1],T=e[1][0],I=e[1][1],A=e[2][0],L=e[2][1],N=e[3][0],P=e[3][1],G=e[4][0],j=e[4][1],ie=e[5][0],oe=e[5][1],fe=e[6][0],pe=e[6][1],Qe=e[7][0],nt=e[7][1],ue=0;ue<80;++ue)l=((G>>>14|j<<18)^(G>>>18|j<<14)^(j>>>9|G<<23))>>>0,f=((G<<18|j>>>14)^(G<<14|j>>>18)^(j<<23|G>>>9))>>>0,c=(fe^G&(ie^fe))>>>0,g=(pe^j&(oe^pe))>>>0,o=((v>>>28|E<<4)^(E>>>2|v<<30)^(E>>>7|v<<25))>>>0,u=((v<<4|E>>>28)^(E<<30|v>>>2)^(E<<25|v>>>7))>>>0,m=(v&T|A&(v^T))>>>0,h=(E&I|L&(E^I))>>>0,V=nt+f+g+Vn[ue][1]+t[ue][1],r=Qe+l+c+Vn[ue][0]+t[ue][0]+(V/4294967296>>>0)>>>0,n=V>>>0,V=u+h,i=o+m+(V/4294967296>>>0)>>>0,s=V>>>0,Qe=fe,nt=pe,fe=ie,pe=oe,ie=G,oe=j,V=P+n,G=N+r+(V/4294967296>>>0)>>>0,j=V>>>0,N=A,P=L,A=T,L=I,T=v,I=E,V=n+s,v=r+i+(V/4294967296>>>0)>>>0,E=V>>>0;V=e[0][1]+E,e[0][0]=e[0][0]+v+(V/4294967296>>>0)>>>0,e[0][1]=V>>>0,V=e[1][1]+I,e[1][0]=e[1][0]+T+(V/4294967296>>>0)>>>0,e[1][1]=V>>>0,V=e[2][1]+L,e[2][0]=e[2][0]+A+(V/4294967296>>>0)>>>0,e[2][1]=V>>>0,V=e[3][1]+P,e[3][0]=e[3][0]+N+(V/4294967296>>>0)>>>0,e[3][1]=V>>>0,V=e[4][1]+j,e[4][0]=e[4][0]+G+(V/4294967296>>>0)>>>0,e[4][1]=V>>>0,V=e[5][1]+oe,e[5][0]=e[5][0]+ie+(V/4294967296>>>0)>>>0,e[5][1]=V>>>0,V=e[6][1]+pe,e[6][0]=e[6][0]+fe+(V/4294967296>>>0)>>>0,e[6][1]=V>>>0,V=e[7][1]+nt,e[7][0]=e[7][0]+Qe+(V/4294967296>>>0)>>>0,e[7][1]=V>>>0,be-=128}}});var Do=H(Kn=>{"use strict";var K0=W();pt();var Be=K0.asn1;Kn.privateKeyValidator={name:"PrivateKeyInfo",tagClass:Be.Class.UNIVERSAL,type:Be.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:Be.Class.UNIVERSAL,type:Be.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:Be.Class.UNIVERSAL,type:Be.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:Be.Class.UNIVERSAL,type:Be.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:Be.Class.UNIVERSAL,type:Be.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]};Kn.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:Be.Class.UNIVERSAL,type:Be.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:Be.Class.UNIVERSAL,type:Be.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:Be.Class.UNIVERSAL,type:Be.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{tagClass:Be.Class.UNIVERSAL,type:Be.Type.BITSTRING,constructed:!1,composed:!0,captureBitStringValue:"ed25519PublicKey"}]}});var Qo=H((Ny,Go)=>{"use strict";var Ne=W();kr();it();Mn();re();var Vo=Do(),q0=Vo.publicKeyValidator,H0=Vo.privateKeyValidator;typeof Lo>"u"&&(Lo=Ne.jsbn.BigInteger);var Lo,zn=Ne.util.ByteBuffer,Je=typeof Buffer>"u"?Uint8Array:Buffer;Ne.pki=Ne.pki||{};Go.exports=Ne.pki.ed25519=Ne.ed25519=Ne.ed25519||{};var X=Ne.ed25519;X.constants={};X.constants.PUBLIC_KEY_BYTE_LENGTH=32;X.constants.PRIVATE_KEY_BYTE_LENGTH=64;X.constants.SEED_BYTE_LENGTH=32;X.constants.SIGN_BYTE_LENGTH=64;X.constants.HASH_BYTE_LENGTH=64;X.generateKeyPair=function(e){e=e||{};var t=e.seed;if(t===void 0)t=Ne.random.getBytesSync(X.constants.SEED_BYTE_LENGTH);else if(typeof t=="string"){if(t.length!==X.constants.SEED_BYTE_LENGTH)throw new TypeError('"seed" must be '+X.constants.SEED_BYTE_LENGTH+" bytes in length.")}else if(!(t instanceof Uint8Array))throw new TypeError('"seed" must be a node.js Buffer, Uint8Array, or a binary string.');t=_t({message:t,encoding:"binary"});for(var a=new Je(X.constants.PUBLIC_KEY_BYTE_LENGTH),r=new Je(X.constants.PRIVATE_KEY_BYTE_LENGTH),n=0;n<32;++n)r[n]=t[n];return W0(a,r),{publicKey:a,privateKey:r}};X.privateKeyFromAsn1=function(e){var t={},a=[],r=Ne.asn1.validate(e,H0,t,a);if(!r){var n=new Error("Invalid Key.");throw n.errors=a,n}var i=Ne.asn1.derToOid(t.privateKeyOid),s=Ne.oids.EdDSA25519;if(i!==s)throw new Error('Invalid OID "'+i+'"; OID must be "'+s+'".');var o=t.privateKey,u=_t({message:Ne.asn1.fromDer(o).value,encoding:"binary"});return{privateKeyBytes:u}};X.publicKeyFromAsn1=function(e){var t={},a=[],r=Ne.asn1.validate(e,q0,t,a);if(!r){var n=new Error("Invalid Key.");throw n.errors=a,n}var i=Ne.asn1.derToOid(t.publicKeyOid),s=Ne.oids.EdDSA25519;if(i!==s)throw new Error('Invalid OID "'+i+'"; OID must be "'+s+'".');var o=t.ed25519PublicKey;if(o.length!==X.constants.PUBLIC_KEY_BYTE_LENGTH)throw new Error("Key length is invalid.");return _t({message:o,encoding:"binary"})};X.publicKeyFromPrivateKey=function(e){e=e||{};var t=_t({message:e.privateKey,encoding:"binary"});if(t.length!==X.constants.PRIVATE_KEY_BYTE_LENGTH)throw new TypeError('"options.privateKey" must have a byte length of '+X.constants.PRIVATE_KEY_BYTE_LENGTH);for(var a=new Je(X.constants.PUBLIC_KEY_BYTE_LENGTH),r=0;r<a.length;++r)a[r]=t[32+r];return a};X.sign=function(e){e=e||{};var t=_t(e),a=_t({message:e.privateKey,encoding:"binary"});if(a.length===X.constants.SEED_BYTE_LENGTH){var r=X.generateKeyPair({seed:a});a=r.privateKey}else if(a.length!==X.constants.PRIVATE_KEY_BYTE_LENGTH)throw new TypeError('"options.privateKey" must have a byte length of '+X.constants.SEED_BYTE_LENGTH+" or "+X.constants.PRIVATE_KEY_BYTE_LENGTH);var n=new Je(X.constants.SIGN_BYTE_LENGTH+t.length);j0(n,t,t.length,a);for(var i=new Je(X.constants.SIGN_BYTE_LENGTH),s=0;s<i.length;++s)i[s]=n[s];return i};X.verify=function(e){e=e||{};var t=_t(e);if(e.signature===void 0)throw new TypeError('"options.signature" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a binary string.');var a=_t({message:e.signature,encoding:"binary"});if(a.length!==X.constants.SIGN_BYTE_LENGTH)throw new TypeError('"options.signature" must have a byte length of '+X.constants.SIGN_BYTE_LENGTH);var r=_t({message:e.publicKey,encoding:"binary"});if(r.length!==X.constants.PUBLIC_KEY_BYTE_LENGTH)throw new TypeError('"options.publicKey" must have a byte length of '+X.constants.PUBLIC_KEY_BYTE_LENGTH);var n=new Je(X.constants.SIGN_BYTE_LENGTH+t.length),i=new Je(X.constants.SIGN_BYTE_LENGTH+t.length),s;for(s=0;s<X.constants.SIGN_BYTE_LENGTH;++s)n[s]=a[s];for(s=0;s<t.length;++s)n[s+X.constants.SIGN_BYTE_LENGTH]=t[s];return $0(i,n,n.length,r)>=0};function _t(e){var t=e.message;if(t instanceof Uint8Array||t instanceof Je)return t;var a=e.encoding;if(t===void 0)if(e.md)t=e.md.digest().getBytes(),a="binary";else throw new TypeError('"options.message" or "options.md" not specified.');if(typeof t=="string"&&!a)throw new TypeError('"options.encoding" must be "binary" or "utf8".');if(typeof t=="string"){if(typeof Buffer<"u")return Buffer.from(t,a);t=new zn(t,a)}else if(!(t instanceof zn))throw new TypeError('"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.');for(var r=new Je(t.length()),n=0;n<r.length;++n)r[n]=t.at(n);return r}var Gn=q(),Aa=q([1]),z0=q([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),G0=q([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),ko=q([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),Uo=q([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),qn=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]),Q0=q([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function Mr(e,t){var a=Ne.md.sha512.create(),r=new zn(e);a.update(r.getBytes(t),"binary");var n=a.digest().getBytes();if(typeof Buffer<"u")return Buffer.from(n,"binary");for(var i=new Je(X.constants.HASH_BYTE_LENGTH),s=0;s<64;++s)i[s]=n.charCodeAt(s);return i}function W0(e,t){var a=[q(),q(),q(),q()],r,n=Mr(t,32);for(n[0]&=248,n[31]&=127,n[31]|=64,$n(a,n),jn(e,a),r=0;r<32;++r)t[r+32]=e[r];return 0}function j0(e,t,a,r){var n,i,s=new Float64Array(64),o=[q(),q(),q(),q()],u=Mr(r,32);u[0]&=248,u[31]&=127,u[31]|=64;var l=a+64;for(n=0;n<a;++n)e[64+n]=t[n];for(n=0;n<32;++n)e[32+n]=u[32+n];var f=Mr(e.subarray(32),a+32);for(Qn(f),$n(o,f),jn(e,o),n=32;n<64;++n)e[n]=r[n];var c=Mr(e,a+64);for(Qn(c),n=32;n<64;++n)s[n]=0;for(n=0;n<32;++n)s[n]=f[n];for(n=0;n<32;++n)for(i=0;i<32;i++)s[n+i]+=c[n]*u[i];return Mo(e.subarray(32),s),l}function $0(e,t,a,r){var n,i,s=new Je(32),o=[q(),q(),q(),q()],u=[q(),q(),q(),q()];if(i=-1,a<64||Y0(u,r))return-1;for(n=0;n<a;++n)e[n]=t[n];for(n=0;n<32;++n)e[n+32]=r[n];var l=Mr(e,a);if(Qn(l),Ho(o,u,l),$n(u,t.subarray(32)),Wn(o,u),jn(s,o),a-=64,Ko(t,0,s,0)){for(n=0;n<a;++n)e[n]=0;return-1}for(n=0;n<a;++n)e[n]=t[n+64];return i=a,i}function Mo(e,t){var a,r,n,i;for(r=63;r>=32;--r){for(a=0,n=r-32,i=r-12;n<i;++n)t[n]+=a-16*t[r]*qn[n-(r-32)],a=t[n]+128>>8,t[n]-=a*256;t[n]+=a,t[r]=0}for(a=0,n=0;n<32;++n)t[n]+=a-(t[31]>>4)*qn[n],a=t[n]>>8,t[n]&=255;for(n=0;n<32;++n)t[n]-=a*qn[n];for(r=0;r<32;++r)t[r+1]+=t[r]>>8,e[r]=t[r]&255}function Qn(e){for(var t=new Float64Array(64),a=0;a<64;++a)t[a]=e[a],e[a]=0;Mo(e,t)}function Wn(e,t){var a=q(),r=q(),n=q(),i=q(),s=q(),o=q(),u=q(),l=q(),f=q();Sr(a,e[1],e[0]),Sr(f,t[1],t[0]),le(a,a,f),xr(r,e[0],e[1]),xr(f,t[0],t[1]),le(r,r,f),le(n,e[3],t[3]),le(n,n,G0),le(i,e[2],t[2]),xr(i,i,i),Sr(s,r,a),Sr(o,i,n),xr(u,i,n),xr(l,r,a),le(e[0],s,o),le(e[1],l,u),le(e[2],u,o),le(e[3],s,l)}function Fo(e,t,a){for(var r=0;r<4;++r)zo(e[r],t[r],a)}function jn(e,t){var a=q(),r=q(),n=q();ed(n,t[2]),le(a,t[0],n),le(r,t[1],n),Ba(e,r),e[31]^=qo(a)<<7}function Ba(e,t){var a,r,n,i=q(),s=q();for(a=0;a<16;++a)s[a]=t[a];for(Hn(s),Hn(s),Hn(s),r=0;r<2;++r){for(i[0]=s[0]-65517,a=1;a<15;++a)i[a]=s[a]-65535-(i[a-1]>>16&1),i[a-1]&=65535;i[15]=s[15]-32767-(i[14]>>16&1),n=i[15]>>16&1,i[14]&=65535,zo(s,i,1-n)}for(a=0;a<16;a++)e[2*a]=s[a]&255,e[2*a+1]=s[a]>>8}function Y0(e,t){var a=q(),r=q(),n=q(),i=q(),s=q(),o=q(),u=q();return zt(e[2],Aa),X0(e[1],t),ir(n,e[1]),le(i,n,z0),Sr(n,n,e[2]),xr(i,e[2],i),ir(s,i),ir(o,s),le(u,o,s),le(a,u,n),le(a,a,i),Z0(a,a),le(a,a,n),le(a,a,i),le(a,a,i),le(e[0],a,i),ir(r,e[0]),le(r,r,i),Oo(r,n)&&le(e[0],e[0],Q0),ir(r,e[0]),le(r,r,i),Oo(r,n)?-1:(qo(e[0])===t[31]>>7&&Sr(e[0],Gn,e[0]),le(e[3],e[0],e[1]),0)}function X0(e,t){var a;for(a=0;a<16;++a)e[a]=t[2*a]+(t[2*a+1]<<8);e[15]&=32767}function Z0(e,t){var a=q(),r;for(r=0;r<16;++r)a[r]=t[r];for(r=250;r>=0;--r)ir(a,a),r!==1&&le(a,a,t);for(r=0;r<16;++r)e[r]=a[r]}function Oo(e,t){var a=new Je(32),r=new Je(32);return Ba(a,e),Ba(r,t),Ko(a,0,r,0)}function Ko(e,t,a,r){return J0(e,t,a,r,32)}function J0(e,t,a,r,n){var i,s=0;for(i=0;i<n;++i)s|=e[t+i]^a[r+i];return(1&s-1>>>8)-1}function qo(e){var t=new Je(32);return Ba(t,e),t[0]&1}function Ho(e,t,a){var r,n;for(zt(e[0],Gn),zt(e[1],Aa),zt(e[2],Aa),zt(e[3],Gn),n=255;n>=0;--n)r=a[n/8|0]>>(n&7)&1,Fo(e,t,r),Wn(t,e),Wn(e,e),Fo(e,t,r)}function $n(e,t){var a=[q(),q(),q(),q()];zt(a[0],ko),zt(a[1],Uo),zt(a[2],Aa),le(a[3],ko,Uo),Ho(e,a,t)}function zt(e,t){var a;for(a=0;a<16;a++)e[a]=t[a]|0}function ed(e,t){var a=q(),r;for(r=0;r<16;++r)a[r]=t[r];for(r=253;r>=0;--r)ir(a,a),r!==2&&r!==4&&le(a,a,t);for(r=0;r<16;++r)e[r]=a[r]}function Hn(e){var t,a,r=1;for(t=0;t<16;++t)a=e[t]+r+65535,r=Math.floor(a/65536),e[t]=a-r*65536;e[0]+=r-1+37*(r-1)}function zo(e,t,a){for(var r,n=~(a-1),i=0;i<16;++i)r=n&(e[i]^t[i]),e[i]^=r,t[i]^=r}function q(e){var t,a=new Float64Array(16);if(e)for(t=0;t<e.length;++t)a[t]=e[t];return a}function xr(e,t,a){for(var r=0;r<16;++r)e[r]=t[r]+a[r]}function Sr(e,t,a){for(var r=0;r<16;++r)e[r]=t[r]-a[r]}function ir(e,t){le(e,t,t)}function le(e,t,a){var r,n,i=0,s=0,o=0,u=0,l=0,f=0,c=0,g=0,m=0,h=0,v=0,E=0,T=0,I=0,A=0,L=0,N=0,P=0,G=0,j=0,ie=0,oe=0,fe=0,pe=0,Qe=0,nt=0,ue=0,Ee=0,V=0,Wt=0,ur=0,xe=a[0],Se=a[1],be=a[2],Pe=a[3],De=a[4],Le=a[5],ke=a[6],Ue=a[7],Fe=a[8],Oe=a[9],Ve=a[10],Me=a[11],Ke=a[12],qe=a[13],He=a[14],ze=a[15];r=t[0],i+=r*xe,s+=r*Se,o+=r*be,u+=r*Pe,l+=r*De,f+=r*Le,c+=r*ke,g+=r*Ue,m+=r*Fe,h+=r*Oe,v+=r*Ve,E+=r*Me,T+=r*Ke,I+=r*qe,A+=r*He,L+=r*ze,r=t[1],s+=r*xe,o+=r*Se,u+=r*be,l+=r*Pe,f+=r*De,c+=r*Le,g+=r*ke,m+=r*Ue,h+=r*Fe,v+=r*Oe,E+=r*Ve,T+=r*Me,I+=r*Ke,A+=r*qe,L+=r*He,N+=r*ze,r=t[2],o+=r*xe,u+=r*Se,l+=r*be,f+=r*Pe,c+=r*De,g+=r*Le,m+=r*ke,h+=r*Ue,v+=r*Fe,E+=r*Oe,T+=r*Ve,I+=r*Me,A+=r*Ke,L+=r*qe,N+=r*He,P+=r*ze,r=t[3],u+=r*xe,l+=r*Se,f+=r*be,c+=r*Pe,g+=r*De,m+=r*Le,h+=r*ke,v+=r*Ue,E+=r*Fe,T+=r*Oe,I+=r*Ve,A+=r*Me,L+=r*Ke,N+=r*qe,P+=r*He,G+=r*ze,r=t[4],l+=r*xe,f+=r*Se,c+=r*be,g+=r*Pe,m+=r*De,h+=r*Le,v+=r*ke,E+=r*Ue,T+=r*Fe,I+=r*Oe,A+=r*Ve,L+=r*Me,N+=r*Ke,P+=r*qe,G+=r*He,j+=r*ze,r=t[5],f+=r*xe,c+=r*Se,g+=r*be,m+=r*Pe,h+=r*De,v+=r*Le,E+=r*ke,T+=r*Ue,I+=r*Fe,A+=r*Oe,L+=r*Ve,N+=r*Me,P+=r*Ke,G+=r*qe,j+=r*He,ie+=r*ze,r=t[6],c+=r*xe,g+=r*Se,m+=r*be,h+=r*Pe,v+=r*De,E+=r*Le,T+=r*ke,I+=r*Ue,A+=r*Fe,L+=r*Oe,N+=r*Ve,P+=r*Me,G+=r*Ke,j+=r*qe,ie+=r*He,oe+=r*ze,r=t[7],g+=r*xe,m+=r*Se,h+=r*be,v+=r*Pe,E+=r*De,T+=r*Le,I+=r*ke,A+=r*Ue,L+=r*Fe,N+=r*Oe,P+=r*Ve,G+=r*Me,j+=r*Ke,ie+=r*qe,oe+=r*He,fe+=r*ze,r=t[8],m+=r*xe,h+=r*Se,v+=r*be,E+=r*Pe,T+=r*De,I+=r*Le,A+=r*ke,L+=r*Ue,N+=r*Fe,P+=r*Oe,G+=r*Ve,j+=r*Me,ie+=r*Ke,oe+=r*qe,fe+=r*He,pe+=r*ze,r=t[9],h+=r*xe,v+=r*Se,E+=r*be,T+=r*Pe,I+=r*De,A+=r*Le,L+=r*ke,N+=r*Ue,P+=r*Fe,G+=r*Oe,j+=r*Ve,ie+=r*Me,oe+=r*Ke,fe+=r*qe,pe+=r*He,Qe+=r*ze,r=t[10],v+=r*xe,E+=r*Se,T+=r*be,I+=r*Pe,A+=r*De,L+=r*Le,N+=r*ke,P+=r*Ue,G+=r*Fe,j+=r*Oe,ie+=r*Ve,oe+=r*Me,fe+=r*Ke,pe+=r*qe,Qe+=r*He,nt+=r*ze,r=t[11],E+=r*xe,T+=r*Se,I+=r*be,A+=r*Pe,L+=r*De,N+=r*Le,P+=r*ke,G+=r*Ue,j+=r*Fe,ie+=r*Oe,oe+=r*Ve,fe+=r*Me,pe+=r*Ke,Qe+=r*qe,nt+=r*He,ue+=r*ze,r=t[12],T+=r*xe,I+=r*Se,A+=r*be,L+=r*Pe,N+=r*De,P+=r*Le,G+=r*ke,j+=r*Ue,ie+=r*Fe,oe+=r*Oe,fe+=r*Ve,pe+=r*Me,Qe+=r*Ke,nt+=r*qe,ue+=r*He,Ee+=r*ze,r=t[13],I+=r*xe,A+=r*Se,L+=r*be,N+=r*Pe,P+=r*De,G+=r*Le,j+=r*ke,ie+=r*Ue,oe+=r*Fe,fe+=r*Oe,pe+=r*Ve,Qe+=r*Me,nt+=r*Ke,ue+=r*qe,Ee+=r*He,V+=r*ze,r=t[14],A+=r*xe,L+=r*Se,N+=r*be,P+=r*Pe,G+=r*De,j+=r*Le,ie+=r*ke,oe+=r*Ue,fe+=r*Fe,pe+=r*Oe,Qe+=r*Ve,nt+=r*Me,ue+=r*Ke,Ee+=r*qe,V+=r*He,Wt+=r*ze,r=t[15],L+=r*xe,N+=r*Se,P+=r*be,G+=r*Pe,j+=r*De,ie+=r*Le,oe+=r*ke,fe+=r*Ue,pe+=r*Fe,Qe+=r*Oe,nt+=r*Ve,ue+=r*Me,Ee+=r*Ke,V+=r*qe,Wt+=r*He,ur+=r*ze,i+=38*N,s+=38*P,o+=38*G,u+=38*j,l+=38*ie,f+=38*oe,c+=38*fe,g+=38*pe,m+=38*Qe,h+=38*nt,v+=38*ue,E+=38*Ee,T+=38*V,I+=38*Wt,A+=38*ur,n=1,r=i+n+65535,n=Math.floor(r/65536),i=r-n*65536,r=s+n+65535,n=Math.floor(r/65536),s=r-n*65536,r=o+n+65535,n=Math.floor(r/65536),o=r-n*65536,r=u+n+65535,n=Math.floor(r/65536),u=r-n*65536,r=l+n+65535,n=Math.floor(r/65536),l=r-n*65536,r=f+n+65535,n=Math.floor(r/65536),f=r-n*65536,r=c+n+65535,n=Math.floor(r/65536),c=r-n*65536,r=g+n+65535,n=Math.floor(r/65536),g=r-n*65536,r=m+n+65535,n=Math.floor(r/65536),m=r-n*65536,r=h+n+65535,n=Math.floor(r/65536),h=r-n*65536,r=v+n+65535,n=Math.floor(r/65536),v=r-n*65536,r=E+n+65535,n=Math.floor(r/65536),E=r-n*65536,r=T+n+65535,n=Math.floor(r/65536),T=r-n*65536,r=I+n+65535,n=Math.floor(r/65536),I=r-n*65536,r=A+n+65535,n=Math.floor(r/65536),A=r-n*65536,r=L+n+65535,n=Math.floor(r/65536),L=r-n*65536,i+=n-1+37*(n-1),n=1,r=i+n+65535,n=Math.floor(r/65536),i=r-n*65536,r=s+n+65535,n=Math.floor(r/65536),s=r-n*65536,r=o+n+65535,n=Math.floor(r/65536),o=r-n*65536,r=u+n+65535,n=Math.floor(r/65536),u=r-n*65536,r=l+n+65535,n=Math.floor(r/65536),l=r-n*65536,r=f+n+65535,n=Math.floor(r/65536),f=r-n*65536,r=c+n+65535,n=Math.floor(r/65536),c=r-n*65536,r=g+n+65535,n=Math.floor(r/65536),g=r-n*65536,r=m+n+65535,n=Math.floor(r/65536),m=r-n*65536,r=h+n+65535,n=Math.floor(r/65536),h=r-n*65536,r=v+n+65535,n=Math.floor(r/65536),v=r-n*65536,r=E+n+65535,n=Math.floor(r/65536),E=r-n*65536,r=T+n+65535,n=Math.floor(r/65536),T=r-n*65536,r=I+n+65535,n=Math.floor(r/65536),I=r-n*65536,r=A+n+65535,n=Math.floor(r/65536),A=r-n*65536,r=L+n+65535,n=Math.floor(r/65536),L=r-n*65536,i+=n-1+37*(n-1),e[0]=i,e[1]=s,e[2]=o,e[3]=u,e[4]=l,e[5]=f,e[6]=c,e[7]=g,e[8]=m,e[9]=h,e[10]=v,e[11]=E,e[12]=T,e[13]=I,e[14]=A,e[15]=L}});var Yo=H((Py,$o)=>{"use strict";var tt=W();re();it();kr();$o.exports=tt.kem=tt.kem||{};var Wo=tt.jsbn.BigInteger;tt.kem.rsa={};tt.kem.rsa.create=function(e,t){t=t||{};var a=t.prng||tt.random,r={};return r.encrypt=function(n,i){var s=Math.ceil(n.n.bitLength()/8),o;do o=new Wo(tt.util.bytesToHex(a.getBytesSync(s)),16).mod(n.n);while(o.compareTo(Wo.ONE)<=0);o=tt.util.hexToBytes(o.toString(16));var u=s-o.length;u>0&&(o=tt.util.fillString("\0",u)+o);var l=n.encrypt(o,"NONE"),f=e.generate(o,i);return{encapsulation:l,key:f}},r.decrypt=function(n,i,s){var o=n.decrypt(i,"NONE");return e.generate(o,s)},r};tt.kem.kdf1=function(e,t){jo(this,e,0,t||e.digestLength)};tt.kem.kdf2=function(e,t){jo(this,e,1,t||e.digestLength)};function jo(e,t,a,r){e.generate=function(n,i){for(var s=new tt.util.ByteBuffer,o=Math.ceil(i/r)+a,u=new tt.util.ByteBuffer,l=a;l<o;++l){u.putInt32(l),t.start(),t.update(n+u.getBytes());var f=t.digest();s.putBytes(f.getBytes(r))}return s.truncate(s.length()-i),s.getBytes()}}});var eu=H((Dy,Jo)=>{"use strict";var J=W();re();Jo.exports=J.log=J.log||{};J.log.levels=["none","error","warning","info","debug","verbose","max"];var Ra={},Zn=[],qr=null;J.log.LEVEL_LOCKED=2;J.log.NO_LEVEL_CHECK=4;J.log.INTERPOLATE=8;for(It=0;It<J.log.levels.length;++It)Yn=J.log.levels[It],Ra[Yn]={index:It,name:Yn.toUpperCase()};var Yn,It;J.log.logMessage=function(e){for(var t=Ra[e.level].index,a=0;a<Zn.length;++a){var r=Zn[a];if(r.flags&J.log.NO_LEVEL_CHECK)r.f(e);else{var n=Ra[r.level].index;t<=n&&r.f(r,e)}}};J.log.prepareStandard=function(e){"standard"in e||(e.standard=Ra[e.level].name+" ["+e.category+"] "+e.message)};J.log.prepareFull=function(e){if(!("full"in e)){var t=[e.message];t=t.concat([]),e.full=J.util.format.apply(this,t)}};J.log.prepareStandardFull=function(e){"standardFull"in e||(J.log.prepareStandard(e),e.standardFull=e.standard)};for(Xn=["error","warning","info","debug","verbose"],It=0;It<Xn.length;++It)(function(t){J.log[t]=function(a,r){var n=Array.prototype.slice.call(arguments).slice(2),i={timestamp:new Date,level:t,category:a,message:r,arguments:n};J.log.logMessage(i)}})(Xn[It]);var Xn,It;J.log.makeLogger=function(e){var t={flags:0,f:e};return J.log.setLevel(t,"none"),t};J.log.setLevel=function(e,t){var a=!1;if(e&&!(e.flags&J.log.LEVEL_LOCKED))for(var r=0;r<J.log.levels.length;++r){var n=J.log.levels[r];if(t==n){e.level=t,a=!0;break}}return a};J.log.lock=function(e,t){typeof t>"u"||t?e.flags|=J.log.LEVEL_LOCKED:e.flags&=~J.log.LEVEL_LOCKED};J.log.addLogger=function(e){Zn.push(e)};typeof console<"u"&&"log"in console?(console.error&&console.warn&&console.info&&console.debug?(Xo={error:console.error,warning:console.warn,info:console.info,debug:console.debug,verbose:console.debug},Hr=function(e,t){J.log.prepareStandard(t);var a=Xo[t.level],r=[t.standard];r=r.concat(t.arguments.slice()),a.apply(console,r)},Tr=J.log.makeLogger(Hr)):(Hr=function(t,a){J.log.prepareStandardFull(a),console.log(a.standardFull)},Tr=J.log.makeLogger(Hr)),J.log.setLevel(Tr,"debug"),J.log.addLogger(Tr),qr=Tr):console={log:function(){}};var Tr,Xo,Hr;qr!==null&&typeof window<"u"&&window.location&&(Kr=new URL(window.location.href).searchParams,Kr.has("console.level")&&J.log.setLevel(qr,Kr.get("console.level").slice(-1)[0]),Kr.has("console.lock")&&(Zo=Kr.get("console.lock").slice(-1)[0],Zo=="true"&&J.log.lock(qr)));var Kr,Zo;J.log.consoleLogger=qr});var ru=H((Ly,tu)=>{"use strict";tu.exports=mt();ua();gr();cn();Mn()});var iu=H((ky,nu)=>{"use strict";var k=W();Ut();pt();Dr();Ft();Zt();In();it();re();Sa();var x=k.asn1,Ye=nu.exports=k.pkcs7=k.pkcs7||{};Ye.messageFromPem=function(e){var t=k.pem.decode(e)[0];if(t.type!=="PKCS7"){var a=new Error('Could not convert PKCS#7 message from PEM; PEM header type is not "PKCS#7".');throw a.headerType=t.type,a}if(t.procType&&t.procType.type==="ENCRYPTED")throw new Error("Could not convert PKCS#7 message from PEM; PEM is encrypted.");var r=x.fromDer(t.body);return Ye.messageFromAsn1(r)};Ye.messageToPem=function(e,t){var a={type:"PKCS7",body:x.toDer(e.toAsn1()).getBytes()};return k.pem.encode(a,{maxline:t})};Ye.messageFromAsn1=function(e){var t={},a=[];if(!x.validate(e,Ye.asn1.contentInfoValidator,t,a)){var r=new Error("Cannot read PKCS#7 message. ASN.1 object is not an PKCS#7 ContentInfo.");throw r.errors=a,r}var n=x.derToOid(t.contentType),i;switch(n){case k.pki.oids.envelopedData:i=Ye.createEnvelopedData();break;case k.pki.oids.encryptedData:i=Ye.createEncryptedData();break;case k.pki.oids.signedData:i=Ye.createSignedData();break;default:throw new Error("Cannot read PKCS#7 message. ContentType with OID "+n+" is not (yet) supported.")}return i.fromAsn1(t.content.value[0]),i};Ye.createSignedData=function(){var e=null;return e={type:k.pki.oids.signedData,version:1,certificates:[],crls:[],signers:[],digestAlgorithmIdentifiers:[],contentInfo:null,signerInfos:[],fromAsn1:function(r){if(ei(e,r,Ye.asn1.signedDataValidator),e.certificates=[],e.crls=[],e.digestAlgorithmIdentifiers=[],e.contentInfo=null,e.signerInfos=[],e.rawCapture.certificates)for(var n=e.rawCapture.certificates.value,i=0;i<n.length;++i)e.certificates.push(k.pki.certificateFromAsn1(n[i]))},toAsn1:function(){e.contentInfo||e.sign();for(var r=[],n=0;n<e.certificates.length;++n)r.push(k.pki.certificateToAsn1(e.certificates[n]));var i=[],s=x.create(x.Class.CONTEXT_SPECIFIC,0,!0,[x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.INTEGER,!1,x.integerToDer(e.version).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.SET,!0,e.digestAlgorithmIdentifiers),e.contentInfo])]);return r.length>0&&s.value[0].value.push(x.create(x.Class.CONTEXT_SPECIFIC,0,!0,r)),i.length>0&&s.value[0].value.push(x.create(x.Class.CONTEXT_SPECIFIC,1,!0,i)),s.value[0].value.push(x.create(x.Class.UNIVERSAL,x.Type.SET,!0,e.signerInfos)),x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(e.type).getBytes()),s])},addSigner:function(r){var n=r.issuer,i=r.serialNumber;if(r.certificate){var s=r.certificate;typeof s=="string"&&(s=k.pki.certificateFromPem(s)),n=s.issuer.attributes,i=s.serialNumber}var o=r.key;if(!o)throw new Error("Could not add PKCS#7 signer; no private key specified.");typeof o=="string"&&(o=k.pki.privateKeyFromPem(o));var u=r.digestAlgorithm||k.pki.oids.sha1;switch(u){case k.pki.oids.sha1:case k.pki.oids.sha256:case k.pki.oids.sha384:case k.pki.oids.sha512:case k.pki.oids.md5:break;default:throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+u)}var l=r.authenticatedAttributes||[];if(l.length>0){for(var f=!1,c=!1,g=0;g<l.length;++g){var m=l[g];if(!f&&m.type===k.pki.oids.contentType){if(f=!0,c)break;continue}if(!c&&m.type===k.pki.oids.messageDigest){if(c=!0,f)break;continue}}if(!f||!c)throw new Error("Invalid signer.authenticatedAttributes. If signer.authenticatedAttributes is specified, then it must contain at least two attributes, PKCS #9 content-type and PKCS #9 message-digest.")}e.signers.push({key:o,version:1,issuer:n,serialNumber:i,digestAlgorithm:u,signatureAlgorithm:k.pki.oids.rsaEncryption,signature:null,authenticatedAttributes:l,unauthenticatedAttributes:[]})},sign:function(r){if(r=r||{},(typeof e.content!="object"||e.contentInfo===null)&&(e.contentInfo=x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(k.pki.oids.data).getBytes())]),"content"in e)){var n;e.content instanceof k.util.ByteBuffer?n=e.content.bytes():typeof e.content=="string"&&(n=k.util.encodeUtf8(e.content)),r.detached?e.detachedContent=x.create(x.Class.UNIVERSAL,x.Type.OCTETSTRING,!1,n):e.contentInfo.value.push(x.create(x.Class.CONTEXT_SPECIFIC,0,!0,[x.create(x.Class.UNIVERSAL,x.Type.OCTETSTRING,!1,n)]))}if(e.signers.length!==0){var i=t();a(i)}},verify:function(){throw new Error("PKCS#7 signature verification not yet implemented.")},addCertificate:function(r){typeof r=="string"&&(r=k.pki.certificateFromPem(r)),e.certificates.push(r)},addCertificateRevokationList:function(r){throw new Error("PKCS#7 CRL support not yet implemented.")}},e;function t(){for(var r={},n=0;n<e.signers.length;++n){var i=e.signers[n],s=i.digestAlgorithm;s in r||(r[s]=k.md[k.pki.oids[s]].create()),i.authenticatedAttributes.length===0?i.md=r[s]:i.md=k.md[k.pki.oids[s]].create()}e.digestAlgorithmIdentifiers=[];for(var s in r)e.digestAlgorithmIdentifiers.push(x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(s).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.NULL,!1,"")]));return r}function a(r){var n;if(e.detachedContent?n=e.detachedContent:(n=e.contentInfo.value[1],n=n.value[0]),!n)throw new Error("Could not sign PKCS#7 message; there is no content to sign.");var i=x.derToOid(e.contentInfo.value[0].value),s=x.toDer(n);s.getByte(),x.getBerValueLength(s),s=s.getBytes();for(var o in r)r[o].start().update(s);for(var u=new Date,l=0;l<e.signers.length;++l){var f=e.signers[l];if(f.authenticatedAttributes.length===0){if(i!==k.pki.oids.data)throw new Error("Invalid signer; authenticatedAttributes must be present when the ContentInfo content type is not PKCS#7 Data.")}else{f.authenticatedAttributesAsn1=x.create(x.Class.CONTEXT_SPECIFIC,0,!0,[]);for(var c=x.create(x.Class.UNIVERSAL,x.Type.SET,!0,[]),g=0;g<f.authenticatedAttributes.length;++g){var m=f.authenticatedAttributes[g];m.type===k.pki.oids.messageDigest?m.value=r[f.digestAlgorithm].digest():m.type===k.pki.oids.signingTime&&(m.value||(m.value=u)),c.value.push(Jn(m)),f.authenticatedAttributesAsn1.value.push(Jn(m))}s=x.toDer(c).getBytes(),f.md.start().update(s)}f.signature=f.key.sign(f.md,"RSASSA-PKCS1-V1_5")}e.signerInfos=sd(e.signers)}};Ye.createEncryptedData=function(){var e=null;return e={type:k.pki.oids.encryptedData,version:0,encryptedContent:{algorithm:k.pki.oids["aes256-CBC"]},fromAsn1:function(t){ei(e,t,Ye.asn1.encryptedDataValidator)},decrypt:function(t){t!==void 0&&(e.encryptedContent.key=t),au(e)}},e};Ye.createEnvelopedData=function(){var e=null;return e={type:k.pki.oids.envelopedData,version:0,recipients:[],encryptedContent:{algorithm:k.pki.oids["aes256-CBC"]},fromAsn1:function(t){var a=ei(e,t,Ye.asn1.envelopedDataValidator);e.recipients=ad(a.recipientInfos.value)},toAsn1:function(){return x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(e.type).getBytes()),x.create(x.Class.CONTEXT_SPECIFIC,0,!0,[x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.INTEGER,!1,x.integerToDer(e.version).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.SET,!0,nd(e.recipients)),x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,od(e.encryptedContent))])])])},findRecipient:function(t){for(var a=t.issuer.attributes,r=0;r<e.recipients.length;++r){var n=e.recipients[r],i=n.issuer;if(n.serialNumber===t.serialNumber&&i.length===a.length){for(var s=!0,o=0;o<a.length;++o)if(i[o].type!==a[o].type||i[o].value!==a[o].value){s=!1;break}if(s)return n}}return null},decrypt:function(t,a){if(e.encryptedContent.key===void 0&&t!==void 0&&a!==void 0)switch(t.encryptedContent.algorithm){case k.pki.oids.rsaEncryption:case k.pki.oids.desCBC:var r=a.decrypt(t.encryptedContent.content);e.encryptedContent.key=k.util.createBuffer(r);break;default:throw new Error("Unsupported asymmetric cipher, OID "+t.encryptedContent.algorithm)}au(e)},addRecipient:function(t){e.recipients.push({version:0,issuer:t.issuer.attributes,serialNumber:t.serialNumber,encryptedContent:{algorithm:k.pki.oids.rsaEncryption,key:t.publicKey}})},encrypt:function(t,a){if(e.encryptedContent.content===void 0){a=a||e.encryptedContent.algorithm,t=t||e.encryptedContent.key;var r,n,i;switch(a){case k.pki.oids["aes128-CBC"]:r=16,n=16,i=k.aes.createEncryptionCipher;break;case k.pki.oids["aes192-CBC"]:r=24,n=16,i=k.aes.createEncryptionCipher;break;case k.pki.oids["aes256-CBC"]:r=32,n=16,i=k.aes.createEncryptionCipher;break;case k.pki.oids["des-EDE3-CBC"]:r=24,n=8,i=k.des.createEncryptionCipher;break;default:throw new Error("Unsupported symmetric cipher, OID "+a)}if(t===void 0)t=k.util.createBuffer(k.random.getBytes(r));else if(t.length()!=r)throw new Error("Symmetric key has wrong length; got "+t.length()+" bytes, expected "+r+".");e.encryptedContent.algorithm=a,e.encryptedContent.key=t,e.encryptedContent.parameter=k.util.createBuffer(k.random.getBytes(n));var s=i(t);if(s.start(e.encryptedContent.parameter.copy()),s.update(e.content),!s.finish())throw new Error("Symmetric encryption failed.");e.encryptedContent.content=s.output}for(var o=0;o<e.recipients.length;++o){var u=e.recipients[o];if(u.encryptedContent.content===void 0)switch(u.encryptedContent.algorithm){case k.pki.oids.rsaEncryption:u.encryptedContent.content=u.encryptedContent.key.encrypt(e.encryptedContent.key.data);break;default:throw new Error("Unsupported asymmetric cipher, OID "+u.encryptedContent.algorithm)}}}},e};function td(e){var t={},a=[];if(!x.validate(e,Ye.asn1.recipientInfoValidator,t,a)){var r=new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");throw r.errors=a,r}return{version:t.version.charCodeAt(0),issuer:k.pki.RDNAttributesAsArray(t.issuer),serialNumber:k.util.createBuffer(t.serial).toHex(),encryptedContent:{algorithm:x.derToOid(t.encAlgorithm),parameter:t.encParameter?t.encParameter.value:void 0,content:t.encKey}}}function rd(e){return x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.INTEGER,!1,x.integerToDer(e.version).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[k.pki.distinguishedNameToAsn1({attributes:e.issuer}),x.create(x.Class.UNIVERSAL,x.Type.INTEGER,!1,k.util.hexToBytes(e.serialNumber))]),x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(e.encryptedContent.algorithm).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.NULL,!1,"")]),x.create(x.Class.UNIVERSAL,x.Type.OCTETSTRING,!1,e.encryptedContent.content)])}function ad(e){for(var t=[],a=0;a<e.length;++a)t.push(td(e[a]));return t}function nd(e){for(var t=[],a=0;a<e.length;++a)t.push(rd(e[a]));return t}function id(e){var t=x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.INTEGER,!1,x.integerToDer(e.version).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[k.pki.distinguishedNameToAsn1({attributes:e.issuer}),x.create(x.Class.UNIVERSAL,x.Type.INTEGER,!1,k.util.hexToBytes(e.serialNumber))]),x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(e.digestAlgorithm).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.NULL,!1,"")])]);if(e.authenticatedAttributesAsn1&&t.value.push(e.authenticatedAttributesAsn1),t.value.push(x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(e.signatureAlgorithm).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.NULL,!1,"")])),t.value.push(x.create(x.Class.UNIVERSAL,x.Type.OCTETSTRING,!1,e.signature)),e.unauthenticatedAttributes.length>0){for(var a=x.create(x.Class.CONTEXT_SPECIFIC,1,!0,[]),r=0;r<e.unauthenticatedAttributes.length;++r){var n=e.unauthenticatedAttributes[r];a.values.push(Jn(n))}t.value.push(a)}return t}function sd(e){for(var t=[],a=0;a<e.length;++a)t.push(id(e[a]));return t}function Jn(e){var t;if(e.type===k.pki.oids.contentType)t=x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(e.value).getBytes());else if(e.type===k.pki.oids.messageDigest)t=x.create(x.Class.UNIVERSAL,x.Type.OCTETSTRING,!1,e.value.bytes());else if(e.type===k.pki.oids.signingTime){var a=new Date("1950-01-01T00:00:00Z"),r=new Date("2050-01-01T00:00:00Z"),n=e.value;if(typeof n=="string"){var i=Date.parse(n);isNaN(i)?n.length===13?n=x.utcTimeToDate(n):n=x.generalizedTimeToDate(n):n=new Date(i)}n>=a&&n<r?t=x.create(x.Class.UNIVERSAL,x.Type.UTCTIME,!1,x.dateToUtcTime(n)):t=x.create(x.Class.UNIVERSAL,x.Type.GENERALIZEDTIME,!1,x.dateToGeneralizedTime(n))}return x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(e.type).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.SET,!0,[t])])}function od(e){return[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(k.pki.oids.data).getBytes()),x.create(x.Class.UNIVERSAL,x.Type.SEQUENCE,!0,[x.create(x.Class.UNIVERSAL,x.Type.OID,!1,x.oidToDer(e.algorithm).getBytes()),e.parameter?x.create(x.Class.UNIVERSAL,x.Type.OCTETSTRING,!1,e.parameter.getBytes()):void 0]),x.create(x.Class.CONTEXT_SPECIFIC,0,!0,[x.create(x.Class.UNIVERSAL,x.Type.OCTETSTRING,!1,e.content.getBytes())])]}function ei(e,t,a){var r={},n=[];if(!x.validate(t,a,r,n)){var i=new Error("Cannot read PKCS#7 message. ASN.1 object is not a supported PKCS#7 message.");throw i.errors=i,i}var s=x.derToOid(r.contentType);if(s!==k.pki.oids.data)throw new Error("Unsupported PKCS#7 message. Only wrapped ContentType Data supported.");if(r.encryptedContent){var o="";if(k.util.isArray(r.encryptedContent))for(var u=0;u<r.encryptedContent.length;++u){if(r.encryptedContent[u].type!==x.Type.OCTETSTRING)throw new Error("Malformed PKCS#7 message, expecting encrypted content constructed of only OCTET STRING objects.");o+=r.encryptedContent[u].value}else o=r.encryptedContent;e.encryptedContent={algorithm:x.derToOid(r.encAlgorithm),parameter:k.util.createBuffer(r.encParameter.value),content:k.util.createBuffer(o)}}if(r.content){var o="";if(k.util.isArray(r.content))for(var u=0;u<r.content.length;++u){if(r.content[u].type!==x.Type.OCTETSTRING)throw new Error("Malformed PKCS#7 message, expecting content constructed of only OCTET STRING objects.");o+=r.content[u].value}else o=r.content;e.content=k.util.createBuffer(o)}return e.version=r.version.charCodeAt(0),e.rawCapture=r,r}function au(e){if(e.encryptedContent.key===void 0)throw new Error("Symmetric key not available.");if(e.content===void 0){var t;switch(e.encryptedContent.algorithm){case k.pki.oids["aes128-CBC"]:case k.pki.oids["aes192-CBC"]:case k.pki.oids["aes256-CBC"]:t=k.aes.createDecryptionCipher(e.encryptedContent.key);break;case k.pki.oids.desCBC:case k.pki.oids["des-EDE3-CBC"]:t=k.des.createDecryptionCipher(e.encryptedContent.key);break;default:throw new Error("Unsupported symmetric cipher, OID "+e.encryptedContent.algorithm)}if(t.start(e.encryptedContent.parameter),t.update(e.encryptedContent.content),!t.finish())throw new Error("Symmetric decryption failed.");e.content=t.output}}});var ou=H((Uy,su)=>{"use strict";var Te=W();Ut();dr();ua();gr();re();var Na=su.exports=Te.ssh=Te.ssh||{};Na.privateKeyToPutty=function(e,t,a){a=a||"",t=t||"";var r="ssh-rsa",n=t===""?"none":"aes256-cbc",i="PuTTY-User-Key-File-2: "+r+`\r
24
+ `;i+="Encryption: "+n+`\r
25
+ `,i+="Comment: "+a+`\r
26
+ `;var s=Te.util.createBuffer();br(s,r),wt(s,e.e),wt(s,e.n);var o=Te.util.encode64(s.bytes(),64),u=Math.floor(o.length/66)+1;i+="Public-Lines: "+u+`\r
27
+ `,i+=o;var l=Te.util.createBuffer();wt(l,e.d),wt(l,e.p),wt(l,e.q),wt(l,e.qInv);var f;if(!t)f=Te.util.encode64(l.bytes(),64);else{var c=l.length()+16-1;c-=c%16;var g=_a(l.bytes());g.truncate(g.length()-c+l.length()),l.putBuffer(g);var m=Te.util.createBuffer();m.putBuffer(_a("\0\0\0\0",t)),m.putBuffer(_a("\0\0\0",t));var h=Te.aes.createEncryptionCipher(m.truncate(8),"CBC");h.start(Te.util.createBuffer().fillWithByte(0,16)),h.update(l.copy()),h.finish();var v=h.output;v.truncate(16),f=Te.util.encode64(v.bytes(),64)}u=Math.floor(f.length/66)+1,i+=`\r
28
+ Private-Lines: `+u+`\r
29
+ `,i+=f;var E=_a("putty-private-key-file-mac-key",t),T=Te.util.createBuffer();br(T,r),br(T,n),br(T,a),T.putInt32(s.length()),T.putBuffer(s),T.putInt32(l.length()),T.putBuffer(l);var I=Te.hmac.create();return I.start("sha1",E),I.update(T.bytes()),i+=`\r
30
+ Private-MAC: `+I.digest().toHex()+`\r
31
+ `,i};Na.publicKeyToOpenSSH=function(e,t){var a="ssh-rsa";t=t||"";var r=Te.util.createBuffer();return br(r,a),wt(r,e.e),wt(r,e.n),a+" "+Te.util.encode64(r.bytes())+" "+t};Na.privateKeyToOpenSSH=function(e,t){return t?Te.pki.encryptRsaPrivateKey(e,t,{legacy:!0,algorithm:"aes128"}):Te.pki.privateKeyToPem(e)};Na.getPublicKeyFingerprint=function(e,t){t=t||{};var a=t.md||Te.md.md5.create(),r="ssh-rsa",n=Te.util.createBuffer();br(n,r),wt(n,e.e),wt(n,e.n),a.start(),a.update(n.getBytes());var i=a.digest();if(t.encoding==="hex"){var s=i.toHex();return t.delimiter?s.match(/.{2}/g).join(t.delimiter):s}else{if(t.encoding==="binary")return i.getBytes();if(t.encoding)throw new Error('Unknown encoding "'+t.encoding+'".')}return i};function wt(e,t){var a=t.toString(16);a[0]>="8"&&(a="00"+a);var r=Te.util.hexToBytes(a);e.putInt32(r.length),e.putBytes(r)}function br(e,t){e.putInt32(t.length),e.putString(t)}function _a(){for(var e=Te.md.sha1.create(),t=arguments.length,a=0;a<t;++a)e.update(arguments[a]);return e.digest()}});var lu=H((Fy,uu)=>{"use strict";uu.exports=W();Ut();Bo();pt();ta();Dr();Qo();dr();Yo();eu();ru();wn();da();Zt();En();Rn();iu();Nn();Sn();dn();Ca();it();yn();ou();Fn();re()});var du=H(cu=>{"use strict";var se=lu();function fu(e){var t=parseInt(e[0],16);return t<8?e:(t-=8,t.toString()+e.substring(1))}function ud(e){switch(e){case"sha256":return se.md.sha256.create();default:return se.md.sha1.create()}}cu.generate=function(t,a,r){typeof t=="function"?(r=t,t=void 0):typeof a=="function"&&(r=a,a={}),a=a||{};var n=function(o){var u=se.pki.createCertificate();u.serialNumber=fu(se.util.bytesToHex(se.random.getBytesSync(9))),u.validity.notBefore=a.notBeforeDate||new Date;var l=new Date;u.validity.notAfter=l,u.validity.notAfter.setDate(l.getDate()+(a.days||365)),t=t||[{name:"commonName",value:"example.org"},{name:"countryName",value:"US"},{shortName:"ST",value:"Virginia"},{name:"localityName",value:"Blacksburg"},{name:"organizationName",value:"Test"},{shortName:"OU",value:"Test"}],u.setSubject(t),u.setIssuer(t),u.publicKey=o.publicKey,u.setExtensions(a.extensions||[{name:"basicConstraints",cA:!0},{name:"keyUsage",keyCertSign:!0,digitalSignature:!0,nonRepudiation:!0,keyEncipherment:!0,dataEncipherment:!0},{name:"subjectAltName",altNames:[{type:6,value:"http://example.org/webid#me"}]}]),u.sign(o.privateKey,ud(a&&a.algorithm));let f=se.md.sha1.create().update(se.asn1.toDer(se.pki.certificateToAsn1(u)).getBytes()).digest().toHex().match(/.{2}/g).join(":");var c={private:se.pki.privateKeyToPem(o.privateKey),public:se.pki.publicKeyToPem(o.publicKey),cert:se.pki.certificateToPem(u),fingerprint:f};if(a&&a.pkcs7){var g=se.pkcs7.createSignedData();g.addCertificate(u),c.pkcs7=se.pkcs7.messageToPem(g)}if(a&&a.clientCertificate){var m=se.pki.rsa.generateKeyPair(a.clientCertificateKeySize||1024),h=se.pki.createCertificate();h.serialNumber=fu(se.util.bytesToHex(se.random.getBytesSync(9))),h.validity.notBefore=new Date,h.validity.notAfter=new Date,h.validity.notAfter.setFullYear(h.validity.notBefore.getFullYear()+1);for(var v=JSON.parse(JSON.stringify(t)),E=0;E<v.length;E++)v[E].name==="commonName"&&(a.clientCertificateCN?v[E]={name:"commonName",value:a.clientCertificateCN}:v[E]={name:"commonName",value:"John Doe jdoe123"});if(h.setSubject(v),h.setIssuer(t),h.publicKey=m.publicKey,h.sign(o.privateKey),c.clientprivate=se.pki.privateKeyToPem(m.privateKey),c.clientpublic=se.pki.publicKeyToPem(m.publicKey),c.clientcert=se.pki.certificateToPem(h),a.pkcs7){var T=se.pkcs7.createSignedData();T.addCertificate(h),c.clientpkcs7=se.pkcs7.messageToPem(T)}}var I=se.pki.createCaStore();I.addCertificate(u);try{se.pki.verifyCertificateChain(I,[u],function(A,L,N){if(A!==!0)throw new Error("Certificate could not be verified.");return!0})}catch(A){throw new Error(A)}return c},i=a.keySize||1024;if(r)return se.pki.rsa.generateKeyPair({bits:i},function(o,u){if(o)return r(o);try{return r(null,n(u))}catch(l){return r(l)}});var s=a.keyPair?{privateKey:se.pki.privateKeyFromPem(a.keyPair.privateKey),publicKey:se.pki.publicKeyFromPem(a.keyPair.publicKey)}:se.pki.rsa.generateKeyPair(i);return n(s)}});function Ui(e,t,a){if(!e||e.skip&&e.skip(t))return Promise.resolve(a());try{let r=e.execute(t,a);return r instanceof Promise?r:Promise.resolve(r)}catch(r){return Promise.reject(r)}}function lr(e){return e.length===0?async(t,a)=>{await Promise.resolve(a())}:async function(t,a){let r=new Set,n=async i=>{if(i>=e.length)return Promise.resolve(a());let s=e[i];return Ui(s,t,()=>{if(r.has(i))throw new Error("next() called multiple times");return r.add(i),n(i+1)})};return n(0)}}function $a(e){if(typeof e=="function")return{name:"anonymous",execute:e,debug:!1};let{name:t="anonymous",handler:a,skip:r,debug:n=!1}=e,i={name:t,execute:a,debug:n};return r!==void 0?{...i,skip:r}:i}function Ya(e,t,a,r={}){if(!e||typeof e!="string")throw new Error("Plugin name must be a non-empty string");if(!t||typeof t!="string")throw new Error("Plugin version must be a non-empty string");if(typeof a!="function")throw new Error("Plugin setup must be a function");return function(i){let s={...r,...i},o={name:e,version:t,register:async u=>{let l=await a(u,s);l&&typeof l=="object"&&Object.assign(o,l)}};return o}}import{fileURLToPath as Sl}from"node:url";var Zr={};function Fi(e){Zr={...Zr,...e}}function Oi(){if(!Zr.routesDir)throw new Error("Routes directory not configured. Make sure server is properly initialized.");return Zr.routesDir}import*as Vi from"node:path";function Jr(e,t){e.startsWith("file://")&&(e=e.replace("file://","")),t.startsWith("file://")&&(t=t.replace("file://",""));let a=e.replace(/\\/g,"/"),r=t.replace(/\\/g,"/"),n=r.endsWith("/")?r:`${r}/`,i=a;a.startsWith(n)?i=a.substring(n.length):a.startsWith(r)?(i=a.substring(r.length),i.startsWith("/")&&(i=i.substring(1))):i=Vi.relative(r,a).replace(/\\/g,"/"),i=i.replace(/\.[^.]+$/,"");let s=i.split("/").filter(Boolean),o=[],u=s.map(f=>{if(f.startsWith("[")&&f.endsWith("]")){let c=f.slice(1,-1);return o.push(c),`:${c}`}return f}),l=u.length>0?`/${u.join("/")}`:"/";return l.endsWith("/index")&&(l=l.slice(0,-6)||"/"),{filePath:e,routePath:l,params:o}}function Tl(){let e=Error.prepareStackTrace;try{Error.prepareStackTrace=(n,i)=>i;let a=new Error().stack[3];if(!a||typeof a.getFileName!="function")throw new Error("Unable to determine caller file frame");let r=a.getFileName();if(!r)throw new Error("Unable to determine caller file name");return r.startsWith("file://")?Sl(r):r}finally{Error.prepareStackTrace=e}}function $t(){let e=Tl(),t=Oi(),a=Jr(e,t);return console.log(`\u{1F50E} Parsed route path: ${a.routePath} from file: ${e}`),a.routePath}var Mi=e=>{Yt("GET",e);let t=$t();return{GET:e,path:t}},Ki=e=>{Yt("POST",e);let t=$t();return{POST:e,path:t}},qi=e=>{Yt("PUT",e);let t=$t();return{PUT:e,path:t}},Hi=e=>{Yt("DELETE",e);let t=$t();return{DELETE:e,path:t}},zi=e=>{Yt("PATCH",e);let t=$t();return{PATCH:e,path:t}},Gi=e=>{Yt("HEAD",e);let t=$t();return{HEAD:e,path:t}},Qi=e=>{Yt("OPTIONS",e);let t=$t();return{OPTIONS:e,path:t}};function Yt(e,t){if(!t.handler||typeof t.handler!="function")throw new Error(`Handler for method ${e} must be a function`);if(t.middleware&&!Array.isArray(t.middleware))throw new Error(`Middleware for method ${e} must be an array`);switch(t.schema&&bl(e,t.schema),e){case"GET":case"HEAD":case"DELETE":t.schema?.body&&console.warn(`Warning: ${e} requests typically don't have request bodies`);break}}function bl(e,t){let{params:a,query:r,body:n,response:i}=t;if(a&&(!a._def||typeof a.parse!="function"))throw new Error(`Params schema for ${e} must be a valid Zod schema`);if(r&&(!r._def||typeof r.parse!="function"))throw new Error(`Query schema for ${e} must be a valid Zod schema`);if(n&&(!n._def||typeof n.parse!="function"))throw new Error(`Body schema for ${e} must be a valid Zod schema`);if(i&&(!i._def||typeof i.parse!="function"))throw new Error(`Response schema for ${e} must be a valid Zod schema`)}import{AsyncLocalStorage as Sh}from"node:async_hooks";import Th from"node:events";import*as ri from"node:fs";import*as Nu from"node:http";import*as Pu from"node:http2";var pu=Cl(du(),1);import*as Nt from"node:fs";import*as Pa from"node:path";async function hu(){let e=Pa.join(process.cwd(),".blaizejs","certs"),t=Pa.join(e,"dev.key"),a=Pa.join(e,"dev.cert");if(Nt.existsSync(t)&&Nt.existsSync(a))return{keyFile:t,certFile:a};Nt.existsSync(e)||Nt.mkdirSync(e,{recursive:!0});let i=pu.generate([{name:"commonName",value:"localhost"}],{days:365,algorithm:"sha256",keySize:2048,extensions:[{name:"basicConstraints",cA:!0},{name:"keyUsage",keyCertSign:!0,digitalSignature:!0,nonRepudiation:!0,keyEncipherment:!0,dataEncipherment:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0},{name:"subjectAltName",altNames:[{type:2,value:"localhost"},{type:7,ip:"127.0.0.1"}]}]});return Nt.writeFileSync(t,Buffer.from(i.private,"utf-8")),Nt.writeFileSync(a,Buffer.from(i.cert,"utf-8")),console.log(`
32
+ \u{1F512} Generated self-signed certificates for development at ${e}
33
+ `),{keyFile:t,certFile:a}}var ct=class extends Error{constructor(t="\u274C Response has already been sent"){super(t),this.name="ResponseSentError"}},zr=class extends ct{constructor(t="Cannot set header after response has been sent"){super(t)}},Da=class extends ct{constructor(t="Cannot set content type after response has been sent"){super(t)}},La=class extends ct{constructor(t="Invalide URL"){super(t)}};import{AsyncLocalStorage as ld}from"node:async_hooks";var fd=new ld;function yu(e,t){return fd.run(e,t)}import{randomUUID as yd}from"node:crypto";import{createWriteStream as gd}from"node:fs";import{tmpdir as md}from"node:os";import{join as vd}from"node:path";import{Readable as Eu}from"node:stream";var cd=/boundary=([^;]+)/i,dd=/Content-Disposition:\s*form-data;\s*name="([^"]+)"(?:;[\s\r\n]*filename="([^"]*)")?/i,pd=/Content-Type:\s*([^\r\n]+)/i,hd=/multipart\/form-data/i;function gu(e){let t=e.match(cd);if(!t||!t[1])return null;let a=t[1].trim();return a.startsWith('"')&&a.endsWith('"')&&(a=a.slice(1,-1)),a||null}function mu(e){let t=e.match(dd);return!t||!t[1]?null:{name:t[1],filename:t[2]!==void 0?t[2]:void 0}}function vu(e){let t=e.match(pd);return t&&t[1]?.trim()?t[1].trim():"application/octet-stream"}function Cu(e){return hd.test(e)}var Cd={maxFileSize:10*1024*1024,maxFiles:10,maxFieldSize:1*1024*1024,allowedMimeTypes:[],allowedExtensions:[],strategy:"stream",tempDir:md(),computeHash:!1};function Ed(e,t={}){return{boundary:Buffer.from(`--${e}`),options:{...Cd,...t},fields:new Map,files:new Map,buffer:Buffer.alloc(0),stage:"boundary",currentHeaders:"",currentField:null,currentFilename:void 0,currentMimetype:"application/octet-stream",currentContentLength:0,fileCount:0,fieldCount:0,currentBufferChunks:[],currentStream:null,currentTempPath:null,currentWriteStream:null,streamController:null,cleanupTasks:[],hasFoundValidBoundary:!1,hasProcessedAnyPart:!1,isFinished:!1}}async function xd(e,t){let a=Buffer.concat([e.buffer,t]),r={...e,buffer:a};for(;r.buffer.length>0&&!r.isFinished;){let n=await Sd(r);if(n===r)break;r=n}return r}async function Sd(e){switch(e.stage){case"boundary":return Td(e);case"headers":return bd(e);case"content":return Id(e);default:{let{InternalServerError:t}=await import("./internal-server-error-JHHSKW5B.js");throw new t("Invalid parser stage",{operation:e.stage})}}}function Td(e){let t=e.buffer.indexOf(e.boundary);if(t===-1)return e;let a=!0,r=e.buffer.subarray(t+e.boundary.length);return r.length>=2&&r.subarray(0,2).equals(Buffer.from("--"))?{...e,buffer:r,hasFoundValidBoundary:a,isFinished:!0,stage:"boundary"}:(r.length>=2&&r.subarray(0,2).equals(Buffer.from(`\r
34
+ `))&&(r=r.subarray(2)),{...e,buffer:r,hasFoundValidBoundary:a,stage:"headers",currentHeaders:""})}async function bd(e){let t=e.buffer.indexOf(`\r
35
+ \r
36
+ `);if(t===-1)return e;let a=e.buffer.subarray(0,t).toString("utf8"),r=e.buffer.subarray(t+4),n=mu(a);if(!n){let{ValidationError:o}=await import("./validation-error-Q6IOTN4C.js");throw new o("Missing or invalid Content-Disposition header")}let i=vu(a),s=n.filename!==void 0;if(s&&e.fileCount>=e.options.maxFiles){let{PayloadTooLargeError:o}=await import("./payload-too-large-error-SOQINKUL.js");throw new o("Too many files in upload",{fileCount:e.fileCount+1,maxFiles:e.options.maxFiles,filename:n.filename})}if(s&&e.options.allowedMimeTypes.length>0&&!e.options.allowedMimeTypes.includes(i)){let{UnsupportedMediaTypeError:o}=await import("./unsupported-media-type-error-KJMHH5CY.js");throw new o("File type not allowed",{receivedMimeType:i,allowedMimeTypes:e.options.allowedMimeTypes,filename:n.filename})}return{...e,buffer:r,stage:"content",currentHeaders:a,currentField:n.name,currentFilename:n.filename,currentMimetype:i,currentContentLength:0,fileCount:s?e.fileCount+1:e.fileCount,fieldCount:s?e.fieldCount:e.fieldCount+1,currentBufferChunks:[]}}async function Id(e){let t=e.buffer.indexOf(e.boundary),a,r=!1,n=e.buffer;if(t===-1){let s=Math.max(0,e.buffer.length-e.boundary.length);if(s===0)return e;a=e.buffer.subarray(0,s),n=e.buffer.subarray(s)}else{let s=Math.max(0,t-2);a=e.buffer.subarray(0,s),n=e.buffer.subarray(t),r=!0}let i={...e,buffer:n};return a.length>0&&(i=await wd(i,a)),r&&(i=await Rd(i),i={...i,stage:"boundary",hasProcessedAnyPart:!0}),i}async function wd(e,t){let a=e.currentContentLength+t.length,r=e.currentFilename!==void 0?e.options.maxFileSize:e.options.maxFieldSize;if(a>r){let n=e.currentFilename!==void 0,{PayloadTooLargeError:i}=await import("./payload-too-large-error-SOQINKUL.js"),s=e.currentField?{contentType:n?"file":"field",currentSize:a,maxSize:r,field:e.currentField,filename:e.currentFilename}:{contentType:n?"file":"field",currentSize:a,maxSize:r,filename:e.currentFilename};throw new i(`${n?"File":"Field"} size exceeds limit`,s)}return e.currentFilename!==void 0?Ad(e,t,a):{...e,currentContentLength:a,currentBufferChunks:[...e.currentBufferChunks,t]}}async function Ad(e,t,a){switch(e.options.strategy){case"memory":return{...e,currentContentLength:a,currentBufferChunks:[...e.currentBufferChunks,t]};case"stream":return e.streamController&&e.streamController.enqueue(t),{...e,currentContentLength:a};case"temp":return e.currentWriteStream&&await Ld(e.currentWriteStream,t),{...e,currentContentLength:a};default:{let{ValidationError:r}=await import("./validation-error-Q6IOTN4C.js");throw new r("Invalid parsing strategy")}}}async function Bd(e){if(e.currentFilename===void 0)return e;switch(e.options.strategy){case"memory":return{...e,currentBufferChunks:[]};case"stream":{let t=null,a=new ReadableStream({start:r=>{t=r}});return{...e,currentStream:a,streamController:t}}case"temp":{let t=vd(e.options.tempDir,`upload-${yd()}`),a=gd(t),r=async()=>{try{let{unlink:n}=await import("node:fs/promises");await n(t)}catch(n){console.warn(`Failed to cleanup temp file: ${t}`,n)}};return{...e,currentTempPath:t,currentWriteStream:a,cleanupTasks:[...e.cleanupTasks,r]}}default:{let{ValidationError:t}=await import("./validation-error-Q6IOTN4C.js");throw new t("Invalid file processing strategy")}}}async function Rd(e){return e.currentField?e.currentFilename!==void 0?_d(e):Nd(e):Gr(e)}async function _d(e){if(!e.currentField||e.currentFilename===void 0)return Gr(e);let t,a,r;switch(e.options.strategy){case"memory":a=Buffer.concat(e.currentBufferChunks),t=Eu.from(a);break;case"stream":e.streamController&&e.streamController.close(),t=e.currentStream;break;case"temp":e.currentWriteStream&&await Su(e.currentWriteStream),r=e.currentTempPath,t=Eu.from(Buffer.alloc(0));break;default:{let{ValidationError:s}=await import("./validation-error-Q6IOTN4C.js");throw new s("Invalid file finalization strategy")}}let n={filename:e.currentFilename,fieldname:e.currentField,mimetype:e.currentMimetype,size:e.currentContentLength,stream:t,buffer:a,tempPath:r},i=xu(e.files,e.currentField,n);return{...Gr(e),files:i}}function Nd(e){if(!e.currentField)return Gr(e);let t=Buffer.concat(e.currentBufferChunks).toString("utf8"),a=xu(e.fields,e.currentField,t);return{...Gr(e),fields:a}}function Gr(e){return{...e,currentField:null,currentFilename:void 0,currentContentLength:0,currentBufferChunks:[],currentStream:null,streamController:null,currentTempPath:null,currentWriteStream:null}}function xu(e,t,a){let r=new Map(e),n=r.get(t)||[];return r.set(t,[...n,a]),r}async function Pd(e){if(!e.hasFoundValidBoundary){let{ValidationError:r}=await import("./validation-error-Q6IOTN4C.js");throw new r("No valid multipart boundary found")}if(e.hasFoundValidBoundary&&!e.hasProcessedAnyPart){let{ValidationError:r}=await import("./validation-error-Q6IOTN4C.js");throw new r("Empty multipart request")}let t={};for(let[r,n]of e.fields.entries())t[r]=n.length===1?n[0]:n;let a={};for(let[r,n]of e.files.entries())a[r]=n.length===1?n[0]:n;return{fields:t,files:a}}async function Dd(e){await Promise.allSettled(e.cleanupTasks.map(t=>t())),e.streamController&&e.streamController.close(),e.currentWriteStream&&await Su(e.currentWriteStream)}async function Ld(e,t){return new Promise((a,r)=>{e.write(t,n=>{n?r(n):a()})})}async function Su(e){return new Promise(t=>{e.end(()=>t())})}async function Tu(e,t={}){let a=e.headers["content-type"]||"",r=gu(a);if(!r){let{UnsupportedMediaTypeError:i}=await import("./unsupported-media-type-error-KJMHH5CY.js");throw new i("Missing boundary in multipart content-type",{receivedContentType:a,expectedFormat:"multipart/form-data; boundary=..."})}let n=Ed(r,t);n.currentFilename!==void 0&&(n=await Bd(n));try{for await(let i of e)n=await xd(n,i);return Pd(n)}finally{await Dd(n)}}var Qr="Content-Type",Pt={json:512*1024,form:1024*1024,text:5*1024*1024,multipart:{maxFileSize:50*1024*1024,maxTotalSize:100*1024*1024,maxFiles:10,maxFieldSize:1024*1024},raw:10*1024*1024};function kd(e){let t=e.url||"/",a=e.headers.host||"localhost",n=`${e.socket&&e.socket.encrypted?"https":"http"}://${a}${t.startsWith("/")?"":"/"}${t}`;try{let i=new URL(n),s=i.pathname,o={};return i.searchParams.forEach((u,l)=>{o[l]!==void 0?Array.isArray(o[l])?o[l].push(u):o[l]=[o[l],u]:o[l]=u}),{path:s,url:i,query:o}}catch(i){throw console.warn(`Invalid URL: ${n}`,i),new La(`Invalid URL: ${n}`)}}function Ud(e){return"stream"in e||"httpVersionMajor"in e&&e.httpVersionMajor===2}function Fd(e){let t=e.socket&&e.socket.encrypted,a=e.headers["x-forwarded-proto"];return a?Array.isArray(a)?a[0]?.split(",")[0]?.trim()||"http":a.split(",")[0]?.trim()||"http":t?"https":"http"}async function bu(e,t,a={}){let{path:r,url:n,query:i}=kd(e),s=e.method||"GET",o=Ud(e),u=Fd(e),l={},f={...a.initialState||{}},c={sent:!1},g={request:Od(e,{path:r,url:n,query:i,params:l,method:s,isHttp2:o,protocol:u}),response:{},state:f};return g.response=Md(t,c,g),a.parseBody&&await Yd(e,g,a),g}function Od(e,t){return{raw:e,...t,header:Iu(e),headers:Vd(e),body:void 0}}function Iu(e){return t=>{let a=e.headers[t.toLowerCase()];return Array.isArray(a)?a.join(", "):a||void 0}}function Vd(e){let t=Iu(e);return a=>a&&Array.isArray(a)&&a.length>0?a.reduce((r,n)=>(r[n]=t(n),r),{}):Object.entries(e.headers).reduce((r,[n,i])=>(r[n]=Array.isArray(i)?i.join(", "):i||void 0,r),{})}function Md(e,t,a){return{raw:e,get sent(){return t.sent},status:Kd(e,t,a),header:qd(e,t,a),headers:Hd(e,t,a),type:zd(e,t,a),json:Gd(e,t),text:Qd(e,t),html:Wd(e,t),redirect:jd(e,t),stream:$d(e,t)}}function Kd(e,t,a){return function(n){if(t.sent)throw new ct;return e.statusCode=n,a.response}}function qd(e,t,a){return function(n,i){if(t.sent)throw new zr;return e.setHeader(n,i),a.response}}function Hd(e,t,a){return function(n){if(t.sent)throw new zr;for(let[i,s]of Object.entries(n))e.setHeader(i,s);return a.response}}function zd(e,t,a){return function(n){if(t.sent)throw new Da;return e.setHeader(Qr,n),a.response}}function Gd(e,t){return function(r,n){if(t.sent)throw new ct;n!==void 0&&(e.statusCode=n),e.setHeader(Qr,"application/json"),e.end(JSON.stringify(r)),t.sent=!0}}function Qd(e,t){return function(r,n){if(t.sent)throw new ct;n!==void 0&&(e.statusCode=n),e.setHeader(Qr,"text/plain"),e.end(r),t.sent=!0}}function Wd(e,t){return function(r,n){if(t.sent)throw new ct;n!==void 0&&(e.statusCode=n),e.setHeader(Qr,"text/html"),e.end(r),t.sent=!0}}function jd(e,t){return function(r,n=302){if(t.sent)throw new ct;e.statusCode=n,e.setHeader("Location",r),e.end(),t.sent=!0}}function $d(e,t){return function(r,n={}){if(t.sent)throw new ct;if(n.status!==void 0&&(e.statusCode=n.status),n.contentType&&e.setHeader(Qr,n.contentType),n.headers)for(let[i,s]of Object.entries(n.headers))e.setHeader(i,s);r.pipe(e),r.on("end",()=>{t.sent=!0}),r.on("error",i=>{console.error("Stream error:",i),t.sent||(e.statusCode=500,e.end("Stream error"),t.sent=!0)})}}async function Yd(e,t,a={}){if(Xd(e.method))return;let r=e.headers["content-type"]||"",n=parseInt(e.headers["content-length"]||"0",10);if(n===0)return;let i={json:a.bodyLimits?.json??Pt.json,form:a.bodyLimits?.form??Pt.form,text:a.bodyLimits?.text??Pt.text,raw:a.bodyLimits?.raw??Pt.raw,multipart:{maxFileSize:a.bodyLimits?.multipart?.maxFileSize??Pt.multipart.maxFileSize,maxFiles:a.bodyLimits?.multipart?.maxFiles??Pt.multipart.maxFiles,maxFieldSize:a.bodyLimits?.multipart?.maxFieldSize??Pt.multipart.maxFieldSize,maxTotalSize:a.bodyLimits?.multipart?.maxTotalSize??Pt.multipart.maxTotalSize}};try{if(r.includes("application/json")){if(n>i.json)throw new Error(`JSON body too large: ${n} > ${i.json} bytes`);await Zd(e,t)}else if(r.includes("application/x-www-form-urlencoded")){if(n>i.form)throw new Error(`Form body too large: ${n} > ${i.form} bytes`);await Jd(e,t)}else if(r.includes("text/")){if(n>i.text)throw new Error(`Text body too large: ${n} > ${i.text} bytes`);await tp(e,t)}else if(Cu(r))await rp(e,t,i.multipart);else{if(n>i.raw)throw new Error(`Request body too large: ${n} > ${i.raw} bytes`);return}}catch(s){let o=r.includes("multipart")?"multipart_parse_error":"body_read_error";ka(t,o,"Error reading request body",s)}}function Xd(e){return["GET","HEAD","OPTIONS"].includes(e||"GET")}async function Zd(e,t){let a=await ti(e);if(!a){console.warn("Empty body, skipping JSON parsing");return}if(a.trim()==="null"){console.warn('Body is the string "null"'),t.request.body=null;return}try{let r=JSON.parse(a);t.request.body=r}catch(r){t.request.body=null,ka(t,"json_parse_error","Invalid JSON in request body",r)}}async function Jd(e,t){let a=await ti(e);if(a)try{t.request.body=ep(a)}catch(r){t.request.body=null,ka(t,"form_parse_error","Invalid form data in request body",r)}}function ep(e){let t=new URLSearchParams(e),a={};return t.forEach((r,n)=>{a[n]!==void 0?Array.isArray(a[n])?a[n].push(r):a[n]=[a[n],r]:a[n]=r}),a}async function tp(e,t){let a=await ti(e);a&&(t.request.body=a)}async function rp(e,t,a){try{let r=a||Pt.multipart,n=await Tu(e,{strategy:"stream",maxFileSize:r.maxFileSize,maxFiles:r.maxFiles,maxFieldSize:r.maxFieldSize});t.request.multipart=n,t.request.files=n.files,t.request.body=n.fields}catch(r){t.request.body=null,ka(t,"multipart_parse_error","Failed to parse multipart data",r)}}function ka(e,t,a,r){let n={type:t,message:a,error:r};e.state._bodyError=n}async function ti(e){return new Promise((t,a)=>{let r=[];e.on("data",n=>{r.push(Buffer.isBuffer(n)?n:Buffer.from(n))}),e.on("end",()=>{t(Buffer.concat(r).toString("utf8"))}),e.on("error",n=>{a(n)})})}var sr=class extends Ge{constructor(t,a=void 0,r=void 0){super("NOT_FOUND",t,404,r??Xe(),a)}};function ap(e){return e instanceof Ge}function wu(e){if(ap(e))return{type:e.type,title:e.title,status:e.status,correlationId:e.correlationId,timestamp:e.timestamp.toISOString(),details:e.details};let t=ja(),a;e instanceof Error?a=e.message:e==null?a="Unknown error occurred":a=String(e);let r=new Ar("Internal Server Error",{originalMessage:a},t);return{type:r.type,title:r.title,status:r.status,correlationId:r.correlationId,timestamp:r.timestamp.toISOString(),details:r.details}}function Au(e){return e("x-correlation-id")??ja()}function Bu(e,t){e("x-correlation-id",t)}function Ru(e={}){let{debug:t=!1}=e;return{name:"ErrorBoundary",execute:async(r,n)=>{try{await n()}catch(i){if(r.response.sent){t&&console.error("Error occurred after response was sent:",i);return}t&&console.error("Error boundary caught error:",i);let s=Au(r.request.header),o=wu(i);o.correlationId=s,Bu(r.response.header,s),r.response.status(o.status).json(o)}},debug:t}}function _u(e){return async(t,a)=>{try{let r=await bu(t,a,{parseBody:!0}),i=[Ru(),...e.middleware],s=lr(i);await yu(r,async()=>{await s(r,async()=>{if(!r.response.sent&&(await e.router.handleRequest(r),!r.response.sent))throw new sr(`Route not found: ${r.request.method} ${r.request.path}`)})})}catch(r){console.error("Error creating context:",r),a.writeHead(500,{"Content-Type":"application/json"}),a.end(JSON.stringify({error:"Internal Server Error",message:"Failed to process request"}))}}}async function np(e){if(!e.enabled)return{};let{keyFile:t,certFile:a}=e,r=process.env.NODE_ENV==="development",n=!t||!a;if(n&&r)return await hu();if(n)throw new Error("HTTP/2 requires SSL certificates. Provide keyFile and certFile in http2 options. In development, set NODE_ENV=development to generate them automatically.");return{keyFile:t,certFile:a}}function ip(e,t){if(!e)return Nu.createServer();let a={allowHTTP1:!0};try{t.keyFile&&(a.key=ri.readFileSync(t.keyFile)),t.certFile&&(a.cert=ri.readFileSync(t.certFile))}catch(r){throw new Error(`Failed to read certificate files: ${r instanceof Error?r.message:String(r)}`)}return Pu.createSecureServer(a)}function sp(e,t,a,r){return new Promise((n,i)=>{e.listen(t,a,()=>{let o=`${r?"https":"http"}://${a}:${t}`;console.log(`
1446
37
  \u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}
1447
38
 
1448
39
  \u26A1 BlaizeJS DEVELOPMENT SERVER HOT AND READY \u26A1
1449
40
 
1450
- \u{1F680} Server: ${url}
41
+ \u{1F680} Server: ${o}
1451
42
  \u{1F525} Hot Reload: Enabled
1452
43
  \u{1F6E0}\uFE0F Mode: Development
1453
44
 
1454
45
  Time to build something amazing! \u{1F680}
1455
46
 
1456
47
  \u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}\u{1F525}
1457
- `);
1458
- resolve3();
1459
- });
1460
- server.on("error", (err) => {
1461
- console.error("Server error:", err);
1462
- reject(err);
1463
- });
1464
- });
1465
- }
1466
- async function initializePlugins(serverInstance) {
1467
- for (const plugin of serverInstance.plugins) {
1468
- if (typeof plugin.initialize === "function") {
1469
- await plugin.initialize(serverInstance);
1470
- }
1471
- }
1472
- }
1473
- async function startServer(serverInstance, serverOptions) {
1474
- if (serverInstance.server) {
1475
- return;
1476
- }
1477
- try {
1478
- const port = serverOptions.port;
1479
- const host = serverOptions.host;
1480
- await initializePlugins(serverInstance);
1481
- const http2Options = serverOptions.http2 || { enabled: true };
1482
- const isHttp2 = !!http2Options.enabled;
1483
- const certOptions = await prepareCertificates(http2Options);
1484
- if (serverOptions.http2 && certOptions.keyFile && certOptions.certFile) {
1485
- serverOptions.http2.keyFile = certOptions.keyFile;
1486
- serverOptions.http2.certFile = certOptions.certFile;
1487
- }
1488
- const server = createServerInstance(isHttp2, certOptions);
1489
- serverInstance.server = server;
1490
- serverInstance.port = port;
1491
- serverInstance.host = host;
1492
- const requestHandler = createRequestHandler(serverInstance);
1493
- server.on("request", requestHandler);
1494
- await listenOnPort(server, port, host, isHttp2);
1495
- } catch (error) {
1496
- console.error("Failed to start server:", error);
1497
- throw error;
1498
- }
1499
- }
1500
-
1501
- // src/server/stop.ts
1502
- var isShuttingDown = false;
1503
- async function stopServer(serverInstance, options = {}) {
1504
- const server = serverInstance.server;
1505
- const events = serverInstance.events;
1506
- if (isShuttingDown) {
1507
- console.log("\u26A0\uFE0F Shutdown already in progress, ignoring duplicate shutdown request");
1508
- return;
1509
- }
1510
- if (!server) {
1511
- return;
1512
- }
1513
- isShuttingDown = true;
1514
- const timeout = options.timeout || 5e3;
1515
- try {
1516
- if (options.onStopping) {
1517
- await options.onStopping();
1518
- }
1519
- events.emit("stopping");
1520
- if (serverInstance.router && typeof serverInstance.router.close === "function") {
1521
- console.log("\u{1F50C} Closing router watchers...");
1522
- try {
1523
- await Promise.race([
1524
- serverInstance.router.close(),
1525
- new Promise(
1526
- (_, reject) => setTimeout(() => reject(new Error("Router close timeout")), 2e3)
1527
- )
1528
- ]);
1529
- console.log("\u2705 Router watchers closed");
1530
- } catch (error) {
1531
- console.error("\u274C Error closing router watchers:", error);
1532
- }
1533
- }
1534
- try {
1535
- await Promise.race([
1536
- serverInstance.pluginManager.onServerStop(serverInstance, server),
1537
- new Promise(
1538
- (_, reject) => setTimeout(() => reject(new Error("Plugin stop timeout")), 2e3)
1539
- )
1540
- ]);
1541
- } catch (error) {
1542
- console.error("\u274C Plugin stop timeout:", error);
1543
- }
1544
- const closePromise = new Promise((resolve3, reject) => {
1545
- server.close((err) => {
1546
- if (err) return reject(err);
1547
- resolve3();
1548
- });
1549
- });
1550
- const timeoutPromise = new Promise((_, reject) => {
1551
- setTimeout(() => {
1552
- reject(new Error("Server shutdown timeout"));
1553
- }, timeout);
1554
- });
1555
- await Promise.race([closePromise, timeoutPromise]);
1556
- try {
1557
- await Promise.race([
1558
- serverInstance.pluginManager.terminatePlugins(serverInstance),
1559
- new Promise(
1560
- (_, reject) => setTimeout(() => reject(new Error("Plugin terminate timeout")), 1e3)
1561
- )
1562
- ]);
1563
- } catch (error) {
1564
- console.error("\u274C Plugin terminate timeout:", error);
1565
- }
1566
- if (options.onStopped) {
1567
- await options.onStopped();
1568
- }
1569
- events.emit("stopped");
1570
- serverInstance.server = null;
1571
- console.log("\u2705 Graceful shutdown completed");
1572
- isShuttingDown = false;
1573
- } catch (error) {
1574
- isShuttingDown = false;
1575
- console.error("\u26A0\uFE0F Shutdown error (forcing exit):", error);
1576
- if (server && typeof server.close === "function") {
1577
- server.close();
1578
- }
1579
- if (process.env.NODE_ENV === "development") {
1580
- console.log("\u{1F504} Forcing exit for development restart...");
1581
- process.exit(0);
1582
- }
1583
- events.emit("error", error);
1584
- throw error;
1585
- }
1586
- }
1587
- function registerSignalHandlers(stopFn) {
1588
- const isDevelopment = process.env.NODE_ENV === "development";
1589
- if (isDevelopment) {
1590
- const sigintHandler = () => {
1591
- console.log("\u{1F4E4} SIGINT received, forcing exit for development restart...");
1592
- process.exit(0);
1593
- };
1594
- const sigtermHandler = () => {
1595
- console.log("\u{1F4E4} SIGTERM received, forcing exit for development restart...");
1596
- process.exit(0);
1597
- };
1598
- process.on("SIGINT", sigintHandler);
1599
- process.on("SIGTERM", sigtermHandler);
1600
- return {
1601
- unregister: () => {
1602
- process.removeListener("SIGINT", sigintHandler);
1603
- process.removeListener("SIGTERM", sigtermHandler);
1604
- }
1605
- };
1606
- } else {
1607
- const sigintHandler = () => {
1608
- console.log("\u{1F4E4} SIGINT received, starting graceful shutdown...");
1609
- stopFn().catch(console.error);
1610
- };
1611
- const sigtermHandler = () => {
1612
- console.log("\u{1F4E4} SIGTERM received, starting graceful shutdown...");
1613
- stopFn().catch(console.error);
1614
- };
1615
- process.on("SIGINT", sigintHandler);
1616
- process.on("SIGTERM", sigtermHandler);
1617
- return {
1618
- unregister: () => {
1619
- process.removeListener("SIGINT", sigintHandler);
1620
- process.removeListener("SIGTERM", sigtermHandler);
1621
- }
1622
- };
1623
- }
1624
- }
1625
-
1626
- // src/server/validation.ts
1627
- import { z } from "zod";
1628
- var middlewareSchema = z.custom(
1629
- (data) => data !== null && typeof data === "object" && "execute" in data && typeof data.execute === "function",
1630
- {
1631
- message: "Expected middleware to have an execute function"
1632
- }
1633
- );
1634
- var pluginSchema = z.custom(
1635
- (data) => data !== null && typeof data === "object" && "register" in data && typeof data.register === "function",
1636
- {
1637
- message: "Expected a valid plugin object with a register method"
1638
- }
1639
- );
1640
- var http2Schema = z.object({
1641
- enabled: z.boolean().optional().default(true),
1642
- keyFile: z.string().optional(),
1643
- certFile: z.string().optional()
1644
- }).refine(
1645
- (data) => {
1646
- if (data.enabled && process.env.NODE_ENV === "production") {
1647
- return data.keyFile && data.certFile;
1648
- }
1649
- return true;
1650
- },
1651
- {
1652
- message: "When HTTP/2 is enabled (outside of development mode), both keyFile and certFile must be provided"
1653
- }
1654
- );
1655
- var serverOptionsSchema = z.object({
1656
- port: z.number().int().positive().optional().default(3e3),
1657
- host: z.string().optional().default("localhost"),
1658
- routesDir: z.string().optional().default("./routes"),
1659
- http2: http2Schema.optional().default({
1660
- enabled: true
1661
- }),
1662
- middleware: z.array(middlewareSchema).optional().default([]),
1663
- plugins: z.array(pluginSchema).optional().default([])
1664
- });
1665
- function validateServerOptions(options) {
1666
- try {
1667
- return serverOptionsSchema.parse(options);
1668
- } catch (error) {
1669
- if (error instanceof z.ZodError) {
1670
- const formattedError = error.format();
1671
- throw new Error(`Invalid server options: ${JSON.stringify(formattedError, null, 2)}`);
1672
- }
1673
- throw new Error(`Invalid server options: ${String(error)}`);
1674
- }
1675
- }
1676
-
1677
- // src/plugins/lifecycle.ts
1678
- function createPluginLifecycleManager(options = {}) {
1679
- const { continueOnError = true, debug = false, onError } = options;
1680
- function log(message, ...args) {
1681
- if (debug) {
1682
- console.log(`[PluginLifecycle] ${message}`, ...args);
1683
- }
1684
- }
1685
- function handleError(plugin, phase, error) {
1686
- const errorMessage = `Plugin ${plugin.name} failed during ${phase}: ${error.message}`;
1687
- if (onError) {
1688
- onError(plugin, phase, error);
1689
- } else {
1690
- console.error(errorMessage, error);
1691
- }
1692
- if (!continueOnError) {
1693
- throw new Error(errorMessage);
1694
- }
1695
- }
1696
- return {
1697
- /**
1698
- * Initialize all plugins
1699
- */
1700
- async initializePlugins(server) {
1701
- log("Initializing plugins...");
1702
- for (const plugin of server.plugins) {
1703
- if (plugin.initialize) {
1704
- try {
1705
- log(`Initializing plugin: ${plugin.name}`);
1706
- await plugin.initialize(server);
1707
- } catch (error) {
1708
- handleError(plugin, "initialize", error);
1709
- }
1710
- }
1711
- }
1712
- log(`Initialized ${server.plugins.length} plugins`);
1713
- },
1714
- /**
1715
- * Terminate all plugins in reverse order
1716
- */
1717
- async terminatePlugins(server) {
1718
- log("Terminating plugins...");
1719
- const pluginsToTerminate = [...server.plugins].reverse();
1720
- for (const plugin of pluginsToTerminate) {
1721
- if (plugin.terminate) {
1722
- try {
1723
- log(`Terminating plugin: ${plugin.name}`);
1724
- await plugin.terminate(server);
1725
- } catch (error) {
1726
- handleError(plugin, "terminate", error);
1727
- }
1728
- }
1729
- }
1730
- log(`Terminated ${pluginsToTerminate.length} plugins`);
1731
- },
1732
- /**
1733
- * Notify plugins that the server has started
1734
- */
1735
- async onServerStart(server, httpServer) {
1736
- log("Notifying plugins of server start...");
1737
- for (const plugin of server.plugins) {
1738
- if (plugin.onServerStart) {
1739
- try {
1740
- log(`Notifying plugin of server start: ${plugin.name}`);
1741
- await plugin.onServerStart(httpServer);
1742
- } catch (error) {
1743
- handleError(plugin, "onServerStart", error);
1744
- }
1745
- }
1746
- }
1747
- },
1748
- /**
1749
- * Notify plugins that the server is stopping
1750
- */
1751
- async onServerStop(server, httpServer) {
1752
- log("Notifying plugins of server stop...");
1753
- const pluginsToNotify = [...server.plugins].reverse();
1754
- for (const plugin of pluginsToNotify) {
1755
- if (plugin.onServerStop) {
1756
- try {
1757
- log(`Notifying plugin of server stop: ${plugin.name}`);
1758
- await plugin.onServerStop(httpServer);
1759
- } catch (error) {
1760
- handleError(plugin, "onServerStop", error);
1761
- }
1762
- }
1763
- }
1764
- }
1765
- };
1766
- }
1767
-
1768
- // src/plugins/errors.ts
1769
- var PluginValidationError = class extends Error {
1770
- constructor(pluginName, message) {
1771
- super(`Plugin validation error${pluginName ? ` for "${pluginName}"` : ""}: ${message}`);
1772
- this.pluginName = pluginName;
1773
- this.name = "PluginValidationError";
1774
- }
1775
- };
1776
-
1777
- // src/plugins/validation.ts
1778
- var RESERVED_NAMES = /* @__PURE__ */ new Set([
1779
- "core",
1780
- "server",
1781
- "router",
1782
- "middleware",
1783
- "context",
1784
- "blaize",
1785
- "blaizejs"
1786
- ]);
1787
- var VALID_NAME_PATTERN = /^[a-z]([a-z0-9-]*[a-z0-9])?$/;
1788
- var VALID_VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[a-zA-Z0-9-.]+)?(?:\+[a-zA-Z0-9-.]+)?$/;
1789
- function validatePlugin(plugin, options = {}) {
1790
- const { requireVersion = true, validateNameFormat = true, checkReservedNames = true } = options;
1791
- if (!plugin || typeof plugin !== "object") {
1792
- throw new PluginValidationError("", "Plugin must be an object");
1793
- }
1794
- const p = plugin;
1795
- if (!p.name || typeof p.name !== "string") {
1796
- throw new PluginValidationError("", "Plugin must have a name (string)");
1797
- }
1798
- if (validateNameFormat && !VALID_NAME_PATTERN.test(p.name)) {
1799
- throw new PluginValidationError(
1800
- p.name,
1801
- "Plugin name must be lowercase letters, numbers, and hyphens only"
1802
- );
1803
- }
1804
- if (checkReservedNames && RESERVED_NAMES.has(p.name.toLowerCase())) {
1805
- throw new PluginValidationError(p.name, `Plugin name "${p.name}" is reserved`);
1806
- }
1807
- if (requireVersion) {
1808
- if (!p.version || typeof p.version !== "string") {
1809
- throw new PluginValidationError(p.name, "Plugin must have a version (string)");
1810
- }
1811
- if (!VALID_VERSION_PATTERN.test(p.version)) {
1812
- throw new PluginValidationError(
1813
- p.name,
1814
- 'Plugin version must follow semantic versioning (e.g., "1.0.0")'
1815
- );
1816
- }
1817
- }
1818
- if (!p.register || typeof p.register !== "function") {
1819
- throw new PluginValidationError(p.name, "Plugin must have a register method (function)");
1820
- }
1821
- const lifecycleMethods = ["initialize", "terminate", "onServerStart", "onServerStop"];
1822
- for (const method of lifecycleMethods) {
1823
- if (p[method] && typeof p[method] !== "function") {
1824
- throw new PluginValidationError(p.name, `Plugin ${method} must be a function if provided`);
1825
- }
1826
- }
1827
- }
1828
-
1829
- // src/router/discovery/cache.ts
1830
- import * as crypto from "node:crypto";
1831
- import * as fs3 from "node:fs/promises";
1832
- import { createRequire } from "node:module";
1833
- import * as path3 from "node:path";
1834
-
1835
- // src/router/discovery/loader.ts
1836
- async function dynamicImport(filePath) {
1837
- const cacheBuster = `?t=${Date.now()}`;
1838
- const importPath = filePath + cacheBuster;
1839
- try {
1840
- const module = await import(importPath);
1841
- console.log(`\u2705 Successfully imported module`);
1842
- return module;
1843
- } catch (error) {
1844
- const errorMessage = error instanceof Error ? error.message : String(error);
1845
- console.log(`\u26A0\uFE0F Error importing with cache buster, trying original path:`, errorMessage);
1846
- return import(filePath);
1847
- }
1848
- }
1849
- async function loadRouteModule(filePath, basePath) {
1850
- try {
1851
- const parsedRoute = parseRoutePath(filePath, basePath);
1852
- const module = await dynamicImport(filePath);
1853
- console.log("\u{1F4E6} Module exports:", Object.keys(module));
1854
- const routes = [];
1855
- if (module.default && typeof module.default === "object") {
1856
- const route = {
1857
- ...module.default,
1858
- path: parsedRoute.routePath
1859
- };
1860
- routes.push(route);
1861
- }
1862
- Object.entries(module).forEach(([exportName, exportValue]) => {
1863
- if (exportName === "default" || !exportValue || typeof exportValue !== "object") {
1864
- return;
1865
- }
1866
- const potentialRoute = exportValue;
1867
- if (isValidRoute(potentialRoute)) {
1868
- const route = {
1869
- ...potentialRoute,
1870
- // Use the route's own path if it has one, otherwise derive from file
1871
- path: parsedRoute.routePath
1872
- };
1873
- routes.push(route);
1874
- }
1875
- });
1876
- if (routes.length === 0) {
1877
- console.warn(`Route file ${filePath} does not export any valid route definitions`);
1878
- return [];
1879
- }
1880
- console.log(`\u2705 Successfully Loaded ${routes.length} route(s)`);
1881
- return routes;
1882
- } catch (error) {
1883
- console.error(`Failed to load route module ${filePath}:`, error);
1884
- return [];
1885
- }
1886
- }
1887
- function isValidRoute(obj) {
1888
- if (!obj || typeof obj !== "object") {
1889
- return false;
1890
- }
1891
- const httpMethods = ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"];
1892
- const hasHttpMethod = httpMethods.some(
1893
- (method) => obj[method] && typeof obj[method] === "object" && obj[method].handler
1894
- );
1895
- return hasHttpMethod;
1896
- }
1897
-
1898
- // src/router/discovery/cache.ts
1899
- var fileRouteCache = /* @__PURE__ */ new Map();
1900
- async function processChangedFile(filePath, routesDir, updateCache = true) {
1901
- const stat3 = await fs3.stat(filePath);
1902
- const lastModified = stat3.mtime.getTime();
1903
- const cachedEntry = fileRouteCache.get(filePath);
1904
- if (updateCache && cachedEntry && cachedEntry.timestamp === lastModified) {
1905
- return cachedEntry.routes;
1906
- }
1907
- invalidateModuleCache(filePath);
1908
- const routes = await loadRouteModule(filePath, routesDir);
1909
- if (updateCache) {
1910
- const hash = hashRoutes(routes);
1911
- fileRouteCache.set(filePath, {
1912
- routes,
1913
- timestamp: lastModified,
1914
- hash
1915
- });
1916
- }
1917
- return routes;
1918
- }
1919
- function hasRouteContentChanged(filePath, newRoutes) {
1920
- const cachedEntry = fileRouteCache.get(filePath);
1921
- if (!cachedEntry) {
1922
- return true;
1923
- }
1924
- const newHash = hashRoutes(newRoutes);
1925
- return cachedEntry.hash !== newHash;
1926
- }
1927
- function clearFileCache(filePath) {
1928
- if (filePath) {
1929
- fileRouteCache.delete(filePath);
1930
- } else {
1931
- fileRouteCache.clear();
1932
- }
1933
- }
1934
- function hashRoutes(routes) {
1935
- const routeData = routes.map((route) => ({
1936
- path: route.path,
1937
- methods: Object.keys(route).filter((key) => key !== "path").sort().map((method) => {
1938
- const methodDef = route[method];
1939
- const handlerString = methodDef?.handler ? methodDef.handler.toString() : null;
1940
- return {
1941
- method,
1942
- // Include handler function string for change detection
1943
- handler: handlerString,
1944
- // Include middleware if present
1945
- middleware: methodDef?.middleware ? methodDef.middleware.length : 0,
1946
- // Include schema structure (but not full serialization which can be unstable)
1947
- hasSchema: !!methodDef?.schema,
1948
- schemaKeys: methodDef?.schema ? Object.keys(methodDef.schema).sort() : []
1949
- };
1950
- })
1951
- }));
1952
- const dataString = JSON.stringify(routeData);
1953
- const hash = crypto.createHash("md5").update(dataString).digest("hex");
1954
- return hash;
1955
- }
1956
- function invalidateModuleCache(filePath) {
1957
- try {
1958
- const absolutePath = path3.resolve(filePath);
1959
- if (typeof __require !== "undefined") {
1960
- delete __require.cache[absolutePath];
1961
- try {
1962
- const resolvedPath = __require.resolve(absolutePath);
1963
- delete __require.cache[resolvedPath];
1964
- } catch (resolveError) {
1965
- const errorMessage = resolveError instanceof Error ? resolveError.message : String(resolveError);
1966
- console.log(`\u26A0\uFE0F Could not resolve path: ${errorMessage}`);
1967
- }
1968
- } else {
1969
- try {
1970
- const require2 = createRequire(import.meta.url);
1971
- delete require2.cache[absolutePath];
1972
- try {
1973
- const resolvedPath = require2.resolve(absolutePath);
1974
- delete require2.cache[resolvedPath];
1975
- } catch {
1976
- console.log(`\u26A0\uFE0F Could not resolve ESM path`);
1977
- }
1978
- } catch {
1979
- console.log(`\u26A0\uFE0F createRequire not available in pure ESM`);
1980
- }
1981
- }
1982
- } catch (error) {
1983
- console.log(`\u26A0\uFE0F Error during module cache invalidation for ${filePath}:`, error);
1984
- }
1985
- }
1986
-
1987
- // src/router/discovery/parallel.ts
1988
- import * as os from "node:os";
1989
-
1990
- // src/router/discovery/finder.ts
1991
- import * as fs4 from "node:fs/promises";
1992
- import * as path4 from "node:path";
1993
- async function findRouteFiles(routesDir, options = {}) {
1994
- const absoluteDir = path4.isAbsolute(routesDir) ? routesDir : path4.resolve(process.cwd(), routesDir);
1995
- console.log("Creating router with routes directory:", absoluteDir);
1996
- try {
1997
- const stats = await fs4.stat(absoluteDir);
1998
- if (!stats.isDirectory()) {
1999
- throw new Error(`Route directory is not a directory: ${absoluteDir}`);
2000
- }
2001
- } catch (error) {
2002
- if (error.code === "ENOENT") {
2003
- throw new Error(`Route directory not found: ${absoluteDir}`);
2004
- }
2005
- throw error;
2006
- }
2007
- const routeFiles = [];
2008
- const ignore = options.ignore || ["node_modules", ".git"];
2009
- async function scanDirectory(dir) {
2010
- const entries = await fs4.readdir(dir, { withFileTypes: true });
2011
- for (const entry of entries) {
2012
- const fullPath = path4.join(dir, entry.name);
2013
- if (entry.isDirectory() && ignore.includes(entry.name)) {
2014
- continue;
2015
- }
2016
- if (entry.isDirectory()) {
2017
- await scanDirectory(fullPath);
2018
- } else if (isRouteFile(entry.name)) {
2019
- routeFiles.push(fullPath);
2020
- }
2021
- }
2022
- }
2023
- await scanDirectory(absoluteDir);
2024
- return routeFiles;
2025
- }
2026
- function isRouteFile(filename) {
2027
- return !filename.startsWith("_") && (filename.endsWith(".ts") || filename.endsWith(".js"));
2028
- }
2029
-
2030
- // src/router/discovery/parallel.ts
2031
- async function processFilesInParallel(filePaths, processor, concurrency = Math.max(1, Math.floor(os.cpus().length / 2))) {
2032
- const chunks = chunkArray(filePaths, concurrency);
2033
- const results = [];
2034
- for (const chunk of chunks) {
2035
- const chunkResults = await Promise.allSettled(chunk.map((filePath) => processor(filePath)));
2036
- const successfulResults = chunkResults.filter((result) => result.status === "fulfilled").map((result) => result.value);
2037
- results.push(...successfulResults);
2038
- }
2039
- return results;
2040
- }
2041
- async function loadInitialRoutesParallel(routesDir) {
2042
- const files = await findRouteFiles(routesDir);
2043
- const routeArrays = await processFilesInParallel(
2044
- files,
2045
- (filePath) => processChangedFile(filePath, routesDir)
2046
- );
2047
- return routeArrays.flat();
2048
- }
2049
- function chunkArray(array, chunkSize) {
2050
- const chunks = [];
2051
- for (let i = 0; i < array.length; i += chunkSize) {
2052
- chunks.push(array.slice(i, i + chunkSize));
2053
- }
2054
- return chunks;
2055
- }
2056
-
2057
- // src/router/discovery/profiler.ts
2058
- var profilerState = {
2059
- fileChanges: 0,
2060
- totalReloadTime: 0,
2061
- averageReloadTime: 0,
2062
- slowReloads: []
2063
- };
2064
- function trackReloadPerformance(filePath, startTime) {
2065
- const duration = Date.now() - startTime;
2066
- profilerState.fileChanges++;
2067
- profilerState.totalReloadTime += duration;
2068
- profilerState.averageReloadTime = profilerState.totalReloadTime / profilerState.fileChanges;
2069
- if (duration > 100) {
2070
- profilerState.slowReloads.push({ file: filePath, time: duration });
2071
- if (profilerState.slowReloads.length > 10) {
2072
- profilerState.slowReloads.shift();
2073
- }
2074
- }
2075
- if (process.env.NODE_ENV === "development") {
2076
- const emoji = duration < 50 ? "\u26A1" : duration < 100 ? "\u{1F504}" : "\u{1F40C}";
2077
- console.log(`${emoji} Route reload: ${filePath} (${duration}ms)`);
2078
- }
2079
- }
2080
- function withPerformanceTracking(fn, filePath) {
2081
- console.log(`Tracking performance for: ${filePath}`);
2082
- return async (...args) => {
2083
- const startTime = Date.now();
2084
- try {
2085
- const result = await fn(...args);
2086
- trackReloadPerformance(filePath, startTime);
2087
- return result;
2088
- } catch (error) {
2089
- trackReloadPerformance(filePath, startTime);
2090
- throw error;
2091
- }
2092
- };
2093
- }
2094
-
2095
- // src/router/discovery/watchers.ts
2096
- import * as path5 from "node:path";
2097
- import { watch } from "chokidar";
2098
- function watchRoutes(routesDir, options = {}) {
2099
- const debounceMs = options.debounceMs || 16;
2100
- const debouncedCallbacks = /* @__PURE__ */ new Map();
2101
- function createDebouncedCallback(fn, filePath) {
2102
- return (...args) => {
2103
- const existingTimeout = debouncedCallbacks.get(filePath);
2104
- if (existingTimeout) {
2105
- clearTimeout(existingTimeout);
2106
- }
2107
- const timeoutId = setTimeout(() => {
2108
- fn(...args);
2109
- debouncedCallbacks.delete(filePath);
2110
- }, debounceMs);
2111
- debouncedCallbacks.set(filePath, timeoutId);
2112
- };
2113
- }
2114
- const routesByPath = /* @__PURE__ */ new Map();
2115
- async function loadInitialRoutes() {
2116
- try {
2117
- const files = await findRouteFiles(routesDir, {
2118
- ignore: options.ignore
2119
- });
2120
- for (const filePath of files) {
2121
- await loadAndNotify(filePath);
2122
- }
2123
- } catch (error) {
2124
- handleError(error);
2125
- }
2126
- }
2127
- async function loadAndNotify(filePath) {
2128
- try {
2129
- const existingRoutes = routesByPath.get(filePath);
2130
- const newRoutes = await processChangedFile(filePath, routesDir, false);
2131
- if (!newRoutes || newRoutes.length === 0) {
2132
- return;
2133
- }
2134
- if (existingRoutes && !hasRouteContentChanged(filePath, newRoutes)) {
2135
- return;
2136
- }
2137
- await processChangedFile(filePath, routesDir, true);
2138
- const normalizedPath = path5.normalize(filePath);
2139
- if (existingRoutes) {
2140
- routesByPath.set(filePath, newRoutes);
2141
- if (options.onRouteChanged) {
2142
- options.onRouteChanged(normalizedPath, newRoutes);
2143
- }
2144
- } else {
2145
- routesByPath.set(filePath, newRoutes);
2146
- if (options.onRouteAdded) {
2147
- options.onRouteAdded(normalizedPath, newRoutes);
2148
- }
2149
- }
2150
- } catch (error) {
2151
- console.log(`\u26A0\uFE0F Error processing file ${filePath}:`, error);
2152
- handleError(error);
2153
- }
2154
- }
2155
- function handleRemoved(filePath) {
2156
- const normalizedPath = path5.normalize(filePath);
2157
- const routes = routesByPath.get(normalizedPath);
2158
- if (routes && routes.length > 0 && options.onRouteRemoved) {
2159
- options.onRouteRemoved(normalizedPath, routes);
2160
- }
2161
- routesByPath.delete(normalizedPath);
2162
- }
2163
- function handleError(error) {
2164
- if (options.onError && error instanceof Error) {
2165
- options.onError(error);
2166
- } else {
2167
- console.error("\u26A0\uFE0F Route watcher error:", error);
2168
- }
2169
- }
2170
- const watcher = watch(routesDir, {
2171
- // Much faster response times
2172
- awaitWriteFinish: {
2173
- stabilityThreshold: 50,
2174
- // Reduced from 300ms
2175
- pollInterval: 10
2176
- // Reduced from 100ms
2177
- },
2178
- // Performance optimizations
2179
- usePolling: false,
2180
- atomic: true,
2181
- followSymlinks: false,
2182
- depth: 10,
2183
- // More aggressive ignoring
2184
- ignored: [
2185
- /(^|[/\\])\../,
2186
- /node_modules/,
2187
- /\.git/,
2188
- /\.DS_Store/,
2189
- /Thumbs\.db/,
2190
- /\.(test|spec)\.(ts|js)$/,
2191
- /\.d\.ts$/,
2192
- /\.map$/,
2193
- /~$/,
2194
- ...options.ignore || []
2195
- ]
2196
- });
2197
- watcher.on("add", (filePath) => {
2198
- const debouncedLoad = createDebouncedCallback(loadAndNotify, filePath);
2199
- debouncedLoad(filePath);
2200
- }).on("change", (filePath) => {
2201
- const debouncedLoad = createDebouncedCallback(loadAndNotify, filePath);
2202
- debouncedLoad(filePath);
2203
- }).on("unlink", (filePath) => {
2204
- const debouncedRemove = createDebouncedCallback(handleRemoved, filePath);
2205
- debouncedRemove(filePath);
2206
- }).on("error", handleError);
2207
- loadInitialRoutes().catch(handleError);
2208
- return {
2209
- close: () => {
2210
- debouncedCallbacks.forEach((timeout) => clearTimeout(timeout));
2211
- debouncedCallbacks.clear();
2212
- return watcher.close();
2213
- },
2214
- getRoutes: () => {
2215
- const allRoutes = [];
2216
- for (const routes of routesByPath.values()) {
2217
- allRoutes.push(...routes);
2218
- }
2219
- return allRoutes;
2220
- },
2221
- getRoutesByFile: () => new Map(routesByPath)
2222
- };
2223
- }
2224
-
2225
- // src/router/validation/schema.ts
2226
- import { z as z6 } from "zod";
2227
-
2228
- // src/router/validation/body.ts
2229
- import { z as z2 } from "zod";
2230
- function validateBody(body, schema) {
2231
- if (schema instanceof z2.ZodObject) {
2232
- return schema.strict().parse(body);
2233
- }
2234
- return schema.parse(body);
2235
- }
2236
-
2237
- // src/router/validation/params.ts
2238
- import { z as z3 } from "zod";
2239
- function validateParams(params, schema) {
2240
- if (schema instanceof z3.ZodObject) {
2241
- return schema.strict().parse(params);
2242
- }
2243
- return schema.parse(params);
2244
- }
2245
-
2246
- // src/router/validation/query.ts
2247
- import { z as z4 } from "zod";
2248
- function validateQuery(query, schema) {
2249
- if (schema instanceof z4.ZodObject) {
2250
- return schema.strict().parse(query);
2251
- }
2252
- return schema.parse(query);
2253
- }
2254
-
2255
- // src/router/validation/response.ts
2256
- import { z as z5 } from "zod";
2257
- function validateResponse(response, schema) {
2258
- if (schema instanceof z5.ZodObject) {
2259
- return schema.strict().parse(response);
2260
- }
2261
- return schema.parse(response);
2262
- }
2263
-
2264
- // src/router/validation/schema.ts
2265
- function createRequestValidator(schema, debug = false) {
2266
- const middlewareFn = async (ctx, next) => {
2267
- if (schema.params && ctx.request.params) {
2268
- try {
2269
- ctx.request.params = validateParams(ctx.request.params, schema.params);
2270
- } catch (error) {
2271
- const fieldErrors = extractZodFieldErrors(error);
2272
- const errorCount = fieldErrors.reduce((sum, fe) => sum + fe.messages.length, 0);
2273
- throw new ValidationError("Request validation failed", {
2274
- fields: fieldErrors,
2275
- errorCount,
2276
- section: "params"
2277
- });
2278
- }
2279
- }
2280
- if (schema.query && ctx.request.query) {
2281
- try {
2282
- ctx.request.query = validateQuery(ctx.request.query, schema.query);
2283
- } catch (error) {
2284
- const fieldErrors = extractZodFieldErrors(error);
2285
- const errorCount = fieldErrors.reduce((sum, fe) => sum + fe.messages.length, 0);
2286
- throw new ValidationError("Request validation failed", {
2287
- fields: fieldErrors,
2288
- errorCount,
2289
- section: "query"
2290
- });
2291
- }
2292
- }
2293
- if (schema.body) {
2294
- try {
2295
- ctx.request.body = validateBody(ctx.request.body, schema.body);
2296
- } catch (error) {
2297
- const fieldErrors = extractZodFieldErrors(error);
2298
- const errorCount = fieldErrors.reduce((sum, fe) => sum + fe.messages.length, 0);
2299
- throw new ValidationError("Request validation failed", {
2300
- fields: fieldErrors,
2301
- errorCount,
2302
- section: "body"
2303
- });
2304
- }
2305
- }
2306
- await next();
2307
- };
2308
- return {
2309
- name: "RequestValidator",
2310
- execute: middlewareFn,
2311
- debug
2312
- };
2313
- }
2314
- function createResponseValidator(responseSchema, debug = false) {
2315
- const middlewareFn = async (ctx, next) => {
2316
- const originalJson = ctx.response.json;
2317
- ctx.response.json = (body, status) => {
2318
- try {
2319
- const validatedBody = validateResponse(body, responseSchema);
2320
- ctx.response.json = originalJson;
2321
- return originalJson.call(ctx.response, validatedBody, status);
2322
- } catch (error) {
2323
- ctx.response.json = originalJson;
2324
- throw new InternalServerError("Response validation failed", {
2325
- responseSchema: responseSchema.description || "Unknown schema",
2326
- validationError: extractZodFieldErrors(error),
2327
- originalResponse: body
2328
- });
2329
- }
2330
- };
2331
- await next();
2332
- };
2333
- return {
2334
- name: "ResponseValidator",
2335
- execute: middlewareFn,
2336
- debug
2337
- };
2338
- }
2339
- function extractZodFieldErrors(error) {
2340
- if (error instanceof z6.ZodError) {
2341
- const fieldErrorMap = /* @__PURE__ */ new Map();
2342
- for (const issue of error.issues) {
2343
- const fieldPath = issue.path.length > 0 ? issue.path.join(".") : "root";
2344
- if (!fieldErrorMap.has(fieldPath)) {
2345
- fieldErrorMap.set(fieldPath, []);
2346
- }
2347
- fieldErrorMap.get(fieldPath).push(issue.message);
2348
- }
2349
- return Array.from(fieldErrorMap.entries()).map(([field, messages]) => ({
2350
- field,
2351
- messages
2352
- }));
2353
- }
2354
- if (error instanceof Error) {
2355
- return [{ field: "unknown", messages: [error.message] }];
2356
- }
2357
- return [{ field: "unknown", messages: [String(error)] }];
2358
- }
2359
-
2360
- // src/router/handlers/executor.ts
2361
- async function executeHandler(ctx, routeOptions, params) {
2362
- const middleware = [...routeOptions.middleware || []];
2363
- if (routeOptions.schema) {
2364
- if (routeOptions.schema.params || routeOptions.schema.query || routeOptions.schema.body) {
2365
- middleware.unshift(createRequestValidator(routeOptions.schema));
2366
- }
2367
- if (routeOptions.schema.response) {
2368
- middleware.push(createResponseValidator(routeOptions.schema.response));
2369
- }
2370
- }
2371
- const handler = compose([...middleware]);
2372
- await handler(ctx, async () => {
2373
- const result = await routeOptions.handler(ctx, params);
2374
- if (!ctx.response.sent && result !== void 0) {
2375
- ctx.response.json(result);
2376
- }
2377
- });
2378
- }
2379
-
2380
- // src/router/matching/params.ts
2381
- function extractParams(path6, pattern, paramNames) {
2382
- const match = pattern.exec(path6);
2383
- if (!match) {
2384
- return {};
2385
- }
2386
- const params = {};
2387
- for (let i = 0; i < paramNames.length; i++) {
2388
- params[paramNames[i]] = match[i + 1] || "";
2389
- }
2390
- return params;
2391
- }
2392
- function compilePathPattern(path6) {
2393
- const paramNames = [];
2394
- if (path6 === "/") {
2395
- return {
2396
- pattern: /^\/$/,
2397
- paramNames: []
2398
- };
2399
- }
2400
- let patternString = path6.replace(/([.+*?^$(){}|\\])/g, "\\$1");
2401
- patternString = patternString.replace(/\/:([^/]+)/g, (_, paramName) => {
2402
- paramNames.push(paramName);
2403
- return "/([^/]+)";
2404
- }).replace(/\/\[([^\]]+)\]/g, (_, paramName) => {
2405
- paramNames.push(paramName);
2406
- return "/([^/]+)";
2407
- });
2408
- patternString = `${patternString}(?:/)?`;
2409
- const pattern = new RegExp(`^${patternString}$`);
2410
- return {
2411
- pattern,
2412
- paramNames
2413
- };
2414
- }
2415
-
2416
- // src/router/matching/matcher.ts
2417
- function createMatcher() {
2418
- const routes = [];
2419
- return {
2420
- /**
2421
- * Add a route to the matcher
2422
- */
2423
- add(path6, method, routeOptions) {
2424
- const { pattern, paramNames } = compilePathPattern(path6);
2425
- const newRoute = {
2426
- path: path6,
2427
- method,
2428
- pattern,
2429
- paramNames,
2430
- routeOptions
2431
- };
2432
- const insertIndex = routes.findIndex((route) => paramNames.length < route.paramNames.length);
2433
- if (insertIndex === -1) {
2434
- routes.push(newRoute);
2435
- } else {
2436
- routes.splice(insertIndex, 0, newRoute);
2437
- }
2438
- },
2439
- /**
2440
- * Remove a route from the matcher by path
2441
- */
2442
- remove(path6) {
2443
- for (let i = routes.length - 1; i >= 0; i--) {
2444
- if (routes[i].path === path6) {
2445
- routes.splice(i, 1);
2446
- }
2447
- }
2448
- },
2449
- /**
2450
- * Clear all routes from the matcher
2451
- */
2452
- clear() {
2453
- routes.length = 0;
2454
- },
2455
- /**
2456
- * Match a URL path to a route
2457
- */
2458
- match(path6, method) {
2459
- const pathname = path6.split("?")[0];
2460
- if (!pathname) return null;
2461
- for (const route of routes) {
2462
- if (route.method !== method) continue;
2463
- const match = route.pattern.exec(pathname);
2464
- if (match) {
2465
- const params = extractParams(path6, route.pattern, route.paramNames);
2466
- return {
2467
- route: route.routeOptions,
2468
- params
2469
- };
2470
- }
2471
- }
2472
- const matchingPath = routes.find(
2473
- (route) => route.method !== method && route.pattern.test(path6)
2474
- );
2475
- if (matchingPath) {
2476
- return {
2477
- route: null,
2478
- params: {},
2479
- methodNotAllowed: true,
2480
- allowedMethods: routes.filter((route) => route.pattern.test(path6)).map((route) => route.method)
2481
- };
2482
- }
2483
- return null;
2484
- },
2485
- /**
2486
- * Get all registered routes
2487
- */
2488
- getRoutes() {
2489
- return routes.map((route) => ({
2490
- path: route.path,
2491
- method: route.method
2492
- }));
2493
- },
2494
- /**
2495
- * Find routes matching a specific path
2496
- */
2497
- findRoutes(path6) {
2498
- return routes.filter((route) => route.pattern.test(path6)).map((route) => ({
2499
- path: route.path,
2500
- method: route.method,
2501
- params: extractParams(path6, route.pattern, route.paramNames)
2502
- }));
2503
- }
2504
- };
2505
- }
2506
-
2507
- // src/router/registry/fast-registry.ts
2508
- function createRouteRegistry() {
2509
- return {
2510
- routesByPath: /* @__PURE__ */ new Map(),
2511
- routesByFile: /* @__PURE__ */ new Map(),
2512
- pathToFile: /* @__PURE__ */ new Map()
2513
- };
2514
- }
2515
- function updateRoutesFromFile(registry, filePath, newRoutes) {
2516
- console.log(`Updating routes from file: ${filePath}`);
2517
- const oldPaths = registry.routesByFile.get(filePath) || /* @__PURE__ */ new Set();
2518
- const newPaths = new Set(newRoutes.map((r) => r.path));
2519
- const added = newRoutes.filter((r) => !oldPaths.has(r.path));
2520
- const removed = Array.from(oldPaths).filter((p) => !newPaths.has(p));
2521
- const potentiallyChanged = newRoutes.filter((r) => oldPaths.has(r.path));
2522
- const changed = potentiallyChanged.filter((route) => {
2523
- const existingRoute = registry.routesByPath.get(route.path);
2524
- return !existingRoute || !routesEqual(existingRoute, route);
2525
- });
2526
- applyRouteUpdates(registry, filePath, { added, removed, changed });
2527
- return { added, removed, changed };
2528
- }
2529
- function getAllRoutesFromRegistry(registry) {
2530
- return Array.from(registry.routesByPath.values());
2531
- }
2532
- function applyRouteUpdates(registry, filePath, updates) {
2533
- const { added, removed, changed } = updates;
2534
- removed.forEach((path6) => {
2535
- registry.routesByPath.delete(path6);
2536
- registry.pathToFile.delete(path6);
2537
- });
2538
- [...added, ...changed].forEach((route) => {
2539
- registry.routesByPath.set(route.path, route);
2540
- registry.pathToFile.set(route.path, filePath);
2541
- });
2542
- const allPathsForFile = /* @__PURE__ */ new Set([
2543
- ...added.map((r) => r.path),
2544
- ...changed.map((r) => r.path),
2545
- ...Array.from(registry.routesByFile.get(filePath) || []).filter((p) => !removed.includes(p))
2546
- ]);
2547
- if (allPathsForFile.size > 0) {
2548
- registry.routesByFile.set(filePath, allPathsForFile);
2549
- } else {
2550
- registry.routesByFile.delete(filePath);
2551
- }
2552
- }
2553
- function routesEqual(route1, route2) {
2554
- if (route1.path !== route2.path) return false;
2555
- const methods1 = Object.keys(route1).filter((k) => k !== "path").sort();
2556
- const methods2 = Object.keys(route2).filter((k) => k !== "path").sort();
2557
- if (methods1.length !== methods2.length) return false;
2558
- return methods1.every((method) => {
2559
- const handler1 = route1[method];
2560
- const handler2 = route2[method];
2561
- return typeof handler1 === typeof handler2;
2562
- });
2563
- }
2564
-
2565
- // src/router/utils/matching-helpers.ts
2566
- function addRouteToMatcher(route, matcher) {
2567
- Object.entries(route).forEach(([method, methodOptions]) => {
2568
- if (method === "path" || !methodOptions) return;
2569
- matcher.add(route.path, method, methodOptions);
2570
- });
2571
- }
2572
- function removeRouteFromMatcher(path6, matcher) {
2573
- if ("remove" in matcher && typeof matcher.remove === "function") {
2574
- matcher.remove(path6);
2575
- } else {
2576
- console.warn("Matcher does not support selective removal, consider adding remove() method");
2577
- }
2578
- }
2579
- function updateRouteInMatcher(route, matcher) {
2580
- removeRouteFromMatcher(route.path, matcher);
2581
- addRouteToMatcher(route, matcher);
2582
- }
2583
-
2584
- // src/router/router.ts
2585
- var DEFAULT_ROUTER_OPTIONS = {
2586
- routesDir: "./routes",
2587
- basePath: "/",
2588
- watchMode: process.env.NODE_ENV === "development"
2589
- };
2590
- function createRouter(options) {
2591
- const routerOptions = {
2592
- ...DEFAULT_ROUTER_OPTIONS,
2593
- ...options
2594
- };
2595
- if (options.basePath && !options.basePath.startsWith("/")) {
2596
- console.warn("Base path does nothing");
2597
- }
2598
- const registry = createRouteRegistry();
2599
- const matcher = createMatcher();
2600
- let initialized = false;
2601
- let initializationPromise = null;
2602
- let _watchers = null;
2603
- const routeDirectories = /* @__PURE__ */ new Set([routerOptions.routesDir]);
2604
- function applyMatcherChanges(changes) {
2605
- console.log("\n\u{1F527} APPLYING MATCHER CHANGES:");
2606
- console.log(` Adding ${changes.added.length} routes`);
2607
- console.log(` Removing ${changes.removed.length} routes`);
2608
- console.log(` Updating ${changes.changed.length} routes`);
2609
- changes.removed.forEach((routePath) => {
2610
- console.log(` \u2796 Removing: ${routePath}`);
2611
- removeRouteFromMatcher(routePath, matcher);
2612
- });
2613
- changes.added.forEach((route) => {
2614
- const methods = Object.keys(route).filter((key) => key !== "path");
2615
- console.log(` \u2795 Adding: ${route.path} [${methods.join(", ")}]`);
2616
- addRouteToMatcher(route, matcher);
2617
- });
2618
- changes.changed.forEach((route) => {
2619
- const methods = Object.keys(route).filter((key) => key !== "path");
2620
- console.log(` \u{1F504} Updating: ${route.path} [${methods.join(", ")}]`);
2621
- updateRouteInMatcher(route, matcher);
2622
- });
2623
- console.log("\u2705 Matcher changes applied\n");
2624
- }
2625
- function addRoutesWithSource(routes, source) {
2626
- try {
2627
- const changes = updateRoutesFromFile(registry, source, routes);
2628
- applyMatcherChanges(changes);
2629
- return changes;
2630
- } catch (error) {
2631
- console.error(`\u26A0\uFE0F Route conflicts from ${source}:`, error);
2632
- throw error;
2633
- }
2634
- }
2635
- async function loadRoutesFromDirectory(directory, source, prefix) {
2636
- try {
2637
- const discoveredRoutes = await loadInitialRoutesParallel(directory);
2638
- const finalRoutes = discoveredRoutes.map(
2639
- (route) => prefix ? { ...route, path: `${prefix}${route.path}` } : route
2640
- );
2641
- const changes = addRoutesWithSource(finalRoutes, source);
2642
- console.log(
2643
- `Loaded ${discoveredRoutes.length} routes from ${source}${prefix ? ` with prefix ${prefix}` : ""} (${changes.added.length} added, ${changes.changed.length} changed, ${changes.removed.length} removed)`
2644
- );
2645
- } catch (error) {
2646
- console.error(`\u26A0\uFE0F Failed to load routes from ${source}:`, error);
2647
- throw error;
2648
- }
2649
- }
2650
- async function initialize() {
2651
- if (initialized || initializationPromise) {
2652
- return initializationPromise;
2653
- }
2654
- initializationPromise = (async () => {
2655
- try {
2656
- await Promise.all(
2657
- Array.from(routeDirectories).map(
2658
- (directory) => loadRoutesFromDirectory(directory, directory)
2659
- )
2660
- );
2661
- if (routerOptions.watchMode) {
2662
- setupOptimizedWatching();
2663
- }
2664
- initialized = true;
2665
- } catch (error) {
2666
- console.error("\u26A0\uFE0F Failed to initialize router:", error);
2667
- throw error;
2668
- }
2669
- })();
2670
- return initializationPromise;
2671
- }
2672
- function setupOptimizedWatching() {
2673
- if (!_watchers) {
2674
- _watchers = /* @__PURE__ */ new Map();
2675
- }
2676
- for (const directory of routeDirectories) {
2677
- if (!_watchers.has(directory)) {
2678
- const watcher = watchRoutes(directory, {
2679
- debounceMs: 16,
2680
- // ~60fps debouncing
2681
- ignore: ["node_modules", ".git"],
2682
- onRouteAdded: (filepath, addedRoutes) => {
2683
- try {
2684
- const changes = updateRoutesFromFile(registry, filepath, addedRoutes);
2685
- applyMatcherChanges(changes);
2686
- } catch (error) {
2687
- console.error(`Error adding routes from ${directory}:`, error);
2688
- }
2689
- },
2690
- onRouteChanged: withPerformanceTracking(
2691
- async (filepath, changedRoutes) => {
2692
- try {
2693
- console.log(`Processing changes for ${filepath}`);
2694
- const changes = updateRoutesFromFile(registry, filepath, changedRoutes);
2695
- console.log(
2696
- `Changes detected: ${changes.added.length} added, ${changes.changed.length} changed, ${changes.removed.length} removed`
2697
- );
2698
- applyMatcherChanges(changes);
2699
- console.log(
2700
- `Route changes applied: ${changes.added.length} added, ${changes.changed.length} changed, ${changes.removed.length} removed`
2701
- );
2702
- } catch (error) {
2703
- console.error(`\u26A0\uFE0F Error updating routes from ${directory}:`, error);
2704
- }
2705
- },
2706
- directory
2707
- ),
2708
- onRouteRemoved: (filePath, removedRoutes) => {
2709
- console.log(`File removed: ${filePath} with ${removedRoutes.length} routes`);
2710
- try {
2711
- removedRoutes.forEach((route) => {
2712
- removeRouteFromMatcher(route.path, matcher);
2713
- });
2714
- clearFileCache(filePath);
2715
- } catch (error) {
2716
- console.error(`\u26A0\uFE0F Error removing routes from ${filePath}:`, error);
2717
- }
2718
- },
2719
- onError: (error) => {
2720
- console.error(`\u26A0\uFE0F Route watcher error for ${directory}:`, error);
2721
- }
2722
- });
2723
- _watchers.set(directory, watcher);
2724
- }
2725
- }
2726
- }
2727
- function setupWatcherForNewDirectory(directory, prefix) {
2728
- if (!_watchers) {
2729
- _watchers = /* @__PURE__ */ new Map();
2730
- }
2731
- const watcher = watchRoutes(directory, {
2732
- debounceMs: 16,
2733
- ignore: ["node_modules", ".git"],
2734
- onRouteAdded: (filePath, addedRoutes) => {
2735
- try {
2736
- const finalRoutes = addedRoutes.map(
2737
- (route) => prefix ? { ...route, path: `${prefix}${route.path}` } : route
2738
- );
2739
- const changes = updateRoutesFromFile(registry, filePath, finalRoutes);
2740
- applyMatcherChanges(changes);
2741
- } catch (error) {
2742
- console.error(`\u26A0\uFE0F Error adding routes from ${directory}:`, error);
2743
- }
2744
- },
2745
- onRouteChanged: withPerformanceTracking(async (filePath, changedRoutes) => {
2746
- try {
2747
- const finalRoutes = changedRoutes.map(
2748
- (route) => prefix ? { ...route, path: `${prefix}${route.path}` } : route
2749
- );
2750
- const changes = updateRoutesFromFile(registry, filePath, finalRoutes);
2751
- applyMatcherChanges(changes);
2752
- } catch (error) {
2753
- console.error(`\u26A0\uFE0F Error updating routes from ${directory}:`, error);
2754
- }
2755
- }, directory),
2756
- onRouteRemoved: (filePath, removedRoutes) => {
2757
- try {
2758
- removedRoutes.forEach((route) => {
2759
- const finalPath = prefix ? `${prefix}${route.path}` : route.path;
2760
- removeRouteFromMatcher(finalPath, matcher);
2761
- });
2762
- clearFileCache(filePath);
2763
- } catch (error) {
2764
- console.error(`Error removing routes from ${filePath}:`, error);
2765
- }
2766
- },
2767
- onError: (error) => {
2768
- console.error(`\u26A0\uFE0F Route watcher error for ${directory}:`, error);
2769
- }
2770
- });
2771
- _watchers.set(directory, watcher);
2772
- return watcher;
2773
- }
2774
- initialize().catch((error) => {
2775
- console.error("\u26A0\uFE0F Failed to initialize router on creation:", error);
2776
- });
2777
- return {
2778
- /**
2779
- * Handle an incoming request
2780
- */
2781
- async handleRequest(ctx) {
2782
- if (!initialized) {
2783
- console.log("\u{1F504} Router not initialized, initializing...");
2784
- await initialize();
2785
- }
2786
- const { method, path: path6 } = ctx.request;
2787
- console.log(`
2788
- \u{1F4E5} Handling request: ${method} ${path6}`);
2789
- const match = matcher.match(path6, method);
2790
- if (!match) {
2791
- console.log(`\u274C No match found for: ${method} ${path6}`);
2792
- throw new NotFoundError("Not found");
2793
- }
2794
- console.log(`\u2705 Route matched: ${method} ${path6}`);
2795
- console.log(` Params: ${JSON.stringify(match.params)}`);
2796
- if (match.methodNotAllowed) {
2797
- ctx.response.status(405).json({
2798
- error: "\u274C Method Not Allowed",
2799
- allowed: match.allowedMethods
2800
- });
2801
- if (match.allowedMethods && match.allowedMethods.length > 0) {
2802
- ctx.response.header("Allow", match.allowedMethods.join(", "));
2803
- }
2804
- return;
2805
- }
2806
- ctx.request.params = match.params;
2807
- await executeHandler(ctx, match.route, match.params);
2808
- },
2809
- /**
2810
- * Get all registered routes (using optimized registry)
2811
- */
2812
- getRoutes() {
2813
- return getAllRoutesFromRegistry(registry);
2814
- },
2815
- /**
2816
- * Add a route programmatically
2817
- */
2818
- addRoute(route) {
2819
- const changes = updateRoutesFromFile(registry, "programmatic", [route]);
2820
- applyMatcherChanges(changes);
2821
- },
2822
- /**
2823
- * Add multiple routes programmatically with batch processing
2824
- */
2825
- addRoutes(routes) {
2826
- const changes = updateRoutesFromFile(registry, "programmatic", routes);
2827
- applyMatcherChanges(changes);
2828
- return changes;
2829
- },
2830
- /**
2831
- * Add a route directory (for plugins) with optimized loading
2832
- */
2833
- async addRouteDirectory(directory, options2 = {}) {
2834
- if (routeDirectories.has(directory)) {
2835
- console.warn(`Route directory ${directory} already registered`);
2836
- return;
2837
- }
2838
- routeDirectories.add(directory);
2839
- if (initialized) {
2840
- await loadRoutesFromDirectory(directory, directory, options2.prefix);
2841
- if (routerOptions.watchMode) {
2842
- setupWatcherForNewDirectory(directory, options2.prefix);
2843
- }
2844
- }
2845
- },
2846
- /**
2847
- * Get route conflicts (using registry)
2848
- */
2849
- getRouteConflicts() {
2850
- const conflicts = [];
2851
- return conflicts;
2852
- },
2853
- /**
2854
- * Close watchers and cleanup (useful for testing)
2855
- */
2856
- async close() {
2857
- if (_watchers) {
2858
- for (const watcher of _watchers.values()) {
2859
- await watcher.close();
2860
- }
2861
- _watchers.clear();
2862
- }
2863
- }
2864
- };
2865
- }
2866
-
2867
- // src/server/create.ts
2868
- var DEFAULT_OPTIONS2 = {
2869
- port: 3e3,
2870
- host: "localhost",
2871
- routesDir: "./routes",
2872
- http2: {
2873
- enabled: true
2874
- },
2875
- middleware: [],
2876
- plugins: []
2877
- };
2878
- function createServerOptions(options = {}) {
2879
- const baseOptions = { ...DEFAULT_OPTIONS2 };
2880
- setRuntimeConfig({ routesDir: options.routesDir || baseOptions.routesDir });
2881
- return {
2882
- port: options.port ?? baseOptions.port,
2883
- host: options.host ?? baseOptions.host,
2884
- routesDir: options.routesDir ?? baseOptions.routesDir,
2885
- http2: {
2886
- enabled: options.http2?.enabled ?? baseOptions.http2?.enabled,
2887
- keyFile: options.http2?.keyFile ?? baseOptions.http2?.keyFile,
2888
- certFile: options.http2?.certFile ?? baseOptions.http2?.certFile
2889
- },
2890
- middleware: [...baseOptions.middleware || [], ...options.middleware || []],
2891
- plugins: [...baseOptions.plugins || [], ...options.plugins || []]
2892
- };
2893
- }
2894
- function createListenMethod(serverInstance, validatedOptions, initialMiddleware, initialPlugins) {
2895
- return async () => {
2896
- await initializeComponents(serverInstance, initialMiddleware, initialPlugins);
2897
- await serverInstance.pluginManager.initializePlugins(serverInstance);
2898
- await startServer(serverInstance, validatedOptions);
2899
- await serverInstance.pluginManager.onServerStart(serverInstance, serverInstance.server);
2900
- setupServerLifecycle(serverInstance);
2901
- return serverInstance;
2902
- };
2903
- }
2904
- async function initializeComponents(serverInstance, initialMiddleware, initialPlugins) {
2905
- for (const mw of initialMiddleware) {
2906
- serverInstance.use(mw);
2907
- }
2908
- for (const p of initialPlugins) {
2909
- await serverInstance.register(p);
2910
- }
2911
- }
2912
- function setupServerLifecycle(serverInstance) {
2913
- const signalHandlers = registerSignalHandlers(() => serverInstance.close());
2914
- serverInstance._signalHandlers = signalHandlers;
2915
- serverInstance.events.emit("started");
2916
- }
2917
- function createCloseMethod(serverInstance) {
2918
- return async (stopOptions) => {
2919
- if (!serverInstance.server) {
2920
- return;
2921
- }
2922
- const options = { ...stopOptions };
2923
- if (serverInstance._signalHandlers) {
2924
- serverInstance._signalHandlers.unregister();
2925
- delete serverInstance._signalHandlers;
2926
- }
2927
- await stopServer(serverInstance, options);
2928
- };
2929
- }
2930
- function createUseMethod(serverInstance) {
2931
- return (middleware) => {
2932
- const middlewareArray = Array.isArray(middleware) ? middleware : [middleware];
2933
- serverInstance.middleware.push(...middlewareArray);
2934
- return serverInstance;
2935
- };
2936
- }
2937
- function createRegisterMethod(serverInstance) {
2938
- return async (plugin) => {
2939
- validatePlugin(plugin);
2940
- serverInstance.plugins.push(plugin);
2941
- await plugin.register(serverInstance);
2942
- return serverInstance;
2943
- };
2944
- }
2945
- function create3(options = {}) {
2946
- const mergedOptions = createServerOptions(options);
2947
- let validatedOptions;
2948
- try {
2949
- validatedOptions = validateServerOptions(mergedOptions);
2950
- } catch (error) {
2951
- if (error instanceof Error) {
2952
- throw new Error(`Failed to create server: ${error.message}`);
2953
- }
2954
- throw new Error(`Failed to create server: ${String(error)}`);
2955
- }
2956
- const { port, host, middleware, plugins } = validatedOptions;
2957
- const initialMiddleware = Array.isArray(middleware) ? [...middleware] : [];
2958
- const initialPlugins = Array.isArray(plugins) ? [...plugins] : [];
2959
- const contextStorage2 = new AsyncLocalStorage2();
2960
- const router = createRouter({
2961
- routesDir: validatedOptions.routesDir,
2962
- watchMode: process.env.NODE_ENV === "development"
2963
- });
2964
- const pluginManager = createPluginLifecycleManager({
2965
- debug: process.env.NODE_ENV === "development",
2966
- continueOnError: true
2967
- });
2968
- const events = new EventEmitter();
2969
- const serverInstance = {
2970
- server: null,
2971
- port,
2972
- host,
2973
- context: contextStorage2,
2974
- events,
2975
- plugins: [],
2976
- middleware: [],
2977
- _signalHandlers: { unregister: () => {
2978
- } },
2979
- use: () => serverInstance,
2980
- register: async () => serverInstance,
2981
- listen: async () => serverInstance,
2982
- close: async () => {
2983
- },
2984
- router,
2985
- pluginManager
2986
- };
2987
- serverInstance.listen = createListenMethod(
2988
- serverInstance,
2989
- validatedOptions,
2990
- initialMiddleware,
2991
- initialPlugins
2992
- );
2993
- serverInstance.close = createCloseMethod(serverInstance);
2994
- serverInstance.use = createUseMethod(serverInstance);
2995
- serverInstance.register = createRegisterMethod(serverInstance);
2996
- return serverInstance;
2997
- }
2998
-
2999
- // src/errors/unauthorized-error.ts
3000
- var UnauthorizedError = class extends BlaizeError {
3001
- /**
3002
- * Creates a new UnauthorizedError instance
3003
- *
3004
- * @param title - Human-readable error message
3005
- * @param details - Optional authentication context
3006
- * @param correlationId - Optional correlation ID (uses current context if not provided)
3007
- */
3008
- constructor(title, details = void 0, correlationId = void 0) {
3009
- super(
3010
- "UNAUTHORIZED" /* UNAUTHORIZED */,
3011
- title,
3012
- 401,
3013
- // HTTP 401 Unauthorized
3014
- correlationId ?? getCurrentCorrelationId(),
3015
- details
3016
- );
3017
- }
3018
- };
3019
-
3020
- // src/errors/forbidden-error.ts
3021
- var ForbiddenError = class extends BlaizeError {
3022
- /**
3023
- * Creates a new ForbiddenError instance
3024
- *
3025
- * @param title - Human-readable error message
3026
- * @param details - Optional permission context
3027
- * @param correlationId - Optional correlation ID (uses current context if not provided)
3028
- */
3029
- constructor(title, details = void 0, correlationId = void 0) {
3030
- super(
3031
- "FORBIDDEN" /* FORBIDDEN */,
3032
- title,
3033
- 403,
3034
- // HTTP 403 Forbidden
3035
- correlationId ?? getCurrentCorrelationId(),
3036
- details
3037
- );
3038
- }
3039
- };
3040
-
3041
- // src/errors/conflict-error.ts
3042
- var ConflictError = class extends BlaizeError {
3043
- /**
3044
- * Creates a new ConflictError instance
3045
- *
3046
- * @param title - Human-readable error message
3047
- * @param details - Optional conflict context
3048
- * @param correlationId - Optional correlation ID (uses current context if not provided)
3049
- */
3050
- constructor(title, details = void 0, correlationId = void 0) {
3051
- super(
3052
- "CONFLICT" /* CONFLICT */,
3053
- title,
3054
- 409,
3055
- // HTTP 409 Conflict
3056
- correlationId ?? getCurrentCorrelationId(),
3057
- details
3058
- );
3059
- }
3060
- };
3061
-
3062
- // src/errors/rate-limit-error.ts
3063
- var RateLimitError = class extends BlaizeError {
3064
- /**
3065
- * Creates a new RateLimitError instance
3066
- *
3067
- * @param title - Human-readable error message
3068
- * @param details - Optional rate limit context
3069
- * @param correlationId - Optional correlation ID (uses current context if not provided)
3070
- */
3071
- constructor(title, details = void 0, correlationId = void 0) {
3072
- super(
3073
- "RATE_LIMITED" /* RATE_LIMITED */,
3074
- title,
3075
- 429,
3076
- // HTTP 429 Too Many Requests
3077
- correlationId ?? getCurrentCorrelationId(),
3078
- details
3079
- );
3080
- }
3081
- };
3082
-
3083
- // src/errors/request-timeout-error.ts
3084
- var RequestTimeoutError = class extends BlaizeError {
3085
- constructor(title, details, correlationId) {
3086
- super(
3087
- "UPLOAD_TIMEOUT" /* UPLOAD_TIMEOUT */,
3088
- title,
3089
- 408,
3090
- correlationId ?? getCurrentCorrelationId(),
3091
- details
3092
- );
3093
- }
3094
- };
3095
-
3096
- // src/errors/unprocessable-entity-error.ts
3097
- var UnprocessableEntityError = class extends BlaizeError {
3098
- constructor(title, details, correlationId) {
3099
- super(
3100
- "UNPROCESSABLE_ENTITY" /* UNPROCESSABLE_ENTITY */,
3101
- title,
3102
- 422,
3103
- correlationId ?? getCurrentCorrelationId(),
3104
- details
3105
- );
3106
- }
3107
- };
3108
-
3109
- // src/index.ts
3110
- var VERSION = "0.1.0";
3111
- var ServerAPI = { createServer: create3 };
3112
- var RouterAPI = {
3113
- createDeleteRoute,
3114
- createGetRoute,
3115
- createHeadRoute,
3116
- createOptionsRoute,
3117
- createPatchRoute,
3118
- createPostRoute,
3119
- createPutRoute
3120
- };
3121
- var MiddlewareAPI = { createMiddleware: create, compose };
3122
- var PluginsAPI = { createPlugin: create2 };
3123
- var Blaize = {
3124
- // Core functions
3125
- createServer: create3,
3126
- createMiddleware: create,
3127
- createPlugin: create2,
3128
- // Namespaces (using the non-conflicting names)
3129
- Server: ServerAPI,
3130
- Router: RouterAPI,
3131
- Middleware: MiddlewareAPI,
3132
- Plugins: PluginsAPI,
3133
- // Constants
3134
- VERSION
3135
- };
3136
- var index_default = Blaize;
3137
- export {
3138
- Blaize,
3139
- BlaizeError,
3140
- ConflictError,
3141
- ErrorSeverity,
3142
- ErrorType,
3143
- ForbiddenError,
3144
- InternalServerError,
3145
- MiddlewareAPI,
3146
- NotFoundError,
3147
- PayloadTooLargeError,
3148
- PluginsAPI,
3149
- RateLimitError,
3150
- RequestTimeoutError,
3151
- RouterAPI,
3152
- ServerAPI,
3153
- UnauthorizedError,
3154
- UnprocessableEntityError,
3155
- UnsupportedMediaTypeError,
3156
- VERSION,
3157
- ValidationError,
3158
- compose,
3159
- createDeleteRoute,
3160
- createGetRoute,
3161
- createHeadRoute,
3162
- create as createMiddleware,
3163
- createOptionsRoute,
3164
- createPatchRoute,
3165
- create2 as createPlugin,
3166
- createPostRoute,
3167
- createPutRoute,
3168
- create3 as createServer,
3169
- index_default as default,
3170
- isBodyParseError
3171
- };
48
+ `),n()}),e.on("error",s=>{console.error("Server error:",s),i(s)})})}async function op(e){for(let t of e.plugins)typeof t.initialize=="function"&&await t.initialize(e)}async function Du(e,t){if(!e.server)try{let a=t.port,r=t.host;await op(e);let n=t.http2||{enabled:!0},i=!!n.enabled,s=await np(n);t.http2&&s.keyFile&&s.certFile&&(t.http2.keyFile=s.keyFile,t.http2.certFile=s.certFile);let o=ip(i,s);e.server=o,e.port=a,e.host=r;let u=_u(e);o.on("request",u),await sp(o,a,r,i)}catch(a){throw console.error("Failed to start server:",a),a}}var Ua=!1;async function Lu(e,t={}){let a=e.server,r=e.events;if(Ua){console.log("\u26A0\uFE0F Shutdown already in progress, ignoring duplicate shutdown request");return}if(!a)return;Ua=!0;let n=t.timeout||5e3;try{if(t.onStopping&&await t.onStopping(),r.emit("stopping"),e.router&&typeof e.router.close=="function"){console.log("\u{1F50C} Closing router watchers...");try{await Promise.race([e.router.close(),new Promise((o,u)=>setTimeout(()=>u(new Error("Router close timeout")),2e3))]),console.log("\u2705 Router watchers closed")}catch(o){console.error("\u274C Error closing router watchers:",o)}}try{await Promise.race([e.pluginManager.onServerStop(e,a),new Promise((o,u)=>setTimeout(()=>u(new Error("Plugin stop timeout")),2e3))])}catch(o){console.error("\u274C Plugin stop timeout:",o)}let i=new Promise((o,u)=>{a.close(l=>{if(l)return u(l);o()})}),s=new Promise((o,u)=>{setTimeout(()=>{u(new Error("Server shutdown timeout"))},n)});await Promise.race([i,s]);try{await Promise.race([e.pluginManager.terminatePlugins(e),new Promise((o,u)=>setTimeout(()=>u(new Error("Plugin terminate timeout")),1e3))])}catch(o){console.error("\u274C Plugin terminate timeout:",o)}t.onStopped&&await t.onStopped(),r.emit("stopped"),e.server=null,console.log("\u2705 Graceful shutdown completed"),Ua=!1}catch(i){throw Ua=!1,console.error("\u26A0\uFE0F Shutdown error (forcing exit):",i),a&&typeof a.close=="function"&&a.close(),process.env.NODE_ENV==="development"&&(console.log("\u{1F504} Forcing exit for development restart..."),process.exit(0)),r.emit("error",i),i}}function ku(e){if(process.env.NODE_ENV==="development"){let a=()=>{console.log("\u{1F4E4} SIGINT received, forcing exit for development restart..."),process.exit(0)},r=()=>{console.log("\u{1F4E4} SIGTERM received, forcing exit for development restart..."),process.exit(0)};return process.on("SIGINT",a),process.on("SIGTERM",r),{unregister:()=>{process.removeListener("SIGINT",a),process.removeListener("SIGTERM",r)}}}else{let a=()=>{console.log("\u{1F4E4} SIGINT received, starting graceful shutdown..."),e().catch(console.error)},r=()=>{console.log("\u{1F4E4} SIGTERM received, starting graceful shutdown..."),e().catch(console.error)};return process.on("SIGINT",a),process.on("SIGTERM",r),{unregister:()=>{process.removeListener("SIGINT",a),process.removeListener("SIGTERM",r)}}}}import{z as rt}from"zod";var up=rt.custom(e=>e!==null&&typeof e=="object"&&"execute"in e&&typeof e.execute=="function",{message:"Expected middleware to have an execute function"}),lp=rt.custom(e=>e!==null&&typeof e=="object"&&"register"in e&&typeof e.register=="function",{message:"Expected a valid plugin object with a register method"}),fp=rt.object({enabled:rt.boolean().optional().default(!0),keyFile:rt.string().optional(),certFile:rt.string().optional()}).refine(e=>e.enabled&&process.env.NODE_ENV==="production"?e.keyFile&&e.certFile:!0,{message:"When HTTP/2 is enabled (outside of development mode), both keyFile and certFile must be provided"}),cp=rt.object({port:rt.number().int().positive().optional().default(3e3),host:rt.string().optional().default("localhost"),routesDir:rt.string().optional().default("./routes"),http2:fp.optional().default({enabled:!0}),middleware:rt.array(up).optional().default([]),plugins:rt.array(lp).optional().default([])});function Uu(e){try{return cp.parse(e)}catch(t){if(t instanceof rt.ZodError){let a=t.format();throw new Error(`Invalid server options: ${JSON.stringify(a,null,2)}`)}throw new Error(`Invalid server options: ${String(t)}`)}}function Fu(e={}){let{continueOnError:t=!0,debug:a=!1,onError:r}=e;function n(s,...o){a&&console.log(`[PluginLifecycle] ${s}`,...o)}function i(s,o,u){let l=`Plugin ${s.name} failed during ${o}: ${u.message}`;if(r?r(s,o,u):console.error(l,u),!t)throw new Error(l)}return{async initializePlugins(s){n("Initializing plugins...");for(let o of s.plugins)if(o.initialize)try{n(`Initializing plugin: ${o.name}`),await o.initialize(s)}catch(u){i(o,"initialize",u)}n(`Initialized ${s.plugins.length} plugins`)},async terminatePlugins(s){n("Terminating plugins...");let o=[...s.plugins].reverse();for(let u of o)if(u.terminate)try{n(`Terminating plugin: ${u.name}`),await u.terminate(s)}catch(l){i(u,"terminate",l)}n(`Terminated ${o.length} plugins`)},async onServerStart(s,o){n("Notifying plugins of server start...");for(let u of s.plugins)if(u.onServerStart)try{n(`Notifying plugin of server start: ${u.name}`),await u.onServerStart(o)}catch(l){i(u,"onServerStart",l)}},async onServerStop(s,o){n("Notifying plugins of server stop...");let u=[...s.plugins].reverse();for(let l of u)if(l.onServerStop)try{n(`Notifying plugin of server stop: ${l.name}`),await l.onServerStop(o)}catch(f){i(l,"onServerStop",f)}}}}var yt=class extends Error{constructor(a,r){super(`Plugin validation error${a?` for "${a}"`:""}: ${r}`);this.pluginName=a;this.name="PluginValidationError"}};var dp=new Set(["core","server","router","middleware","context","blaize","blaizejs"]),pp=/^[a-z]([a-z0-9-]*[a-z0-9])?$/,hp=/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9-.]+)?(?:\+[a-zA-Z0-9-.]+)?$/;function Ou(e,t={}){let{requireVersion:a=!0,validateNameFormat:r=!0,checkReservedNames:n=!0}=t;if(!e||typeof e!="object")throw new yt("","Plugin must be an object");let i=e;if(!i.name||typeof i.name!="string")throw new yt("","Plugin must have a name (string)");if(r&&!pp.test(i.name))throw new yt(i.name,"Plugin name must be lowercase letters, numbers, and hyphens only");if(n&&dp.has(i.name.toLowerCase()))throw new yt(i.name,`Plugin name "${i.name}" is reserved`);if(a){if(!i.version||typeof i.version!="string")throw new yt(i.name,"Plugin must have a version (string)");if(!hp.test(i.version))throw new yt(i.name,'Plugin version must follow semantic versioning (e.g., "1.0.0")')}if(!i.register||typeof i.register!="function")throw new yt(i.name,"Plugin must have a register method (function)");let s=["initialize","terminate","onServerStart","onServerStop"];for(let o of s)if(i[o]&&typeof i[o]!="function")throw new yt(i.name,`Plugin ${o} must be a function if provided`)}import*as Mu from"node:crypto";import*as Ku from"node:fs/promises";import{createRequire as mp}from"node:module";import*as qu from"node:path";async function yp(e){let t=`?t=${Date.now()}`,a=e+t;try{let r=await import(a);return console.log("\u2705 Successfully imported module"),r}catch(r){let n=r instanceof Error?r.message:String(r);return console.log("\u26A0\uFE0F Error importing with cache buster, trying original path:",n),import(e)}}async function Vu(e,t){try{let a=Jr(e,t),r=await yp(e);console.log("\u{1F4E6} Module exports:",Object.keys(r));let n=[];if(r.default&&typeof r.default=="object"){let i={...r.default,path:a.routePath};n.push(i)}return Object.entries(r).forEach(([i,s])=>{if(i==="default"||!s||typeof s!="object")return;let o=s;if(gp(o)){let u={...o,path:a.routePath};n.push(u)}}),n.length===0?(console.warn(`Route file ${e} does not export any valid route definitions`),[]):(console.log(`\u2705 Successfully Loaded ${n.length} route(s)`),n)}catch(a){return console.error(`Failed to load route module ${e}:`,a),[]}}function gp(e){return!e||typeof e!="object"?!1:["GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS"].some(r=>e[r]&&typeof e[r]=="object"&&e[r].handler)}var Wr=new Map;async function jr(e,t,a=!0){let n=(await Ku.stat(e)).mtime.getTime(),i=Wr.get(e);if(a&&i&&i.timestamp===n)return i.routes;vp(e);let s=await Vu(e,t);if(a){let o=zu(s);Wr.set(e,{routes:s,timestamp:n,hash:o})}return s}function Hu(e,t){let a=Wr.get(e);if(!a)return!0;let r=zu(t);return a.hash!==r}function ai(e){e?Wr.delete(e):Wr.clear()}function zu(e){let t=e.map(n=>({path:n.path,methods:Object.keys(n).filter(i=>i!=="path").sort().map(i=>{let s=n[i],o=s?.handler?s.handler.toString():null;return{method:i,handler:o,middleware:s?.middleware?s.middleware.length:0,hasSchema:!!s?.schema,schemaKeys:s?.schema?Object.keys(s.schema).sort():[]}})})),a=JSON.stringify(t);return Mu.createHash("md5").update(a).digest("hex")}function vp(e){try{let t=qu.resolve(e);if(typeof Dt<"u"){delete Dt.cache[t];try{let a=Dt.resolve(t);delete Dt.cache[a]}catch(a){let r=a instanceof Error?a.message:String(a);console.log(`\u26A0\uFE0F Could not resolve path: ${r}`)}}else try{let a=mp(import.meta.url);delete a.cache[t];try{let r=a.resolve(t);delete a.cache[r]}catch{console.log("\u26A0\uFE0F Could not resolve ESM path")}}catch{console.log("\u26A0\uFE0F createRequire not available in pure ESM")}}catch(t){console.log(`\u26A0\uFE0F Error during module cache invalidation for ${e}:`,t)}}import*as Gu from"node:os";import*as Fa from"node:fs/promises";import*as Ir from"node:path";async function Oa(e,t={}){let a=Ir.isAbsolute(e)?e:Ir.resolve(process.cwd(),e);console.log("Creating router with routes directory:",a);try{if(!(await Fa.stat(a)).isDirectory())throw new Error(`Route directory is not a directory: ${a}`)}catch(s){throw s.code==="ENOENT"?new Error(`Route directory not found: ${a}`):s}let r=[],n=t.ignore||["node_modules",".git"];async function i(s){let o=await Fa.readdir(s,{withFileTypes:!0});for(let u of o){let l=Ir.join(s,u.name);u.isDirectory()&&n.includes(u.name)||(u.isDirectory()?await i(l):Cp(u.name)&&r.push(l))}}return await i(a),r}function Cp(e){return!e.startsWith("_")&&(e.endsWith(".ts")||e.endsWith(".js"))}async function Ep(e,t,a=Math.max(1,Math.floor(Gu.cpus().length/2))){let r=xp(e,a),n=[];for(let i of r){let o=(await Promise.allSettled(i.map(u=>t(u)))).filter(u=>u.status==="fulfilled").map(u=>u.value);n.push(...o)}return n}async function Qu(e){let t=await Oa(e);return(await Ep(t,r=>jr(r,e))).flat()}function xp(e,t){let a=[];for(let r=0;r<e.length;r+=t)a.push(e.slice(r,r+t));return a}var Gt={fileChanges:0,totalReloadTime:0,averageReloadTime:0,slowReloads:[]};function Wu(e,t){let a=Date.now()-t;if(Gt.fileChanges++,Gt.totalReloadTime+=a,Gt.averageReloadTime=Gt.totalReloadTime/Gt.fileChanges,a>100&&(Gt.slowReloads.push({file:e,time:a}),Gt.slowReloads.length>10&&Gt.slowReloads.shift()),process.env.NODE_ENV==="development"){let r=a<50?"\u26A1":a<100?"\u{1F504}":"\u{1F40C}";console.log(`${r} Route reload: ${e} (${a}ms)`)}}function ni(e,t){return console.log(`Tracking performance for: ${t}`),async(...a)=>{let r=Date.now();try{let n=await e(...a);return Wu(t,r),n}catch(n){throw Wu(t,r),n}}}import*as mi from"node:path";import{stat as Xp}from"fs";import{stat as Zp,readdir as Jp}from"fs/promises";import{EventEmitter as eh}from"events";import*as Z from"path";import{stat as Sp,lstat as ju,readdir as Tp,realpath as bp}from"node:fs/promises";import{Readable as Ip}from"node:stream";import{resolve as $u,relative as wp,join as Ap,sep as Bp}from"node:path";var at={FILE_TYPE:"files",DIR_TYPE:"directories",FILE_DIR_TYPE:"files_directories",EVERYTHING_TYPE:"all"},ii={root:".",fileFilter:e=>!0,directoryFilter:e=>!0,type:at.FILE_TYPE,lstat:!1,depth:2147483648,alwaysStat:!1,highWaterMark:4096};Object.freeze(ii);var Ju="READDIRP_RECURSIVE_ERROR",Rp=new Set(["ENOENT","EPERM","EACCES","ELOOP",Ju]),Yu=[at.DIR_TYPE,at.EVERYTHING_TYPE,at.FILE_DIR_TYPE,at.FILE_TYPE],_p=new Set([at.DIR_TYPE,at.EVERYTHING_TYPE,at.FILE_DIR_TYPE]),Np=new Set([at.EVERYTHING_TYPE,at.FILE_DIR_TYPE,at.FILE_TYPE]),Pp=e=>Rp.has(e.code),Dp=process.platform==="win32",Xu=e=>!0,Zu=e=>{if(e===void 0)return Xu;if(typeof e=="function")return e;if(typeof e=="string"){let t=e.trim();return a=>a.basename===t}if(Array.isArray(e)){let t=e.map(a=>a.trim());return a=>t.some(r=>a.basename===r)}return Xu},si=class extends Ip{constructor(t={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:t.highWaterMark});let a={...ii,...t},{root:r,type:n}=a;this._fileFilter=Zu(a.fileFilter),this._directoryFilter=Zu(a.directoryFilter);let i=a.lstat?ju:Sp;Dp?this._stat=s=>i(s,{bigint:!0}):this._stat=i,this._maxDepth=a.depth??ii.depth,this._wantsDir=n?_p.has(n):!1,this._wantsFile=n?Np.has(n):!1,this._wantsEverything=n===at.EVERYTHING_TYPE,this._root=$u(r),this._isDirent=!a.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(r,1)],this.reading=!1,this.parent=void 0}async _read(t){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&t>0;){let a=this.parent,r=a&&a.files;if(r&&r.length>0){let{path:n,depth:i}=a,s=r.splice(0,t).map(u=>this._formatEntry(u,n)),o=await Promise.all(s);for(let u of o){if(!u)continue;if(this.destroyed)return;let l=await this._getEntryType(u);l==="directory"&&this._directoryFilter(u)?(i<=this._maxDepth&&this.parents.push(this._exploreDir(u.fullPath,i+1)),this._wantsDir&&(this.push(u),t--)):(l==="file"||this._includeAsFile(u))&&this._fileFilter(u)&&this._wantsFile&&(this.push(u),t--)}}else{let n=this.parents.pop();if(!n){this.push(null);break}if(this.parent=await n,this.destroyed)return}}}catch(a){this.destroy(a)}finally{this.reading=!1}}}async _exploreDir(t,a){let r;try{r=await Tp(t,this._rdOptions)}catch(n){this._onError(n)}return{files:r,depth:a,path:t}}async _formatEntry(t,a){let r,n=this._isDirent?t.name:t;try{let i=$u(Ap(a,n));r={path:wp(this._root,i),fullPath:i,basename:n},r[this._statsProp]=this._isDirent?t:await this._stat(i)}catch(i){this._onError(i);return}return r}_onError(t){Pp(t)&&!this.destroyed?this.emit("warn",t):this.destroy(t)}async _getEntryType(t){if(!t&&this._statsProp in t)return"";let a=t[this._statsProp];if(a.isFile())return"file";if(a.isDirectory())return"directory";if(a&&a.isSymbolicLink()){let r=t.fullPath;try{let n=await bp(r),i=await ju(n);if(i.isFile())return"file";if(i.isDirectory()){let s=n.length;if(r.startsWith(n)&&r.substr(s,1)===Bp){let o=new Error(`Circular symlink detected: "${r}" points to "${n}"`);return o.code=Ju,this._onError(o)}return"directory"}}catch(n){return this._onError(n),""}}}_includeAsFile(t){let a=t&&t[this._statsProp];return a&&this._wantsEverything&&!a.isDirectory()}};function el(e,t={}){let a=t.entryType||t.type;if(a==="both"&&(a=at.FILE_DIR_TYPE),a&&(t.type=a),e){if(typeof e!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(a&&!Yu.includes(a))throw new Error(`readdirp: Invalid type passed. Use one of ${Yu.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return t.root=e,new si(t)}import{watchFile as Lp,unwatchFile as tl,watch as kp}from"fs";import{open as Up,stat as al,lstat as Fp,realpath as oi}from"fs/promises";import*as me from"path";import{type as Op}from"os";var Vp="data",fi="end",nl="close",Ha=()=>{};var za=process.platform,ci=za==="win32",Mp=za==="darwin",Kp=za==="linux",qp=za==="freebsd",il=Op()==="OS400",ve={ALL:"all",READY:"ready",ADD:"add",CHANGE:"change",ADD_DIR:"addDir",UNLINK:"unlink",UNLINK_DIR:"unlinkDir",RAW:"raw",ERROR:"error"},gt=ve,Hp="watch",zp={lstat:Fp,stat:al},or="listeners",Va="errHandlers",wr="rawEmitters",Gp=[or,Va,wr],Qp=new Set(["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]),Wp=e=>Qp.has(me.extname(e).slice(1).toLowerCase()),li=(e,t)=>{e instanceof Set?e.forEach(t):t(e)},$r=(e,t,a)=>{let r=e[t];r instanceof Set||(e[t]=r=new Set([r])),r.add(a)},jp=e=>t=>{let a=e[t];a instanceof Set?a.clear():delete e[t]},Yr=(e,t,a)=>{let r=e[t];r instanceof Set?r.delete(a):r===a&&delete e[t]},sl=e=>e instanceof Set?e.size===0:!e,Ma=new Map;function rl(e,t,a,r,n){let i=(s,o)=>{a(e),n(s,o,{watchedPath:e}),o&&e!==o&&Ka(me.resolve(e,o),or,me.join(e,o))};try{return kp(e,{persistent:t.persistent},i)}catch(s){r(s);return}}var Ka=(e,t,a,r,n)=>{let i=Ma.get(e);i&&li(i[t],s=>{s(a,r,n)})},$p=(e,t,a,r)=>{let{listener:n,errHandler:i,rawEmitter:s}=r,o=Ma.get(t),u;if(!a.persistent)return u=rl(e,a,n,i,s),u?u.close.bind(u):void 0;if(o)$r(o,or,n),$r(o,Va,i),$r(o,wr,s);else{if(u=rl(e,a,Ka.bind(null,t,or),i,Ka.bind(null,t,wr)),!u)return;u.on(gt.ERROR,async l=>{let f=Ka.bind(null,t,Va);if(o&&(o.watcherUnusable=!0),ci&&l.code==="EPERM")try{await(await Up(e,"r")).close(),f(l)}catch{}else f(l)}),o={listeners:n,errHandlers:i,rawEmitters:s,watcher:u},Ma.set(t,o)}return()=>{Yr(o,or,n),Yr(o,Va,i),Yr(o,wr,s),sl(o.listeners)&&(o.watcher.close(),Ma.delete(t),Gp.forEach(jp(o)),o.watcher=void 0,Object.freeze(o))}},ui=new Map,Yp=(e,t,a,r)=>{let{listener:n,rawEmitter:i}=r,s=ui.get(t),o=s&&s.options;return o&&(o.persistent<a.persistent||o.interval>a.interval)&&(tl(t),s=void 0),s?($r(s,or,n),$r(s,wr,i)):(s={listeners:n,rawEmitters:i,options:a,watcher:Lp(t,a,(u,l)=>{li(s.rawEmitters,c=>{c(gt.CHANGE,t,{curr:u,prev:l})});let f=u.mtimeMs;(u.size!==l.size||f>l.mtimeMs||f===0)&&li(s.listeners,c=>c(e,u))})},ui.set(t,s)),()=>{Yr(s,or,n),Yr(s,wr,i),sl(s.listeners)&&(ui.delete(t),tl(t),s.options=s.watcher=void 0,Object.freeze(s))}},qa=class{constructor(t){this.fsw=t,this._boundHandleError=a=>t._handleError(a)}_watchWithNodeFs(t,a){let r=this.fsw.options,n=me.dirname(t),i=me.basename(t);this.fsw._getWatchedDir(n).add(i);let o=me.resolve(t),u={persistent:r.persistent};a||(a=Ha);let l;if(r.usePolling){let f=r.interval!==r.binaryInterval;u.interval=f&&Wp(i)?r.binaryInterval:r.interval,l=Yp(t,o,u,{listener:a,rawEmitter:this.fsw._emitRaw})}else l=$p(t,o,u,{listener:a,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw});return l}_handleFile(t,a,r){if(this.fsw.closed)return;let n=me.dirname(t),i=me.basename(t),s=this.fsw._getWatchedDir(n),o=a;if(s.has(i))return;let u=async(f,c)=>{if(this.fsw._throttle(Hp,t,5)){if(!c||c.mtimeMs===0)try{let g=await al(t);if(this.fsw.closed)return;let m=g.atimeMs,h=g.mtimeMs;if((!m||m<=h||h!==o.mtimeMs)&&this.fsw._emit(gt.CHANGE,t,g),(Mp||Kp||qp)&&o.ino!==g.ino){this.fsw._closeFile(f),o=g;let v=this._watchWithNodeFs(t,u);v&&this.fsw._addPathCloser(f,v)}else o=g}catch{this.fsw._remove(n,i)}else if(s.has(i)){let g=c.atimeMs,m=c.mtimeMs;(!g||g<=m||m!==o.mtimeMs)&&this.fsw._emit(gt.CHANGE,t,c),o=c}}},l=this._watchWithNodeFs(t,u);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(t)){if(!this.fsw._throttle(gt.ADD,t,0))return;this.fsw._emit(gt.ADD,t,a)}return l}async _handleSymlink(t,a,r,n){if(this.fsw.closed)return;let i=t.fullPath,s=this.fsw._getWatchedDir(a);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let o;try{o=await oi(r)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(s.has(n)?this.fsw._symlinkPaths.get(i)!==o&&(this.fsw._symlinkPaths.set(i,o),this.fsw._emit(gt.CHANGE,r,t.stats)):(s.add(n),this.fsw._symlinkPaths.set(i,o),this.fsw._emit(gt.ADD,r,t.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(i))return!0;this.fsw._symlinkPaths.set(i,!0)}_handleRead(t,a,r,n,i,s,o){if(t=me.join(t,""),o=this.fsw._throttle("readdir",t,1e3),!o)return;let u=this.fsw._getWatchedDir(r.path),l=new Set,f=this.fsw._readdirp(t,{fileFilter:c=>r.filterPath(c),directoryFilter:c=>r.filterDir(c)});if(f)return f.on(Vp,async c=>{if(this.fsw.closed){f=void 0;return}let g=c.path,m=me.join(t,g);if(l.add(g),!(c.stats.isSymbolicLink()&&await this._handleSymlink(c,t,m,g))){if(this.fsw.closed){f=void 0;return}(g===n||!n&&!u.has(g))&&(this.fsw._incrReadyCount(),m=me.join(i,me.relative(i,m)),this._addToNodeFs(m,a,r,s+1))}}).on(gt.ERROR,this._boundHandleError),new Promise((c,g)=>{if(!f)return g();f.once(fi,()=>{if(this.fsw.closed){f=void 0;return}let m=o?o.clear():!1;c(void 0),u.getChildren().filter(h=>h!==t&&!l.has(h)).forEach(h=>{this.fsw._remove(t,h)}),f=void 0,m&&this._handleRead(t,!1,r,n,i,s,o)})})}async _handleDir(t,a,r,n,i,s,o){let u=this.fsw._getWatchedDir(me.dirname(t)),l=u.has(me.basename(t));!(r&&this.fsw.options.ignoreInitial)&&!i&&!l&&this.fsw._emit(gt.ADD_DIR,t,a),u.add(me.basename(t)),this.fsw._getWatchedDir(t);let f,c,g=this.fsw.options.depth;if((g==null||n<=g)&&!this.fsw._symlinkPaths.has(o)){if(!i&&(await this._handleRead(t,r,s,i,t,n,f),this.fsw.closed))return;c=this._watchWithNodeFs(t,(m,h)=>{h&&h.mtimeMs===0||this._handleRead(m,!1,s,i,t,n,f)})}return c}async _addToNodeFs(t,a,r,n,i){let s=this.fsw._emitReady;if(this.fsw._isIgnored(t)||this.fsw.closed)return s(),!1;let o=this.fsw._getWatchHelpers(t);r&&(o.filterPath=u=>r.filterPath(u),o.filterDir=u=>r.filterDir(u));try{let u=await zp[o.statMethod](o.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(o.watchPath,u))return s(),!1;let l=this.fsw.options.followSymlinks,f;if(u.isDirectory()){let c=me.resolve(t),g=l?await oi(t):t;if(this.fsw.closed||(f=await this._handleDir(o.watchPath,u,a,n,i,o,g),this.fsw.closed))return;c!==g&&g!==void 0&&this.fsw._symlinkPaths.set(c,g)}else if(u.isSymbolicLink()){let c=l?await oi(t):t;if(this.fsw.closed)return;let g=me.dirname(o.watchPath);if(this.fsw._getWatchedDir(g).add(o.watchPath),this.fsw._emit(gt.ADD,o.watchPath,u),f=await this._handleDir(g,u,a,n,t,o,c),this.fsw.closed)return;c!==void 0&&this.fsw._symlinkPaths.set(me.resolve(t),c)}else f=this._handleFile(o.watchPath,u,a);return s(),f&&this.fsw._addPathCloser(t,f),!1}catch(u){if(this.fsw._handleError(u))return s(),t}}};var di="/",th="//",dl=".",rh="..",ah="string",nh=/\\/g,ol=/\/\//,ih=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/,sh=/^\.[/\\]/;function Ga(e){return Array.isArray(e)?e:[e]}var pi=e=>typeof e=="object"&&e!==null&&!(e instanceof RegExp);function oh(e){return typeof e=="function"?e:typeof e=="string"?t=>e===t:e instanceof RegExp?t=>e.test(t):typeof e=="object"&&e!==null?t=>{if(e.path===t)return!0;if(e.recursive){let a=Z.relative(e.path,t);return a?!a.startsWith("..")&&!Z.isAbsolute(a):!1}return!1}:()=>!1}function uh(e){if(typeof e!="string")throw new Error("string expected");e=Z.normalize(e),e=e.replace(/\\/g,"/");let t=!1;e.startsWith("//")&&(t=!0);let a=/\/\//;for(;e.match(a);)e=e.replace(a,"/");return t&&(e="/"+e),e}function ul(e,t,a){let r=uh(t);for(let n=0;n<e.length;n++){let i=e[n];if(i(r,a))return!0}return!1}function lh(e,t){if(e==null)throw new TypeError("anymatch: specify first argument");let r=Ga(e).map(n=>oh(n));return t==null?(n,i)=>ul(r,n,i):ul(r,t)}var ll=e=>{let t=Ga(e).flat();if(!t.every(a=>typeof a===ah))throw new TypeError(`Non-string provided as watch path: ${t}`);return t.map(pl)},fl=e=>{let t=e.replace(nh,di),a=!1;for(t.startsWith(th)&&(a=!0);t.match(ol);)t=t.replace(ol,di);return a&&(t=di+t),t},pl=e=>fl(Z.normalize(fl(e))),cl=(e="")=>t=>typeof t=="string"?pl(Z.isAbsolute(t)?t:Z.join(e,t)):t,fh=(e,t)=>Z.isAbsolute(e)?e:Z.join(t,e),ch=Object.freeze(new Set),hi=class{constructor(t,a){this.path=t,this._removeWatcher=a,this.items=new Set}add(t){let{items:a}=this;a&&t!==dl&&t!==rh&&a.add(t)}async remove(t){let{items:a}=this;if(!a||(a.delete(t),a.size>0))return;let r=this.path;try{await Jp(r)}catch{this._removeWatcher&&this._removeWatcher(Z.dirname(r),Z.basename(r))}}has(t){let{items:a}=this;if(a)return a.has(t)}getChildren(){let{items:t}=this;return t?[...t.values()]:[]}dispose(){this.items.clear(),this.path="",this._removeWatcher=Ha,this.items=ch,Object.freeze(this)}},dh="stat",ph="lstat",yi=class{constructor(t,a,r){this.fsw=r;let n=t;this.path=t=t.replace(sh,""),this.watchPath=n,this.fullWatchPath=Z.resolve(n),this.dirParts=[],this.dirParts.forEach(i=>{i.length>1&&i.pop()}),this.followSymlinks=a,this.statMethod=a?dh:ph}entryPath(t){return Z.join(this.watchPath,Z.relative(this.watchPath,t.fullPath))}filterPath(t){let{stats:a}=t;if(a&&a.isSymbolicLink())return this.filterDir(t);let r=this.entryPath(t);return this.fsw._isntIgnored(r,a)&&this.fsw._hasReadPermissions(a)}filterDir(t){return this.fsw._isntIgnored(this.entryPath(t),t.stats)}},gi=class extends eh{constructor(t={}){super(),this.closed=!1,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._streams=new Set,this._symlinkPaths=new Map,this._watched=new Map,this._pendingWrites=new Map,this._pendingUnlinks=new Map,this._readyCount=0,this._readyEmitted=!1;let a=t.awaitWriteFinish,r={stabilityThreshold:2e3,pollInterval:100},n={persistent:!0,ignoreInitial:!1,ignorePermissionErrors:!1,interval:100,binaryInterval:300,followSymlinks:!0,usePolling:!1,atomic:!0,...t,ignored:t.ignored?Ga(t.ignored):Ga([]),awaitWriteFinish:a===!0?r:typeof a=="object"?{...r,...a}:!1};il&&(n.usePolling=!0),n.atomic===void 0&&(n.atomic=!n.usePolling);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let u=i.toLowerCase();u==="false"||u==="0"?n.usePolling=!1:u==="true"||u==="1"?n.usePolling=!0:n.usePolling=!!u}let s=process.env.CHOKIDAR_INTERVAL;s&&(n.interval=Number.parseInt(s,10));let o=0;this._emitReady=()=>{o++,o>=this._readyCount&&(this._emitReady=Ha,this._readyEmitted=!0,process.nextTick(()=>this.emit(ve.READY)))},this._emitRaw=(...u)=>this.emit(ve.RAW,...u),this._boundRemove=this._remove.bind(this),this.options=n,this._nodeFsHandler=new qa(this),Object.freeze(n)}_addIgnoredPath(t){if(pi(t)){for(let a of this._ignoredPaths)if(pi(a)&&a.path===t.path&&a.recursive===t.recursive)return}this._ignoredPaths.add(t)}_removeIgnoredPath(t){if(this._ignoredPaths.delete(t),typeof t=="string")for(let a of this._ignoredPaths)pi(a)&&a.path===t&&this._ignoredPaths.delete(a)}add(t,a,r){let{cwd:n}=this.options;this.closed=!1,this._closePromise=void 0;let i=ll(t);return n&&(i=i.map(s=>fh(s,n))),i.forEach(s=>{this._removeIgnoredPath(s)}),this._userIgnored=void 0,this._readyCount||(this._readyCount=0),this._readyCount+=i.length,Promise.all(i.map(async s=>{let o=await this._nodeFsHandler._addToNodeFs(s,!r,void 0,0,a);return o&&this._emitReady(),o})).then(s=>{this.closed||s.forEach(o=>{o&&this.add(Z.dirname(o),Z.basename(a||o))})}),this}unwatch(t){if(this.closed)return this;let a=ll(t),{cwd:r}=this.options;return a.forEach(n=>{!Z.isAbsolute(n)&&!this._closers.has(n)&&(r&&(n=Z.join(r,n)),n=Z.resolve(n)),this._closePath(n),this._addIgnoredPath(n),this._watched.has(n)&&this._addIgnoredPath({path:n,recursive:!0}),this._userIgnored=void 0}),this}close(){if(this._closePromise)return this._closePromise;this.closed=!0,this.removeAllListeners();let t=[];return this._closers.forEach(a=>a.forEach(r=>{let n=r();n instanceof Promise&&t.push(n)})),this._streams.forEach(a=>a.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(a=>a.dispose()),this._closers.clear(),this._watched.clear(),this._streams.clear(),this._symlinkPaths.clear(),this._throttled.clear(),this._closePromise=t.length?Promise.all(t).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let t={};return this._watched.forEach((a,r)=>{let i=(this.options.cwd?Z.relative(this.options.cwd,r):r)||dl;t[i]=a.getChildren().sort()}),t}emitWithAll(t,a){this.emit(t,...a),t!==ve.ERROR&&this.emit(ve.ALL,t,...a)}async _emit(t,a,r){if(this.closed)return;let n=this.options;ci&&(a=Z.normalize(a)),n.cwd&&(a=Z.relative(n.cwd,a));let i=[a];r!=null&&i.push(r);let s=n.awaitWriteFinish,o;if(s&&(o=this._pendingWrites.get(a)))return o.lastChange=new Date,this;if(n.atomic){if(t===ve.UNLINK)return this._pendingUnlinks.set(a,[t,...i]),setTimeout(()=>{this._pendingUnlinks.forEach((u,l)=>{this.emit(...u),this.emit(ve.ALL,...u),this._pendingUnlinks.delete(l)})},typeof n.atomic=="number"?n.atomic:100),this;t===ve.ADD&&this._pendingUnlinks.has(a)&&(t=ve.CHANGE,this._pendingUnlinks.delete(a))}if(s&&(t===ve.ADD||t===ve.CHANGE)&&this._readyEmitted){let u=(l,f)=>{l?(t=ve.ERROR,i[0]=l,this.emitWithAll(t,i)):f&&(i.length>1?i[1]=f:i.push(f),this.emitWithAll(t,i))};return this._awaitWriteFinish(a,s.stabilityThreshold,t,u),this}if(t===ve.CHANGE&&!this._throttle(ve.CHANGE,a,50))return this;if(n.alwaysStat&&r===void 0&&(t===ve.ADD||t===ve.ADD_DIR||t===ve.CHANGE)){let u=n.cwd?Z.join(n.cwd,a):a,l;try{l=await Zp(u)}catch{}if(!l||this.closed)return;i.push(l)}return this.emitWithAll(t,i),this}_handleError(t){let a=t&&t.code;return t&&a!=="ENOENT"&&a!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||a!=="EPERM"&&a!=="EACCES")&&this.emit(ve.ERROR,t),t||this.closed}_throttle(t,a,r){this._throttled.has(t)||this._throttled.set(t,new Map);let n=this._throttled.get(t);if(!n)throw new Error("invalid throttle");let i=n.get(a);if(i)return i.count++,!1;let s,o=()=>{let l=n.get(a),f=l?l.count:0;return n.delete(a),clearTimeout(s),l&&clearTimeout(l.timeoutObject),f};s=setTimeout(o,r);let u={timeoutObject:s,clear:o,count:0};return n.set(a,u),u}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(t,a,r,n){let i=this.options.awaitWriteFinish;if(typeof i!="object")return;let s=i.pollInterval,o,u=t;this.options.cwd&&!Z.isAbsolute(t)&&(u=Z.join(this.options.cwd,t));let l=new Date,f=this._pendingWrites;function c(g){Xp(u,(m,h)=>{if(m||!f.has(t)){m&&m.code!=="ENOENT"&&n(m);return}let v=Number(new Date);g&&h.size!==g.size&&(f.get(t).lastChange=v);let E=f.get(t);v-E.lastChange>=a?(f.delete(t),n(void 0,h)):o=setTimeout(c,s,h)})}f.has(t)||(f.set(t,{lastChange:l,cancelWait:()=>(f.delete(t),clearTimeout(o),r)}),o=setTimeout(c,s))}_isIgnored(t,a){if(this.options.atomic&&ih.test(t))return!0;if(!this._userIgnored){let{cwd:r}=this.options,i=(this.options.ignored||[]).map(cl(r)),o=[...[...this._ignoredPaths].map(cl(r)),...i];this._userIgnored=lh(o,void 0)}return this._userIgnored(t,a)}_isntIgnored(t,a){return!this._isIgnored(t,a)}_getWatchHelpers(t){return new yi(t,this.options.followSymlinks,this)}_getWatchedDir(t){let a=Z.resolve(t);return this._watched.has(a)||this._watched.set(a,new hi(a,this._boundRemove)),this._watched.get(a)}_hasReadPermissions(t){return this.options.ignorePermissionErrors?!0:!!(Number(t.mode)&256)}_remove(t,a,r){let n=Z.join(t,a),i=Z.resolve(n);if(r=r??(this._watched.has(n)||this._watched.has(i)),!this._throttle("remove",n,100))return;!r&&this._watched.size===1&&this.add(t,a,!0),this._getWatchedDir(n).getChildren().forEach(g=>this._remove(n,g));let u=this._getWatchedDir(t),l=u.has(a);u.remove(a),this._symlinkPaths.has(i)&&this._symlinkPaths.delete(i);let f=n;if(this.options.cwd&&(f=Z.relative(this.options.cwd,n)),this.options.awaitWriteFinish&&this._pendingWrites.has(f)&&this._pendingWrites.get(f).cancelWait()===ve.ADD)return;this._watched.delete(n),this._watched.delete(i);let c=r?ve.UNLINK_DIR:ve.UNLINK;l&&!this._isIgnored(n)&&this._emit(c,n),this._closePath(n)}_closePath(t){this._closeFile(t);let a=Z.dirname(t);this._getWatchedDir(a).remove(Z.basename(t))}_closeFile(t){let a=this._closers.get(t);a&&(a.forEach(r=>r()),this._closers.delete(t))}_addPathCloser(t,a){if(!a)return;let r=this._closers.get(t);r||(r=[],this._closers.set(t,r)),r.push(a)}_readdirp(t,a){if(this.closed)return;let r={type:ve.ALL,alwaysStat:!0,lstat:!0,...a,depth:0},n=el(t,r);return this._streams.add(n),n.once(nl,()=>{n=void 0}),n.once(fi,()=>{n&&(this._streams.delete(n),n=void 0)}),n}};function hl(e,t={}){let a=new gi(t);return a.add(e),a}function vi(e,t={}){let a=t.debounceMs||16,r=new Map;function n(c,g){return(...m)=>{let h=r.get(g);h&&clearTimeout(h);let v=setTimeout(()=>{c(...m),r.delete(g)},a);r.set(g,v)}}let i=new Map;async function s(){try{let c=await Oa(e,{ignore:t.ignore});for(let g of c)await o(g)}catch(c){l(c)}}async function o(c){try{let g=i.get(c),m=await jr(c,e,!1);if(!m||m.length===0||g&&!Hu(c,m))return;await jr(c,e,!0);let h=mi.normalize(c);g?(i.set(c,m),t.onRouteChanged&&t.onRouteChanged(h,m)):(i.set(c,m),t.onRouteAdded&&t.onRouteAdded(h,m))}catch(g){console.log(`\u26A0\uFE0F Error processing file ${c}:`,g),l(g)}}function u(c){let g=mi.normalize(c),m=i.get(g);m&&m.length>0&&t.onRouteRemoved&&t.onRouteRemoved(g,m),i.delete(g)}function l(c){t.onError&&c instanceof Error?t.onError(c):console.error("\u26A0\uFE0F Route watcher error:",c)}let f=hl(e,{awaitWriteFinish:{stabilityThreshold:50,pollInterval:10},usePolling:!1,atomic:!0,followSymlinks:!1,depth:10,ignored:[/(^|[/\\])\../,/node_modules/,/\.git/,/\.DS_Store/,/Thumbs\.db/,/\.(test|spec)\.(ts|js)$/,/\.d\.ts$/,/\.map$/,/~$/,...t.ignore||[]]});return f.on("add",c=>{n(o,c)(c)}).on("change",c=>{n(o,c)(c)}).on("unlink",c=>{n(u,c)(c)}).on("error",l),s().catch(l),{close:()=>(r.forEach(c=>clearTimeout(c)),r.clear(),f.close()),getRoutes:()=>{let c=[];for(let g of i.values())c.push(...g);return c},getRoutesByFile:()=>new Map(i)}}import{z as vh}from"zod";import{z as hh}from"zod";function Ci(e,t){return t instanceof hh.ZodObject?t.strict().parse(e):t.parse(e)}import{z as yh}from"zod";function Ei(e,t){return t instanceof yh.ZodObject?t.strict().parse(e):t.parse(e)}import{z as gh}from"zod";function xi(e,t){return t instanceof gh.ZodObject?t.strict().parse(e):t.parse(e)}import{z as mh}from"zod";function Si(e,t){return t instanceof mh.ZodObject?t.strict().parse(e):t.parse(e)}function Ti(e,t=!1){return{name:"RequestValidator",execute:async(r,n)=>{if(e.params&&r.request.params)try{r.request.params=Ei(r.request.params,e.params)}catch(i){let s=Qa(i),o=s.reduce((u,l)=>u+l.messages.length,0);throw new Br("Request validation failed",{fields:s,errorCount:o,section:"params"})}if(e.query&&r.request.query)try{r.request.query=xi(r.request.query,e.query)}catch(i){let s=Qa(i),o=s.reduce((u,l)=>u+l.messages.length,0);throw new Br("Request validation failed",{fields:s,errorCount:o,section:"query"})}if(e.body)try{r.request.body=Ci(r.request.body,e.body)}catch(i){let s=Qa(i),o=s.reduce((u,l)=>u+l.messages.length,0);throw new Br("Request validation failed",{fields:s,errorCount:o,section:"body"})}await n()},debug:t}}function bi(e,t=!1){return{name:"ResponseValidator",execute:async(r,n)=>{let i=r.response.json;r.response.json=(s,o)=>{try{let u=Si(s,e);return r.response.json=i,i.call(r.response,u,o)}catch(u){throw r.response.json=i,new Ar("Response validation failed",{responseSchema:e.description||"Unknown schema",validationError:Qa(u),originalResponse:s})}},await n()},debug:t}}function Qa(e){if(e instanceof vh.ZodError){let t=new Map;for(let a of e.issues){let r=a.path.length>0?a.path.join("."):"root";t.has(r)||t.set(r,[]),t.get(r).push(a.message)}return Array.from(t.entries()).map(([a,r])=>({field:a,messages:r}))}return e instanceof Error?[{field:"unknown",messages:[e.message]}]:[{field:"unknown",messages:[String(e)]}]}async function Ii(e,t,a){let r=[...t.middleware||[]];t.schema&&((t.schema.params||t.schema.query||t.schema.body)&&r.unshift(Ti(t.schema)),t.schema.response&&r.push(bi(t.schema.response))),await lr([...r])(e,async()=>{let i=await t.handler(e,a);!e.response.sent&&i!==void 0&&e.response.json(i)})}function Wa(e,t,a){let r=t.exec(e);if(!r)return{};let n={};for(let i=0;i<a.length;i++)n[a[i]]=r[i+1]||"";return n}function wi(e){let t=[];if(e==="/")return{pattern:/^\/$/,paramNames:[]};let a=e.replace(/([.+*?^$(){}|\\])/g,"\\$1");return a=a.replace(/\/:([^/]+)/g,(n,i)=>(t.push(i),"/([^/]+)")).replace(/\/\[([^\]]+)\]/g,(n,i)=>(t.push(i),"/([^/]+)")),a=`${a}(?:/)?`,{pattern:new RegExp(`^${a}$`),paramNames:t}}function Ai(){let e=[];return{add(t,a,r){let{pattern:n,paramNames:i}=wi(t),s={path:t,method:a,pattern:n,paramNames:i,routeOptions:r},o=e.findIndex(u=>i.length<u.paramNames.length);o===-1?e.push(s):e.splice(o,0,s)},remove(t){for(let a=e.length-1;a>=0;a--)e[a].path===t&&e.splice(a,1)},clear(){e.length=0},match(t,a){let r=t.split("?")[0];if(!r)return null;for(let i of e){if(i.method!==a)continue;if(i.pattern.exec(r)){let o=Wa(t,i.pattern,i.paramNames);return{route:i.routeOptions,params:o}}}return e.find(i=>i.method!==a&&i.pattern.test(t))?{route:null,params:{},methodNotAllowed:!0,allowedMethods:e.filter(i=>i.pattern.test(t)).map(i=>i.method)}:null},getRoutes(){return e.map(t=>({path:t.path,method:t.method}))},findRoutes(t){return e.filter(a=>a.pattern.test(t)).map(a=>({path:a.path,method:a.method,params:Wa(t,a.pattern,a.paramNames)}))}}}function yl(){return{routesByPath:new Map,routesByFile:new Map,pathToFile:new Map}}function Qt(e,t,a){console.log(`Updating routes from file: ${t}`);let r=e.routesByFile.get(t)||new Set,n=new Set(a.map(l=>l.path)),i=a.filter(l=>!r.has(l.path)),s=Array.from(r).filter(l=>!n.has(l)),u=a.filter(l=>r.has(l.path)).filter(l=>{let f=e.routesByPath.get(l.path);return!f||!Eh(f,l)});return Ch(e,t,{added:i,removed:s,changed:u}),{added:i,removed:s,changed:u}}function gl(e){return Array.from(e.routesByPath.values())}function Ch(e,t,a){let{added:r,removed:n,changed:i}=a;n.forEach(o=>{e.routesByPath.delete(o),e.pathToFile.delete(o)}),[...r,...i].forEach(o=>{e.routesByPath.set(o.path,o),e.pathToFile.set(o.path,t)});let s=new Set([...r.map(o=>o.path),...i.map(o=>o.path),...Array.from(e.routesByFile.get(t)||[]).filter(o=>!n.includes(o))]);s.size>0?e.routesByFile.set(t,s):e.routesByFile.delete(t)}function Eh(e,t){if(e.path!==t.path)return!1;let a=Object.keys(e).filter(n=>n!=="path").sort(),r=Object.keys(t).filter(n=>n!=="path").sort();return a.length!==r.length?!1:a.every(n=>{let i=e[n],s=t[n];return typeof i==typeof s})}function Bi(e,t){Object.entries(e).forEach(([a,r])=>{a==="path"||!r||t.add(e.path,a,r)})}function Xr(e,t){"remove"in t&&typeof t.remove=="function"?t.remove(e):console.warn("Matcher does not support selective removal, consider adding remove() method")}function ml(e,t){Xr(e.path,t),Bi(e,t)}var xh={routesDir:"./routes",basePath:"/",watchMode:process.env.NODE_ENV==="development"};function vl(e){let t={...xh,...e};e.basePath&&!e.basePath.startsWith("/")&&console.warn("Base path does nothing");let a=yl(),r=Ai(),n=!1,i=null,s=null,o=new Set([t.routesDir]);function u(h){console.log(`
49
+ \u{1F527} APPLYING MATCHER CHANGES:`),console.log(` Adding ${h.added.length} routes`),console.log(` Removing ${h.removed.length} routes`),console.log(` Updating ${h.changed.length} routes`),h.removed.forEach(v=>{console.log(` \u2796 Removing: ${v}`),Xr(v,r)}),h.added.forEach(v=>{let E=Object.keys(v).filter(T=>T!=="path");console.log(` \u2795 Adding: ${v.path} [${E.join(", ")}]`),Bi(v,r)}),h.changed.forEach(v=>{let E=Object.keys(v).filter(T=>T!=="path");console.log(` \u{1F504} Updating: ${v.path} [${E.join(", ")}]`),ml(v,r)}),console.log(`\u2705 Matcher changes applied
50
+ `)}function l(h,v){try{let E=Qt(a,v,h);return u(E),E}catch(E){throw console.error(`\u26A0\uFE0F Route conflicts from ${v}:`,E),E}}async function f(h,v,E){try{let T=await Qu(h),I=T.map(L=>E?{...L,path:`${E}${L.path}`}:L),A=l(I,v);console.log(`Loaded ${T.length} routes from ${v}${E?` with prefix ${E}`:""} (${A.added.length} added, ${A.changed.length} changed, ${A.removed.length} removed)`)}catch(T){throw console.error(`\u26A0\uFE0F Failed to load routes from ${v}:`,T),T}}async function c(){return n||i||(i=(async()=>{try{await Promise.all(Array.from(o).map(h=>f(h,h))),t.watchMode&&g(),n=!0}catch(h){throw console.error("\u26A0\uFE0F Failed to initialize router:",h),h}})()),i}function g(){s||(s=new Map);for(let h of o)if(!s.has(h)){let v=vi(h,{debounceMs:16,ignore:["node_modules",".git"],onRouteAdded:(E,T)=>{try{let I=Qt(a,E,T);u(I)}catch(I){console.error(`Error adding routes from ${h}:`,I)}},onRouteChanged:ni(async(E,T)=>{try{console.log(`Processing changes for ${E}`);let I=Qt(a,E,T);console.log(`Changes detected: ${I.added.length} added, ${I.changed.length} changed, ${I.removed.length} removed`),u(I),console.log(`Route changes applied: ${I.added.length} added, ${I.changed.length} changed, ${I.removed.length} removed`)}catch(I){console.error(`\u26A0\uFE0F Error updating routes from ${h}:`,I)}},h),onRouteRemoved:(E,T)=>{console.log(`File removed: ${E} with ${T.length} routes`);try{T.forEach(I=>{Xr(I.path,r)}),ai(E)}catch(I){console.error(`\u26A0\uFE0F Error removing routes from ${E}:`,I)}},onError:E=>{console.error(`\u26A0\uFE0F Route watcher error for ${h}:`,E)}});s.set(h,v)}}function m(h,v){s||(s=new Map);let E=vi(h,{debounceMs:16,ignore:["node_modules",".git"],onRouteAdded:(T,I)=>{try{let A=I.map(N=>v?{...N,path:`${v}${N.path}`}:N),L=Qt(a,T,A);u(L)}catch(A){console.error(`\u26A0\uFE0F Error adding routes from ${h}:`,A)}},onRouteChanged:ni(async(T,I)=>{try{let A=I.map(N=>v?{...N,path:`${v}${N.path}`}:N),L=Qt(a,T,A);u(L)}catch(A){console.error(`\u26A0\uFE0F Error updating routes from ${h}:`,A)}},h),onRouteRemoved:(T,I)=>{try{I.forEach(A=>{let L=v?`${v}${A.path}`:A.path;Xr(L,r)}),ai(T)}catch(A){console.error(`Error removing routes from ${T}:`,A)}},onError:T=>{console.error(`\u26A0\uFE0F Route watcher error for ${h}:`,T)}});return s.set(h,E),E}return c().catch(h=>{console.error("\u26A0\uFE0F Failed to initialize router on creation:",h)}),{async handleRequest(h){n||(console.log("\u{1F504} Router not initialized, initializing..."),await c());let{method:v,path:E}=h.request;console.log(`
51
+ \u{1F4E5} Handling request: ${v} ${E}`);let T=r.match(E,v);if(!T)throw console.log(`\u274C No match found for: ${v} ${E}`),new sr("Not found");if(console.log(`\u2705 Route matched: ${v} ${E}`),console.log(` Params: ${JSON.stringify(T.params)}`),T.methodNotAllowed){h.response.status(405).json({error:"\u274C Method Not Allowed",allowed:T.allowedMethods}),T.allowedMethods&&T.allowedMethods.length>0&&h.response.header("Allow",T.allowedMethods.join(", "));return}h.request.params=T.params,await Ii(h,T.route,T.params)},getRoutes(){return gl(a)},addRoute(h){let v=Qt(a,"programmatic",[h]);u(v)},addRoutes(h){let v=Qt(a,"programmatic",h);return u(v),v},async addRouteDirectory(h,v={}){if(o.has(h)){console.warn(`Route directory ${h} already registered`);return}o.add(h),n&&(await f(h,h,v.prefix),t.watchMode&&m(h,v.prefix))},getRouteConflicts(){return[]},async close(){if(s){for(let h of s.values())await h.close();s.clear()}}}}var bh={port:3e3,host:"localhost",routesDir:"./routes",http2:{enabled:!0},middleware:[],plugins:[]};function Ih(e={}){let t={...bh};return Fi({routesDir:e.routesDir||t.routesDir}),{port:e.port??t.port,host:e.host??t.host,routesDir:e.routesDir??t.routesDir,http2:{enabled:e.http2?.enabled??t.http2?.enabled,keyFile:e.http2?.keyFile??t.http2?.keyFile,certFile:e.http2?.certFile??t.http2?.certFile},middleware:[...t.middleware||[],...e.middleware||[]],plugins:[...t.plugins||[],...e.plugins||[]]}}function wh(e,t,a,r){return async()=>(await Ah(e,a,r),await e.pluginManager.initializePlugins(e),await Du(e,t),await e.pluginManager.onServerStart(e,e.server),Bh(e),e)}async function Ah(e,t,a){for(let r of t)e.use(r);for(let r of a)await e.register(r)}function Bh(e){let t=ku(()=>e.close());e._signalHandlers=t,e.events.emit("started")}function Rh(e){return async t=>{if(!e.server)return;let a={...t};e._signalHandlers&&(e._signalHandlers.unregister(),delete e._signalHandlers),await Lu(e,a)}}function _h(e){return t=>{let a=Array.isArray(t)?t:[t];return e.middleware.push(...a),e}}function Nh(e){return async t=>(Ou(t),e.plugins.push(t),await t.register(e),e)}function Ri(e={}){let t=Ih(e),a;try{a=Uu(t)}catch(h){throw h instanceof Error?new Error(`Failed to create server: ${h.message}`):new Error(`Failed to create server: ${String(h)}`)}let{port:r,host:n,middleware:i,plugins:s}=a,o=Array.isArray(i)?[...i]:[],u=Array.isArray(s)?[...s]:[],l=new Sh,f=vl({routesDir:a.routesDir,watchMode:process.env.NODE_ENV==="development"}),c=Fu({debug:process.env.NODE_ENV==="development",continueOnError:!0}),g=new Th,m={server:null,port:r,host:n,context:l,events:g,plugins:[],middleware:[],_signalHandlers:{unregister:()=>{}},use:()=>m,register:async()=>m,listen:async()=>m,close:async()=>{},router:f,pluginManager:c};return m.listen=wh(m,a,o,u),m.close=Rh(m),m.use=_h(m),m.register=Nh(m),m}var _i=class extends Ge{constructor(t,a=void 0,r=void 0){super("UNAUTHORIZED",t,401,r??Xe(),a)}};var Ni=class extends Ge{constructor(t,a=void 0,r=void 0){super("FORBIDDEN",t,403,r??Xe(),a)}};var Pi=class extends Ge{constructor(t,a=void 0,r=void 0){super("CONFLICT",t,409,r??Xe(),a)}};var Di=class extends Ge{constructor(t,a=void 0,r=void 0){super("RATE_LIMITED",t,429,r??Xe(),a)}};var Li=class extends Ge{constructor(t,a,r){super("UPLOAD_TIMEOUT",t,408,r??Xe(),a)}};var ki=class extends Ge{constructor(t,a,r){super("UNPROCESSABLE_ENTITY",t,422,r??Xe(),a)}};var Ph="0.1.0",Dh={createServer:Ri},Lh={createDeleteRoute:Hi,createGetRoute:Mi,createHeadRoute:Gi,createOptionsRoute:Qi,createPatchRoute:zi,createPostRoute:Ki,createPutRoute:qi},kh={createMiddleware:$a,compose:lr},Uh={createPlugin:Ya},qv={createServer:Ri,createMiddleware:$a,createPlugin:Ya,Server:Dh,Router:Lh,Middleware:kh,Plugins:Uh,VERSION:Ph};export{qv as Blaize,Ge as BlaizeError,Pi as ConflictError,Fh as ErrorSeverity,jt as ErrorType,Ni as ForbiddenError,Ar as InternalServerError,kh as MiddlewareAPI,sr as NotFoundError,El as PayloadTooLargeError,Uh as PluginsAPI,Di as RateLimitError,Li as RequestTimeoutError,Lh as RouterAPI,Dh as ServerAPI,_i as UnauthorizedError,ki as UnprocessableEntityError,xl as UnsupportedMediaTypeError,Ph as VERSION,Br as ValidationError,lr as compose,Hi as createDeleteRoute,Mi as createGetRoute,Gi as createHeadRoute,$a as createMiddleware,Qi as createOptionsRoute,zi as createPatchRoute,Ya as createPlugin,Ki as createPostRoute,qi as createPutRoute,Ri as createServer,Oh as isBodyParseError};
52
+ /*! Bundled license information:
53
+
54
+ chokidar/esm/index.js:
55
+ (*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) *)
56
+ */
3172
57
  //# sourceMappingURL=index.js.map