openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
38,464 lines • 1.37 MB
JavaScript
import { a as __require, n as __esmMin, o as __toCommonJS, r as __exportAll, s as __toESM, t as __commonJSMin } from "./rolldown-runtime-Dr7-SnC6.js";
import { a as require_build$3, i as require_build$2, n as require_base64, o as init_tslib_es6$1, r as require_bytes, s as tslib_es6_exports$1, t as require_encoding } from "./encoding-DrEPzsV2.js";
import { n as supports_color_exports, t as init_supports_color } from "./supports-color-Bm9uHdjc.js";
import * as net$1 from "node:net";
import { connect, createServer, isIP, isIPv4, isIPv6 } from "node:net";
import * as os$1 from "node:os";
import * as nc from "node:crypto";
import { EventEmitter } from "node:events";
import * as tls$1 from "node:tls";
import { promises } from "node:dns";
import * as timers from "node:timers/promises";
import { isIPv4 as isIPv4$1 } from "net";
import { createCipheriv as createCipheriv$1, createDecipheriv as createDecipheriv$1, createHash as createHash$1, createHmac as createHmac$1, createSign, randomBytes as randomBytes$1, randomUUID as randomUUID$1, timingSafeEqual as timingSafeEqual$1, webcrypto } from "crypto";
import { createSocket } from "dgram";
import { setTimeout as setTimeout$2 } from "timers/promises";
import { performance as performance$1 } from "perf_hooks";
//#region node_modules/.pnpm/debug@4.4.0_supports-color@10.2.2/node_modules/debug/src/common.js
var require_common$2 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
*/
function setup(env) {
createDebug.debug = createDebug;
createDebug.default = createDebug;
createDebug.coerce = coerce;
createDebug.disable = disable;
createDebug.enable = enable;
createDebug.enabled = enabled;
createDebug.humanize = __require("ms");
createDebug.destroy = destroy;
Object.keys(env).forEach((key) => {
createDebug[key] = env[key];
});
/**
* The currently active debug mode names, and names to skip.
*/
createDebug.names = [];
createDebug.skips = [];
/**
* Map of special "%n" handling functions, for the debug "format" argument.
*
* Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
*/
createDebug.formatters = {};
/**
* Selects a color for a debug namespace
* @param {String} namespace The namespace string for the debug instance to be colored
* @return {Number|String} An ANSI color code for the given namespace
* @api private
*/
function selectColor(namespace) {
let hash = 0;
for (let i = 0; i < namespace.length; i++) {
hash = (hash << 5) - hash + namespace.charCodeAt(i);
hash |= 0;
}
return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
createDebug.selectColor = selectColor;
/**
* Create a debugger with the given `namespace`.
*
* @param {String} namespace
* @return {Function}
* @api public
*/
function createDebug(namespace) {
let prevTime;
let enableOverride = null;
let namespacesCache;
let enabledCache;
function debug(...args) {
if (!debug.enabled) return;
const self = debug;
const curr = Number(/* @__PURE__ */ new Date());
self.diff = curr - (prevTime || curr);
self.prev = prevTime;
self.curr = curr;
prevTime = curr;
args[0] = createDebug.coerce(args[0]);
if (typeof args[0] !== "string") args.unshift("%O");
let index = 0;
args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
if (match === "%%") return "%";
index++;
const formatter = createDebug.formatters[format];
if (typeof formatter === "function") {
const val = args[index];
match = formatter.call(self, val);
args.splice(index, 1);
index--;
}
return match;
});
createDebug.formatArgs.call(self, args);
(self.log || createDebug.log).apply(self, args);
}
debug.namespace = namespace;
debug.useColors = createDebug.useColors();
debug.color = createDebug.selectColor(namespace);
debug.extend = extend;
debug.destroy = createDebug.destroy;
Object.defineProperty(debug, "enabled", {
enumerable: true,
configurable: false,
get: () => {
if (enableOverride !== null) return enableOverride;
if (namespacesCache !== createDebug.namespaces) {
namespacesCache = createDebug.namespaces;
enabledCache = createDebug.enabled(namespace);
}
return enabledCache;
},
set: (v) => {
enableOverride = v;
}
});
if (typeof createDebug.init === "function") createDebug.init(debug);
return debug;
}
function extend(namespace, delimiter) {
const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace);
newDebug.log = this.log;
return newDebug;
}
/**
* Enables a debug mode by namespaces. This can include modes
* separated by a colon and wildcards.
*
* @param {String} namespaces
* @api public
*/
function enable(namespaces) {
createDebug.save(namespaces);
createDebug.namespaces = namespaces;
createDebug.names = [];
createDebug.skips = [];
const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(" ", ",").split(",").filter(Boolean);
for (const ns of split) if (ns[0] === "-") createDebug.skips.push(ns.slice(1));
else createDebug.names.push(ns);
}
/**
* Checks if the given string matches a namespace template, honoring
* asterisks as wildcards.
*
* @param {String} search
* @param {String} template
* @return {Boolean}
*/
function matchesTemplate(search, template) {
let searchIndex = 0;
let templateIndex = 0;
let starIndex = -1;
let matchIndex = 0;
while (searchIndex < search.length) if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
if (template[templateIndex] === "*") {
starIndex = templateIndex;
matchIndex = searchIndex;
templateIndex++;
} else {
searchIndex++;
templateIndex++;
}
} else if (starIndex !== -1) {
templateIndex = starIndex + 1;
matchIndex++;
searchIndex = matchIndex;
} else return false;
while (templateIndex < template.length && template[templateIndex] === "*") templateIndex++;
return templateIndex === template.length;
}
/**
* Disable debug output.
*
* @return {String} namespaces
* @api public
*/
function disable() {
const namespaces = [...createDebug.names, ...createDebug.skips.map((namespace) => "-" + namespace)].join(",");
createDebug.enable("");
return namespaces;
}
/**
* Returns true if the given mode name is enabled, false otherwise.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
function enabled(name) {
for (const skip of createDebug.skips) if (matchesTemplate(name, skip)) return false;
for (const ns of createDebug.names) if (matchesTemplate(name, ns)) return true;
return false;
}
/**
* Coerce `val`.
*
* @param {Mixed} val
* @return {Mixed}
* @api private
*/
function coerce(val) {
if (val instanceof Error) return val.stack || val.message;
return val;
}
/**
* XXX DO NOT USE. This is a temporary stub function.
* XXX It WILL be removed in the next major release.
*/
function destroy() {
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}
createDebug.enable(createDebug.load());
return createDebug;
}
module.exports = setup;
}));
//#endregion
//#region node_modules/.pnpm/debug@4.4.0_supports-color@10.2.2/node_modules/debug/src/browser.js
var require_browser = /* @__PURE__ */ __commonJSMin(((exports, module) => {
/**
* This is the web browser implementation of `debug()`.
*/
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = localstorage();
exports.destroy = (() => {
let warned = false;
return () => {
if (!warned) {
warned = true;
console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
}
};
})();
/**
* Colors.
*/
exports.colors = [
"#0000CC",
"#0000FF",
"#0033CC",
"#0033FF",
"#0066CC",
"#0066FF",
"#0099CC",
"#0099FF",
"#00CC00",
"#00CC33",
"#00CC66",
"#00CC99",
"#00CCCC",
"#00CCFF",
"#3300CC",
"#3300FF",
"#3333CC",
"#3333FF",
"#3366CC",
"#3366FF",
"#3399CC",
"#3399FF",
"#33CC00",
"#33CC33",
"#33CC66",
"#33CC99",
"#33CCCC",
"#33CCFF",
"#6600CC",
"#6600FF",
"#6633CC",
"#6633FF",
"#66CC00",
"#66CC33",
"#9900CC",
"#9900FF",
"#9933CC",
"#9933FF",
"#99CC00",
"#99CC33",
"#CC0000",
"#CC0033",
"#CC0066",
"#CC0099",
"#CC00CC",
"#CC00FF",
"#CC3300",
"#CC3333",
"#CC3366",
"#CC3399",
"#CC33CC",
"#CC33FF",
"#CC6600",
"#CC6633",
"#CC9900",
"#CC9933",
"#CCCC00",
"#CCCC33",
"#FF0000",
"#FF0033",
"#FF0066",
"#FF0099",
"#FF00CC",
"#FF00FF",
"#FF3300",
"#FF3333",
"#FF3366",
"#FF3399",
"#FF33CC",
"#FF33FF",
"#FF6600",
"#FF6633",
"#FF9900",
"#FF9933",
"#FFCC00",
"#FFCC33"
];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
* to support "%c" CSS customizations.
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
function useColors() {
if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) return true;
if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) return false;
let m;
return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}
/**
* Colorize log arguments if enabled.
*
* @api public
*/
function formatArgs(args) {
args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff);
if (!this.useColors) return;
const c = "color: " + this.color;
args.splice(1, 0, c, "color: inherit");
let index = 0;
let lastC = 0;
args[0].replace(/%[a-zA-Z%]/g, (match) => {
if (match === "%%") return;
index++;
if (match === "%c") lastC = index;
});
args.splice(lastC, 0, c);
}
/**
* Invokes `console.debug()` when available.
* No-op when `console.debug` is not a "function".
* If `console.debug` is not available, falls back
* to `console.log`.
*
* @api public
*/
exports.log = console.debug || console.log || (() => {});
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
try {
if (namespaces) exports.storage.setItem("debug", namespaces);
else exports.storage.removeItem("debug");
} catch (error) {}
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
let r;
try {
r = exports.storage.getItem("debug");
} catch (error) {}
if (!r && typeof process !== "undefined" && "env" in process) r = process.env.DEBUG;
return r;
}
/**
* Localstorage attempts to return the localstorage.
*
* This is necessary because safari throws
* when a user disables cookies/localstorage
* and you attempt to access it.
*
* @return {LocalStorage}
* @api private
*/
function localstorage() {
try {
return localStorage;
} catch (error) {}
}
module.exports = require_common$2()(exports);
const { formatters } = module.exports;
/**
* Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
*/
formatters.j = function(v) {
try {
return JSON.stringify(v);
} catch (error) {
return "[UnexpectedJSONParseError]: " + error.message;
}
};
}));
//#endregion
//#region node_modules/.pnpm/debug@4.4.0_supports-color@10.2.2/node_modules/debug/src/node.js
var require_node = /* @__PURE__ */ __commonJSMin(((exports, module) => {
/**
* Module dependencies.
*/
const tty = __require("tty");
const util$1 = __require("util");
/**
* This is the Node.js implementation of `debug()`.
*/
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.destroy = util$1.deprecate(() => {}, "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
/**
* Colors.
*/
exports.colors = [
6,
2,
3,
4,
5,
1
];
try {
const supportsColor = (init_supports_color(), __toCommonJS(supports_color_exports));
if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) exports.colors = [
20,
21,
26,
27,
32,
33,
38,
39,
40,
41,
42,
43,
44,
45,
56,
57,
62,
63,
68,
69,
74,
75,
76,
77,
78,
79,
80,
81,
92,
93,
98,
99,
112,
113,
128,
129,
134,
135,
148,
149,
160,
161,
162,
163,
164,
165,
166,
167,
168,
169,
170,
171,
172,
173,
178,
179,
184,
185,
196,
197,
198,
199,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
214,
215,
220,
221
];
} catch (error) {}
/**
* Build up the default `inspectOpts` object from the environment variables.
*
* $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
*/
exports.inspectOpts = Object.keys(process.env).filter((key) => {
return /^debug_/i.test(key);
}).reduce((obj, key) => {
const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => {
return k.toUpperCase();
});
let val = process.env[key];
if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
else if (val === "null") val = null;
else val = Number(val);
obj[prop] = val;
return obj;
}, {});
/**
* Is stdout a TTY? Colored output is enabled when `true`.
*/
function useColors() {
return "colors" in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd);
}
/**
* Adds ANSI color escape codes if enabled.
*
* @api public
*/
function formatArgs(args) {
const { namespace: name, useColors } = this;
if (useColors) {
const c = this.color;
const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c);
const prefix = ` ${colorCode};1m${name} \u001B[0m`;
args[0] = prefix + args[0].split("\n").join("\n" + prefix);
args.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m");
} else args[0] = getDate() + name + " " + args[0];
}
function getDate() {
if (exports.inspectOpts.hideDate) return "";
return (/* @__PURE__ */ new Date()).toISOString() + " ";
}
/**
* Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr.
*/
function log(...args) {
return process.stderr.write(util$1.formatWithOptions(exports.inspectOpts, ...args) + "\n");
}
/**
* Save `namespaces`.
*
* @param {String} namespaces
* @api private
*/
function save(namespaces) {
if (namespaces) process.env.DEBUG = namespaces;
else delete process.env.DEBUG;
}
/**
* Load `namespaces`.
*
* @return {String} returns the previously persisted debug modes
* @api private
*/
function load() {
return process.env.DEBUG;
}
/**
* Init logic for `debug` instances.
*
* Create a new `inspectOpts` object in case `useColors` is set
* differently for a particular `debug` instance.
*/
function init(debug) {
debug.inspectOpts = {};
const keys = Object.keys(exports.inspectOpts);
for (let i = 0; i < keys.length; i++) debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
}
module.exports = require_common$2()(exports);
const { formatters } = module.exports;
/**
* Map %o to `util.inspect()`, all on a single line.
*/
formatters.o = function(v) {
this.inspectOpts.colors = this.useColors;
return util$1.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" ");
};
/**
* Map %O to `util.inspect()`, allowing multiple lines if needed.
*/
formatters.O = function(v) {
this.inspectOpts.colors = this.useColors;
return util$1.inspect(v, this.inspectOpts);
};
}));
//#endregion
//#region node_modules/.pnpm/debug@4.4.0_supports-color@10.2.2/node_modules/debug/src/index.js
var require_src$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => {
/**
* Detect Electron renderer / nwjs process, which is node, but we should
* treat as a browser.
*/
if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) module.exports = require_browser();
else module.exports = require_node();
}));
//#endregion
//#region node_modules/.pnpm/@fidm+x509@1.2.1/node_modules/@fidm/x509/build/common.js
var require_common$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const net_1 = __require("net");
/**
* Converts IP string into buffer, 4 bytes for IPv4, and 16 bytes for IPv6.
* It will return null when IP string invalid.
*
* ```js
* console.log(bytesFromIP('::1')) // <Buffer 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01>
* ```
* @param ip IP string to convert
*/
function bytesFromIP(ip) {
switch (net_1.isIP(ip)) {
case 4: return Buffer.from(ip.split(".").map((val) => parseInt(val, 10)));
case 6:
const vals = ip.split(":");
const buf = Buffer.alloc(16);
let offset = 0;
if (vals[vals.length - 1] === "") vals[vals.length - 1] = "0";
for (let i = 0; i < vals.length; i++) {
if (vals[i] === "") {
if (i + 1 < vals.length && vals[i + 1] !== "") offset = 16 - (vals.length - i - 1) * 2;
continue;
}
buf.writeUInt16BE(parseInt(vals[i], 16), offset);
offset += 2;
}
return buf;
default: return null;
}
}
exports.bytesFromIP = bytesFromIP;
/**
* Converts 4-bytes into an IPv4 string representation or 16-bytes into
* an IPv6 string representation. The bytes must be in network order.
*
* ```js
* console.log(bytesToIP(Buffer.from([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]))) // '::1'
* ```
* @param bytes buffer to convert
*/
function bytesToIP(bytes) {
switch (bytes.length) {
case 4: return [
bytes[0],
bytes[1],
bytes[2],
bytes[3]
].join(".");
case 16:
const ip = [];
let zeroAt = -1;
let zeroLen = 0;
let maxAt = -1;
let maxLen = 0;
for (let i = 0; i < bytes.length; i += 2) {
const hex = bytes[i] << 8 | bytes[i + 1];
if (hex === 0) {
zeroLen++;
if (zeroAt === -1) zeroAt = ip.length;
if (zeroLen > maxLen) {
maxLen = zeroLen;
maxAt = zeroAt;
}
} else {
zeroAt = -1;
zeroLen = 0;
}
ip.push(hex.toString(16));
}
if (maxLen > 0) {
let padding = "";
const rest = ip.slice(maxAt + maxLen);
ip.length = maxAt;
if (ip.length === 0) padding += ":";
if (rest.length === 0) padding += ":";
ip.push(padding, ...rest);
}
return ip.join(":");
default: return "";
}
}
exports.bytesToIP = bytesToIP;
const oids = Object.create(null);
const oidReg = /^[0-9.]+$/;
/**
* Returns Object Identifier (dot-separated numeric string) that registered by initOID function.
* It will return empty string if not exists.
* @param nameOrId OID name or OID
*/
function getOID(nameOrId) {
if (oidReg.test(nameOrId) && oids[nameOrId] !== "") return nameOrId;
return oids[nameOrId] == null ? "" : oids[nameOrId];
}
exports.getOID = getOID;
/**
* Returns Object Identifier name that registered by initOID function.
* It will return the argument nameOrId if not exists.
* @param nameOrId OID name or OID
*/
function getOIDName(nameOrId) {
if (!oidReg.test(nameOrId) && oids[nameOrId] !== "") return nameOrId;
return oids[nameOrId] == null ? nameOrId : oids[nameOrId];
}
exports.getOIDName = getOIDName;
/**
* Register OID and name
* @param oid Object Identifier
* @param name Object Identifier name
*/
function initOID(oid, name) {
oids[oid] = name;
oids[name] = oid;
}
initOID("1.2.840.113549.1.1.1", "rsaEncryption");
initOID("1.2.840.113549.1.1.4", "md5WithRsaEncryption");
initOID("1.2.840.113549.1.1.5", "sha1WithRsaEncryption");
initOID("1.2.840.113549.1.1.8", "mgf1");
initOID("1.2.840.113549.1.1.10", "RSASSA-PSS");
initOID("1.2.840.113549.1.1.11", "sha256WithRsaEncryption");
initOID("1.2.840.113549.1.1.12", "sha384WithRsaEncryption");
initOID("1.2.840.113549.1.1.13", "sha512WithRsaEncryption");
initOID("1.2.840.10045.2.1", "ecEncryption");
initOID("1.2.840.10045.4.1", "ecdsaWithSha1");
initOID("1.2.840.10045.4.3.2", "ecdsaWithSha256");
initOID("1.2.840.10045.4.3.3", "ecdsaWithSha384");
initOID("1.2.840.10045.4.3.4", "ecdsaWithSha512");
initOID("1.2.840.10040.4.3", "dsaWithSha1");
initOID("2.16.840.1.101.3.4.3.2", "dsaWithSha256");
initOID("1.3.14.3.2.7", "desCBC");
initOID("1.3.14.3.2.26", "sha1");
initOID("2.16.840.1.101.3.4.2.1", "sha256");
initOID("2.16.840.1.101.3.4.2.2", "sha384");
initOID("2.16.840.1.101.3.4.2.3", "sha512");
initOID("1.2.840.113549.2.5", "md5");
initOID("1.3.101.110", "X25519");
initOID("1.3.101.111", "X448");
initOID("1.3.101.112", "Ed25519");
initOID("1.3.101.113", "Ed448");
initOID("1.2.840.113549.1.7.1", "data");
initOID("1.2.840.113549.1.7.2", "signedData");
initOID("1.2.840.113549.1.7.3", "envelopedData");
initOID("1.2.840.113549.1.7.4", "signedAndEnvelopedData");
initOID("1.2.840.113549.1.7.5", "digestedData");
initOID("1.2.840.113549.1.7.6", "encryptedData");
initOID("1.2.840.113549.1.9.1", "emailAddress");
initOID("1.2.840.113549.1.9.2", "unstructuredName");
initOID("1.2.840.113549.1.9.3", "contentType");
initOID("1.2.840.113549.1.9.4", "messageDigest");
initOID("1.2.840.113549.1.9.5", "signingTime");
initOID("1.2.840.113549.1.9.6", "counterSignature");
initOID("1.2.840.113549.1.9.7", "challengePassword");
initOID("1.2.840.113549.1.9.8", "unstructuredAddress");
initOID("1.2.840.113549.1.9.14", "extensionRequest");
initOID("1.2.840.113549.1.9.20", "friendlyName");
initOID("1.2.840.113549.1.9.21", "localKeyId");
initOID("1.2.840.113549.1.9.22.1", "x509Certificate");
initOID("1.2.840.113549.1.12.10.1.1", "keyBag");
initOID("1.2.840.113549.1.12.10.1.2", "pkcs8ShroudedKeyBag");
initOID("1.2.840.113549.1.12.10.1.3", "certBag");
initOID("1.2.840.113549.1.12.10.1.4", "crlBag");
initOID("1.2.840.113549.1.12.10.1.5", "secretBag");
initOID("1.2.840.113549.1.12.10.1.6", "safeContentsBag");
initOID("1.2.840.113549.1.5.13", "pkcs5PBES2");
initOID("1.2.840.113549.1.5.12", "pkcs5PBKDF2");
initOID("1.2.840.113549.2.7", "hmacWithSha1");
initOID("1.2.840.113549.2.9", "hmacWithSha256");
initOID("1.2.840.113549.2.10", "hmacWithSha384");
initOID("1.2.840.113549.2.11", "hmacWithSha512");
initOID("1.2.840.113549.3.7", "3desCBC");
initOID("2.16.840.1.101.3.4.1.2", "aesCBC128");
initOID("2.16.840.1.101.3.4.1.42", "aesCBC256");
initOID("2.5.4.3", "commonName");
initOID("2.5.4.5", "serialName");
initOID("2.5.4.6", "countryName");
initOID("2.5.4.7", "localityName");
initOID("2.5.4.8", "stateOrProvinceName");
initOID("2.5.4.10", "organizationName");
initOID("2.5.4.11", "organizationalUnitName");
initOID("2.5.4.15", "businessCategory");
initOID("2.16.840.1.113730.1.1", "nsCertType");
initOID("2.5.29.2", "keyAttributes");
initOID("2.5.29.4", "keyUsageRestriction");
initOID("2.5.29.6", "subtreesConstraint");
initOID("2.5.29.9", "subjectDirectoryAttributes");
initOID("2.5.29.14", "subjectKeyIdentifier");
initOID("2.5.29.15", "keyUsage");
initOID("2.5.29.16", "privateKeyUsagePeriod");
initOID("2.5.29.17", "subjectAltName");
initOID("2.5.29.18", "issuerAltName");
initOID("2.5.29.19", "basicConstraints");
initOID("2.5.29.20", "cRLNumber");
initOID("2.5.29.21", "cRLReason");
initOID("2.5.29.22", "expirationDate");
initOID("2.5.29.23", "instructionCode");
initOID("2.5.29.24", "invalidityDate");
initOID("2.5.29.27", "deltaCRLIndicator");
initOID("2.5.29.28", "issuingDistributionPoint");
initOID("2.5.29.29", "certificateIssuer");
initOID("2.5.29.30", "nameConstraints");
initOID("2.5.29.31", "cRLDistributionPoints");
initOID("2.5.29.32", "certificatePolicies");
initOID("2.5.29.33", "policyMappings");
initOID("2.5.29.35", "authorityKeyIdentifier");
initOID("2.5.29.36", "policyConstraints");
initOID("2.5.29.37", "extKeyUsage");
initOID("2.5.29.46", "freshestCRL");
initOID("2.5.29.54", "inhibitAnyPolicy");
initOID("1.3.6.1.4.1.311.60.2.1.2", "jurisdictionST");
initOID("1.3.6.1.4.1.311.60.2.1.3", "jurisdictionC");
initOID("1.3.6.1.4.1.11129.2.4.2", "timestampList");
initOID("1.3.6.1.5.5.7.1.1", "authorityInfoAccess");
initOID("1.3.6.1.5.5.7.3.1", "serverAuth");
initOID("1.3.6.1.5.5.7.3.2", "clientAuth");
initOID("1.3.6.1.5.5.7.3.3", "codeSigning");
initOID("1.3.6.1.5.5.7.3.4", "emailProtection");
initOID("1.3.6.1.5.5.7.3.8", "timeStamping");
initOID("1.3.6.1.5.5.7.48.1", "authorityInfoAccessOcsp");
initOID("1.3.6.1.5.5.7.48.2", "authorityInfoAccessIssuers");
}));
//#endregion
//#region node_modules/.pnpm/tweetnacl@1.0.3/node_modules/tweetnacl/nacl-fast.js
var require_nacl_fast = /* @__PURE__ */ __commonJSMin(((exports, module) => {
(function(nacl) {
"use strict";
var gf = function(init) {
var i, r = /* @__PURE__ */ new Float64Array(16);
if (init) for (i = 0; i < init.length; i++) r[i] = init[i];
return r;
};
var randombytes = function() {
throw new Error("no PRNG");
};
var _0 = /* @__PURE__ */ new Uint8Array(16);
var _9 = /* @__PURE__ */ new Uint8Array(32);
_9[0] = 9;
var gf0 = gf(), gf1 = gf([1]), _121665 = gf([56129, 1]), D = gf([
30883,
4953,
19914,
30187,
55467,
16705,
2637,
112,
59544,
30585,
16505,
36039,
65139,
11119,
27886,
20995
]), D2 = gf([
61785,
9906,
39828,
60374,
45398,
33411,
5274,
224,
53552,
61171,
33010,
6542,
64743,
22239,
55772,
9222
]), X = gf([
54554,
36645,
11616,
51542,
42930,
38181,
51040,
26924,
56412,
64982,
57905,
49316,
21502,
52590,
14035,
8553
]), Y = gf([
26200,
26214,
26214,
26214,
26214,
26214,
26214,
26214,
26214,
26214,
26214,
26214,
26214,
26214,
26214,
26214
]), I = gf([
41136,
18958,
6951,
50414,
58488,
44335,
6150,
12099,
55207,
15867,
153,
11085,
57099,
20417,
9344,
11139
]);
function ts64(x, i, h, l) {
x[i] = h >> 24 & 255;
x[i + 1] = h >> 16 & 255;
x[i + 2] = h >> 8 & 255;
x[i + 3] = h & 255;
x[i + 4] = l >> 24 & 255;
x[i + 5] = l >> 16 & 255;
x[i + 6] = l >> 8 & 255;
x[i + 7] = l & 255;
}
function vn(x, xi, y, yi, n) {
var i, d = 0;
for (i = 0; i < n; i++) d |= x[xi + i] ^ y[yi + i];
return (1 & d - 1 >>> 8) - 1;
}
function crypto_verify_16(x, xi, y, yi) {
return vn(x, xi, y, yi, 16);
}
function crypto_verify_32(x, xi, y, yi) {
return vn(x, xi, y, yi, 32);
}
function core_salsa20(o, p, k, c) {
var j0 = c[0] & 255 | (c[1] & 255) << 8 | (c[2] & 255) << 16 | (c[3] & 255) << 24, j1 = k[0] & 255 | (k[1] & 255) << 8 | (k[2] & 255) << 16 | (k[3] & 255) << 24, j2 = k[4] & 255 | (k[5] & 255) << 8 | (k[6] & 255) << 16 | (k[7] & 255) << 24, j3 = k[8] & 255 | (k[9] & 255) << 8 | (k[10] & 255) << 16 | (k[11] & 255) << 24, j4 = k[12] & 255 | (k[13] & 255) << 8 | (k[14] & 255) << 16 | (k[15] & 255) << 24, j5 = c[4] & 255 | (c[5] & 255) << 8 | (c[6] & 255) << 16 | (c[7] & 255) << 24, j6 = p[0] & 255 | (p[1] & 255) << 8 | (p[2] & 255) << 16 | (p[3] & 255) << 24, j7 = p[4] & 255 | (p[5] & 255) << 8 | (p[6] & 255) << 16 | (p[7] & 255) << 24, j8 = p[8] & 255 | (p[9] & 255) << 8 | (p[10] & 255) << 16 | (p[11] & 255) << 24, j9 = p[12] & 255 | (p[13] & 255) << 8 | (p[14] & 255) << 16 | (p[15] & 255) << 24, j10 = c[8] & 255 | (c[9] & 255) << 8 | (c[10] & 255) << 16 | (c[11] & 255) << 24, j11 = k[16] & 255 | (k[17] & 255) << 8 | (k[18] & 255) << 16 | (k[19] & 255) << 24, j12 = k[20] & 255 | (k[21] & 255) << 8 | (k[22] & 255) << 16 | (k[23] & 255) << 24, j13 = k[24] & 255 | (k[25] & 255) << 8 | (k[26] & 255) << 16 | (k[27] & 255) << 24, j14 = k[28] & 255 | (k[29] & 255) << 8 | (k[30] & 255) << 16 | (k[31] & 255) << 24, j15 = c[12] & 255 | (c[13] & 255) << 8 | (c[14] & 255) << 16 | (c[15] & 255) << 24;
var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u;
for (var i = 0; i < 20; i += 2) {
u = x0 + x12 | 0;
x4 ^= u << 7 | u >>> 25;
u = x4 + x0 | 0;
x8 ^= u << 9 | u >>> 23;
u = x8 + x4 | 0;
x12 ^= u << 13 | u >>> 19;
u = x12 + x8 | 0;
x0 ^= u << 18 | u >>> 14;
u = x5 + x1 | 0;
x9 ^= u << 7 | u >>> 25;
u = x9 + x5 | 0;
x13 ^= u << 9 | u >>> 23;
u = x13 + x9 | 0;
x1 ^= u << 13 | u >>> 19;
u = x1 + x13 | 0;
x5 ^= u << 18 | u >>> 14;
u = x10 + x6 | 0;
x14 ^= u << 7 | u >>> 25;
u = x14 + x10 | 0;
x2 ^= u << 9 | u >>> 23;
u = x2 + x14 | 0;
x6 ^= u << 13 | u >>> 19;
u = x6 + x2 | 0;
x10 ^= u << 18 | u >>> 14;
u = x15 + x11 | 0;
x3 ^= u << 7 | u >>> 25;
u = x3 + x15 | 0;
x7 ^= u << 9 | u >>> 23;
u = x7 + x3 | 0;
x11 ^= u << 13 | u >>> 19;
u = x11 + x7 | 0;
x15 ^= u << 18 | u >>> 14;
u = x0 + x3 | 0;
x1 ^= u << 7 | u >>> 25;
u = x1 + x0 | 0;
x2 ^= u << 9 | u >>> 23;
u = x2 + x1 | 0;
x3 ^= u << 13 | u >>> 19;
u = x3 + x2 | 0;
x0 ^= u << 18 | u >>> 14;
u = x5 + x4 | 0;
x6 ^= u << 7 | u >>> 25;
u = x6 + x5 | 0;
x7 ^= u << 9 | u >>> 23;
u = x7 + x6 | 0;
x4 ^= u << 13 | u >>> 19;
u = x4 + x7 | 0;
x5 ^= u << 18 | u >>> 14;
u = x10 + x9 | 0;
x11 ^= u << 7 | u >>> 25;
u = x11 + x10 | 0;
x8 ^= u << 9 | u >>> 23;
u = x8 + x11 | 0;
x9 ^= u << 13 | u >>> 19;
u = x9 + x8 | 0;
x10 ^= u << 18 | u >>> 14;
u = x15 + x14 | 0;
x12 ^= u << 7 | u >>> 25;
u = x12 + x15 | 0;
x13 ^= u << 9 | u >>> 23;
u = x13 + x12 | 0;
x14 ^= u << 13 | u >>> 19;
u = x14 + x13 | 0;
x15 ^= u << 18 | u >>> 14;
}
x0 = x0 + j0 | 0;
x1 = x1 + j1 | 0;
x2 = x2 + j2 | 0;
x3 = x3 + j3 | 0;
x4 = x4 + j4 | 0;
x5 = x5 + j5 | 0;
x6 = x6 + j6 | 0;
x7 = x7 + j7 | 0;
x8 = x8 + j8 | 0;
x9 = x9 + j9 | 0;
x10 = x10 + j10 | 0;
x11 = x11 + j11 | 0;
x12 = x12 + j12 | 0;
x13 = x13 + j13 | 0;
x14 = x14 + j14 | 0;
x15 = x15 + j15 | 0;
o[0] = x0 >>> 0 & 255;
o[1] = x0 >>> 8 & 255;
o[2] = x0 >>> 16 & 255;
o[3] = x0 >>> 24 & 255;
o[4] = x1 >>> 0 & 255;
o[5] = x1 >>> 8 & 255;
o[6] = x1 >>> 16 & 255;
o[7] = x1 >>> 24 & 255;
o[8] = x2 >>> 0 & 255;
o[9] = x2 >>> 8 & 255;
o[10] = x2 >>> 16 & 255;
o[11] = x2 >>> 24 & 255;
o[12] = x3 >>> 0 & 255;
o[13] = x3 >>> 8 & 255;
o[14] = x3 >>> 16 & 255;
o[15] = x3 >>> 24 & 255;
o[16] = x4 >>> 0 & 255;
o[17] = x4 >>> 8 & 255;
o[18] = x4 >>> 16 & 255;
o[19] = x4 >>> 24 & 255;
o[20] = x5 >>> 0 & 255;
o[21] = x5 >>> 8 & 255;
o[22] = x5 >>> 16 & 255;
o[23] = x5 >>> 24 & 255;
o[24] = x6 >>> 0 & 255;
o[25] = x6 >>> 8 & 255;
o[26] = x6 >>> 16 & 255;
o[27] = x6 >>> 24 & 255;
o[28] = x7 >>> 0 & 255;
o[29] = x7 >>> 8 & 255;
o[30] = x7 >>> 16 & 255;
o[31] = x7 >>> 24 & 255;
o[32] = x8 >>> 0 & 255;
o[33] = x8 >>> 8 & 255;
o[34] = x8 >>> 16 & 255;
o[35] = x8 >>> 24 & 255;
o[36] = x9 >>> 0 & 255;
o[37] = x9 >>> 8 & 255;
o[38] = x9 >>> 16 & 255;
o[39] = x9 >>> 24 & 255;
o[40] = x10 >>> 0 & 255;
o[41] = x10 >>> 8 & 255;
o[42] = x10 >>> 16 & 255;
o[43] = x10 >>> 24 & 255;
o[44] = x11 >>> 0 & 255;
o[45] = x11 >>> 8 & 255;
o[46] = x11 >>> 16 & 255;
o[47] = x11 >>> 24 & 255;
o[48] = x12 >>> 0 & 255;
o[49] = x12 >>> 8 & 255;
o[50] = x12 >>> 16 & 255;
o[51] = x12 >>> 24 & 255;
o[52] = x13 >>> 0 & 255;
o[53] = x13 >>> 8 & 255;
o[54] = x13 >>> 16 & 255;
o[55] = x13 >>> 24 & 255;
o[56] = x14 >>> 0 & 255;
o[57] = x14 >>> 8 & 255;
o[58] = x14 >>> 16 & 255;
o[59] = x14 >>> 24 & 255;
o[60] = x15 >>> 0 & 255;
o[61] = x15 >>> 8 & 255;
o[62] = x15 >>> 16 & 255;
o[63] = x15 >>> 24 & 255;
}
function core_hsalsa20(o, p, k, c) {
var j0 = c[0] & 255 | (c[1] & 255) << 8 | (c[2] & 255) << 16 | (c[3] & 255) << 24, j1 = k[0] & 255 | (k[1] & 255) << 8 | (k[2] & 255) << 16 | (k[3] & 255) << 24, j2 = k[4] & 255 | (k[5] & 255) << 8 | (k[6] & 255) << 16 | (k[7] & 255) << 24, j3 = k[8] & 255 | (k[9] & 255) << 8 | (k[10] & 255) << 16 | (k[11] & 255) << 24, j4 = k[12] & 255 | (k[13] & 255) << 8 | (k[14] & 255) << 16 | (k[15] & 255) << 24, j5 = c[4] & 255 | (c[5] & 255) << 8 | (c[6] & 255) << 16 | (c[7] & 255) << 24, j6 = p[0] & 255 | (p[1] & 255) << 8 | (p[2] & 255) << 16 | (p[3] & 255) << 24, j7 = p[4] & 255 | (p[5] & 255) << 8 | (p[6] & 255) << 16 | (p[7] & 255) << 24, j8 = p[8] & 255 | (p[9] & 255) << 8 | (p[10] & 255) << 16 | (p[11] & 255) << 24, j9 = p[12] & 255 | (p[13] & 255) << 8 | (p[14] & 255) << 16 | (p[15] & 255) << 24, j10 = c[8] & 255 | (c[9] & 255) << 8 | (c[10] & 255) << 16 | (c[11] & 255) << 24, j11 = k[16] & 255 | (k[17] & 255) << 8 | (k[18] & 255) << 16 | (k[19] & 255) << 24, j12 = k[20] & 255 | (k[21] & 255) << 8 | (k[22] & 255) << 16 | (k[23] & 255) << 24, j13 = k[24] & 255 | (k[25] & 255) << 8 | (k[26] & 255) << 16 | (k[27] & 255) << 24, j14 = k[28] & 255 | (k[29] & 255) << 8 | (k[30] & 255) << 16 | (k[31] & 255) << 24, j15 = c[12] & 255 | (c[13] & 255) << 8 | (c[14] & 255) << 16 | (c[15] & 255) << 24;
var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u;
for (var i = 0; i < 20; i += 2) {
u = x0 + x12 | 0;
x4 ^= u << 7 | u >>> 25;
u = x4 + x0 | 0;
x8 ^= u << 9 | u >>> 23;
u = x8 + x4 | 0;
x12 ^= u << 13 | u >>> 19;
u = x12 + x8 | 0;
x0 ^= u << 18 | u >>> 14;
u = x5 + x1 | 0;
x9 ^= u << 7 | u >>> 25;
u = x9 + x5 | 0;
x13 ^= u << 9 | u >>> 23;
u = x13 + x9 | 0;
x1 ^= u << 13 | u >>> 19;
u = x1 + x13 | 0;
x5 ^= u << 18 | u >>> 14;
u = x10 + x6 | 0;
x14 ^= u << 7 | u >>> 25;
u = x14 + x10 | 0;
x2 ^= u << 9 | u >>> 23;
u = x2 + x14 | 0;
x6 ^= u << 13 | u >>> 19;
u = x6 + x2 | 0;
x10 ^= u << 18 | u >>> 14;
u = x15 + x11 | 0;
x3 ^= u << 7 | u >>> 25;
u = x3 + x15 | 0;
x7 ^= u << 9 | u >>> 23;
u = x7 + x3 | 0;
x11 ^= u << 13 | u >>> 19;
u = x11 + x7 | 0;
x15 ^= u << 18 | u >>> 14;
u = x0 + x3 | 0;
x1 ^= u << 7 | u >>> 25;
u = x1 + x0 | 0;
x2 ^= u << 9 | u >>> 23;
u = x2 + x1 | 0;
x3 ^= u << 13 | u >>> 19;
u = x3 + x2 | 0;
x0 ^= u << 18 | u >>> 14;
u = x5 + x4 | 0;
x6 ^= u << 7 | u >>> 25;
u = x6 + x5 | 0;
x7 ^= u << 9 | u >>> 23;
u = x7 + x6 | 0;
x4 ^= u << 13 | u >>> 19;
u = x4 + x7 | 0;
x5 ^= u << 18 | u >>> 14;
u = x10 + x9 | 0;
x11 ^= u << 7 | u >>> 25;
u = x11 + x10 | 0;
x8 ^= u << 9 | u >>> 23;
u = x8 + x11 | 0;
x9 ^= u << 13 | u >>> 19;
u = x9 + x8 | 0;
x10 ^= u << 18 | u >>> 14;
u = x15 + x14 | 0;
x12 ^= u << 7 | u >>> 25;
u = x12 + x15 | 0;
x13 ^= u << 9 | u >>> 23;
u = x13 + x12 | 0;
x14 ^= u << 13 | u >>> 19;
u = x14 + x13 | 0;
x15 ^= u << 18 | u >>> 14;
}
o[0] = x0 >>> 0 & 255;
o[1] = x0 >>> 8 & 255;
o[2] = x0 >>> 16 & 255;
o[3] = x0 >>> 24 & 255;
o[4] = x5 >>> 0 & 255;
o[5] = x5 >>> 8 & 255;
o[6] = x5 >>> 16 & 255;
o[7] = x5 >>> 24 & 255;
o[8] = x10 >>> 0 & 255;
o[9] = x10 >>> 8 & 255;
o[10] = x10 >>> 16 & 255;
o[11] = x10 >>> 24 & 255;
o[12] = x15 >>> 0 & 255;
o[13] = x15 >>> 8 & 255;
o[14] = x15 >>> 16 & 255;
o[15] = x15 >>> 24 & 255;
o[16] = x6 >>> 0 & 255;
o[17] = x6 >>> 8 & 255;
o[18] = x6 >>> 16 & 255;
o[19] = x6 >>> 24 & 255;
o[20] = x7 >>> 0 & 255;
o[21] = x7 >>> 8 & 255;
o[22] = x7 >>> 16 & 255;
o[23] = x7 >>> 24 & 255;
o[24] = x8 >>> 0 & 255;
o[25] = x8 >>> 8 & 255;
o[26] = x8 >>> 16 & 255;
o[27] = x8 >>> 24 & 255;
o[28] = x9 >>> 0 & 255;
o[29] = x9 >>> 8 & 255;
o[30] = x9 >>> 16 & 255;
o[31] = x9 >>> 24 & 255;
}
function crypto_core_salsa20(out, inp, k, c) {
core_salsa20(out, inp, k, c);
}
function crypto_core_hsalsa20(out, inp, k, c) {
core_hsalsa20(out, inp, k, c);
}
var sigma = new Uint8Array([
101,
120,
112,
97,
110,
100,
32,
51,
50,
45,
98,
121,
116,
101,
32,
107
]);
function crypto_stream_salsa20_xor(c, cpos, m, mpos, b, n, k) {
var z = /* @__PURE__ */ new Uint8Array(16), x = /* @__PURE__ */ new Uint8Array(64);
var u, i;
for (i = 0; i < 16; i++) z[i] = 0;
for (i = 0; i < 8; i++) z[i] = n[i];
while (b >= 64) {
crypto_core_salsa20(x, z, k, sigma);
for (i = 0; i < 64; i++) c[cpos + i] = m[mpos + i] ^ x[i];
u = 1;
for (i = 8; i < 16; i++) {
u = u + (z[i] & 255) | 0;
z[i] = u & 255;
u >>>= 8;
}
b -= 64;
cpos += 64;
mpos += 64;
}
if (b > 0) {
crypto_core_salsa20(x, z, k, sigma);
for (i = 0; i < b; i++) c[cpos + i] = m[mpos + i] ^ x[i];
}
return 0;
}
function crypto_stream_salsa20(c, cpos, b, n, k) {
var z = /* @__PURE__ */ new Uint8Array(16), x = /* @__PURE__ */ new Uint8Array(64);
var u, i;
for (i = 0; i < 16; i++) z[i] = 0;
for (i = 0; i < 8; i++) z[i] = n[i];
while (b >= 64) {
crypto_core_salsa20(x, z, k, sigma);
for (i = 0; i < 64; i++) c[cpos + i] = x[i];
u = 1;
for (i = 8; i < 16; i++) {
u = u + (z[i] & 255) | 0;
z[i] = u & 255;
u >>>= 8;
}
b -= 64;
cpos += 64;
}
if (b > 0) {
crypto_core_salsa20(x, z, k, sigma);
for (i = 0; i < b; i++) c[cpos + i] = x[i];
}
return 0;
}
function crypto_stream(c, cpos, d, n, k) {
var s = /* @__PURE__ */ new Uint8Array(32);
crypto_core_hsalsa20(s, n, k, sigma);
var sn = /* @__PURE__ */ new Uint8Array(8);
for (var i = 0; i < 8; i++) sn[i] = n[i + 16];
return crypto_stream_salsa20(c, cpos, d, sn, s);
}
function crypto_stream_xor(c, cpos, m, mpos, d, n, k) {
var s = /* @__PURE__ */ new Uint8Array(32);
crypto_core_hsalsa20(s, n, k, sigma);
var sn = /* @__PURE__ */ new Uint8Array(8);
for (var i = 0; i < 8; i++) sn[i] = n[i + 16];
return crypto_stream_salsa20_xor(c, cpos, m, mpos, d, sn, s);
}
var poly1305 = function(key) {
this.buffer = /* @__PURE__ */ new Uint8Array(16);
this.r = /* @__PURE__ */ new Uint16Array(10);
this.h = /* @__PURE__ */ new Uint16Array(10);
this.pad = /* @__PURE__ */ new Uint16Array(8);
this.leftover = 0;
this.fin = 0;
var t0 = key[0] & 255 | (key[1] & 255) << 8, t1, t2, t3, t4, t5, t6, t7;
this.r[0] = t0 & 8191;
t1 = key[2] & 255 | (key[3] & 255) << 8;
this.r[1] = (t0 >>> 13 | t1 << 3) & 8191;
t2 = key[4] & 255 | (key[5] & 255) << 8;
this.r[2] = (t1 >>> 10 | t2 << 6) & 7939;
t3 = key[6] & 255 | (key[7] & 255) << 8;
this.r[3] = (t2 >>> 7 | t3 << 9) & 8191;
t4 = key[8] & 255 | (key[9] & 255) << 8;
this.r[4] = (t3 >>> 4 | t4 << 12) & 255;
this.r[5] = t4 >>> 1 & 8190;
t5 = key[10] & 255 | (key[11] & 255) << 8;
this.r[6] = (t4 >>> 14 | t5 << 2) & 8191;
t6 = key[12] & 255 | (key[13] & 255) << 8;
this.r[7] = (t5 >>> 11 | t6 << 5) & 8065;
t7 = key[14] & 255 | (key[15] & 255) << 8;
this.r[8] = (t6 >>> 8 | t7 << 8) & 8191;
this.r[9] = t7 >>> 5 & 127;
this.pad[0] = key[16] & 255 | (key[17] & 255) << 8;
this.pad[1] = key[18] & 255 | (key[19] & 255) << 8;
this.pad[2] = key[20] & 255 | (key[21] & 255) << 8;
this.pad[3] = key[22] & 255 | (key[23] & 255) << 8;
this.pad[4] = key[24] & 255 | (key[25] & 255) << 8;
this.pad[5] = key[26] & 255 | (key[27] & 255) << 8;
this.pad[6] = key[28] & 255 | (key[29] & 255) << 8;
this.pad[7] = key[30] & 255 | (key[31] & 255) << 8;
};
poly1305.prototype.blocks = function(m, mpos, bytes) {
var hibit = this.fin ? 0 : 2048;
var t0, t1, t2, t3, t4, t5, t6, t7, c;
var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9;
var h0 = this.h[0], h1 = this.h[1], h2 = this.h[2], h3 = this.h[3], h4 = this.h[4], h5 = this.h[5], h6 = this.h[6], h7 = this.h[7], h8 = this.h[8], h9 = this.h[9];
var r0 = this.r[0], r1 = this.r[1], r2 = this.r[2], r3 = this.r[3], r4 = this.r[4], r5 = this.r[5], r6 = this.r[6], r7 = this.r[7], r8 = this.r[8], r9 = this.r[9];
while (bytes >= 16) {
t0 = m[mpos + 0] & 255 | (m[mpos + 1] & 255) << 8;
h0 += t0 & 8191;
t1 = m[mpos + 2] & 255 | (m[mpos + 3] & 255) << 8;
h1 += (t0 >>> 13 | t1 << 3) & 8191;
t2 = m[mpos + 4] & 255 | (m[mpos + 5] & 255) << 8;
h2 += (t1 >>> 10 | t2 << 6) & 8191;
t3 = m[mpos + 6] & 255 | (m[mpos + 7] & 255) << 8;
h3 += (t2 >>> 7 | t3 << 9) & 8191;
t4 = m[mpos + 8] & 255 | (m[mpos + 9] & 255) << 8;
h4 += (t3 >>> 4 | t4 << 12) & 8191;
h5 += t4 >>> 1 & 8191;
t5 = m[mpos + 10] & 255 | (m[mpos + 11] & 255) << 8;
h6 += (t4 >>> 14 | t5 << 2) & 8191;
t6 = m[mpos + 12] & 255 | (m[mpos + 13] & 255) << 8;
h7 += (t5 >>> 11 | t6 << 5) & 8191;
t7 = m[mpos + 14] & 255 | (m[mpos + 15] & 255) << 8;
h8 += (t6 >>> 8 | t7 << 8) & 8191;
h9 += t7 >>> 5 | hibit;
c = 0;
d0 = c;
d0 += h0 * r0;
d0 += h1 * (5 * r9);
d0 += h2 * (5 * r8);
d0 += h3 * (5 * r7);
d0 += h4 * (5 * r6);
c = d0 >>> 13;
d0 &= 8191;
d0 += h5 * (5 * r5);
d0 += h6 * (5 * r4);
d0 += h7 * (5 * r3);
d0 += h8 * (5 * r2);
d0 += h9 * (5 * r1);
c += d0 >>> 13;
d0 &= 8191;
d1 = c;
d1 += h0 * r1;
d1 += h1 * r0;
d1 += h2 * (5 * r9);
d1 += h3 * (5 * r8);
d1 += h4 * (5 * r7);
c = d1 >>> 13;
d1 &= 8191;
d1 += h5 * (5 * r6);
d1 += h6 * (5 * r5);
d1 += h7 * (5 * r4);
d1 += h8 * (5 * r3);
d1 += h9 * (5 * r2);
c += d1 >>> 13;
d1 &= 8191;
d2 = c;
d2 += h0 * r2;
d2 += h1 * r1;
d2 += h2 * r0;
d2 += h3 * (5 * r9);
d2 += h4 * (5 * r8);
c = d2 >>> 13;
d2 &= 8191;
d2 += h5 * (5 * r7);
d2 += h6 * (5 * r6);
d2 += h7 * (5 * r5);
d2 += h8 * (5 * r4);
d2 += h9 * (5 * r3);
c += d2 >>> 13;
d2 &= 8191;
d3 = c;
d3 += h0 * r3;
d3 += h1 * r2;
d3 += h2 * r1;
d3 += h3 * r0;
d3 += h4 * (5 * r9);
c = d3 >>> 13;
d3 &= 8191;
d3 += h5 * (5 * r8);
d3 += h6 * (5 * r7);
d3 += h7 * (5 * r6);
d3 += h8 * (5 * r5);
d3 += h9 * (5 * r4);
c += d3 >>> 13;
d3 &= 8191;
d4 = c;
d4 += h0 * r4;
d4 += h1 * r3;
d4 += h2 * r2;
d4 += h3 * r1;
d4 += h4 * r0;
c = d4 >>> 13;
d4 &= 8191;
d4 += h5 * (5 * r9);
d4 += h6 * (5 * r8);
d4 += h7 * (5 * r7);
d4 += h8 * (5 * r6);
d4 += h9 * (5 * r5);
c += d4 >>> 13;
d4 &= 8191;
d5 = c;
d5 += h0 * r5;
d5 += h1 * r4;
d5 += h2 * r3;
d5 += h3 * r2;
d5 += h4 * r1;
c = d5 >>> 13;
d5 &= 8191;
d5 += h5 * r0;
d5 += h6 * (5 * r9);
d5 += h7 * (5 * r8);
d5 += h8 * (5 * r7);
d5 += h9 * (5 * r6);
c += d5 >>> 13;
d5 &= 8191;
d6 = c;
d6 += h0 * r6;
d6 += h1 * r5;
d6 += h2 * r4;
d6 += h3 * r3;
d6 += h4 * r2;
c = d6 >>> 13;
d6 &= 8191;
d6 += h5 * r1;
d6 += h6 * r0;
d6 += h7 * (5 * r9);
d6 += h8 * (5 * r8);
d6 += h9 * (5 * r7);
c += d6 >>> 13;
d6 &= 8191;
d7 = c;
d7 += h0 * r7;
d7 += h1 * r6;
d7 += h2 * r5;
d7 += h3 * r4;
d7 += h4 * r3;
c = d7 >>> 13;
d7 &= 8191;
d7 += h5 * r2;
d7 += h6 * r1;
d7 += h7 * r0;
d7 += h8 * (5 * r9);
d7 += h9 * (5 * r8);
c += d7 >>> 13;
d7 &= 8191;
d8 = c;
d8 += h0 * r8;
d8 += h1 * r7;
d8 += h2 * r6;
d8 += h3 * r5;
d8 += h4 * r4;
c = d8 >>> 13;
d8 &= 8191;
d8 += h5 * r3;
d8 += h6 * r2;
d8 += h7 * r1;
d8 += h8 * r0;
d8 += h9 * (5 * r9);
c += d8 >>> 13;
d8 &= 8191;
d9 = c;
d9 += h0 * r9;
d9 += h1 * r8;
d9 += h2 * r7;
d9 += h3 * r6;
d9 += h4 * r5;
c = d9 >>> 13;
d9 &= 8191;
d9 += h5 * r4;
d9 += h6 * r3;
d9 += h7 * r2;
d9 += h8 * r1;
d9 += h9 * r0;
c += d9 >>> 13;
d9 &= 8191;
c = (c << 2) + c | 0;
c = c + d0 | 0;
d0 = c & 8191;
c = c >>> 13;
d1 += c;
h0 = d0;
h1 = d1;
h2 = d2;
h3 = d3;
h4 = d4;
h5 = d5;
h6 = d6;
h7 = d7;
h8 = d8;
h9 = d9;
mpos += 16;
bytes -= 16;
}
this.h[0] = h0;
this.h[1] = h1;
this.h[2] = h2;
this.h[3] = h3;
this.h[4] = h4;
this.h[5] = h5;
this.h[6] = h6;
this.h[7] = h7;
this.h[8] = h8;
this.h[9] = h9;
};
poly1305.prototype.finish = function(mac, macpos) {
var g = /* @__PURE__ */ new Uint16Array(10);
var c, mask, f, i;
if (this.leftover) {
i = this.leftover;
this.buffer[i++] = 1;
for (; i < 16; i++) this.buffer[i] = 0;
this.fin = 1;
this.blocks(this.buffer, 0, 16);
}
c = this.h[1] >>> 13;
this.h[1] &= 8191;
for (i = 2; i < 10; i++) {
this.h[i] += c;
c = this.h[i] >>> 13;
this.h[i] &= 8191;
}
this.h[0] += c * 5;
c = this.h[0] >>> 13;
this.h[0] &= 8191;
this.h[1] += c;
c = this.h[1] >>> 13;
this.h[1] &= 8191;
this.h[2] += c;
g[0] = this.h[0] + 5;
c = g[0] >>> 13;
g[0] &= 8191;
for (i = 1; i < 10; i++) {
g[i] = this.h[i] + c;
c = g[i] >>> 13;
g[i] &= 8191;
}
g[9] -= 8192;
mask = (c ^ 1) - 1;
for (i = 0; i < 10; i++) g[i] &= mask;
mask = ~mask;
for (i = 0; i < 10; i++) this.h[i] = this.h[i] & mask | g[i];
this.h[0] = (this.h[0] | this.h[1] << 13) & 65535;
this.h[1] = (this.h[1] >>> 3 | this.h[2] << 10) & 65535;
this.h[2] = (this.h[2] >>> 6 | this.h[3] << 7) & 65535;
this.h[3] = (this.h[3] >>> 9 | this.h[4] << 4) & 65535;
this.h[4] = (this.h[4] >>> 12 | this.h[5] << 1 | this.h[6] << 14) & 65535;
this.h[5] = (this.h[6] >>> 2 | this.h[7] << 11) & 65535;
this.h[6] = (this.h[7] >>> 5 | this.h[8] << 8) & 65535;
this.h[7] = (this.h[8] >>> 8 | this.h[9] << 5) & 65535;
f = this.h[0] + this.pad[0];
this.h[0] = f & 65535;
for (i = 1; i < 8; i++) {
f = (this.h[i] + this.pad[i] | 0) + (f >>> 16) | 0;
this.h[i] = f & 65535;
}
mac[macpos + 0] = this.h[0] >>> 0 & 255;
mac[macpos + 1] = this.h[0] >>> 8 & 255;
mac[macpos + 2] = this.h[1] >>> 0 & 255;
mac[macpos + 3] = this.h[1] >>> 8 & 255;
mac[macpos + 4] = this.h[2] >>> 0 & 255;
mac[macpos + 5] = this.h[2] >>> 8 & 255;
mac[macpos + 6] = this.h[3] >>> 0 & 255;
mac[macpos + 7] = this.h[3] >>> 8 & 255;
mac[macpos + 8] = this.h[4] >>> 0 & 255;
mac[macpos + 9] = this.h[4] >>> 8 & 255;
mac[macpos + 10] = this.h[5] >>> 0 & 255;
mac[macpos + 11] = this.h[5] >>> 8 & 255;
mac[macpos + 12] = this.h[6] >>> 0 & 255;
mac[macpos + 13] = this.h[6] >>> 8 & 255;
mac[macpos + 14] = this.h[7] >>> 0 & 255;
mac[macpos + 15] = this.h[7] >>> 8 & 255;
};
poly1305.prototype.update = function(m, mpos, bytes) {
var i, want;
if (this.leftover) {
want = 16 - this.leftover;
if (want > bytes) want = bytes;
for (i = 0; i < want; i++) this.buffer[this.leftover + i] = m[mpos + i];
bytes -= want;
mpos += want;
this.leftover += want;
if (this.leftover < 16) return;
this.blocks(this.buffer, 0, 16);
this.leftover = 0;
}
if (bytes >= 16) {
want = bytes - bytes % 16;
this.blocks(m, mpos, want);
mpos += want;
bytes -= want;
}
if (bytes) {
for (i = 0; i < bytes; i++) this.buffer[this.leftover + i] = m[mpos + i];
this.leftover += bytes;
}
};
function crypto_onetimeauth(out, outpos, m, mpos, n, k) {
var s = new poly1305(k);
s.update(m, mpos, n);
s.finish(out, outpos);
return 0;
}
function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) {
var x = /* @__PURE__ */ new Uint8Array(16);
crypto_onetimeauth(x, 0, m, mpos, n, k);
return crypto_verify_16(h, hpos, x, 0);
}
function crypto_secretbox(c, m, d, n, k) {
var i;
if (d < 32) return -1;
crypto_stream_xor(c, 0, m, 0, d, n, k);
crypto_onetimeauth(c, 16, c, 32, d - 32, c);
for (i = 0; i < 16; i++) c[i] = 0;
return 0;
}
function crypto_secretbox_open(m, c, d, n, k) {
var i;
var x = /* @__PURE__ */ new Uint8Array(32);
if (d < 32) return -1;
crypto_stream(x, 0, 32, n, k);
if (crypto_onetimeauth_verify(c, 16, c, 32, d - 32, x) !== 0) return -1;
crypto_stream_xor(m, 0, c, 0, d, n, k);
for (i = 0; i < 32; i++) m[i] = 0;
return 0;
}
function set25519(r, a) {
var i;
for (i = 0; i < 16; i++) r[i] = a[i] | 0;
}
function car25519(o) {
var i, v, c = 1;
for (i = 0; i < 16; i++) {
v = o[i] + c + 65535;
c = Math.floor(v / 65536);
o[i] = v - c * 65536;
}
o[0] += c - 1 + 37 * (c - 1);
}
function sel25519(p, q, b) {
var t, c = ~(b - 1);
for (var i = 0; i < 16; i++) {
t = c & (p[i] ^ q[i]);
p[i] ^= t;
q[i] ^= t;
}
}
function pack25519(o, n) {
var i, j, b;
var m = gf(), t = gf();
for (i = 0; i < 16; i++) t[i] = n[i];
car25519(t);
car25519(t);
car25519(t);
for (j = 0; j < 2; j++) {
m[0] = t[0] - 65517;
for (i = 1; i < 15; i++) {
m[i] = t[i] - 65535 - (m[i - 1] >> 16 & 1);
m[i - 1] &= 65535;
}
m[15] = t[15] - 32767 - (m[14] >> 16 & 1);
b = m[15] >> 16 & 1;
m[14] &= 65535;
sel25519(t, m, 1 - b);
}
for (i = 0; i < 16; i++) {
o[2 * i] = t[i] & 255;
o[2 * i + 1] = t[i] >> 8;
}
}
function neq25519(a, b) {
var c = /* @__PURE__ */ new Uint8Array(32), d = /* @__PURE__ */ new Uint8Array(32);
pack25519(c, a);
pack25519(d, b);
return crypto_verify_32(c, 0, d, 0);
}
function par25519(a) {
var d = /* @__PURE__ */ new Uint8Array(32);
pack25519(d, a);
return d[0] & 1;
}
function unpack25519(o, n) {
var i;
for (i = 0; i < 16; i++) o[i] = n[2 * i] + (n[2 * i + 1] << 8);
o[15] &= 32767;
}
function A(o, a, b) {
for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];
}
function Z(o, a, b) {
for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];
}
function M(o, a, b) {
var v, c, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11], b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15];
v = a[0];
t0 += v * b0;
t1 += v * b1;
t2 += v * b2;
t3 += v * b3;
t4 += v * b4;
t5 += v * b5;
t6 += v * b6;
t7 += v * b7;
t8 += v * b8;
t9 += v * b9;
t10 += v * b10;
t11 += v * b11;
t12 += v * b12;
t13 += v * b13;
t14 += v * b14;
t15 += v * b15;
v = a[1];
t1 += v * b0;
t2 += v * b1;
t3 += v * b2;
t4 += v * b3;
t5 += v * b4;
t6 += v * b5;
t7 += v * b6;
t8 += v * b7;
t9 += v * b8;
t10 += v * b9;
t11 += v * b10;
t12 += v * b11;
t13 += v * b12;
t14 += v * b13;
t15 += v * b14;
t16 += v * b15;
v = a[2];
t2 += v * b0;
t3 += v * b1;
t4 += v * b2;
t5 += v * b3;
t6 += v * b4;
t7 += v * b5;
t8 += v * b6;
t9 += v * b7;
t10 += v * b8;
t11 += v * b9;
t12 += v * b10;
t13 += v * b11;
t14 += v * b12;
t15 += v * b13;
t16 += v * b14;
t17 += v * b15;
v = a[3];
t3 += v * b0;
t4 += v * b1;
t5 += v * b2;
t6 += v * b3;
t7 += v * b4;
t8 += v * b5;
t9 += v * b6;
t10 += v * b7;
t11 += v * b8;
t12 += v * b9;
t13 += v * b10;
t14 += v * b11;
t15 += v * b12;
t16 += v * b13;
t17 += v * b14;
t18 += v * b15;
v = a[4];
t4 += v * b0;
t5 += v * b1;
t6 += v * b2;
t7 += v * b3;
t8 += v * b4;
t9 += v * b5;
t10 += v * b6;
t11 += v * b7;
t12 += v * b8;
t13 += v * b9;
t14 += v * b10;
t15 += v * b11;
t16 += v * b12;
t17 += v * b13;
t18 += v * b14;
t19 += v * b15;
v = a[5];
t5 += v * b0;
t6 += v * b1;
t7 += v * b2;
t8 += v * b3;
t9 += v * b4;
t10 += v * b5;
t11 += v * b6;
t12 += v * b7;
t13 += v * b8;
t14 += v * b9;
t15 += v * b10;
t16 += v * b11;
t17 += v * b12;
t18 += v * b13;
t19 += v * b14;
t20 += v * b15;
v = a[6];
t6 += v * b0;
t7 += v * b1;
t8 += v * b2;
t9 += v * b3;
t10 += v * b4;
t11 += v * b5;
t12 += v * b6;
t13 += v * b7;
t14 += v * b8;
t15 += v * b9;
t16 += v * b10;
t17 += v * b11;
t18 += v * b12;
t19 += v * b13;
t20 += v * b14;
t21 += v * b15;
v = a[7];
t7 += v * b0;
t8 += v * b1;
t9 += v * b2;
t10 += v * b3;
t11 += v * b4;
t12 += v * b5;
t13 += v * b6;
t14 += v * b7;
t15 += v * b8;
t16 += v * b9;
t17 += v * b10;
t18 += v * b11;
t19 += v * b12;
t20 += v * b13;
t21 += v * b14;
t22 += v * b15;
v = a[8];
t8 += v * b0;
t9 += v * b1;
t10 += v * b2;
t11 += v * b3;
t12 += v * b4;
t13 += v * b5;
t14 += v * b6;
t15 += v * b7;
t16 += v * b8;
t17 += v * b9;
t18 += v * b10;
t19 += v * b11;
t20 += v * b12;
t21 += v * b13;
t22 += v * b14;
t23 += v * b15;
v = a[9];
t9 += v * b0;
t10 += v * b1;
t11 += v * b2;
t12 += v * b3;
t13 += v * b4;
t14 += v * b5;
t15 += v * b6;
t16 += v * b7;
t17 += v * b8;
t18 += v * b9;
t19 += v * b10;
t20 += v * b11;
t21 += v * b12;
t22 += v * b13;
t23 += v * b14;
t24 += v * b15;
v = a[10];
t10 += v * b0;
t11 += v * b1;
t12 += v * b2;
t13 += v * b3;
t14 += v * b4;
t15 += v * b5;
t16 += v * b6;
t17 += v * b7;
t18 += v * b8;
t19 += v * b9;
t20 += v * b10;
t21 += v * b11;
t22 += v * b12;
t23 += v * b13;
t24 += v * b14;
t25 += v * b15;
v = a[11];
t11 += v * b0;
t12 += v * b1;
t13 += v * b2;
t14 += v * b3;
t15 += v * b4;
t16 += v * b5;
t17 += v * b6;
t18 += v * b7;
t19 += v * b8;
t20 += v * b9;
t21 += v * b10;
t22 += v * b11;
t23 += v * b12;
t24 += v * b13;
t25 += v * b14;
t26 += v * b15;
v = a[12];
t12 += v * b0;
t13 += v * b1;
t14 += v * b2;
t15 += v * b3;
t16 += v * b4;
t17 += v * b5;
t18 += v * b6;
t19 += v * b7;
t20 += v * b8;
t21 += v * b9;
t22 += v * b10;
t23 += v * b11;
t24 += v * b12;
t25 += v * b13;
t26 += v * b14;
t27 += v * b15;
v = a[13];
t13 += v * b0;
t14 += v * b1;
t15 += v * b2;
t16 += v * b3;
t17 += v * b4;
t18 += v * b5;
t19 += v * b6;
t20 += v * b7;
t21 += v * b8;
t22 += v * b9;
t23 += v * b10;
t24 += v * b11;
t25 += v * b12;
t26 += v * b13;
t27 += v * b14;
t28 += v * b15;
v = a[14];
t14 += v * b0;
t15 += v * b1;
t16 += v * b2;
t17 += v * b3;
t18 += v * b4;
t19 += v * b5;
t20 += v * b6;
t21 += v * b7;
t22 += v * b8;
t23 += v * b9;
t24 += v * b10;
t25 += v * b11;
t26 += v * b12;
t27 += v * b13;
t28 += v * b14;
t29 += v * b15;
v = a[15];
t15 += v * b0;
t16 += v * b1;
t17 += v * b2;
t18 += v * b3;
t19 += v * b4;
t20 += v * b5;
t21 += v * b6;
t22 += v * b7;
t23 += v * b8;
t24 += v * b9;
t25 += v * b10;
t26 += v * b11;
t27 += v * b12;
t28 += v * b13;
t29 += v * b14;
t30 += v * b15;
t0 += 38 * t16;
t1 += 38 * t17;
t2 += 38 * t18;
t3 += 38 * t19;
t4 += 38 * t20;
t5 += 38 * t21;
t6 += 38 * t22;
t7 += 38 * t23;
t8 += 38 * t24;
t9 += 38 * t25;
t10 += 38 * t26;
t11 += 38 * t27;
t12 += 38 * t28;
t13 += 38 * t29;
t14 += 38 * t30;
c = 1;
v = t0 + c + 65535;
c = Math.floor(v / 65536);
t0 = v - c * 65536;
v = t1 + c + 65535;
c = Math.floor(v / 65536);
t1 = v - c * 65536;
v = t2 + c + 65535;
c = Math.floor(v / 65536);
t2 = v - c * 65536;
v = t3 + c + 65535;
c = Math.floor(v / 65536);
t3 = v - c * 65536;
v = t4 + c + 65535;
c = Math.floor(v / 65536);
t4 = v - c * 65536;
v = t5 + c + 65535;
c = Math.floor(v / 65536);
t5 = v - c * 65536;
v = t6 + c + 65535;
c = Math.floor(v / 65536);
t6 = v - c * 65536;
v = t7 + c + 65535;
c = Math.floor(v / 65536);
t7 = v - c * 65536;
v = t8 + c + 65535;
c = Math.floor(v / 65536);
t8 = v - c * 65536;
v = t9 + c + 65535;
c = Math.floor(v / 65536);
t9 = v - c * 65536;
v = t10 + c + 65535;
c = Math.floor(v / 65536);
t10 = v - c * 65536;
v = t11 + c + 65535;
c = Math.floor(v / 65536);
t11 = v - c * 65536;
v = t12 + c + 65535;
c = Math.floor(v / 65536);
t12 = v - c * 65536;
v = t13 + c + 65535;
c = Math.floor(v / 65536);
t13 = v - c * 65536;
v = t14 + c + 65535;
c = Math.floor(v / 65536);
t14 = v - c * 65536;
v = t15 + c + 65535;
c = Math.floor(v / 65536);
t15 = v - c * 65536;
t0 += c - 1 + 37 * (c - 1);
c = 1;
v = t0 + c + 65535;
c = Math.floor(v / 65536);
t0 = v - c * 65536;
v = t1 + c + 65535;
c = Math.floor(v / 65536);
t1 = v - c * 65536;
v = t2 + c + 65535;
c = Math.floor(v / 65536);
t2 = v - c * 65536;
v = t3 + c + 65535;
c = Math.floor(v / 65536);
t3 = v - c * 65536;
v = t4 + c + 65535;
c = Math.floor(v / 65536);
t4 = v - c * 65536;
v = t5 + c + 65535;
c = Math.floor(v / 65536);
t5 = v - c * 65536;
v = t6 + c + 65535;
c = Math.floor(v / 65536);
t6 = v - c * 65536;
v = t7 + c + 65535;
c = Math.floor(v / 65536);
t7 = v - c * 65536;
v = t8 + c + 65535;
c = Math.floor(v / 65536);
t8 = v - c * 65536;
v = t9 + c + 65535;
c = Math.floor(v / 65536);
t9 = v - c * 65536;
v = t10 + c + 65535;
c = Math.floor(v / 65536);
t10 = v - c * 65536;
v = t11 + c + 65535;
c = Math.floor(v / 65536);
t11 = v - c * 65536;
v = t12 + c + 65535;
c = Math.floor(v / 65536);
t12 = v - c * 65536;
v = t13 + c + 65535;
c = Math.floor(v / 65536);
t13 = v - c * 65536;
v = t14 + c + 65535;
c = Math.floor(v / 65536);
t14 = v - c * 65536;
v = t15 + c + 65535;
c = Math.floor(v / 65536);
t15 = v - c * 65536;
t0 += c - 1 + 37 * (c - 1);
o[0] = t0;
o[1] = t1;
o[2] = t2;
o[3] = t3;
o[4] = t4;
o[5] = t5;
o[6] = t6;
o[7] = t7;
o[8] = t8;
o[9] = t9;
o[10] = t10;
o[11] = t11;
o[12] = t12;
o[13] = t13;
o[14] = t14;
o[15] = t15;
}
function S(o, a) {
M(o, a, a);
}
function inv25519(o, i) {
var c = gf();
var a;
for (a = 0; a < 16; a++) c[a] = i[a];
for (a = 253; a >= 0; a--) {
S(c, c);
if (a !== 2 && a !== 4) M(c, c, i);
}
for (a = 0; a < 16; a++) o[a] = c[a];
}
function pow2523(o, i) {
var c = gf();
var a;
for (a = 0; a < 16; a++) c[a] = i[a];
for (a = 250; a >= 0; a--) {
S(c, c);
if (a !== 1) M(c, c, i);
}
for (a = 0; a < 16; a++) o[a] = c[a];
}
function crypto_scalarmult(q, n, p) {
var z = /* @__PURE__ */ new Uint8Array(32);
var x = /* @__PURE__ */ new Float64Array(80), r, i;
var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf();
for (i = 0; i < 31; i++) z[i] = n[i];
z[31] = n[31] & 127 | 64;
z[0] &= 248;
unpack25519(x, p);
for (i = 0; i < 16; i++) {
b[i] = x[i];
d[i] = a[i] = c[i] = 0;
}
a[0] = d[0] = 1;
for (i = 254; i >= 0; --i) {
r = z[i >>> 3] >>> (i & 7) & 1;
sel25519(a, b, r);
sel25519(c, d, r);
A(e, a, c);
Z(a, a, c);
A(c, b, d);
Z(b, b, d);
S(d, e);
S(f, a);
M(a, c, a);
M(c, b, e);
A(e, a, c);
Z(a, a, c);
S(b, a);
Z(c, d, f);
M(a, c, _121665);
A(a, a, d);
M(c, c, a);
M(a, d, f);
M(d, b, x);
S(b, e);
sel25519(a, b, r);
sel25519(c, d, r);
}
for (i = 0; i < 16; i++) {
x[i + 16] = a[i];
x[i + 32] = c[i];
x[i + 48] = b[i];
x[i + 64] = d[i];
}
var x32 = x.subarray(32);
var x16 = x.subarray(16);
inv25519(x32, x32);
M(x16, x16, x32);
pack25519(q, x16);
return 0;
}
function crypto_scalarmult_base(q, n) {
return crypto_scalarmult(q, n, _9);
}
function crypto_box_keypair(y, x) {
randombytes(x, 32);
return crypto_scalarmult_base(y, x);
}
function crypto_box_beforenm(k, y, x) {
var s = /* @__PURE__ */ new Uint8Array(32);
crypto_scalarmult(s, x, y);
return crypto_core_hsalsa20(k, _0, s, sigma);
}
var crypto_box_afternm = crypto_secretbox;
var crypto_box_open_afternm = crypto_secretbox_open;
function crypto_box(c, m, d, n, y, x) {
var k = /* @__PURE__ */ new Uint8Array(32);
crypto_box_beforenm(k, y, x);
return crypto_box_afternm(c, m, d, n, k);
}
function crypto_box_open(m, c, d, n, y, x) {
var k = /* @__PURE__ */ new Uint8Array(32);
crypto_box_beforenm(k, y, x);
return crypto_box_open_afternm(m, c, d, n, k);
}
var K = [
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
];
function crypto_hashblocks_hl(hh, hl, m, n) {
var wh = /* @__PURE__ */ new Int32Array(16), wl = /* @__PURE__ */ new Int32Array(16), bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, th, tl, i, j, h, l, a, b, c, d;
var ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7];
var pos = 0;
while (n >= 128) {
for (i = 0; i < 16; i++) {
j = 8 * i + pos;
wh[i] = m[j + 0] << 24 | m[j + 1] << 16 | m[j + 2] << 8 | m[j + 3];
wl[i] = m[j + 4] << 24 | m[j + 5] << 16 | m[j + 6] << 8 | m[j + 7];
}
for (i = 0; i < 80; i++) {
bh0 = ah0;
bh1 = ah1;
bh2 = ah2;
bh3 = ah3;
bh4 = ah4;
bh5 = ah5;
bh6 = ah6;
bh7 = ah7;
bl0 = al0;
bl1 = al1;
bl2 = al2;
bl3 = al3;
bl4 = al4;
bl5 = al5;
bl6 = al6;
bl7 = al7;
h = ah7;
l = al7;
a = l & 65535;
b = l >>> 16;
c = h & 65535;
d = h >>> 16;
h = (ah4 >>> 14 | al4 << 18) ^ (ah4 >>> 18 | al4 << 14) ^ (al4 >>> 9 | ah4 << 23);
l = (al4 >>> 14 | ah4 << 18) ^ (al4 >>> 18 | ah4 << 14) ^ (ah4 >>> 9 | al4 << 23);
a += l & 65535;
b += l >>> 16;
c += h & 65535;
d += h >>> 16;
h = ah4 & ah5 ^ ~ah4 & ah6;
l = al4 & al5 ^ ~al4 & al6;
a += l & 65535;
b += l >>> 16;
c += h & 65535;
d += h >>> 16;
h = K[i * 2];
l = K[i * 2 + 1];
a += l & 65535;
b += l >>> 16;
c += h & 65535;
d += h >>> 16;
h = wh[i % 16];
l = wl[i % 16];
a += l & 65535;
b += l >>> 16;
c += h & 65535;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
th = c & 65535 | d << 16;
tl = a & 65535 | b << 16;
h = th;
l = tl;
a = l & 65535;
b = l >>> 16;
c = h & 65535;
d = h >>> 16;
h = (ah0 >>> 28 | al0 << 4) ^ (al0 >>> 2 | ah0 << 30) ^ (al0 >>> 7 | ah0 << 25);
l = (al0 >>> 28 | ah0 << 4) ^ (ah0 >>> 2 | al0 << 30) ^ (ah0 >>> 7 | al0 << 25);
a += l & 65535;
b += l >>> 16;
c += h & 65535;
d += h >>> 16;
h = ah0 & ah1 ^ ah0 & ah2 ^ ah1 & ah2;
l = al0 & al1 ^ al0 & al2 ^ al1 & al2;
a += l & 65535;
b += l >>> 16;
c += h & 65535;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
bh7 = c & 65535 | d << 16;
bl7 = a & 65535 | b << 16;
h = bh3;
l = bl3;
a = l & 65535;
b = l >>> 16;
c = h & 65535;
d = h >>> 16;
h = th;
l = tl;
a += l & 65535;
b += l >>> 16;
c += h & 65535;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
bh3 = c & 65535 | d << 16;
bl3 = a & 65535 | b << 16;
ah1 = bh0;
ah2 = bh1;
ah3 = bh2;
ah4 = bh3;
ah5 = bh4;
ah6 = bh5;
ah7 = bh6;
ah0 = bh7;
al1 = bl0;
al2 = bl1;
al3 = bl2;
al4 = bl3;
al5 = bl4;
al6 = bl5;
al7 = bl6;
al0 = bl7;
if (i % 16 === 15) for (j = 0; j < 16; j++) {
h = wh[j];
l = wl[j];
a = l & 65535;
b = l >>> 16;
c = h & 65535;
d = h >>> 16;
h = wh[(j + 9) % 16];
l = wl[(j + 9) % 16];
a += l & 65535;
b += l >>> 16;
c += h & 65535;
d += h >>> 16;
th = wh[(j + 1) % 16];
tl = wl[(j + 1) % 16];
h = (th >>> 1 | tl << 31) ^ (th >>> 8 | tl << 24) ^ th >>> 7;
l = (tl >>> 1 | th << 31) ^ (tl >>> 8 | th << 24) ^ (tl >>> 7 | th << 25);
a += l & 65535;
b += l >>> 16;
c += h & 65535;
d += h >>> 16;
th = wh[(j + 14) % 16];
tl = wl[(j + 14) % 16];
h = (th >>> 19 | tl << 13) ^ (tl >>> 29 | th << 3) ^ th >>> 6;
l = (tl >>> 19 | th << 13) ^ (th >>> 29 | tl << 3) ^ (tl >>> 6 | th << 26);
a += l & 65535;
b += l >>> 16;
c += h & 65535;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
wh[j] = c & 65535 | d << 16;
wl[j] = a & 65535 | b << 16;
}
}
h = ah0;
l = al0;
a = l & 65535;
b = l >>> 16;
c = h & 65535;
d = h >>> 16;
h = hh[0];
l = hl[0];
a += l & 65535;
b += l >>> 16;
c += h & 65535;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[0] = ah0 = c & 65535 | d << 16;
hl[0] = al0 = a & 65535 | b << 16;
h = ah1;
l = al1;
a = l & 65535;
b = l >>> 16;
c = h & 65535;
d = h >>> 16;
h = hh[1];
l = hl[1];
a += l & 65535;
b += l >>> 16;
c += h & 65535;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[1] = ah1 = c & 65535 | d << 16;
hl[1] = al1 = a & 65535 | b << 16;
h = ah2;
l = al2;
a = l & 65535;
b = l >>> 16;
c = h & 65535;
d = h >>> 16;
h = hh[2];
l = hl[2];
a += l & 65535;
b += l >>> 16;
c += h & 65535;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[2] = ah2 = c & 65535 | d << 16;
hl[2] = al2 = a & 65535 | b << 16;
h = ah3;
l = al3;
a = l & 65535;
b = l >>> 16;
c = h & 65535;
d = h >>> 16;
h = hh[3];
l = hl[3];
a += l & 65535;
b += l >>> 16;
c += h & 65535;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[3] = ah3 = c & 65535 | d << 16;
hl[3] = al3 = a & 65535 | b << 16;
h = ah4;
l = al4;
a = l & 65535;
b = l >>> 16;
c = h & 65535;
d = h >>> 16;
h = hh[4];
l = hl[4];
a += l & 65535;
b += l >>> 16;
c += h & 65535;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[4] = ah4 = c & 65535 | d << 16;
hl[4] = al4 = a & 65535 | b << 16;
h = ah5;
l = al5;
a = l & 65535;
b = l >>> 16;
c = h & 65535;
d = h >>> 16;
h = hh[5];
l = hl[5];
a += l & 65535;
b += l >>> 16;
c += h & 65535;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[5] = ah5 = c & 65535 | d << 16;
hl[5] = al5 = a & 65535 | b << 16;
h = ah6;
l = al6;
a = l & 65535;
b = l >>> 16;
c = h & 65535;
d = h >>> 16;
h = hh[6];
l = hl[6];
a += l & 65535;
b += l >>> 16;
c += h & 65535;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[6] = ah6 = c & 65535 | d << 16;
hl[6] = al6 = a & 65535 | b << 16;
h = ah7;
l = al7;
a = l & 65535;
b = l >>> 16;
c = h & 65535;
d = h >>> 16;
h = hh[7];
l = hl[7];
a += l & 65535;
b += l >>> 16;
c += h & 65535;
d += h >>> 16;
b += a >>> 16;
c += b >>> 16;
d += c >>> 16;
hh[7] = ah7 = c & 65535 | d << 16;
hl[7] = al7 = a & 65535 | b << 16;
pos += 128;
n -= 128;
}
return n;
}
function crypto_hash(out, m, n) {
var hh = /* @__PURE__ */ new Int32Array(8), hl = /* @__PURE__ */ new Int32Array(8), x = /* @__PURE__ */ new Uint8Array(256), i, b = n;
hh[0] = 1779033703;
hh[1] = 3144134277;
hh[2] = 1013904242;
hh[3] = 2773480762;
hh[4] = 1359893119;
hh[5] = 2600822924;
hh[6] = 528734635;
hh[7] = 1541459225;
hl[0] = 4089235720;
hl[1] = 2227873595;
hl[2] = 4271175723;
hl[3] = 1595750129;
hl[4] = 2917565137;
hl[5] = 725511199;
hl[6] = 4215389547;
hl[7] = 327033209;
crypto_hashblocks_hl(hh, hl, m, n);
n %= 128;
for (i = 0; i < n; i++) x[i] = m[b - n + i];
x[n] = 128;
n = 256 - 128 * (n < 112 ? 1 : 0);
x[n - 9] = 0;
ts64(x, n - 8, b / 536870912 | 0, b << 3);
crypto_hashblocks_hl(hh, hl, x, n);
for (i = 0; i < 8; i++) ts64(out, 8 * i, hh[i], hl[i]);
return 0;
}
function add(p, q) {
var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf();
Z(a, p[1], p[0]);
Z(t, q[1], q[0]);
M(a, a, t);
A(b, p[0], p[1]);
A(t, q[0], q[1]);
M(b, b, t);
M(c, p[3], q[3]);
M(c, c, D2);
M(d, p[2], q[2]);
A(d, d, d);
Z(e, b, a);
Z(f, d, c);
A(g, d, c);
A(h, b, a);
M(p[0], e, f);
M(p[1], h, g);
M(p[2], g, f);
M(p[3], e, h);
}
function cswap(p, q, b) {
var i;
for (i = 0; i < 4; i++) sel25519(p[i], q[i], b);
}
function pack(r, p) {
var tx = gf(), ty = gf(), zi = gf();
inv25519(zi, p[2]);
M(tx, p[0], zi);
M(ty, p[1], zi);
pack25519(r, ty);
r[31] ^= par25519(tx) << 7;
}
function scalarmult(p, q, s) {
var b, i;
set25519(p[0], gf0);
set25519(p[1], gf1);
set25519(p[2], gf1);
set25519(p[3], gf0);
for (i = 255; i >= 0; --i) {
b = s[i / 8 | 0] >> (i & 7) & 1;
cswap(p, q, b);
add(q, p);
add(p, p);
cswap(p, q, b);
}
}
function scalarbase(p, s) {
var q = [
gf(),
gf(),
gf(),
gf()
];
set25519(q[0], X);
set25519(q[1], Y);
set25519(q[2], gf1);
M(q[3], X, Y);
scalarmult(p, q, s);
}
function crypto_sign_keypair(pk, sk, seeded) {
var d = /* @__PURE__ */ new Uint8Array(64);
var p = [
gf(),
gf(),
gf(),
gf()
];
var i;
if (!seeded) randombytes(sk, 32);
crypto_hash(d, sk, 32);
d[0] &= 248;
d[31] &= 127;
d[31] |= 64;
scalarbase(p, d);
pack(pk, p);
for (i = 0; i < 32; i++) sk[i + 32] = pk[i];
return 0;
}
var L = 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
]);
function modL(r, x) {
var carry, i, j, k;
for (i = 63; i >= 32; --i) {
carry = 0;
for (j = i - 32, k = i - 12; j < k; ++j) {
x[j] += carry - 16 * x[i] * L[j - (i - 32)];
carry = Math.floor((x[j] + 128) / 256);
x[j] -= carry * 256;
}
x[j] += carry;
x[i] = 0;
}
carry = 0;
for (j = 0; j < 32; j++) {
x[j] += carry - (x[31] >> 4) * L[j];
carry = x[j] >> 8;
x[j] &= 255;
}
for (j = 0; j < 32; j++) x[j] -= carry * L[j];
for (i = 0; i < 32; i++) {
x[i + 1] += x[i] >> 8;
r[i] = x[i] & 255;
}
}
function reduce(r) {
var x = /* @__PURE__ */ new Float64Array(64), i;
for (i = 0; i < 64; i++) x[i] = r[i];
for (i = 0; i < 64; i++) r[i] = 0;
modL(r, x);
}
function crypto_sign(sm, m, n, sk) {
var d = /* @__PURE__ */ new Uint8Array(64), h = /* @__PURE__ */ new Uint8Array(64), r = /* @__PURE__ */ new Uint8Array(64);
var i, j, x = /* @__PURE__ */ new Float64Array(64);
var p = [
gf(),
gf(),
gf(),
gf()
];
crypto_hash(d, sk, 32);
d[0] &= 248;
d[31] &= 127;
d[31] |= 64;
var smlen = n + 64;
for (i = 0; i < n; i++) sm[64 + i] = m[i];
for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];
crypto_hash(r, sm.subarray(32), n + 32);
reduce(r);
scalarbase(p, r);
pack(sm, p);
for (i = 32; i < 64; i++) sm[i] = sk[i];
crypto_hash(h, sm, n + 64);
reduce(h);
for (i = 0; i < 64; i++) x[i] = 0;
for (i = 0; i < 32; i++) x[i] = r[i];
for (i = 0; i < 32; i++) for (j = 0; j < 32; j++) x[i + j] += h[i] * d[j];
modL(sm.subarray(32), x);
return smlen;
}
function unpackneg(r, p) {
var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf();
set25519(r[2], gf1);
unpack25519(r[1], p);
S(num, r[1]);
M(den, num, D);
Z(num, num, r[2]);
A(den, r[2], den);
S(den2, den);
S(den4, den2);
M(den6, den4, den2);
M(t, den6, num);
M(t, t, den);
pow2523(t, t);
M(t, t, num);
M(t, t, den);
M(t, t, den);
M(r[0], t, den);
S(chk, r[0]);
M(chk, chk, den);
if (neq25519(chk, num)) M(r[0], r[0], I);
S(chk, r[0]);
M(chk, chk, den);
if (neq25519(chk, num)) return -1;
if (par25519(r[0]) === p[31] >> 7) Z(r[0], gf0, r[0]);
M(r[3], r[0], r[1]);
return 0;
}
function crypto_sign_open(m, sm, n, pk) {
var i;
var t = /* @__PURE__ */ new Uint8Array(32), h = /* @__PURE__ */ new Uint8Array(64);
var p = [
gf(),
gf(),
gf(),
gf()
], q = [
gf(),
gf(),
gf(),
gf()
];
if (n < 64) return -1;
if (unpackneg(q, pk)) return -1;
for (i = 0; i < n; i++) m[i] = sm[i];
for (i = 0; i < 32; i++) m[i + 32] = pk[i];
crypto_hash(h, m, n);
reduce(h);
scalarmult(p, q, h);
scalarbase(q, sm.subarray(32));
add(p, q);
pack(t, p);
n -= 64;
if (crypto_verify_32(sm, 0, t, 0)) {
for (i = 0; i < n; i++) m[i] = 0;
return -1;
}
for (i = 0; i < n; i++) m[i] = sm[i + 64];
return n;
}
var crypto_secretbox_KEYBYTES = 32, crypto_secretbox_NONCEBYTES = 24, crypto_secretbox_ZEROBYTES = 32, crypto_secretbox_BOXZEROBYTES = 16, crypto_scalarmult_BYTES = 32, crypto_scalarmult_SCALARBYTES = 32, crypto_box_PUBLICKEYBYTES = 32, crypto_box_SECRETKEYBYTES = 32, crypto_box_BEFORENMBYTES = 32, crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, crypto_sign_BYTES = 64, crypto_sign_PUBLICKEYBYTES = 32, crypto_sign_SECRETKEYBYTES = 64, crypto_sign_SEEDBYTES = 32, crypto_hash_BYTES = 64;
nacl.lowlevel = {
crypto_core_hsalsa20,
crypto_stream_xor,
crypto_stream,
crypto_stream_salsa20_xor,
crypto_stream_salsa20,
crypto_onetimeauth,
crypto_onetimeauth_verify,
crypto_verify_16,
crypto_verify_32,
crypto_secretbox,
crypto_secretbox_open,
crypto_scalarmult,
crypto_scalarmult_base,
crypto_box_beforenm,
crypto_box_afternm,
crypto_box,
crypto_box_open,
crypto_box_keypair,
crypto_hash,
crypto_sign,
crypto_sign_keypair,
crypto_sign_open,
crypto_secretbox_KEYBYTES,
crypto_secretbox_NONCEBYTES,
crypto_secretbox_ZEROBYTES,
crypto_secretbox_BOXZEROBYTES,
crypto_scalarmult_BYTES,
crypto_scalarmult_SCALARBYTES,
crypto_box_PUBLICKEYBYTES,
crypto_box_SECRETKEYBYTES,
crypto_box_BEFORENMBYTES,
crypto_box_NONCEBYTES,
crypto_box_ZEROBYTES,
crypto_box_BOXZEROBYTES,
crypto_sign_BYTES,
crypto_sign_PUBLICKEYBYTES,
crypto_sign_SECRETKEYBYTES,
crypto_sign_SEEDBYTES,
crypto_hash_BYTES,
gf,
D,
L,
pack25519,
unpack25519,
M,
A,
S,
Z,
pow2523,
add,
set25519,
modL,
scalarmult,
scalarbase
};
function checkLengths(k, n) {
if (k.length !== crypto_secretbox_KEYBYTES) throw new Error("bad key size");
if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error("bad nonce size");
}
function checkBoxLengths(pk, sk) {
if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error("bad public key size");
if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error("bad secret key size");
}
function checkArrayTypes() {
for (var i = 0; i < arguments.length; i++) if (!(arguments[i] instanceof Uint8Array)) throw new TypeError("unexpected type, use Uint8Array");
}
function cleanup(arr) {
for (var i = 0; i < arr.length; i++) arr[i] = 0;
}
nacl.randomBytes = function(n) {
var b = new Uint8Array(n);
randombytes(b, n);
return b;
};
nacl.secretbox = function(msg, nonce, key) {
checkArrayTypes(msg, nonce, key);
checkLengths(key, nonce);
var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length);
var c = new Uint8Array(m.length);
for (var i = 0; i < msg.length; i++) m[i + crypto_secretbox_ZEROBYTES] = msg[i];
crypto_secretbox(c, m, m.length, nonce, key);
return c.subarray(crypto_secretbox_BOXZEROBYTES);
};
nacl.secretbox.open = function(box, nonce, key) {
checkArrayTypes(box, nonce, key);
checkLengths(key, nonce);
var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length);
var m = new Uint8Array(c.length);
for (var i = 0; i < box.length; i++) c[i + crypto_secretbox_BOXZEROBYTES] = box[i];
if (c.length < 32) return null;
if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return null;
return m.subarray(crypto_secretbox_ZEROBYTES);
};
nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES;
nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES;
nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES;
nacl.scalarMult = function(n, p) {
checkArrayTypes(n, p);
if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error("bad n size");
if (p.length !== crypto_scalarmult_BYTES) throw new Error("bad p size");
var q = new Uint8Array(crypto_scalarmult_BYTES);
crypto_scalarmult(q, n, p);
return q;
};
nacl.scalarMult.base = function(n) {
checkArrayTypes(n);
if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error("bad n size");
var q = new Uint8Array(crypto_scalarmult_BYTES);
crypto_scalarmult_base(q, n);
return q;
};
nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES;
nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES;
nacl.box = function(msg, nonce, publicKey, secretKey) {
var k = nacl.box.before(publicKey, secretKey);
return nacl.secretbox(msg, nonce, k);
};
nacl.box.before = function(publicKey, secretKey) {
checkArrayTypes(publicKey, secretKey);
checkBoxLengths(publicKey, secretKey);
var k = new Uint8Array(crypto_box_BEFORENMBYTES);
crypto_box_beforenm(k, publicKey, secretKey);
return k;
};
nacl.box.after = nacl.secretbox;
nacl.box.open = function(msg, nonce, publicKey, secretKey) {
var k = nacl.box.before(publicKey, secretKey);
return nacl.secretbox.open(msg, nonce, k);
};
nacl.box.open.after = nacl.secretbox.open;
nacl.box.keyPair = function() {
var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
crypto_box_keypair(pk, sk);
return {
publicKey: pk,
secretKey: sk
};
};
nacl.box.keyPair.fromSecretKey = function(secretKey) {
checkArrayTypes(secretKey);
if (secretKey.length !== crypto_box_SECRETKEYBYTES) throw new Error("bad secret key size");
var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
crypto_scalarmult_base(pk, secretKey);
return {
publicKey: pk,
secretKey: new Uint8Array(secretKey)
};
};
nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES;
nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES;
nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES;
nacl.box.nonceLength = crypto_box_NONCEBYTES;
nacl.box.overheadLength = nacl.secretbox.overheadLength;
nacl.sign = function(msg, secretKey) {
checkArrayTypes(msg, secretKey);
if (secretKey.length !== crypto_sign_SECRETKEYBYTES) throw new Error("bad secret key size");
var signedMsg = new Uint8Array(crypto_sign_BYTES + msg.length);
crypto_sign(signedMsg, msg, msg.length, secretKey);
return signedMsg;
};
nacl.sign.open = function(signedMsg, publicKey) {
checkArrayTypes(signedMsg, publicKey);
if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) throw new Error("bad public key size");
var tmp = new Uint8Array(signedMsg.length);
var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey);
if (mlen < 0) return null;
var m = new Uint8Array(mlen);
for (var i = 0; i < m.length; i++) m[i] = tmp[i];
return m;
};
nacl.sign.detached = function(msg, secretKey) {
var signedMsg = nacl.sign(msg, secretKey);
var sig = new Uint8Array(crypto_sign_BYTES);
for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];
return sig;
};
nacl.sign.detached.verify = function(msg, sig, publicKey) {
checkArrayTypes(msg, sig, publicKey);
if (sig.length !== crypto_sign_BYTES) throw new Error("bad signature size");
if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) throw new Error("bad public key size");
var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
var m = new Uint8Array(crypto_sign_BYTES + msg.length);
var i;
for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
for (i = 0; i < msg.length; i++) sm[i + crypto_sign_BYTES] = msg[i];
return crypto_sign_open(m, sm, sm.length, publicKey) >= 0;
};
nacl.sign.keyPair = function() {
var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
crypto_sign_keypair(pk, sk);
return {
publicKey: pk,
secretKey: sk
};
};
nacl.sign.keyPair.fromSecretKey = function(secretKey) {
checkArrayTypes(secretKey);
if (secretKey.length !== crypto_sign_SECRETKEYBYTES) throw new Error("bad secret key size");
var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32 + i];
return {
publicKey: pk,
secretKey: new Uint8Array(secretKey)
};
};
nacl.sign.keyPair.fromSeed = function(seed) {
checkArrayTypes(seed);
if (seed.length !== crypto_sign_SEEDBYTES) throw new Error("bad seed size");
var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
for (var i = 0; i < 32; i++) sk[i] = seed[i];
crypto_sign_keypair(pk, sk, true);
return {
publicKey: pk,
secretKey: sk
};
};
nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES;
nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES;
nacl.sign.seedLength = crypto_sign_SEEDBYTES;
nacl.sign.signatureLength = crypto_sign_BYTES;
nacl.hash = function(msg) {
checkArrayTypes(msg);
var h = new Uint8Array(crypto_hash_BYTES);
crypto_hash(h, msg, msg.length);
return h;
};
nacl.hash.hashLength = crypto_hash_BYTES;
nacl.verify = function(x, y) {
checkArrayTypes(x, y);
if (x.length === 0 || y.length === 0) return false;
if (x.length !== y.length) return false;
return vn(x, 0, y, 0, x.length) === 0 ? true : false;
};
nacl.setPRNG = function(fn) {
randombytes = fn;
};
(function() {
var crypto = typeof self !== "undefined" ? self.crypto || self.msCrypto : null;
if (crypto && crypto.getRandomValues) {
var QUOTA = 65536;
nacl.setPRNG(function(x, n) {
var i, v = new Uint8Array(n);
for (i = 0; i < n; i += QUOTA) crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
for (i = 0; i < n; i++) x[i] = v[i];
cleanup(v);
});
} else if (typeof __require !== "undefined") {
crypto = __require("crypto");
if (crypto && crypto.randomBytes) nacl.setPRNG(function(x, n) {
var i, v = crypto.randomBytes(n);
for (i = 0; i < n; i++) x[i] = v[i];
cleanup(v);
});
}
})();
})(typeof module !== "undefined" && module.exports ? module.exports : self.nacl = self.nacl || {});
}));
//#endregion
//#region node_modules/.pnpm/@fidm+asn1@1.0.4/node_modules/@fidm/asn1/build/common.js
var require_common = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
/**
* BufferVisitor is a visit tool to manipulate buffer.
*/
var BufferVisitor = class {
constructor(buf, start = 0, end = 0) {
this.start = start;
this.end = end > start ? end : start;
this.buf = buf;
}
/**
* return the underlying buffer length
*/
get length() {
return this.buf.length;
}
/**
* Reset visitor' start and end value.
* @param start
* @param end
*/
reset(start = 0, end = 0) {
this.start = start;
if (end >= this.start) this.end = end;
else if (this.end < this.start) this.end = this.start;
return this;
}
/**
* consume some bytes.
* @param steps steps to walk
*/
walk(steps) {
this.start = this.end;
this.end += steps;
return this;
}
/**
* The buffer should have remaining the "steps" of bytes to consume,
* otherwise it will throw an error with given message.
* @param steps steps to consume.
* @param message message to throw.
*/
mustHas(steps, message = "Too few bytes to parse.") {
const requested = this.end + steps;
if (requested > this.buf.length) {
const error = new Error(message);
error.available = this.buf.length;
error.requested = requested;
throw error;
}
this.walk(0);
return this;
}
/**
* Check the remaining bytes with bufferVisitor.mustHas method and then walk.
* @param steps steps to consume.
* @param message message to throw.
*/
mustWalk(steps, message) {
this.mustHas(steps, message);
this.walk(steps);
return this;
}
};
exports.BufferVisitor = BufferVisitor;
}));
//#endregion
//#region node_modules/.pnpm/@fidm+asn1@1.0.4/node_modules/@fidm/asn1/build/pem.js
var require_pem$2 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const util_1$3 = __require("util");
const pemLineLength = 64;
const pemStart = "-----BEGIN ";
const pemEnd = "-----END ";
const pemEndOfLine = "-----";
const procType = "Proc-Type";
/**
* Implements the PEM data encoding, which originated in Privacy
* Enhanced Mail. The most common use of PEM encoding today is in TLS keys and
* certificates. See RFC 1421.
*
* A PEM represents a PEM encoded structure.
*
* The encoded form is:
* ```
* -----BEGIN Type-----
* Headers
* base64-encoded Bytes
* -----END Type-----
* ```
*
* Headers like:
* ```
* Proc-Type: 4,ENCRYPTED
* DEK-Info: DES-EDE3-CBC,29DE8F99F382D122
* ```
*/
var PEM = class {
/**
* Parse PEM formatted buffer, returns one or more PEM object.
* If there is no PEM object, it will throw error.
* @param data buffer to parse.
*/
static parse(data) {
const res = [];
const lines = data.toString("utf8").split("\n").map((s) => s.trim()).filter((s) => s !== "" && !s.startsWith("#"));
while (lines.length > 0) res.push(parse(lines));
if (res.length === 0) throw new Error("PEM: no block");
return res;
}
constructor(type, body) {
this.type = type;
this.body = body;
this.headers = Object.create(null);
}
/**
* Return exists Proc-Type header or empty string
*/
get procType() {
return this.getHeader(procType);
}
/**
* Return a header or empty string with given key.
*/
getHeader(key) {
const val = this.headers[key];
return val == null ? "" : val;
}
/**
* Set a header with given key/value.
*/
setHeader(key, val) {
if (key.includes(":")) throw new Error("pem: cannot encode a header key that contains a colon");
if (key === "" || val === "") throw new Error("pem: invalid header key or value");
this.headers[key] = val;
}
/**
* Encode to PEM formatted string.
*/
toString() {
let rVal = pemStart + this.type + "-----\n";
const headers = Object.keys(this.headers);
if (headers.length > 0) {
const type = this.procType;
if (type !== "") rVal += `${procType}: ${type}\n`;
headers.sort();
for (const key of headers) if (key !== procType) rVal += `${key}: ${this.headers[key]}\n`;
rVal += "\n";
}
const body = this.body.toString("base64");
let offset = 0;
while (offset < body.length) {
rVal += body.slice(offset, offset + pemLineLength) + "\n";
offset += pemLineLength;
}
rVal += pemEnd + this.type + "-----\n";
return rVal;
}
/**
* Encode to PEM formatted buffer.
*/
toBuffer() {
return Buffer.from(this.toString(), "utf8");
}
/**
* Returns the body.
*/
valueOf() {
return this.body;
}
/**
* Return a friendly JSON object for debuging.
*/
toJSON() {
return {
type: this.type,
body: this.body,
headers: this.headers
};
}
[util_1$3.inspect.custom](_depth, options) {
return `<${this.constructor.name} ${util_1$3.inspect(this.toJSON(), options)}>`;
}
};
exports.PEM = PEM;
function parse(lines) {
let line = lines.shift();
if (line == null || !line.startsWith(pemStart) || !line.endsWith(pemEndOfLine)) throw new Error("pem: invalid BEGIN line");
const type = line.slice(11, line.length - 5);
if (type === "") throw new Error("pem: invalid type");
const headers = [];
line = lines.shift();
while (line != null && line.includes(": ")) {
const header = line.split(": ");
if (header.length !== 2 || header[0] === "" || header[1] === "") throw new Error("pem: invalid Header line");
headers.push(header);
line = lines.shift();
}
let body = "";
while (line != null && !line.startsWith(pemEnd)) {
body += line;
line = lines.shift();
}
if (line == null || line !== `${pemEnd}${type}${pemEndOfLine}`) throw new Error("pem: invalid END line");
const pem = new PEM(type, Buffer.from(body, "base64"));
if (body === "" || pem.body.toString("base64") !== body) throw new Error("pem: invalid base64 body");
for (const header of headers) pem.setHeader(header[0], header[1]);
return pem;
}
}));
//#endregion
//#region node_modules/.pnpm/@fidm+asn1@1.0.4/node_modules/@fidm/asn1/build/asn1.js
var require_asn1 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const util_1$2 = __require("util");
const common_1 = require_common();
/**
* ASN.1 classes.
*/
var Class;
(function(Class) {
Class[Class["UNIVERSAL"] = 0] = "UNIVERSAL";
Class[Class["APPLICATION"] = 64] = "APPLICATION";
Class[Class["CONTEXT_SPECIFIC"] = 128] = "CONTEXT_SPECIFIC";
Class[Class["PRIVATE"] = 192] = "PRIVATE";
})(Class = exports.Class || (exports.Class = {}));
/**
* ASN.1 types. Not all types are supported by this implementation.
*/
var Tag;
(function(Tag) {
Tag[Tag["NONE"] = 0] = "NONE";
Tag[Tag["BOOLEAN"] = 1] = "BOOLEAN";
Tag[Tag["INTEGER"] = 2] = "INTEGER";
Tag[Tag["BITSTRING"] = 3] = "BITSTRING";
Tag[Tag["OCTETSTRING"] = 4] = "OCTETSTRING";
Tag[Tag["NULL"] = 5] = "NULL";
Tag[Tag["OID"] = 6] = "OID";
Tag[Tag["ENUMERATED"] = 10] = "ENUMERATED";
Tag[Tag["UTF8"] = 12] = "UTF8";
Tag[Tag["SEQUENCE"] = 16] = "SEQUENCE";
Tag[Tag["SET"] = 17] = "SET";
Tag[Tag["NUMERICSTRING"] = 18] = "NUMERICSTRING";
Tag[Tag["PRINTABLESTRING"] = 19] = "PRINTABLESTRING";
Tag[Tag["T61STRING"] = 20] = "T61STRING";
Tag[Tag["IA5STRING"] = 22] = "IA5STRING";
Tag[Tag["UTCTIME"] = 23] = "UTCTIME";
Tag[Tag["GENERALIZEDTIME"] = 24] = "GENERALIZEDTIME";
Tag[Tag["GENERALSTRING"] = 27] = "GENERALSTRING";
})(Tag = exports.Tag || (exports.Tag = {}));
/**
* BitString is the structure to use when you want an ASN.1 BIT STRING type. A
* bit string is padded up to the nearest byte in memory and the number of
* valid bits is recorded. Padding bits will be zero.
*/
var BitString = class {
constructor(buf, bitLen) {
this.buf = buf;
this.bitLen = bitLen;
}
/**
* Returns the value for the given bits offset.
* @param i bits offet
*/
at(i) {
if (i < 0 || i >= this.bitLen || !Number.isInteger(i)) return 0;
const x = Math.floor(i / 8);
const y = 7 - i % 8;
return this.buf[x] >> y & 1;
}
/**
* Align buffer
*/
rightAlign() {
const shift = 8 - this.bitLen % 8;
if (shift === 8 || this.buf.length === 0) return this.buf;
const buf = Buffer.alloc(this.buf.length);
buf[0] = this.buf[0] >> shift;
for (let i = 1; i < this.buf.length; i++) {
buf[i] = this.buf[i - 1] << 8 - shift;
buf[i] |= this.buf[i] >> shift;
}
return buf;
}
};
exports.BitString = BitString;
exports.ASN1 = class ASN1 {
/**
* Creates a Tag.BOOLEAN ASN.1 object.
* @param val boolean value.
*/
static Bool(val) {
const asn1 = new ASN1(Class.UNIVERSAL, Tag.BOOLEAN, Buffer.from([val ? 255 : 0]));
asn1._value = val;
return asn1;
}
/**
* Parse a Tag.BOOLEAN value from ASN.1 object' value.
* @param buf the buffer to parse.
*/
static parseBool(buf) {
if (!(buf instanceof Buffer) || buf.length !== 1) throw new Error("ASN1 syntax error: invalid boolean");
switch (buf[0]) {
case 0: return false;
case 255: return true;
default: throw new Error("ASN1 syntax error: invalid boolean");
}
}
/**
* Creates a Tag.INTEGER ASN.1 object.
* @param val integer value or buffer.
*/
static Integer(val) {
if (val instanceof Buffer) {
const asn = new ASN1(Class.UNIVERSAL, Tag.INTEGER, val);
asn._value = val.toString("hex");
return asn;
}
if (!Number.isSafeInteger(val)) throw new Error("ASN1 syntax error: invalid integer");
let buf;
if (val >= -128 && val < 128) {
buf = Buffer.alloc(1);
buf.writeInt8(val, 0);
} else if (val >= -32768 && val < 32768) {
buf = Buffer.alloc(2);
buf.writeIntBE(val, 0, 2);
} else if (val >= -8388608 && val < 8388608) {
buf = Buffer.alloc(3);
buf.writeIntBE(val, 0, 3);
} else if (val >= -2147483648 && val < 2147483648) {
buf = Buffer.alloc(4);
buf.writeIntBE(val, 0, 4);
} else if (val >= -549755813888 && val < 549755813888) {
buf = Buffer.alloc(5);
buf.writeIntBE(val, 0, 5);
} else if (val >= -0x800000000000 && val < 0x800000000000) {
buf = Buffer.alloc(6);
buf.writeIntBE(val, 0, 6);
} else throw new Error("ASN1 syntax error: invalid Integer");
const asn1 = new ASN1(Class.UNIVERSAL, Tag.INTEGER, buf);
asn1._value = val;
return asn1;
}
/**
* Parse a Tag.INTEGER value from ASN.1 object' value.
* @param buf the buffer to parse.
*/
static parseInteger(buf) {
if (!(buf instanceof Buffer) || buf.length === 0) throw new Error("ASN1 syntax error: invalid Integer");
if (buf.length > 6) return buf.toString("hex");
return buf.readIntBE(0, buf.length);
}
/**
* Parse a Tag.INTEGER value as a number from ASN.1 object' value.
* @param buf the buffer to parse.
*/
static parseIntegerNum(buf) {
const value = ASN1.parseInteger(buf);
if (typeof value !== "number") throw new Error("ASN1 syntax error: invalid Integer number");
return value;
}
/**
* Parse a Tag.INTEGER value as a hex string(for BigInt) from ASN.1 object' value.
* @param buf the buffer to parse.
*/
static parseIntegerStr(buf) {
const value = ASN1.parseInteger(buf);
if (typeof value === "number") return value.toString(16);
return value;
}
/**
* Creates a Tag.BITSTRING ASN.1 object.
* @param val BitString object or buffer.
*/
static BitString(val) {
if (val instanceof Buffer) val = new BitString(val, val.length * 8);
const paddingBits = val.buf.length * 8 - val.bitLen;
const buf = Buffer.alloc(val.buf.length + 1);
buf.writeInt8(paddingBits, 0);
val.buf.copy(buf, 1);
return new ASN1(Class.UNIVERSAL, Tag.BITSTRING, buf);
}
/**
* Parse a Tag.BITSTRING value from ASN.1 object' value.
* @param buf the buffer to parse.
*/
static parseBitString(buf) {
if (!(buf instanceof Buffer) || buf.length === 0) throw new Error("ASN1 syntax error: invalid BitString");
const paddingBits = buf[0];
if (paddingBits > 7 || buf.length === 1 && paddingBits > 0 || (buf[buf.length - 1] & (1 << buf[0]) - 1) !== 0) throw new Error("ASN1 syntax error: invalid padding bits in BIT STRING");
return new BitString(buf.slice(1), (buf.length - 1) * 8 - paddingBits);
}
/**
* Creates a Tag.NULL ASN.1 object.
*/
static Null() {
const asn1 = new ASN1(Class.UNIVERSAL, Tag.NULL, Buffer.alloc(0));
asn1._value = null;
return asn1;
}
/**
* Parse a Tag.NULL value from ASN.1 object' value.
* @param buf the buffer to parse.
*/
static parseNull(buf) {
if (!(buf instanceof Buffer) || buf.length !== 0) throw new Error("ASN1 syntax error: invalid null");
return null;
}
/**
* Creates an Tag.OID (dot-separated numeric string) ASN.1 object.
* @param val dot-separated numeric string.
*/
static OID(val) {
const values = val.split(".");
if (values.length === 0) throw new Error("ASN1 syntax error: invalid Object Identifier");
const bytes = [];
bytes.push(40 * mustParseInt(values[0]) + mustParseInt(values[1]));
const valueBytes = [];
for (let i = 2; i < values.length; ++i) {
let value = mustParseInt(values[i]);
valueBytes.length = 0;
valueBytes.push(value & 127);
while (value > 127) {
value = value >>> 7;
valueBytes.unshift(value & 127 | 128);
}
bytes.push(...valueBytes);
}
const asn1 = new ASN1(Class.UNIVERSAL, Tag.OID, Buffer.from(bytes));
asn1._value = val;
return asn1;
}
/**
* Parse a Tag.OID value from ASN.1 object' value.
* @param buf the buffer to parse.
*/
static parseOID(buf) {
if (!(buf instanceof Buffer) || buf.length === 0) throw new Error("ASN1 syntax error: invalid OID");
let oid = Math.floor(buf[0] / 40) + "." + buf[0] % 40;
let high = 0;
for (let i = 1; i < buf.length; i++) if (buf[i] >= 128) {
high += buf[i] & 127;
high = high << 7;
} else {
oid += "." + (high + buf[i]);
high = 0;
}
return oid;
}
/**
* Creates an Tag.UTF8 ASN.1 object.
* @param val utf8 string.
*/
static UTF8(val) {
const asn1 = new ASN1(Class.UNIVERSAL, Tag.UTF8, Buffer.from(val, "utf8"));
asn1._value = val;
return asn1;
}
/**
* Parse a Tag.UTF8 string from ASN.1 object' value.
* @param buf the buffer to parse.
*/
static parseUTF8(buf) {
if (!(buf instanceof Buffer)) throw new Error("parse ASN1 error: invalid Buffer");
return buf.toString("utf8");
}
/**
* Creates an Tag.NUMERICSTRING ASN.1 object.
* @param val numeric string.
*/
static NumericString(val) {
if (!isNumericString(val)) throw new Error("ASN1 syntax error: invalid NumericString");
const asn1 = new ASN1(Class.UNIVERSAL, Tag.NUMERICSTRING, Buffer.from(val, "utf8"));
asn1._value = val;
return asn1;
}
/**
* Parse a Tag.UTF8 string from ASN.1 object' value.
* @param buf the buffer to parse.
*/
static parseNumericString(buf) {
if (!(buf instanceof Buffer)) throw new Error("parse ASN1 error: invalid Buffer");
const str = buf.toString("utf8");
if (!isNumericString(str)) throw new Error("ASN1 syntax error: invalid NumericString");
return str;
}
/**
* Creates an Tag.NUMERICSTRING ASN.1 object.
* @param val printable string.
*/
static PrintableString(val) {
const asn1 = new ASN1(Class.UNIVERSAL, Tag.PRINTABLESTRING, Buffer.from(val, "utf8"));
asn1._value = val;
return asn1;
}
/**
* Parse a Tag.PRINTABLESTRING string from ASN.1 object' value.
* @param buf the buffer to parse.
*/
static parsePrintableString(buf) {
if (!(buf instanceof Buffer)) throw new Error("parse ASN1 error: invalid Buffer");
return buf.toString("utf8");
}
/**
* Creates an Tag.IA5STRING (ASCII string) ASN.1 object.
* @param val ASCII string.
*/
static IA5String(val) {
if (!isIA5String(val)) throw new Error("ASN1 syntax error: invalid IA5String");
const asn1 = new ASN1(Class.UNIVERSAL, Tag.IA5STRING, Buffer.from(val, "utf8"));
asn1._value = val;
return asn1;
}
/**
* Parse a Tag.IA5STRING string from ASN.1 object' value.
* @param buf the buffer to parse.
*/
static parseIA5String(buf) {
if (!(buf instanceof Buffer)) throw new Error("parse ASN1 error: invalid Buffer");
const str = buf.toString("utf8");
if (!isIA5String(str)) throw new Error("ASN1 syntax error: invalid IA5String");
return str;
}
/**
* Creates an Tag.T61STRING (8-bit clean string) ASN.1 object.
* @param val 8-bit clean string.
*/
static T61String(val) {
const asn1 = new ASN1(Class.UNIVERSAL, Tag.T61STRING, Buffer.from(val, "utf8"));
asn1._value = val;
return asn1;
}
/**
* Parse a Tag.T61STRING string from ASN.1 object' value.
* @param buf the buffer to parse.
*/
static parseT61String(buf) {
if (!(buf instanceof Buffer)) throw new Error("parse ASN1 error: invalid Buffer");
return buf.toString("utf8");
}
/**
* Creates an Tag.GENERALSTRING (specified in ISO-2022/ECMA-35) ASN.1 object.
* @param val general string.
*/
static GeneralString(val) {
const asn1 = new ASN1(Class.UNIVERSAL, Tag.GENERALSTRING, Buffer.from(val, "utf8"));
asn1._value = val;
return asn1;
}
/**
* Parse a Tag.GENERALSTRING string from ASN.1 object' value.
* @param buf the buffer to parse.
*/
static parseGeneralString(buf) {
if (!(buf instanceof Buffer)) throw new Error("parse ASN1 error: invalid Buffer");
return buf.toString("utf8");
}
/**
* Creates an Tag.UTCTIME ASN.1 object.
*
* Note: GeneralizedTime has 4 digits for the year and is used for X.509.
* dates past 2049. Converting to a GeneralizedTime hasn't been implemented yet.
* @param date date value.
*/
static UTCTime(date) {
let rval = "";
const format = [];
format.push(("" + date.getUTCFullYear()).substr(2));
format.push("" + (date.getUTCMonth() + 1));
format.push("" + date.getUTCDate());
format.push("" + date.getUTCHours());
format.push("" + date.getUTCMinutes());
format.push("" + date.getUTCSeconds());
for (const s of format) {
if (s.length < 2) rval += "0";
rval += s;
}
rval += "Z";
const asn1 = new ASN1(Class.UNIVERSAL, Tag.UTCTIME, Buffer.from(rval, "utf8"));
asn1._value = date;
return asn1;
}
/**
* Parse a Tag.UTCTIME date from ASN.1 object' value.
* @param buf the buffer to parse.
*/
static parseUTCTime(buf) {
if (!(buf instanceof Buffer) || buf.length === 0) throw new Error("ASN1 syntax error: invalid UTC Time");
const utc = buf.toString("utf8");
const date = /* @__PURE__ */ new Date();
let year = mustParseInt(utc.substr(0, 2));
year = year >= 50 ? 1900 + year : 2e3 + year;
const MM = mustParseInt(utc.substr(2, 2)) - 1;
const DD = mustParseInt(utc.substr(4, 2));
const hh = mustParseInt(utc.substr(6, 2));
const mm = mustParseInt(utc.substr(8, 2));
let ss = 0;
let end = 0;
let c = "";
if (utc.length > 11) {
end = 10;
c = utc.charAt(end);
if (c !== "+" && c !== "-") {
ss = mustParseInt(utc.substr(10, 2));
end += 2;
}
}
date.setUTCFullYear(year, MM, DD);
date.setUTCHours(hh, mm, ss, 0);
if (end > 0) {
c = utc.charAt(end);
if (c === "+" || c === "-") {
const hhoffset = mustParseInt(utc.substr(end + 1, 2));
const mmoffset = mustParseInt(utc.substr(end + 4, 2));
let offset = hhoffset * 60 + mmoffset;
offset *= 6e4;
if (c === "+") date.setTime(+date - offset);
else date.setTime(+date + offset);
}
}
return date;
}
/**
* Creates an Tag.GENERALIZEDTIME ASN.1 object.
* @param date date value.
*/
static GeneralizedTime(date) {
let rval = "";
const format = [];
format.push("" + date.getUTCFullYear());
format.push("" + (date.getUTCMonth() + 1));
format.push("" + date.getUTCDate());
format.push("" + date.getUTCHours());
format.push("" + date.getUTCMinutes());
format.push("" + date.getUTCSeconds());
for (const s of format) {
if (s.length < 2) rval += "0";
rval += s;
}
rval += "Z";
const asn1 = new ASN1(Class.UNIVERSAL, Tag.GENERALIZEDTIME, Buffer.from(rval, "utf8"));
asn1._value = date;
return asn1;
}
/**
* Parse a Tag.GENERALIZEDTIME date from ASN.1 object' value.
* @param buf the buffer to parse.
*/
static parseGeneralizedTime(buf) {
if (!(buf instanceof Buffer) || buf.length === 0) throw new Error("ASN1 syntax error: invalid Generalized Time");
const gentime = buf.toString("utf8");
const date = /* @__PURE__ */ new Date();
const YYYY = mustParseInt(gentime.substr(0, 4));
const MM = mustParseInt(gentime.substr(4, 2)) - 1;
const DD = mustParseInt(gentime.substr(6, 2));
const hh = mustParseInt(gentime.substr(8, 2));
const mm = mustParseInt(gentime.substr(10, 2));
const ss = mustParseInt(gentime.substr(12, 2));
let fff = 0;
let offset = 0;
let isUTC = false;
if (gentime.charAt(gentime.length - 1) === "Z") isUTC = true;
const end = gentime.length - 5;
const c = gentime.charAt(end);
if (c === "+" || c === "-") {
const hhoffset = mustParseInt(gentime.substr(end + 1, 2));
const mmoffset = mustParseInt(gentime.substr(end + 4, 2));
offset = hhoffset * 60 + mmoffset;
offset *= 6e4;
if (c === "+") offset *= -1;
isUTC = true;
}
if (gentime.charAt(14) === ".") fff = parseFloat(gentime.substr(14)) * 1e3;
if (isUTC) {
date.setUTCFullYear(YYYY, MM, DD);
date.setUTCHours(hh, mm, ss, fff);
date.setTime(+date + offset);
} else {
date.setFullYear(YYYY, MM, DD);
date.setHours(hh, mm, ss, fff);
}
return date;
}
/**
* Parse a Tag.UTCTIME date of Tag.GENERALIZEDTIME date from ASN.1 object' value.
* @param tag the type.
* @param buf the buffer to parse.
*/
static parseTime(tag, buf) {
switch (tag) {
case Tag.UTCTIME: return ASN1.parseUTCTime(buf);
case Tag.GENERALIZEDTIME: return ASN1.parseGeneralizedTime(buf);
default: throw new Error("Invalid ASN1 time tag");
}
}
/**
* Creates an Tag.SET ASN.1 object.
* @param objs an array of ASN.1 objects.
*/
static Set(objs) {
const asn1 = new ASN1(Class.UNIVERSAL, Tag.SET, Buffer.concat(objs.map((obj) => obj.toDER())));
asn1._value = objs;
return asn1;
}
/**
* Creates an Tag.SEQUENCE ASN.1 object.
* @param objs an array of ASN.1 objects.
*/
static Seq(objs) {
const asn1 = new ASN1(Class.UNIVERSAL, Tag.SEQUENCE, Buffer.concat(objs.map((obj) => obj.toDER())));
asn1._value = objs;
return asn1;
}
/**
* Creates an Class.CONTEXT_SPECIFIC ASN.1 object.
*
* Note: the tag means nothing with Class.CONTEXT_SPECIFIC
* @param tag number.
* @param objs an array of ASN.1 objects or a ASN.1 object.
* @param isCompound when objs is a array, the isCompound will be set to true.
*/
static Spec(tag, objs, isCompound = true) {
const bytes = Array.isArray(objs) ? Buffer.concat(objs.map((obj) => obj.toDER())) : objs.toDER();
if (Array.isArray(objs)) isCompound = true;
const asn1 = new ASN1(Class.CONTEXT_SPECIFIC, tag, bytes, isCompound);
asn1._value = objs;
return asn1;
}
/**
* Parse a ASN.1 object from a buffer in DER format.
*
* @param buf the buffer to parse.
* @param deepParse deeply parse or not.
*/
static fromDER(buf, deepParse = false) {
return ASN1._fromDER(new common_1.BufferVisitor(buf), deepParse);
}
/**
* Parse a ASN.1 object from a buffer in DER format with given class and tag.
* If class or tag is not match, it will throw a error.
*
* @param tagClass expect class to parse.
* @param tag expect type to parse.
* @param buf the buffer to parse.
*/
static parseDER(buf, tagClass, tag) {
const obj = ASN1._fromDER(new common_1.BufferVisitor(buf), false);
if (obj.class !== tagClass && obj.tag !== tag) throw new Error(`invalid ASN.1 DER for class ${tagClass} and tag ${tag}`);
return obj;
}
/**
* Parse a ASN.1 object from a buffer in DER format with given Template object.
* If template is not match, it will throw a error.
*
* @param buf the buffer to parse.
* @param tpl expect template to parse.
*
* @return a Captures object with captured ASN.1 objects
*/
static parseDERWithTemplate(buf, tpl) {
const obj = ASN1._fromDER(new common_1.BufferVisitor(buf), true);
const captures = {};
const err = obj.validate(tpl, captures);
if (err != null) {
err.data = obj;
throw err;
}
return captures;
}
static _parseCompound(buf, deepParse) {
const values = [];
const len = buf.length;
const bufv = new common_1.BufferVisitor(buf);
let readByteLen = 0;
while (readByteLen < len) {
const start = bufv.end;
values.push(ASN1._fromDER(bufv, deepParse));
readByteLen += bufv.end - start;
}
return values;
}
static _fromDER(bufv, deepParse) {
if (!(bufv.buf instanceof Buffer) || bufv.length === 0) throw new Error("ASN1 syntax error: invalid Generalized Time");
bufv.mustWalk(1, "Too few bytes to read ASN.1 tag.");
const start = bufv.start;
const b1 = bufv.buf[start];
const tagClass = b1 & 192;
const tag = b1 & 31;
const valueLen = getValueLength(bufv);
bufv.mustHas(valueLen);
if (valueLen !== 0 && tag === Tag.NULL) throw new Error("invalid value length or NULL tag.");
bufv.mustWalk(valueLen);
const isCompound = (b1 & 32) === 32;
const asn1 = new ASN1(tagClass, tag, bufv.buf.slice(bufv.start, bufv.end), isCompound);
if (isCompound && deepParse) asn1._value = ASN1._parseCompound(asn1.bytes, deepParse);
asn1._der = bufv.buf.slice(start, bufv.end);
return asn1;
}
constructor(tagClass, tag, data, isCompound = false) {
this.class = tagClass;
this.tag = tag;
this.bytes = data;
this.isCompound = isCompound || tag === Tag.SEQUENCE || tag === Tag.SET;
this._value = void 0;
this._der = null;
}
/**
* the well parsed value of this ASN.1 object.
* It will be boolean, number, string, BitString, Date, array of ASN.1 objects and so on.
*/
get value() {
if (this._value === void 0) this._value = this.valueOf();
return this._value;
}
/**
* the DER format Buffer of this ASN.1 object.
*/
get DER() {
if (this._der == null) this._der = this.toDER();
return this._der;
}
/**
* Expecting it is compound ASN.1 object and returns an array of sub ASN.1 objects.
* @param msg error message to throw when it is not compound ASN.1 object.
*/
mustCompound(msg = "asn1 object value is not compound") {
if (!this.isCompound || !Array.isArray(this.value)) {
const err = new Error(msg);
err.data = this.toJSON();
throw err;
}
return this.value;
}
/**
* Returns true if two ASN.1 objects equally.
* @param obj another ASN.1 object.
*/
equals(obj) {
if (!(obj instanceof ASN1)) return false;
if (this.class !== obj.class || this.tag !== obj.tag || this.isCompound !== obj.isCompound) return false;
if (!this.bytes.equals(obj.bytes)) return false;
return true;
}
/**
* Converts this ASN.1 object to a buffer of bytes in DER format.
*/
toDER() {
let b1 = this.class | this.tag;
if (this.isCompound) b1 |= 32;
const valueLenBytes = getValueLengthByte(this.bytes.length);
const buf = Buffer.allocUnsafe(2 + valueLenBytes + this.bytes.length);
buf.writeInt8(b1, 0);
if (valueLenBytes === 0) {
buf.writeUInt8(this.bytes.length, 1);
this.bytes.copy(buf, 2);
} else {
buf.writeUInt8(valueLenBytes | 128, 1);
buf.writeUIntBE(this.bytes.length, 2, valueLenBytes);
this.bytes.copy(buf, 2 + valueLenBytes);
}
return buf;
}
/**
* Parse the value of this ASN.1 object when it is Class.UNIVERSAL.
* The value will be boolean, number, string, BitString, Date, array of ASN.1 objects and so on.
*/
valueOf() {
if (this.isCompound) return ASN1._parseCompound(this.bytes, false);
if (this.class !== Class.UNIVERSAL) return this.bytes;
switch (this.tag) {
case Tag.BOOLEAN: return ASN1.parseBool(this.bytes);
case Tag.INTEGER: return ASN1.parseInteger(this.bytes);
case Tag.BITSTRING: return ASN1.parseBitString(this.bytes);
case Tag.NULL: return ASN1.parseNull(this.bytes);
case Tag.OID: return ASN1.parseOID(this.bytes);
case Tag.UTF8: return ASN1.parseUTF8(this.bytes);
case Tag.NUMERICSTRING: return ASN1.parseNumericString(this.bytes);
case Tag.PRINTABLESTRING: return ASN1.parsePrintableString(this.bytes);
case Tag.T61STRING: return ASN1.parseT61String(this.bytes);
case Tag.IA5STRING: return ASN1.parseIA5String(this.bytes);
case Tag.GENERALSTRING: return ASN1.parseGeneralString(this.bytes);
case Tag.UTCTIME: return ASN1.parseUTCTime(this.bytes);
case Tag.GENERALIZEDTIME: return ASN1.parseGeneralizedTime(this.bytes);
default: return this.bytes;
}
}
/**
* Validates that the given ASN.1 object is at least a super set of the
* given ASN.1 structure. Only tag classes and types are checked. An
* optional map may also be provided to capture ASN.1 values while the
* structure is checked.
*
* To capture an ASN.1 object, set an object in the validator's 'capture'
* parameter to the key to use in the capture map.
*
* Objects in the validator may set a field 'optional' to true to indicate
* that it isn't necessary to pass validation.
*
* @param tpl Template object to validate.
* @param captures Captures object to capture ASN.1 object.
*/
validate(tpl, captures = {}) {
if (this.class !== tpl.class) return /* @__PURE__ */ new Error(`ASN.1 object validate failure for ${tpl.name} : error class ${Class[this.class]}`);
if (!(Array.isArray(tpl.tag) ? tpl.tag : [tpl.tag]).includes(this.tag)) return /* @__PURE__ */ new Error(`ASN.1 object validate failure for ${tpl.name}: error tag ${Tag[this.tag]}`);
if (tpl.capture != null) captures[tpl.capture] = this;
if (Array.isArray(tpl.value)) {
const values = this.mustCompound(`${tpl.name} need compound ASN1 value`);
for (let i = 0, j = 0; i < tpl.value.length; i++) if (values[j] != null) {
const err = values[j].validate(tpl.value[i], captures);
if (err == null) j++;
else if (tpl.value[i].optional !== true) return err;
} else if (tpl.value[i].optional !== true) return /* @__PURE__ */ new Error(`ASN.1 object validate failure for ${tpl.value[i].name}: not exists`);
} else if (tpl.value != null) {
const buf = this.tag === Tag.BITSTRING ? this.bytes.slice(1) : this.bytes;
return ASN1.fromDER(buf).validate(tpl.value, captures);
}
return null;
}
/**
* Return a friendly JSON object for debuging.
*/
toJSON() {
let value = this.value;
if (Array.isArray(value)) value = value.map((val) => val.toJSON());
return {
class: Class[this.class],
tag: this.class === Class.UNIVERSAL ? Tag[this.tag] : this.tag,
value
};
}
[util_1$2.inspect.custom](_depth, options) {
if (options.depth <= 2) options.depth = 10;
return `<${this.constructor.name} ${util_1$2.inspect(this.toJSON(), options)}>`;
}
};
function getValueLength(bufv) {
bufv.mustWalk(1, "Too few bytes to read ASN.1 value length.");
const byte = bufv.buf[bufv.start];
if ((byte & 128) === 0) return byte;
const byteLen = byte & 127;
bufv.mustWalk(byteLen, "Too few bytes to read ASN.1 value length.");
return bufv.buf.readUIntBE(bufv.start, byteLen);
}
function getValueLengthByte(valueLen) {
if (valueLen <= 127) return 0;
else if (valueLen <= 255) return 1;
else if (valueLen <= 65535) return 2;
else if (valueLen <= 16777215) return 3;
else if (valueLen <= 4294967295) return 4;
else if (valueLen <= 0xffffffffff) return 5;
else if (valueLen <= 0xffffffffffff) return 6;
else throw new Error("invalid value length");
}
function isNumericString(str) {
for (const s of str) {
const n = s.charCodeAt(0);
if (n !== 32 && (n < 48 || n > 57)) return false;
}
return true;
}
function isIA5String(str) {
for (const s of str) if (s.charCodeAt(0) >= 128) return false;
return true;
}
function mustParseInt(str, radix = 10) {
const val = parseInt(str, radix);
if (Number.isNaN(val)) throw new Error(`Invalid numeric string "${str}" in radix ${radix}.`);
return val;
}
}));
//#endregion
//#region node_modules/.pnpm/@fidm+asn1@1.0.4/node_modules/@fidm/asn1/build/index.js
var require_build$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.BufferVisitor = require_common().BufferVisitor;
exports.PEM = require_pem$2().PEM;
var asn1_1 = require_asn1();
exports.ASN1 = asn1_1.ASN1;
exports.Class = asn1_1.Class;
exports.Tag = asn1_1.Tag;
exports.BitString = asn1_1.BitString;
}));
//#endregion
//#region node_modules/.pnpm/@fidm+x509@1.2.1/node_modules/@fidm/x509/build/pki.js
var require_pki = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const util_1$1 = __require("util");
const crypto_1$1 = __require("crypto");
const tweetnacl_1 = require_nacl_fast();
const asn1_1 = require_build$1();
const common_1 = require_common$1();
/**
* ASN.1 Template for PKCS#8 Public Key.
*/
exports.publicKeyValidator = {
name: "PublicKeyInfo",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.SEQUENCE,
capture: "publicKeyInfo",
value: [{
name: "PublicKeyInfo.AlgorithmIdentifier",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.SEQUENCE,
value: [{
name: "PublicKeyAlgorithmIdentifier.algorithm",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.OID,
capture: "publicKeyOID"
}]
}, {
name: "PublicKeyInfo.PublicKey",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.BITSTRING,
capture: "publicKey"
}]
};
/**
* ASN.1 Template for PKCS#8 Private Key. https://tools.ietf.org/html/rfc5208
*/
exports.privateKeyValidator = {
name: "PrivateKeyInfo",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.SEQUENCE,
capture: "privateKeyInfo",
value: [
{
name: "PrivateKeyInfo.Version",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.INTEGER,
capture: "privateKeyVersion"
},
{
name: "PrivateKeyInfo.AlgorithmIdentifier",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.SEQUENCE,
value: [{
name: "PrivateKeyAlgorithmIdentifier.algorithm",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.OID,
capture: "privateKeyOID"
}]
},
{
name: "PrivateKeyInfo.PrivateKey",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.OCTETSTRING,
capture: "privateKey"
}
]
};
const rsaPublicKeyValidator = {
name: "RSAPublicKey",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.SEQUENCE,
value: [{
name: "RSAPublicKey.modulus",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.INTEGER,
capture: "publicKeyModulus"
}, {
name: "RSAPublicKey.exponent",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.INTEGER,
capture: "publicKeyExponent"
}]
};
const rsaPrivateKeyValidator = {
name: "RSAPrivateKey",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.SEQUENCE,
value: [
{
name: "RSAPrivateKey.version",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.INTEGER,
capture: "privateKeyVersion"
},
{
name: "RSAPrivateKey.modulus",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.INTEGER,
capture: "privateKeyModulus"
},
{
name: "RSAPrivateKey.publicExponent",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.INTEGER,
capture: "privateKeyPublicExponent"
},
{
name: "RSAPrivateKey.privateExponent",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.INTEGER,
capture: "privateKeyPrivateExponent"
},
{
name: "RSAPrivateKey.prime1",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.INTEGER,
capture: "privateKeyPrime1"
},
{
name: "RSAPrivateKey.prime2",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.INTEGER,
capture: "privateKeyPrime2"
},
{
name: "RSAPrivateKey.exponent1",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.INTEGER,
capture: "privateKeyExponent1"
},
{
name: "RSAPrivateKey.exponent2",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.INTEGER,
capture: "privateKeyExponent2"
},
{
name: "RSAPrivateKey.coefficient",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.INTEGER,
capture: "privateKeyCoefficient"
}
]
};
const EdDSAPrivateKeyOIDs = [
common_1.getOID("X25519"),
common_1.getOID("X448"),
common_1.getOID("Ed25519"),
common_1.getOID("Ed448")
];
/**
* PKCS#8 Public Key
*/
var PublicKey = class PublicKey {
constructor(obj) {
const captures = {};
const err = obj.validate(exports.publicKeyValidator, captures);
if (err != null) throw new Error("Cannot read X.509 public key: " + err.message);
this.oid = asn1_1.ASN1.parseOID(captures.publicKeyOID.bytes);
this.algo = common_1.getOIDName(this.oid);
this._pkcs8 = obj;
this._keyRaw = asn1_1.ASN1.parseBitString(captures.publicKey.bytes).buf;
this._finalKey = this._keyRaw;
this._finalPEM = "";
}
/**
* Parse an PublicKey for X.509 certificate from PKCS#8 PEM formatted buffer or PKCS#1 RSA PEM formatted buffer.
* @param pem PEM formatted buffer
*/
static fromPEM(pem) {
const msg = asn1_1.PEM.parse(pem)[0];
if (msg.procType.includes("ENCRYPTED")) throw new Error("Could not convert public key from PEM, PEM is encrypted.");
const obj = asn1_1.ASN1.fromDER(msg.body, true);
switch (msg.type) {
case "PUBLIC KEY": return new PublicKey(obj);
case "RSA PUBLIC KEY":
const _pkcs8 = asn1_1.ASN1.Seq([asn1_1.ASN1.Seq([asn1_1.ASN1.OID(common_1.getOID("rsaEncryption")), asn1_1.ASN1.Null()]), asn1_1.ASN1.BitString(obj.DER)]);
return new PublicKey(_pkcs8);
default: throw new Error("Could not convert public key from PEM, recommend PKCS#8 PEM");
}
}
/**
* Registers an external Verifier with object identifier.
* Built-in verifiers: Ed25519, RSA, others see https://nodejs.org/api/crypto.html#crypto_class_verify
* ```js
* PublicKey.addVerifier(getOID('Ed25519'), function (this: PublicKey, data: Buffer, signature: Buffer): boolean {
* return ed25519.detached.verify(data, signature, this.keyRaw)
* })
* ```
* @param oid algorithm object identifier
* @param fn Verifier function
*/
static addVerifier(oid, fn) {
oid = common_1.getOID(oid);
if (oid === "") throw new Error(`Invalid object identifier: ${oid}`);
if (PublicKey._verifiers[oid] != null) throw new Error(`Verifier ${oid} exists`);
PublicKey._verifiers[oid] = fn;
}
/**
* underlying key buffer
*/
get keyRaw() {
return this._finalKey;
}
/**
* Returns true if the provided data and the given signature matched.
* ```js
* certificate.publicKey.verify(data, signature, 'sha256') // => true or false
* ```
* @param data data to verify
* @param signature signature that signed by private key
* @param hashAlgorithm hash algorithm, such as 'sha256', 'sha1'
*/
verify(data, signature, hashAlgorithm) {
const verifier = PublicKey._verifiers[this.oid];
if (verifier != null) {
const sum = crypto_1$1.createHash(hashAlgorithm).update(data).digest();
return verifier.call(this, sum, signature);
}
const verify = crypto_1$1.createVerify(hashAlgorithm);
verify.update(data);
return verify.verify(this.toPEM(), signature);
}
/**
* Returns the digest of the PublicKey with given hash algorithm.
* ```js
* certificate.publicKey.getFingerprint('sha1', 'PublicKey') // => Buffer
* ```
* @param hashAlgorithm hash algorithm, such as 'sha256', 'sha1'
* @param type 'PublicKey' or 'PublicKeyInfo'
*/
getFingerprint(hashAlgorithm, type = "PublicKey") {
let bytes;
switch (type) {
case "PublicKeyInfo":
bytes = this._pkcs8.DER;
break;
case "PublicKey":
bytes = this._keyRaw;
break;
default: throw new Error(`Unknown fingerprint type "${type}".`);
}
const hasher = crypto_1$1.createHash(hashAlgorithm);
hasher.update(bytes);
return hasher.digest();
}
/**
* Returns an ASN.1 object of this PublicKey
*/
toASN1() {
return this._pkcs8;
}
/**
* Returns an DER formatted buffer of this PublicKey
*/
toDER() {
return this._pkcs8.DER;
}
/**
* Returns an PEM formatted string of this PublicKey
*/
toPEM() {
if (this._finalPEM === "") this._finalPEM = new asn1_1.PEM("PUBLIC KEY", this._pkcs8.DER).toString();
return this._finalPEM;
}
/**
* Return a friendly JSON object for debuging.
*/
toJSON() {
return {
oid: this.oid,
algo: this.algo,
publicKey: this._keyRaw
};
}
[util_1$1.inspect.custom](_depth, options) {
return `<${this.constructor.name} ${util_1$1.inspect(this.toJSON(), options)}>`;
}
};
PublicKey._verifiers = Object.create(null);
exports.PublicKey = PublicKey;
/**
* PKCS#8 Private Key
*/
var PrivateKey = class PrivateKey {
constructor(obj) {
const captures = Object.create(null);
const err = obj.validate(exports.privateKeyValidator, captures);
if (err != null) throw new Error("Cannot read X.509 private key: " + err.message);
this.version = asn1_1.ASN1.parseIntegerNum(captures.privateKeyVersion.bytes) + 1;
this.oid = asn1_1.ASN1.parseOID(captures.privateKeyOID.bytes);
this.algo = common_1.getOIDName(this.oid);
this._pkcs8 = obj;
this._keyRaw = captures.privateKey.bytes;
this._publicKeyRaw = null;
this._finalKey = this._keyRaw;
this._finalPEM = "";
if (EdDSAPrivateKeyOIDs.includes(this.oid)) {
this._finalKey = this._keyRaw = asn1_1.ASN1.parseDER(this._keyRaw, asn1_1.Class.UNIVERSAL, asn1_1.Tag.OCTETSTRING).bytes;
if (this.oid === "1.3.101.112") {
const keypair = tweetnacl_1.sign.keyPair.fromSeed(this._keyRaw);
this._publicKeyRaw = Buffer.from(keypair.publicKey);
this._finalKey = Buffer.from(keypair.secretKey);
} else if (this.version === 2) {
for (const val of obj.mustCompound()) if (val.class === asn1_1.Class.CONTEXT_SPECIFIC && val.tag === 1) {
this._publicKeyRaw = asn1_1.ASN1.parseBitString(val.bytes).buf;
this._finalKey = Buffer.concat([this._keyRaw, this._publicKeyRaw]);
}
}
}
}
/**
* Parse an PrivateKey for X.509 certificate from PKCS#8 PEM formatted buffer or PKCS#1 RSA PEM formatted buffer.
* @param pem PEM formatted buffer
*/
static fromPEM(pem) {
const msg = asn1_1.PEM.parse(pem)[0];
if (msg.procType.includes("ENCRYPTED")) throw new Error("Could not convert private key from PEM, PEM is encrypted.");
let obj = asn1_1.ASN1.fromDER(msg.body, true);
switch (msg.type) {
case "PRIVATE KEY": return new PrivateKey(obj);
case "RSA PRIVATE KEY":
obj = asn1_1.ASN1.Seq([
obj.value[0],
asn1_1.ASN1.Seq([asn1_1.ASN1.OID(common_1.getOID("rsaEncryption")), asn1_1.ASN1.Null()]),
new asn1_1.ASN1(asn1_1.Class.UNIVERSAL, asn1_1.Tag.OCTETSTRING, obj.DER)
]);
return new PrivateKey(obj);
default: throw new Error("Could not convert private key from PEM, recommend PKCS#8 PEM");
}
}
/**
* Registers an external Signer with object identifier.
* Built-in verifiers: Ed25519, RSA, others see https://nodejs.org/api/crypto.html#crypto_class_sign
* ```js
* PrivateKey.addSigner(getOID('Ed25519'), function (this: PrivateKey, data: Buffer): Buffer {
* const key = this.keyRaw
* if (key.length !== 64) {
* throw new Error('Invalid signing key.')
* }
* return Buffer.from(ed25519.detached(data, key))
* })
* ```
* @param oid algorithm object identifier
* @param fn Verifier function
*/
static addSigner(oid, fn) {
oid = common_1.getOID(oid);
if (oid === "") throw new Error(`Invalid object identifier: ${oid}`);
if (PrivateKey._signers[oid] != null) throw new Error(`Signer ${oid} exists`);
PrivateKey._signers[oid] = fn;
}
/**
* underlying key buffer
*/
get keyRaw() {
return this._finalKey;
}
/**
* Returns publicKey buffer, it is used for Ed25519/Ed448.
*/
get publicKeyRaw() {
return this._publicKeyRaw;
}
/**
* Returns signature for the given data and hash algorithm.
* @param data
* @param hashAlgorithm
*/
sign(data, hashAlgorithm) {
const signer = PrivateKey._signers[this.oid];
if (signer != null) {
const sum = crypto_1$1.createHash(hashAlgorithm).update(data).digest();
return signer.call(this, sum);
}
const sign = crypto_1$1.createSign(hashAlgorithm);
sign.update(data);
return sign.sign(this.toPEM());
}
/**
* Returns an ASN.1 object of this PrivateKey
*/
toASN1() {
return this._pkcs8;
}
/**
* Returns an DER formatted buffer of this PrivateKey
*/
toDER() {
return this._pkcs8.DER;
}
/**
* Returns an PEM formatted string of this PrivateKey
*/
toPEM() {
if (this._finalPEM === "") this._finalPEM = new asn1_1.PEM("PRIVATE KEY", this._pkcs8.DER).toString();
return this._finalPEM;
}
/**
* Return a friendly JSON object for debuging.
*/
toJSON() {
return {
version: this.version,
oid: this.oid,
algo: this.algo,
privateKey: this._keyRaw,
publicKey: this._publicKeyRaw
};
}
[util_1$1.inspect.custom](_depth, options) {
return `<${this.constructor.name} ${util_1$1.inspect(this.toJSON(), options)}>`;
}
};
PrivateKey._signers = Object.create(null);
exports.PrivateKey = PrivateKey;
exports.RSAPublicKey = class RSAPublicKey extends PublicKey {
static fromPublicKey(publicKey) {
return new RSAPublicKey(publicKey.toASN1());
}
constructor(obj) {
super(obj);
if (common_1.getOID(this.oid) !== common_1.getOID("rsaEncryption")) throw new Error(`Invalid RSA public key, unknown OID: ${this.oid}`);
const captures = Object.create(null);
this._pkcs1 = asn1_1.ASN1.fromDER(this._keyRaw, true);
const err = this._pkcs1.validate(rsaPublicKeyValidator, captures);
if (err != null) throw new Error("Cannot read RSA public key: " + err.message);
this.modulus = asn1_1.ASN1.parseIntegerStr(captures.publicKeyModulus.bytes);
this.exponent = asn1_1.ASN1.parseIntegerNum(captures.publicKeyExponent.bytes);
}
/**
* Returns an PKCS#1 ASN.1 object of this RSAPublicKey
*/
toASN1() {
return this._pkcs1;
}
/**
* Returns an PKCS#1 DER formatted buffer of this RSAPublicKey
*/
toDER() {
return this._keyRaw;
}
/**
* Returns an PKCS#1 PEM formatted string of this RSAPublicKey
*/
toPEM() {
if (this._finalPEM === "") this._finalPEM = new asn1_1.PEM("RSA PUBLIC KEY", this._keyRaw).toString();
return this._finalPEM;
}
/**
* Returns an PKCS#8 PEM formatted string of this RSAPublicKey
*/
toPublicKeyPEM() {
return new asn1_1.PEM("PUBLIC KEY", this._pkcs8.DER).toString();
}
/**
* Return a friendly JSON object for debuging.
*/
toJSON() {
return {
oid: this.oid,
algo: this.algo,
modulus: trimLeadingZeroByte(this.modulus),
exponent: this.exponent
};
}
[util_1$1.inspect.custom](_depth, options) {
return `<${this.constructor.name} ${util_1$1.inspect(this.toJSON(), options)}>`;
}
};
exports.RSAPrivateKey = class RSAPrivateKey extends PrivateKey {
static fromPrivateKey(privateKey) {
return new RSAPrivateKey(privateKey.toASN1());
}
constructor(obj) {
super(obj);
if (common_1.getOID(this.oid) !== common_1.getOID("rsaEncryption")) throw new Error(`Invalid RSA private key, unknown OID: ${this.oid}`);
const captures = Object.create(null);
this._pkcs1 = asn1_1.ASN1.fromDER(this._keyRaw, true);
const err = this._pkcs1.validate(rsaPrivateKeyValidator, captures);
if (err != null) throw new Error("Cannot read RSA private key: " + err.message);
this.publicExponent = asn1_1.ASN1.parseIntegerNum(captures.privateKeyPublicExponent.bytes);
this.privateExponent = asn1_1.ASN1.parseIntegerStr(captures.privateKeyPrivateExponent.bytes);
this.modulus = asn1_1.ASN1.parseIntegerStr(captures.privateKeyModulus.bytes);
this.prime1 = asn1_1.ASN1.parseIntegerStr(captures.privateKeyPrime1.bytes);
this.prime2 = asn1_1.ASN1.parseIntegerStr(captures.privateKeyPrime2.bytes);
this.exponent1 = asn1_1.ASN1.parseIntegerStr(captures.privateKeyExponent1.bytes);
this.exponent2 = asn1_1.ASN1.parseIntegerStr(captures.privateKeyExponent2.bytes);
this.coefficient = asn1_1.ASN1.parseIntegerStr(captures.privateKeyCoefficient.bytes);
}
/**
* Returns an PKCS#1 ASN.1 object of this RSAPrivateKey
*/
toASN1() {
return this._pkcs1;
}
/**
* Returns an PKCS#1 DER formatted buffer of this RSAPrivateKey
*/
toDER() {
return this._keyRaw;
}
/**
* Returns an PKCS#1 PEM formatted string of this RSAPrivateKey
*/
toPEM() {
if (this._finalPEM === "") this._finalPEM = new asn1_1.PEM("RSA PRIVATE KEY", this._keyRaw).toString();
return this._finalPEM;
}
/**
* Returns an PKCS#8 PEM formatted string of this RSAPrivateKey
*/
toPrivateKeyPEM() {
return new asn1_1.PEM("PRIVATE KEY", this._pkcs8.DER).toString();
}
/**
* Return a friendly JSON object for debuging.
*/
toJSON() {
return {
version: this.version,
oid: this.oid,
algo: this.algo,
publicExponent: this.publicExponent,
privateExponent: trimLeadingZeroByte(this.privateExponent),
modulus: trimLeadingZeroByte(this.modulus),
prime1: trimLeadingZeroByte(this.prime1),
prime2: trimLeadingZeroByte(this.prime2),
exponent1: trimLeadingZeroByte(this.exponent1),
exponent2: trimLeadingZeroByte(this.exponent2),
coefficient: trimLeadingZeroByte(this.coefficient)
};
}
[util_1$1.inspect.custom](_depth, options) {
return `<${this.constructor.name} ${util_1$1.inspect(this.toJSON(), options)}>`;
}
};
function trimLeadingZeroByte(hex) {
return hex.length % 8 !== 0 && hex.startsWith("00") ? hex.slice(2) : hex;
}
PublicKey.addVerifier(common_1.getOID("Ed25519"), function(data, signature) {
return tweetnacl_1.sign.detached.verify(data, signature, this.keyRaw);
});
PrivateKey.addSigner(common_1.getOID("Ed25519"), function(data) {
const key = this.keyRaw;
if (key.length !== 64) throw new Error("Invalid signing key.");
return Buffer.from(tweetnacl_1.sign.detached(data, key));
});
}));
//#endregion
//#region node_modules/.pnpm/@fidm+x509@1.2.1/node_modules/@fidm/x509/build/x509.js
var require_x509 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = __require("util");
const crypto_1 = __require("crypto");
const asn1_1 = require_build$1();
const common_1 = require_common$1();
const pki_1 = require_pki();
const shortNames = Object.create(null);
shortNames.CN = common_1.getOID("commonName");
shortNames.commonName = "CN";
shortNames.C = common_1.getOID("countryName");
shortNames.countryName = "C";
shortNames.L = common_1.getOID("localityName");
shortNames.localityName = "L";
shortNames.ST = common_1.getOID("stateOrProvinceName");
shortNames.stateOrProvinceName = "ST";
shortNames.O = common_1.getOID("organizationName");
shortNames.organizationName = "O";
shortNames.OU = common_1.getOID("organizationalUnitName");
shortNames.organizationalUnitName = "OU";
shortNames.E = common_1.getOID("emailAddress");
shortNames.emailAddress = "E";
function getShortName(name) {
return shortNames[name] == null ? "" : shortNames[name];
}
const x509CertificateValidator = {
name: "Certificate",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.SEQUENCE,
value: [
{
name: "Certificate.TBSCertificate",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.SEQUENCE,
capture: "tbsCertificate",
value: [
{
name: "Certificate.TBSCertificate.version",
class: asn1_1.Class.CONTEXT_SPECIFIC,
tag: asn1_1.Tag.NONE,
optional: true,
value: [{
name: "Certificate.TBSCertificate.version.integer",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.INTEGER,
capture: "certVersion"
}]
},
{
name: "Certificate.TBSCertificate.serialNumber",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.INTEGER,
capture: "certSerialNumber"
},
{
name: "Certificate.TBSCertificate.signature",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.SEQUENCE,
value: [{
name: "Certificate.TBSCertificate.signature.algorithm",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.OID,
capture: "certinfoSignatureOID"
}, {
name: "Certificate.TBSCertificate.signature.parameters",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.OCTETSTRING,
optional: true,
capture: "certinfoSignatureParams"
}]
},
{
name: "Certificate.TBSCertificate.issuer",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.SEQUENCE,
capture: "certIssuer"
},
{
name: "Certificate.TBSCertificate.validity",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.SEQUENCE,
value: [{
name: "Certificate.TBSCertificate.validity.notBefore",
class: asn1_1.Class.UNIVERSAL,
tag: [asn1_1.Tag.UTCTIME, asn1_1.Tag.GENERALIZEDTIME],
capture: "certValidityNotBefore"
}, {
name: "Certificate.TBSCertificate.validity.notAfter",
class: asn1_1.Class.UNIVERSAL,
tag: [asn1_1.Tag.UTCTIME, asn1_1.Tag.GENERALIZEDTIME],
capture: "certValidityNotAfter"
}]
},
{
name: "Certificate.TBSCertificate.subject",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.SEQUENCE,
capture: "certSubject"
},
pki_1.publicKeyValidator,
{
name: "Certificate.TBSCertificate.issuerUniqueID",
class: asn1_1.Class.CONTEXT_SPECIFIC,
tag: asn1_1.Tag.BOOLEAN,
optional: true,
value: [{
name: "Certificate.TBSCertificate.issuerUniqueID.id",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.BITSTRING,
capture: "certIssuerUniqueId"
}]
},
{
name: "Certificate.TBSCertificate.subjectUniqueID",
class: asn1_1.Class.CONTEXT_SPECIFIC,
tag: asn1_1.Tag.INTEGER,
optional: true,
value: [{
name: "Certificate.TBSCertificate.subjectUniqueID.id",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.BITSTRING,
capture: "certSubjectUniqueId"
}]
},
{
name: "Certificate.TBSCertificate.extensions",
class: asn1_1.Class.CONTEXT_SPECIFIC,
tag: asn1_1.Tag.BITSTRING,
capture: "certExtensions",
optional: true
}
]
},
{
name: "Certificate.signatureAlgorithm",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.SEQUENCE,
value: [{
name: "Certificate.signatureAlgorithm.algorithm",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.OID,
capture: "certSignatureOID"
}, {
name: "Certificate.TBSCertificate.signature.parameters",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.OCTETSTRING,
optional: true,
capture: "certSignatureParams"
}]
},
{
name: "Certificate.signatureValue",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.BITSTRING,
capture: "certSignature"
}
]
};
/**
* DistinguishedName for X.509v3 certificate.
*/
var DistinguishedName = class {
constructor() {
this.attributes = [];
this.uniqueId = null;
}
get commonName() {
return this.getFieldValue("commonName");
}
get organizationName() {
return this.getFieldValue("organizationName");
}
get organizationalUnitName() {
return this.getFieldValue("organizationalUnitName");
}
get countryName() {
return this.getFieldValue("countryName");
}
get localityName() {
return this.getFieldValue("localityName");
}
get serialName() {
return this.getFieldValue("serialName");
}
getHash() {
const hasher = crypto_1.createHash("sha1");
for (const attr of this.attributes) {
hasher.update(attr.oid);
hasher.update(attr.value);
}
return hasher.digest();
}
getField(key) {
for (const attr of this.attributes) if (key === attr.oid || key === attr.name || key === attr.shortName) return attr;
return null;
}
addField(attr) {
fillMissingFields([attr]);
this.attributes.push(attr);
}
setAttrs(attrs) {
fillMissingFields(attrs);
this.attributes = attrs;
}
toJSON() {
const obj = {};
for (const attr of this.attributes) {
const key = attr.shortName;
if (typeof key === "string" && key !== "") obj[key] = attr.value;
}
obj.uniqueId = this.uniqueId;
obj.attributes = this.attributes;
return obj;
}
getFieldValue(key) {
const val = this.getField(key);
if (val != null) return val.value;
return "";
}
};
exports.DistinguishedName = DistinguishedName;
exports.Certificate = class Certificate {
/**
* Parse one or more X.509 certificates from PEM formatted buffer.
* If there is no certificate, it will throw error.
* @param data PEM formatted buffer
*/
static fromPEMs(data) {
const certs = [];
const pems = asn1_1.PEM.parse(data);
for (const pem of pems) {
if (pem.type !== "CERTIFICATE" && pem.type !== "X509 CERTIFICATE" && pem.type !== "TRUSTED CERTIFICATE") throw new Error("Could not convert certificate from PEM: invalid type");
if (pem.procType.includes("ENCRYPTED")) throw new Error("Could not convert certificate from PEM: PEM is encrypted.");
const obj = asn1_1.ASN1.fromDER(pem.body);
certs.push(new Certificate(obj));
}
if (certs.length === 0) throw new Error("No Certificate");
return certs;
}
/**
* Parse an X.509 certificate from PEM formatted buffer.
* @param data PEM formatted buffer
*/
static fromPEM(data) {
return Certificate.fromPEMs(data)[0];
}
/**
* Creates an X.509 certificate from an ASN.1 object
* @param obj an ASN.1 object
*/
constructor(obj) {
const captures = Object.create(null);
const err = obj.validate(x509CertificateValidator, captures);
if (err != null) throw new Error("Cannot read X.509 certificate: " + err.message);
this.raw = obj.DER;
this.version = captures.certVersion == null ? 0 : asn1_1.ASN1.parseIntegerNum(captures.certVersion.bytes) + 1;
this.serialNumber = asn1_1.ASN1.parseIntegerStr(captures.certSerialNumber.bytes);
this.signatureOID = asn1_1.ASN1.parseOID(captures.certSignatureOID.bytes);
this.signatureAlgorithm = common_1.getOIDName(this.signatureOID);
this.infoSignatureOID = asn1_1.ASN1.parseOID(captures.certinfoSignatureOID.bytes);
this.signature = asn1_1.ASN1.parseBitString(captures.certSignature.bytes).buf;
this.validFrom = asn1_1.ASN1.parseTime(captures.certValidityNotBefore.tag, captures.certValidityNotBefore.bytes);
this.validTo = asn1_1.ASN1.parseTime(captures.certValidityNotAfter.tag, captures.certValidityNotAfter.bytes);
this.issuer = new DistinguishedName();
this.issuer.setAttrs(RDNAttributesAsArray(captures.certIssuer));
if (captures.certIssuerUniqueId != null) this.issuer.uniqueId = asn1_1.ASN1.parseBitString(captures.certIssuerUniqueId.bytes);
this.subject = new DistinguishedName();
this.subject.setAttrs(RDNAttributesAsArray(captures.certSubject));
if (captures.certSubjectUniqueId != null) this.subject.uniqueId = asn1_1.ASN1.parseBitString(captures.certSubjectUniqueId.bytes);
this.extensions = [];
this.subjectKeyIdentifier = "";
this.authorityKeyIdentifier = "";
this.ocspServer = "";
this.issuingCertificateURL = "";
this.isCA = false;
this.maxPathLen = -1;
this.basicConstraintsValid = false;
this.keyUsage = 0;
this.dnsNames = [];
this.emailAddresses = [];
this.ipAddresses = [];
this.uris = [];
if (captures.certExtensions != null) {
this.extensions = certificateExtensionsFromAsn1(captures.certExtensions);
for (const ext of this.extensions) {
if (typeof ext.subjectKeyIdentifier === "string") this.subjectKeyIdentifier = ext.subjectKeyIdentifier;
if (typeof ext.authorityKeyIdentifier === "string") this.authorityKeyIdentifier = ext.authorityKeyIdentifier;
if (typeof ext.authorityInfoAccessOcsp === "string") this.ocspServer = ext.authorityInfoAccessOcsp;
if (typeof ext.authorityInfoAccessIssuers === "string") this.issuingCertificateURL = ext.authorityInfoAccessIssuers;
if (typeof ext.basicConstraintsValid === "boolean") {
this.isCA = ext.isCA;
this.maxPathLen = ext.maxPathLen;
this.basicConstraintsValid = ext.basicConstraintsValid;
}
if (typeof ext.keyUsage === "number") this.keyUsage = ext.keyUsage;
if (Array.isArray(ext.altNames)) for (const item of ext.altNames) {
if (item.dnsName != null) this.dnsNames.push(item.dnsName);
if (item.email != null) this.emailAddresses.push(item.email);
if (item.ip != null) this.ipAddresses.push(item.ip);
if (item.uri != null) this.uris.push(item.uri);
}
}
}
this.publicKey = new pki_1.PublicKey(captures.publicKeyInfo);
this.publicKeyRaw = this.publicKey.toDER();
this.tbsCertificate = captures.tbsCertificate;
}
/**
* Gets an extension by its name or oid.
* If extension exists and a key provided, it will return extension[key].
* ```js
* certificate.getExtension('keyUsage')
* certificate.getExtension('2.5.29.15')
* // => { oid: '2.5.29.15',
* // critical: true,
* // value: <Buffer 03 02 05 a0>,
* // name: 'keyUsage',
* // digitalSignature: true,
* // nonRepudiation: false,
* // keyEncipherment: true,
* // dataEncipherment: false,
* // keyAgreement: false,
* // keyCertSign: false,
* // cRLSign: false,
* // encipherOnly: false,
* // decipherOnly: false }
* certificate.getExtension('keyUsage', 'keyCertSign') // => false
* ```
* @param name extension name or OID
* @param key key in extension
*/
getExtension(name, key = "") {
for (const ext of this.extensions) if (name === ext.oid || name === ext.name) return key === "" ? ext : ext[key];
return null;
}
/**
* Returns null if a subject certificate is valid, or error if invalid.
* Note that it does not check validity time, DNS name, ip or others.
* @param child subject's Certificate
*/
checkSignature(child) {
if (this.version === 3 && !this.basicConstraintsValid || this.basicConstraintsValid && !this.isCA) return /* @__PURE__ */ new Error("The parent constraint violation error");
if (this.getExtension("keyUsage", "keyCertSign") !== true) return /* @__PURE__ */ new Error("The parent constraint violation error");
if (!child.isIssuer(this)) return /* @__PURE__ */ new Error("The parent certificate did not issue the given child certificate");
const agl = getHashAgl(child.signatureOID);
if (agl === "") return /* @__PURE__ */ new Error("Unknown child signature OID.");
if (this.publicKey.verify(child.tbsCertificate.DER, child.signature, agl) === false) return /* @__PURE__ */ new Error("Child signature not matched");
return null;
}
/**
* Returns true if this certificate's issuer matches the passed
* certificate's subject. Note that no signature check is performed.
* @param parent issuer's Certificate
*/
isIssuer(parent) {
return this.issuer.getHash().equals(parent.subject.getHash());
}
/**
* Verifies the subjectKeyIdentifier extension value for this certificate
* against its public key.
*/
verifySubjectKeyIdentifier() {
return this.publicKey.getFingerprint("sha1", "PublicKey").toString("hex") === this.subjectKeyIdentifier;
}
/**
* Return a friendly JSON object for debuging.
*/
toJSON() {
const obj = {};
for (const key of Object.keys(this)) obj[key] = toJSONify(this[key]);
delete obj.tbsCertificate;
return obj;
}
[util_1.inspect.custom](_depth, options) {
if (options.depth <= 2) options.depth = 10;
return `<${this.constructor.name} ${util_1.inspect(this.toJSON(), options)}>`;
}
};
function certificateExtensionsFromAsn1(exts) {
const res = [];
for (const val of exts.mustCompound()) for (const ext of val.mustCompound()) res.push(certificateExtensionFromAsn1(ext));
return res;
}
function certificateExtensionFromAsn1(ext) {
const e = {};
e.oid = asn1_1.ASN1.parseOID(ext.value[0].bytes);
e.critical = false;
if (ext.value[1].tag === asn1_1.Tag.BOOLEAN) {
e.critical = asn1_1.ASN1.parseBool(ext.value[1].bytes);
e.value = ext.value[2].bytes;
} else e.value = ext.value[1].bytes;
e.name = common_1.getOIDName(e.oid);
switch (e.name) {
case "keyUsage":
decodeExtKeyUsage(e);
break;
case "basicConstraints":
decodeExtBasicConstraints(e);
break;
case "extKeyUsage":
decodeExtExtKeyUsage(e);
break;
case "nsCertType":
decodeExtNsCertType(e);
break;
case "subjectAltName":
decodeExtAltName(e);
break;
case "issuerAltName":
decodeExtAltName(e);
break;
case "subjectKeyIdentifier":
decodeExtSubjectKeyIdentifier(e);
break;
case "authorityKeyIdentifier":
decodeExtAuthorityKeyIdentifier(e);
break;
case "authorityInfoAccess": decodeExtAuthorityInfoAccess(e);
}
return e;
}
function decodeExtKeyUsage(e) {
const ev = asn1_1.ASN1.parseBitString(asn1_1.ASN1.fromDER(e.value).bytes);
let b2 = 0;
let b3 = 0;
e.keyUsage = 0;
for (let i = 0; i < 9; i++) if (ev.at(i) !== 0) e.keyUsage |= 1 << i;
if (ev.buf.length > 0) {
b2 = ev.buf[0];
b3 = ev.buf.length > 1 ? ev.buf[1] : 0;
}
e.digitalSignature = (b2 & 128) === 128;
e.nonRepudiation = (b2 & 64) === 64;
e.keyEncipherment = (b2 & 32) === 32;
e.dataEncipherment = (b2 & 16) === 16;
e.keyAgreement = (b2 & 8) === 8;
e.keyCertSign = (b2 & 4) === 4;
e.cRLSign = (b2 & 2) === 2;
e.encipherOnly = (b2 & 1) === 1;
e.decipherOnly = (b3 & 128) === 128;
}
function decodeExtBasicConstraints(e) {
const vals = asn1_1.ASN1.fromDER(e.value).mustCompound();
if (vals.length > 0 && vals[0].tag === asn1_1.Tag.BOOLEAN) e.isCA = asn1_1.ASN1.parseBool(vals[0].bytes);
else e.isCA = false;
let value = null;
if (vals.length > 0 && vals[0].tag === asn1_1.Tag.INTEGER) value = vals[0].bytes;
else if (vals.length > 1) value = vals[1].bytes;
if (value !== null) e.maxPathLen = asn1_1.ASN1.parseInteger(value);
else e.maxPathLen = -1;
e.basicConstraintsValid = true;
}
function decodeExtExtKeyUsage(e) {
const vals = asn1_1.ASN1.fromDER(e.value).mustCompound();
for (const val of vals) e[common_1.getOIDName(asn1_1.ASN1.parseOID(val.bytes))] = true;
}
function decodeExtNsCertType(e) {
const ev = asn1_1.ASN1.parseBitString(asn1_1.ASN1.fromDER(e.value).bytes);
let b2 = 0;
if (ev.buf.length > 0) b2 = ev.buf[0];
e.client = (b2 & 128) === 128;
e.server = (b2 & 64) === 64;
e.email = (b2 & 32) === 32;
e.objsign = (b2 & 16) === 16;
e.reserved = (b2 & 8) === 8;
e.sslCA = (b2 & 4) === 4;
e.emailCA = (b2 & 2) === 2;
e.objCA = (b2 & 1) === 1;
}
function decodeExtAltName(e) {
e.altNames = [];
const vals = asn1_1.ASN1.fromDER(e.value).mustCompound();
for (const gn of vals) {
const item = {
tag: gn.tag,
value: gn.bytes
};
e.altNames.push(item);
switch (gn.tag) {
case 1:
item.email = gn.bytes.toString();
break;
case 2:
item.dnsName = gn.bytes.toString();
break;
case 6:
item.uri = gn.bytes.toString();
break;
case 7:
item.ip = common_1.bytesToIP(gn.bytes);
break;
case 8: item.oid = asn1_1.ASN1.parseOID(gn.bytes);
}
}
}
const subjectKeyIdentifierValidator = {
name: "subjectKeyIdentifier",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.OCTETSTRING,
capture: "subjectKeyIdentifier"
};
function decodeExtSubjectKeyIdentifier(e) {
e.subjectKeyIdentifier = asn1_1.ASN1.parseDERWithTemplate(e.value, subjectKeyIdentifierValidator).subjectKeyIdentifier.bytes.toString("hex");
}
const authorityKeyIdentifierValidator = {
name: "authorityKeyIdentifier",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.SEQUENCE,
value: [{
name: "authorityKeyIdentifier.value",
class: asn1_1.Class.CONTEXT_SPECIFIC,
tag: asn1_1.Tag.NONE,
capture: "authorityKeyIdentifier"
}]
};
function decodeExtAuthorityKeyIdentifier(e) {
e.authorityKeyIdentifier = asn1_1.ASN1.parseDERWithTemplate(e.value, authorityKeyIdentifierValidator).authorityKeyIdentifier.bytes.toString("hex");
}
const authorityInfoAccessValidator = {
name: "authorityInfoAccess",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.SEQUENCE,
value: [{
name: "authorityInfoAccess.authorityInfoAccessOcsp",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.SEQUENCE,
optional: true,
value: [{
name: "authorityInfoAccess.authorityInfoAccessOcsp.oid",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.OID
}, {
name: "authorityInfoAccess.authorityInfoAccessOcsp.value",
class: asn1_1.Class.CONTEXT_SPECIFIC,
tag: asn1_1.Tag.OID,
capture: "authorityInfoAccessOcsp"
}]
}, {
name: "authorityInfoAccess.authorityInfoAccessIssuers",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.SEQUENCE,
optional: true,
value: [{
name: "authorityInfoAccess.authorityInfoAccessIssuers.oid",
class: asn1_1.Class.UNIVERSAL,
tag: asn1_1.Tag.OID
}, {
name: "authorityInfoAccess.authorityInfoAccessIssuers.value",
class: asn1_1.Class.CONTEXT_SPECIFIC,
tag: asn1_1.Tag.OID,
capture: "authorityInfoAccessIssuers"
}]
}]
};
function decodeExtAuthorityInfoAccess(e) {
const captures = asn1_1.ASN1.parseDERWithTemplate(e.value, authorityInfoAccessValidator);
if (captures.authorityInfoAccessOcsp != null) e.authorityInfoAccessOcsp = captures.authorityInfoAccessOcsp.bytes.toString();
if (captures.authorityInfoAccessIssuers != null) e.authorityInfoAccessIssuers = captures.authorityInfoAccessIssuers.bytes.toString();
}
function fillMissingFields(attrs) {
for (const attr of attrs) {
if (attr.name == null || attr.name === "") {
if (attr.oid != null) attr.name = common_1.getOIDName(attr.oid);
if (attr.name === "" && attr.shortName != null) attr.name = common_1.getOIDName(shortNames[attr.shortName]);
}
if (attr.oid == null || attr.oid === "") {
if (attr.name !== "") attr.oid = common_1.getOID(attr.name);
else throw new Error("Attribute oid not specified.");
}
if (attr.shortName == null || attr.shortName === "") attr.shortName = shortNames[attr.name] == null ? "" : shortNames[attr.name];
if (attr.value == null) throw new Error("Attribute value not specified.");
}
}
function getHashAgl(oid) {
switch (common_1.getOIDName(oid)) {
case "sha1WithRsaEncryption": return "sha1";
case "md5WithRsaEncryption": return "md5";
case "sha256WithRsaEncryption": return "sha256";
case "sha384WithRsaEncryption": return "sha384";
case "sha512WithRsaEncryption": return "sha512";
case "RSASSA-PSS": return "sha256";
case "ecdsaWithSha1": return "sha1";
case "ecdsaWithSha256": return "sha256";
case "ecdsaWithSha384": return "sha384";
case "ecdsaWithSha512": return "sha512";
case "dsaWithSha1": return "sha1";
case "dsaWithSha256": return "sha256";
default: return "";
}
}
function RDNAttributesAsArray(rdn) {
const rval = [];
for (const set of rdn.mustCompound()) for (const attr of set.mustCompound()) {
const values = attr.mustCompound();
const obj = {};
obj.oid = asn1_1.ASN1.parseOID(values[0].bytes);
obj.value = values[1].value;
obj.valueTag = values[1].tag;
obj.name = common_1.getOIDName(obj.oid);
obj.shortName = getShortName(obj.name);
rval.push(obj);
}
return rval;
}
function toJSONify(val) {
if (val != null && !(val instanceof Buffer) && typeof val.toJSON === "function") return val.toJSON();
return val;
}
}));
//#endregion
//#region node_modules/.pnpm/@fidm+x509@1.2.1/node_modules/@fidm/x509/build/index.js
var require_build = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
var common_1 = require_common$1();
exports.bytesFromIP = common_1.bytesFromIP;
exports.bytesToIP = common_1.bytesToIP;
exports.getOID = common_1.getOID;
exports.getOIDName = common_1.getOIDName;
var pki_1 = require_pki();
exports.PublicKey = pki_1.PublicKey;
exports.PrivateKey = pki_1.PrivateKey;
exports.RSAPublicKey = pki_1.RSAPublicKey;
exports.RSAPrivateKey = pki_1.RSAPrivateKey;
var x509_1 = require_x509();
exports.Certificate = x509_1.Certificate;
exports.DistinguishedName = x509_1.DistinguishedName;
}));
//#endregion
//#region node_modules/.pnpm/reflect-metadata@0.2.2/node_modules/reflect-metadata/Reflect.js
var require_Reflect = /* @__PURE__ */ __commonJSMin((() => {
/*! *****************************************************************************
Copyright (C) Microsoft. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
var Reflect;
(function(Reflect) {
(function(factory) {
var root = typeof globalThis === "object" ? globalThis : typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : sloppyModeThis();
var exporter = makeExporter(Reflect);
if (typeof root.Reflect !== "undefined") exporter = makeExporter(root.Reflect, exporter);
factory(exporter, root);
if (typeof root.Reflect === "undefined") root.Reflect = Reflect;
function makeExporter(target, previous) {
return function(key, value) {
Object.defineProperty(target, key, {
configurable: true,
writable: true,
value
});
if (previous) previous(key, value);
};
}
function functionThis() {
try {
return Function("return this;")();
} catch (_) {}
}
function indirectEvalThis() {
try {
return (0, eval)("(function() { return this; })()");
} catch (_) {}
}
function sloppyModeThis() {
return functionThis() || indirectEvalThis();
}
})(function(exporter, root) {
var hasOwn = Object.prototype.hasOwnProperty;
var supportsSymbol = typeof Symbol === "function";
var toPrimitiveSymbol = supportsSymbol && typeof Symbol.toPrimitive !== "undefined" ? Symbol.toPrimitive : "@@toPrimitive";
var iteratorSymbol = supportsSymbol && typeof Symbol.iterator !== "undefined" ? Symbol.iterator : "@@iterator";
var supportsCreate = typeof Object.create === "function";
var supportsProto = { __proto__: [] } instanceof Array;
var downLevel = !supportsCreate && !supportsProto;
var HashMap = {
create: supportsCreate ? function() {
return MakeDictionary(Object.create(null));
} : supportsProto ? function() {
return MakeDictionary({ __proto__: null });
} : function() {
return MakeDictionary({});
},
has: downLevel ? function(map, key) {
return hasOwn.call(map, key);
} : function(map, key) {
return key in map;
},
get: downLevel ? function(map, key) {
return hasOwn.call(map, key) ? map[key] : void 0;
} : function(map, key) {
return map[key];
}
};
var functionPrototype = Object.getPrototypeOf(Function);
var _Map = typeof Map === "function" && typeof Map.prototype.entries === "function" ? Map : CreateMapPolyfill();
var _Set = typeof Set === "function" && typeof Set.prototype.entries === "function" ? Set : CreateSetPolyfill();
var _WeakMap = typeof WeakMap === "function" ? WeakMap : CreateWeakMapPolyfill();
var registrySymbol = supportsSymbol ? Symbol.for("@reflect-metadata:registry") : void 0;
var metadataRegistry = GetOrCreateMetadataRegistry();
var metadataProvider = CreateMetadataProvider(metadataRegistry);
/**
* Applies a set of decorators to a property of a target object.
* @param decorators An array of decorators.
* @param target The target object.
* @param propertyKey (Optional) The property key to decorate.
* @param attributes (Optional) The property descriptor for the target key.
* @remarks Decorators are applied in reverse order.
* @example
*
* class Example {
* // property declarations are not part of ES6, though they are valid in TypeScript:
* // static staticProperty;
* // property;
*
* constructor(p) { }
* static staticMethod(p) { }
* method(p) { }
* }
*
* // constructor
* Example = Reflect.decorate(decoratorsArray, Example);
*
* // property (on constructor)
* Reflect.decorate(decoratorsArray, Example, "staticProperty");
*
* // property (on prototype)
* Reflect.decorate(decoratorsArray, Example.prototype, "property");
*
* // method (on constructor)
* Object.defineProperty(Example, "staticMethod",
* Reflect.decorate(decoratorsArray, Example, "staticMethod",
* Object.getOwnPropertyDescriptor(Example, "staticMethod")));
*
* // method (on prototype)
* Object.defineProperty(Example.prototype, "method",
* Reflect.decorate(decoratorsArray, Example.prototype, "method",
* Object.getOwnPropertyDescriptor(Example.prototype, "method")));
*
*/
function decorate(decorators, target, propertyKey, attributes) {
if (!IsUndefined(propertyKey)) {
if (!IsArray(decorators)) throw new TypeError();
if (!IsObject(target)) throw new TypeError();
if (!IsObject(attributes) && !IsUndefined(attributes) && !IsNull(attributes)) throw new TypeError();
if (IsNull(attributes)) attributes = void 0;
propertyKey = ToPropertyKey(propertyKey);
return DecorateProperty(decorators, target, propertyKey, attributes);
} else {
if (!IsArray(decorators)) throw new TypeError();
if (!IsConstructor(target)) throw new TypeError();
return DecorateConstructor(decorators, target);
}
}
exporter("decorate", decorate);
/**
* A default metadata decorator factory that can be used on a class, class member, or parameter.
* @param metadataKey The key for the metadata entry.
* @param metadataValue The value for the metadata entry.
* @returns A decorator function.
* @remarks
* If `metadataKey` is already defined for the target and target key, the
* metadataValue for that key will be overwritten.
* @example
*
* // constructor
* @Reflect.metadata(key, value)
* class Example {
* }
*
* // property (on constructor, TypeScript only)
* class Example {
* @Reflect.metadata(key, value)
* static staticProperty;
* }
*
* // property (on prototype, TypeScript only)
* class Example {
* @Reflect.metadata(key, value)
* property;
* }
*
* // method (on constructor)
* class Example {
* @Reflect.metadata(key, value)
* static staticMethod() { }
* }
*
* // method (on prototype)
* class Example {
* @Reflect.metadata(key, value)
* method() { }
* }
*
*/
function metadata(metadataKey, metadataValue) {
function decorator(target, propertyKey) {
if (!IsObject(target)) throw new TypeError();
if (!IsUndefined(propertyKey) && !IsPropertyKey(propertyKey)) throw new TypeError();
OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey);
}
return decorator;
}
exporter("metadata", metadata);
/**
* Define a unique metadata entry on the target.
* @param metadataKey A key used to store and retrieve metadata.
* @param metadataValue A value that contains attached metadata.
* @param target The target object on which to define metadata.
* @param propertyKey (Optional) The property key for the target.
* @example
*
* class Example {
* // property declarations are not part of ES6, though they are valid in TypeScript:
* // static staticProperty;
* // property;
*
* constructor(p) { }
* static staticMethod(p) { }
* method(p) { }
* }
*
* // constructor
* Reflect.defineMetadata("custom:annotation", options, Example);
*
* // property (on constructor)
* Reflect.defineMetadata("custom:annotation", options, Example, "staticProperty");
*
* // property (on prototype)
* Reflect.defineMetadata("custom:annotation", options, Example.prototype, "property");
*
* // method (on constructor)
* Reflect.defineMetadata("custom:annotation", options, Example, "staticMethod");
*
* // method (on prototype)
* Reflect.defineMetadata("custom:annotation", options, Example.prototype, "method");
*
* // decorator factory as metadata-producing annotation.
* function MyAnnotation(options): Decorator {
* return (target, key?) => Reflect.defineMetadata("custom:annotation", options, target, key);
* }
*
*/
function defineMetadata(metadataKey, metadataValue, target, propertyKey) {
if (!IsObject(target)) throw new TypeError();
if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey);
return OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey);
}
exporter("defineMetadata", defineMetadata);
/**
* Gets a value indicating whether the target object or its prototype chain has the provided metadata key defined.
* @param metadataKey A key used to store and retrieve metadata.
* @param target The target object on which the metadata is defined.
* @param propertyKey (Optional) The property key for the target.
* @returns `true` if the metadata key was defined on the target object or its prototype chain; otherwise, `false`.
* @example
*
* class Example {
* // property declarations are not part of ES6, though they are valid in TypeScript:
* // static staticProperty;
* // property;
*
* constructor(p) { }
* static staticMethod(p) { }
* method(p) { }
* }
*
* // constructor
* result = Reflect.hasMetadata("custom:annotation", Example);
*
* // property (on constructor)
* result = Reflect.hasMetadata("custom:annotation", Example, "staticProperty");
*
* // property (on prototype)
* result = Reflect.hasMetadata("custom:annotation", Example.prototype, "property");
*
* // method (on constructor)
* result = Reflect.hasMetadata("custom:annotation", Example, "staticMethod");
*
* // method (on prototype)
* result = Reflect.hasMetadata("custom:annotation", Example.prototype, "method");
*
*/
function hasMetadata(metadataKey, target, propertyKey) {
if (!IsObject(target)) throw new TypeError();
if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey);
return OrdinaryHasMetadata(metadataKey, target, propertyKey);
}
exporter("hasMetadata", hasMetadata);
/**
* Gets a value indicating whether the target object has the provided metadata key defined.
* @param metadataKey A key used to store and retrieve metadata.
* @param target The target object on which the metadata is defined.
* @param propertyKey (Optional) The property key for the target.
* @returns `true` if the metadata key was defined on the target object; otherwise, `false`.
* @example
*
* class Example {
* // property declarations are not part of ES6, though they are valid in TypeScript:
* // static staticProperty;
* // property;
*
* constructor(p) { }
* static staticMethod(p) { }
* method(p) { }
* }
*
* // constructor
* result = Reflect.hasOwnMetadata("custom:annotation", Example);
*
* // property (on constructor)
* result = Reflect.hasOwnMetadata("custom:annotation", Example, "staticProperty");
*
* // property (on prototype)
* result = Reflect.hasOwnMetadata("custom:annotation", Example.prototype, "property");
*
* // method (on constructor)
* result = Reflect.hasOwnMetadata("custom:annotation", Example, "staticMethod");
*
* // method (on prototype)
* result = Reflect.hasOwnMetadata("custom:annotation", Example.prototype, "method");
*
*/
function hasOwnMetadata(metadataKey, target, propertyKey) {
if (!IsObject(target)) throw new TypeError();
if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey);
return OrdinaryHasOwnMetadata(metadataKey, target, propertyKey);
}
exporter("hasOwnMetadata", hasOwnMetadata);
/**
* Gets the metadata value for the provided metadata key on the target object or its prototype chain.
* @param metadataKey A key used to store and retrieve metadata.
* @param target The target object on which the metadata is defined.
* @param propertyKey (Optional) The property key for the target.
* @returns The metadata value for the metadata key if found; otherwise, `undefined`.
* @example
*
* class Example {
* // property declarations are not part of ES6, though they are valid in TypeScript:
* // static staticProperty;
* // property;
*
* constructor(p) { }
* static staticMethod(p) { }
* method(p) { }
* }
*
* // constructor
* result = Reflect.getMetadata("custom:annotation", Example);
*
* // property (on constructor)
* result = Reflect.getMetadata("custom:annotation", Example, "staticProperty");
*
* // property (on prototype)
* result = Reflect.getMetadata("custom:annotation", Example.prototype, "property");
*
* // method (on constructor)
* result = Reflect.getMetadata("custom:annotation", Example, "staticMethod");
*
* // method (on prototype)
* result = Reflect.getMetadata("custom:annotation", Example.prototype, "method");
*
*/
function getMetadata(metadataKey, target, propertyKey) {
if (!IsObject(target)) throw new TypeError();
if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey);
return OrdinaryGetMetadata(metadataKey, target, propertyKey);
}
exporter("getMetadata", getMetadata);
/**
* Gets the metadata value for the provided metadata key on the target object.
* @param metadataKey A key used to store and retrieve metadata.
* @param target The target object on which the metadata is defined.
* @param propertyKey (Optional) The property key for the target.
* @returns The metadata value for the metadata key if found; otherwise, `undefined`.
* @example
*
* class Example {
* // property declarations are not part of ES6, though they are valid in TypeScript:
* // static staticProperty;
* // property;
*
* constructor(p) { }
* static staticMethod(p) { }
* method(p) { }
* }
*
* // constructor
* result = Reflect.getOwnMetadata("custom:annotation", Example);
*
* // property (on constructor)
* result = Reflect.getOwnMetadata("custom:annotation", Example, "staticProperty");
*
* // property (on prototype)
* result = Reflect.getOwnMetadata("custom:annotation", Example.prototype, "property");
*
* // method (on constructor)
* result = Reflect.getOwnMetadata("custom:annotation", Example, "staticMethod");
*
* // method (on prototype)
* result = Reflect.getOwnMetadata("custom:annotation", Example.prototype, "method");
*
*/
function getOwnMetadata(metadataKey, target, propertyKey) {
if (!IsObject(target)) throw new TypeError();
if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey);
return OrdinaryGetOwnMetadata(metadataKey, target, propertyKey);
}
exporter("getOwnMetadata", getOwnMetadata);
/**
* Gets the metadata keys defined on the target object or its prototype chain.
* @param target The target object on which the metadata is defined.
* @param propertyKey (Optional) The property key for the target.
* @returns An array of unique metadata keys.
* @example
*
* class Example {
* // property declarations are not part of ES6, though they are valid in TypeScript:
* // static staticProperty;
* // property;
*
* constructor(p) { }
* static staticMethod(p) { }
* method(p) { }
* }
*
* // constructor
* result = Reflect.getMetadataKeys(Example);
*
* // property (on constructor)
* result = Reflect.getMetadataKeys(Example, "staticProperty");
*
* // property (on prototype)
* result = Reflect.getMetadataKeys(Example.prototype, "property");
*
* // method (on constructor)
* result = Reflect.getMetadataKeys(Example, "staticMethod");
*
* // method (on prototype)
* result = Reflect.getMetadataKeys(Example.prototype, "method");
*
*/
function getMetadataKeys(target, propertyKey) {
if (!IsObject(target)) throw new TypeError();
if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey);
return OrdinaryMetadataKeys(target, propertyKey);
}
exporter("getMetadataKeys", getMetadataKeys);
/**
* Gets the unique metadata keys defined on the target object.
* @param target The target object on which the metadata is defined.
* @param propertyKey (Optional) The property key for the target.
* @returns An array of unique metadata keys.
* @example
*
* class Example {
* // property declarations are not part of ES6, though they are valid in TypeScript:
* // static staticProperty;
* // property;
*
* constructor(p) { }
* static staticMethod(p) { }
* method(p) { }
* }
*
* // constructor
* result = Reflect.getOwnMetadataKeys(Example);
*
* // property (on constructor)
* result = Reflect.getOwnMetadataKeys(Example, "staticProperty");
*
* // property (on prototype)
* result = Reflect.getOwnMetadataKeys(Example.prototype, "property");
*
* // method (on constructor)
* result = Reflect.getOwnMetadataKeys(Example, "staticMethod");
*
* // method (on prototype)
* result = Reflect.getOwnMetadataKeys(Example.prototype, "method");
*
*/
function getOwnMetadataKeys(target, propertyKey) {
if (!IsObject(target)) throw new TypeError();
if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey);
return OrdinaryOwnMetadataKeys(target, propertyKey);
}
exporter("getOwnMetadataKeys", getOwnMetadataKeys);
/**
* Deletes the metadata entry from the target object with the provided key.
* @param metadataKey A key used to store and retrieve metadata.
* @param target The target object on which the metadata is defined.
* @param propertyKey (Optional) The property key for the target.
* @returns `true` if the metadata entry was found and deleted; otherwise, false.
* @example
*
* class Example {
* // property declarations are not part of ES6, though they are valid in TypeScript:
* // static staticProperty;
* // property;
*
* constructor(p) { }
* static staticMethod(p) { }
* method(p) { }
* }
*
* // constructor
* result = Reflect.deleteMetadata("custom:annotation", Example);
*
* // property (on constructor)
* result = Reflect.deleteMetadata("custom:annotation", Example, "staticProperty");
*
* // property (on prototype)
* result = Reflect.deleteMetadata("custom:annotation", Example.prototype, "property");
*
* // method (on constructor)
* result = Reflect.deleteMetadata("custom:annotation", Example, "staticMethod");
*
* // method (on prototype)
* result = Reflect.deleteMetadata("custom:annotation", Example.prototype, "method");
*
*/
function deleteMetadata(metadataKey, target, propertyKey) {
if (!IsObject(target)) throw new TypeError();
if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey);
if (!IsObject(target)) throw new TypeError();
if (!IsUndefined(propertyKey)) propertyKey = ToPropertyKey(propertyKey);
var provider = GetMetadataProvider(target, propertyKey, false);
if (IsUndefined(provider)) return false;
return provider.OrdinaryDeleteMetadata(metadataKey, target, propertyKey);
}
exporter("deleteMetadata", deleteMetadata);
function DecorateConstructor(decorators, target) {
for (var i = decorators.length - 1; i >= 0; --i) {
var decorator = decorators[i];
var decorated = decorator(target);
if (!IsUndefined(decorated) && !IsNull(decorated)) {
if (!IsConstructor(decorated)) throw new TypeError();
target = decorated;
}
}
return target;
}
function DecorateProperty(decorators, target, propertyKey, descriptor) {
for (var i = decorators.length - 1; i >= 0; --i) {
var decorator = decorators[i];
var decorated = decorator(target, propertyKey, descriptor);
if (!IsUndefined(decorated) && !IsNull(decorated)) {
if (!IsObject(decorated)) throw new TypeError();
descriptor = decorated;
}
}
return descriptor;
}
function OrdinaryHasMetadata(MetadataKey, O, P) {
if (OrdinaryHasOwnMetadata(MetadataKey, O, P)) return true;
var parent = OrdinaryGetPrototypeOf(O);
if (!IsNull(parent)) return OrdinaryHasMetadata(MetadataKey, parent, P);
return false;
}
function OrdinaryHasOwnMetadata(MetadataKey, O, P) {
var provider = GetMetadataProvider(O, P, false);
if (IsUndefined(provider)) return false;
return ToBoolean(provider.OrdinaryHasOwnMetadata(MetadataKey, O, P));
}
function OrdinaryGetMetadata(MetadataKey, O, P) {
if (OrdinaryHasOwnMetadata(MetadataKey, O, P)) return OrdinaryGetOwnMetadata(MetadataKey, O, P);
var parent = OrdinaryGetPrototypeOf(O);
if (!IsNull(parent)) return OrdinaryGetMetadata(MetadataKey, parent, P);
}
function OrdinaryGetOwnMetadata(MetadataKey, O, P) {
var provider = GetMetadataProvider(O, P, false);
if (IsUndefined(provider)) return;
return provider.OrdinaryGetOwnMetadata(MetadataKey, O, P);
}
function OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) {
GetMetadataProvider(O, P, true).OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P);
}
function OrdinaryMetadataKeys(O, P) {
var ownKeys = OrdinaryOwnMetadataKeys(O, P);
var parent = OrdinaryGetPrototypeOf(O);
if (parent === null) return ownKeys;
var parentKeys = OrdinaryMetadataKeys(parent, P);
if (parentKeys.length <= 0) return ownKeys;
if (ownKeys.length <= 0) return parentKeys;
var set = new _Set();
var keys = [];
for (var _i = 0, ownKeys_1 = ownKeys; _i < ownKeys_1.length; _i++) {
var key = ownKeys_1[_i];
var hasKey = set.has(key);
if (!hasKey) {
set.add(key);
keys.push(key);
}
}
for (var _a = 0, parentKeys_1 = parentKeys; _a < parentKeys_1.length; _a++) {
var key = parentKeys_1[_a];
var hasKey = set.has(key);
if (!hasKey) {
set.add(key);
keys.push(key);
}
}
return keys;
}
function OrdinaryOwnMetadataKeys(O, P) {
var provider = GetMetadataProvider(O, P, false);
if (!provider) return [];
return provider.OrdinaryOwnMetadataKeys(O, P);
}
function Type(x) {
if (x === null) return 1;
switch (typeof x) {
case "undefined": return 0;
case "boolean": return 2;
case "string": return 3;
case "symbol": return 4;
case "number": return 5;
case "object": return x === null ? 1 : 6;
default: return 6;
}
}
function IsUndefined(x) {
return x === void 0;
}
function IsNull(x) {
return x === null;
}
function IsSymbol(x) {
return typeof x === "symbol";
}
function IsObject(x) {
return typeof x === "object" ? x !== null : typeof x === "function";
}
function ToPrimitive(input, PreferredType) {
switch (Type(input)) {
case 0: return input;
case 1: return input;
case 2: return input;
case 3: return input;
case 4: return input;
case 5: return input;
}
var hint = PreferredType === 3 ? "string" : PreferredType === 5 ? "number" : "default";
var exoticToPrim = GetMethod(input, toPrimitiveSymbol);
if (exoticToPrim !== void 0) {
var result = exoticToPrim.call(input, hint);
if (IsObject(result)) throw new TypeError();
return result;
}
return OrdinaryToPrimitive(input, hint === "default" ? "number" : hint);
}
function OrdinaryToPrimitive(O, hint) {
if (hint === "string") {
var toString_1 = O.toString;
if (IsCallable(toString_1)) {
var result = toString_1.call(O);
if (!IsObject(result)) return result;
}
var valueOf = O.valueOf;
if (IsCallable(valueOf)) {
var result = valueOf.call(O);
if (!IsObject(result)) return result;
}
} else {
var valueOf = O.valueOf;
if (IsCallable(valueOf)) {
var result = valueOf.call(O);
if (!IsObject(result)) return result;
}
var toString_2 = O.toString;
if (IsCallable(toString_2)) {
var result = toString_2.call(O);
if (!IsObject(result)) return result;
}
}
throw new TypeError();
}
function ToBoolean(argument) {
return !!argument;
}
function ToString(argument) {
return "" + argument;
}
function ToPropertyKey(argument) {
var key = ToPrimitive(argument, 3);
if (IsSymbol(key)) return key;
return ToString(key);
}
function IsArray(argument) {
return Array.isArray ? Array.isArray(argument) : argument instanceof Object ? argument instanceof Array : Object.prototype.toString.call(argument) === "[object Array]";
}
function IsCallable(argument) {
return typeof argument === "function";
}
function IsConstructor(argument) {
return typeof argument === "function";
}
function IsPropertyKey(argument) {
switch (Type(argument)) {
case 3: return true;
case 4: return true;
default: return false;
}
}
function SameValueZero(x, y) {
return x === y || x !== x && y !== y;
}
function GetMethod(V, P) {
var func = V[P];
if (func === void 0 || func === null) return void 0;
if (!IsCallable(func)) throw new TypeError();
return func;
}
function GetIterator(obj) {
var method = GetMethod(obj, iteratorSymbol);
if (!IsCallable(method)) throw new TypeError();
var iterator = method.call(obj);
if (!IsObject(iterator)) throw new TypeError();
return iterator;
}
function IteratorValue(iterResult) {
return iterResult.value;
}
function IteratorStep(iterator) {
var result = iterator.next();
return result.done ? false : result;
}
function IteratorClose(iterator) {
var f = iterator["return"];
if (f) f.call(iterator);
}
function OrdinaryGetPrototypeOf(O) {
var proto = Object.getPrototypeOf(O);
if (typeof O !== "function" || O === functionPrototype) return proto;
if (proto !== functionPrototype) return proto;
var prototype = O.prototype;
var prototypeProto = prototype && Object.getPrototypeOf(prototype);
if (prototypeProto == null || prototypeProto === Object.prototype) return proto;
var constructor = prototypeProto.constructor;
if (typeof constructor !== "function") return proto;
if (constructor === O) return proto;
return constructor;
}
/**
* Creates a registry used to allow multiple `reflect-metadata` providers.
*/
function CreateMetadataRegistry() {
var fallback;
if (!IsUndefined(registrySymbol) && typeof root.Reflect !== "undefined" && !(registrySymbol in root.Reflect) && typeof root.Reflect.defineMetadata === "function") fallback = CreateFallbackProvider(root.Reflect);
var first;
var second;
var rest;
var targetProviderMap = new _WeakMap();
var registry = {
registerProvider,
getProvider,
setProvider
};
return registry;
function registerProvider(provider) {
if (!Object.isExtensible(registry)) throw new Error("Cannot add provider to a frozen registry.");
switch (true) {
case fallback === provider: break;
case IsUndefined(first):
first = provider;
break;
case first === provider: break;
case IsUndefined(second):
second = provider;
break;
case second === provider: break;
default:
if (rest === void 0) rest = new _Set();
rest.add(provider);
}
}
function getProviderNoCache(O, P) {
if (!IsUndefined(first)) {
if (first.isProviderFor(O, P)) return first;
if (!IsUndefined(second)) {
if (second.isProviderFor(O, P)) return first;
if (!IsUndefined(rest)) {
var iterator = GetIterator(rest);
while (true) {
var next = IteratorStep(iterator);
if (!next) return;
var provider = IteratorValue(next);
if (provider.isProviderFor(O, P)) {
IteratorClose(iterator);
return provider;
}
}
}
}
}
if (!IsUndefined(fallback) && fallback.isProviderFor(O, P)) return fallback;
}
function getProvider(O, P) {
var providerMap = targetProviderMap.get(O);
var provider;
if (!IsUndefined(providerMap)) provider = providerMap.get(P);
if (!IsUndefined(provider)) return provider;
provider = getProviderNoCache(O, P);
if (!IsUndefined(provider)) {
if (IsUndefined(providerMap)) {
providerMap = new _Map();
targetProviderMap.set(O, providerMap);
}
providerMap.set(P, provider);
}
return provider;
}
function hasProvider(provider) {
if (IsUndefined(provider)) throw new TypeError();
return first === provider || second === provider || !IsUndefined(rest) && rest.has(provider);
}
function setProvider(O, P, provider) {
if (!hasProvider(provider)) throw new Error("Metadata provider not registered.");
var existingProvider = getProvider(O, P);
if (existingProvider !== provider) {
if (!IsUndefined(existingProvider)) return false;
var providerMap = targetProviderMap.get(O);
if (IsUndefined(providerMap)) {
providerMap = new _Map();
targetProviderMap.set(O, providerMap);
}
providerMap.set(P, provider);
}
return true;
}
}
/**
* Gets or creates the shared registry of metadata providers.
*/
function GetOrCreateMetadataRegistry() {
var metadataRegistry;
if (!IsUndefined(registrySymbol) && IsObject(root.Reflect) && Object.isExtensible(root.Reflect)) metadataRegistry = root.Reflect[registrySymbol];
if (IsUndefined(metadataRegistry)) metadataRegistry = CreateMetadataRegistry();
if (!IsUndefined(registrySymbol) && IsObject(root.Reflect) && Object.isExtensible(root.Reflect)) Object.defineProperty(root.Reflect, registrySymbol, {
enumerable: false,
configurable: false,
writable: false,
value: metadataRegistry
});
return metadataRegistry;
}
function CreateMetadataProvider(registry) {
var metadata = new _WeakMap();
var provider = {
isProviderFor: function(O, P) {
var targetMetadata = metadata.get(O);
if (IsUndefined(targetMetadata)) return false;
return targetMetadata.has(P);
},
OrdinaryDefineOwnMetadata,
OrdinaryHasOwnMetadata,
OrdinaryGetOwnMetadata,
OrdinaryOwnMetadataKeys,
OrdinaryDeleteMetadata
};
metadataRegistry.registerProvider(provider);
return provider;
function GetOrCreateMetadataMap(O, P, Create) {
var targetMetadata = metadata.get(O);
var createdTargetMetadata = false;
if (IsUndefined(targetMetadata)) {
if (!Create) return void 0;
targetMetadata = new _Map();
metadata.set(O, targetMetadata);
createdTargetMetadata = true;
}
var metadataMap = targetMetadata.get(P);
if (IsUndefined(metadataMap)) {
if (!Create) return void 0;
metadataMap = new _Map();
targetMetadata.set(P, metadataMap);
if (!registry.setProvider(O, P, provider)) {
targetMetadata.delete(P);
if (createdTargetMetadata) metadata.delete(O);
throw new Error("Wrong provider for target.");
}
}
return metadataMap;
}
function OrdinaryHasOwnMetadata(MetadataKey, O, P) {
var metadataMap = GetOrCreateMetadataMap(O, P, false);
if (IsUndefined(metadataMap)) return false;
return ToBoolean(metadataMap.has(MetadataKey));
}
function OrdinaryGetOwnMetadata(MetadataKey, O, P) {
var metadataMap = GetOrCreateMetadataMap(O, P, false);
if (IsUndefined(metadataMap)) return void 0;
return metadataMap.get(MetadataKey);
}
function OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) {
GetOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue);
}
function OrdinaryOwnMetadataKeys(O, P) {
var keys = [];
var metadataMap = GetOrCreateMetadataMap(O, P, false);
if (IsUndefined(metadataMap)) return keys;
var iterator = GetIterator(metadataMap.keys());
var k = 0;
while (true) {
var next = IteratorStep(iterator);
if (!next) {
keys.length = k;
return keys;
}
var nextValue = IteratorValue(next);
try {
keys[k] = nextValue;
} catch (e) {
try {
IteratorClose(iterator);
} finally {
throw e;
}
}
k++;
}
}
function OrdinaryDeleteMetadata(MetadataKey, O, P) {
var metadataMap = GetOrCreateMetadataMap(O, P, false);
if (IsUndefined(metadataMap)) return false;
if (!metadataMap.delete(MetadataKey)) return false;
if (metadataMap.size === 0) {
var targetMetadata = metadata.get(O);
if (!IsUndefined(targetMetadata)) {
targetMetadata.delete(P);
if (targetMetadata.size === 0) metadata.delete(targetMetadata);
}
}
return true;
}
}
function CreateFallbackProvider(reflect) {
var defineMetadata = reflect.defineMetadata, hasOwnMetadata = reflect.hasOwnMetadata, getOwnMetadata = reflect.getOwnMetadata, getOwnMetadataKeys = reflect.getOwnMetadataKeys, deleteMetadata = reflect.deleteMetadata;
var metadataOwner = new _WeakMap();
return {
isProviderFor: function(O, P) {
var metadataPropertySet = metadataOwner.get(O);
if (!IsUndefined(metadataPropertySet) && metadataPropertySet.has(P)) return true;
if (getOwnMetadataKeys(O, P).length) {
if (IsUndefined(metadataPropertySet)) {
metadataPropertySet = new _Set();
metadataOwner.set(O, metadataPropertySet);
}
metadataPropertySet.add(P);
return true;
}
return false;
},
OrdinaryDefineOwnMetadata: defineMetadata,
OrdinaryHasOwnMetadata: hasOwnMetadata,
OrdinaryGetOwnMetadata: getOwnMetadata,
OrdinaryOwnMetadataKeys: getOwnMetadataKeys,
OrdinaryDeleteMetadata: deleteMetadata
};
}
/**
* Gets the metadata provider for an object. If the object has no metadata provider and this is for a create operation,
* then this module's metadata provider is assigned to the object.
*/
function GetMetadataProvider(O, P, Create) {
var registeredProvider = metadataRegistry.getProvider(O, P);
if (!IsUndefined(registeredProvider)) return registeredProvider;
if (Create) {
if (metadataRegistry.setProvider(O, P, metadataProvider)) return metadataProvider;
throw new Error("Illegal state.");
}
}
function CreateMapPolyfill() {
var cacheSentinel = {};
var arraySentinel = [];
var MapIterator = function() {
function MapIterator(keys, values, selector) {
this._index = 0;
this._keys = keys;
this._values = values;
this._selector = selector;
}
MapIterator.prototype["@@iterator"] = function() {
return this;
};
MapIterator.prototype[iteratorSymbol] = function() {
return this;
};
MapIterator.prototype.next = function() {
var index = this._index;
if (index >= 0 && index < this._keys.length) {
var result = this._selector(this._keys[index], this._values[index]);
if (index + 1 >= this._keys.length) {
this._index = -1;
this._keys = arraySentinel;
this._values = arraySentinel;
} else this._index++;
return {
value: result,
done: false
};
}
return {
value: void 0,
done: true
};
};
MapIterator.prototype.throw = function(error) {
if (this._index >= 0) {
this._index = -1;
this._keys = arraySentinel;
this._values = arraySentinel;
}
throw error;
};
MapIterator.prototype.return = function(value) {
if (this._index >= 0) {
this._index = -1;
this._keys = arraySentinel;
this._values = arraySentinel;
}
return {
value,
done: true
};
};
return MapIterator;
}();
return function() {
function Map() {
this._keys = [];
this._values = [];
this._cacheKey = cacheSentinel;
this._cacheIndex = -2;
}
Object.defineProperty(Map.prototype, "size", {
get: function() {
return this._keys.length;
},
enumerable: true,
configurable: true
});
Map.prototype.has = function(key) {
return this._find(key, false) >= 0;
};
Map.prototype.get = function(key) {
var index = this._find(key, false);
return index >= 0 ? this._values[index] : void 0;
};
Map.prototype.set = function(key, value) {
var index = this._find(key, true);
this._values[index] = value;
return this;
};
Map.prototype.delete = function(key) {
var index = this._find(key, false);
if (index >= 0) {
var size = this._keys.length;
for (var i = index + 1; i < size; i++) {
this._keys[i - 1] = this._keys[i];
this._values[i - 1] = this._values[i];
}
this._keys.length--;
this._values.length--;
if (SameValueZero(key, this._cacheKey)) {
this._cacheKey = cacheSentinel;
this._cacheIndex = -2;
}
return true;
}
return false;
};
Map.prototype.clear = function() {
this._keys.length = 0;
this._values.length = 0;
this._cacheKey = cacheSentinel;
this._cacheIndex = -2;
};
Map.prototype.keys = function() {
return new MapIterator(this._keys, this._values, getKey);
};
Map.prototype.values = function() {
return new MapIterator(this._keys, this._values, getValue);
};
Map.prototype.entries = function() {
return new MapIterator(this._keys, this._values, getEntry);
};
Map.prototype["@@iterator"] = function() {
return this.entries();
};
Map.prototype[iteratorSymbol] = function() {
return this.entries();
};
Map.prototype._find = function(key, insert) {
if (!SameValueZero(this._cacheKey, key)) {
this._cacheIndex = -1;
for (var i = 0; i < this._keys.length; i++) if (SameValueZero(this._keys[i], key)) {
this._cacheIndex = i;
break;
}
}
if (this._cacheIndex < 0 && insert) {
this._cacheIndex = this._keys.length;
this._keys.push(key);
this._values.push(void 0);
}
return this._cacheIndex;
};
return Map;
}();
function getKey(key, _) {
return key;
}
function getValue(_, value) {
return value;
}
function getEntry(key, value) {
return [key, value];
}
}
function CreateSetPolyfill() {
return function() {
function Set() {
this._map = new _Map();
}
Object.defineProperty(Set.prototype, "size", {
get: function() {
return this._map.size;
},
enumerable: true,
configurable: true
});
Set.prototype.has = function(value) {
return this._map.has(value);
};
Set.prototype.add = function(value) {
return this._map.set(value, value), this;
};
Set.prototype.delete = function(value) {
return this._map.delete(value);
};
Set.prototype.clear = function() {
this._map.clear();
};
Set.prototype.keys = function() {
return this._map.keys();
};
Set.prototype.values = function() {
return this._map.keys();
};
Set.prototype.entries = function() {
return this._map.entries();
};
Set.prototype["@@iterator"] = function() {
return this.keys();
};
Set.prototype[iteratorSymbol] = function() {
return this.keys();
};
return Set;
}();
}
function CreateWeakMapPolyfill() {
var UUID_SIZE = 16;
var keys = HashMap.create();
var rootKey = CreateUniqueKey();
return function() {
function WeakMap() {
this._key = CreateUniqueKey();
}
WeakMap.prototype.has = function(target) {
var table = GetOrCreateWeakMapTable(target, false);
return table !== void 0 ? HashMap.has(table, this._key) : false;
};
WeakMap.prototype.get = function(target) {
var table = GetOrCreateWeakMapTable(target, false);
return table !== void 0 ? HashMap.get(table, this._key) : void 0;
};
WeakMap.prototype.set = function(target, value) {
var table = GetOrCreateWeakMapTable(target, true);
table[this._key] = value;
return this;
};
WeakMap.prototype.delete = function(target) {
var table = GetOrCreateWeakMapTable(target, false);
return table !== void 0 ? delete table[this._key] : false;
};
WeakMap.prototype.clear = function() {
this._key = CreateUniqueKey();
};
return WeakMap;
}();
function CreateUniqueKey() {
var key;
do
key = "@@WeakMap@@" + CreateUUID();
while (HashMap.has(keys, key));
keys[key] = true;
return key;
}
function GetOrCreateWeakMapTable(target, create) {
if (!hasOwn.call(target, rootKey)) {
if (!create) return void 0;
Object.defineProperty(target, rootKey, { value: HashMap.create() });
}
return target[rootKey];
}
function FillRandomBytes(buffer, size) {
for (var i = 0; i < size; ++i) buffer[i] = Math.random() * 255 | 0;
return buffer;
}
function GenRandomBytes(size) {
if (typeof Uint8Array === "function") {
var array = new Uint8Array(size);
if (typeof crypto !== "undefined") crypto.getRandomValues(array);
else if (typeof msCrypto !== "undefined") msCrypto.getRandomValues(array);
else FillRandomBytes(array, size);
return array;
}
return FillRandomBytes(new Array(size), size);
}
function CreateUUID() {
var data = GenRandomBytes(UUID_SIZE);
data[6] = data[6] & 79 | 64;
data[8] = data[8] & 191 | 128;
var result = "";
for (var offset = 0; offset < UUID_SIZE; ++offset) {
var byte = data[offset];
if (offset === 4 || offset === 6 || offset === 8) result += "-";
if (byte < 16) result += "0";
result += byte.toString(16).toLowerCase();
}
return result;
}
}
function MakeDictionary(obj) {
obj.__ = void 0;
delete obj.__;
return obj;
}
});
})(Reflect || (Reflect = {}));
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/pem/pem.js
var require_pem$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.pemConverter = exports.pem = void 0;
exports.encode = encode;
exports.encodeMany = encodeMany;
exports.decode = decode;
exports.find = find;
exports.findAll = findAll;
exports.decodeFirst = decodeFirst;
exports.parse = parse;
exports.format = format;
const base64_js_1 = require_base64();
const LABEL_REGEX = /^[A-Z0-9][A-Z0-9 ._-]*[A-Z0-9]$/i;
const PEM_BLOCK_REGEX = /-----BEGIN ([^-]+)-----([\s\S]*?)-----END \1-----/g;
function assertLabel(label) {
if (!LABEL_REGEX.test(label)) throw new TypeError(`Invalid PEM label '${label}'`);
}
function wrap(text, lineLength) {
const result = [];
for (let i = 0; i < text.length; i += lineLength) result.push(text.slice(i, i + lineLength));
return result;
}
function parseBody(body) {
const lines = body.trim().replace(/\r\n/g, "\n").split("\n").map((line) => line.trim()).filter(Boolean);
const headers = {};
let index = 0;
for (; index < lines.length; index++) {
const line = lines[index];
const separator = line.indexOf(":");
if (separator <= 0) break;
headers[line.slice(0, separator).trim()] = line.slice(separator + 1).trim();
}
return {
headers: Object.keys(headers).length ? headers : void 0,
base64Lines: lines.slice(index),
base64Text: lines.slice(index).join("")
};
}
function detectNewline(text) {
return /\r\n/.test(text) ? "\r\n" : "\n";
}
function collectBlocks(text, options = {}) {
const blocks = [];
const requestedLabel = options.label;
let match;
PEM_BLOCK_REGEX.lastIndex = 0;
while (match = PEM_BLOCK_REGEX.exec(text)) {
const label = match[1].trim();
if (requestedLabel && label !== requestedLabel) continue;
assertLabel(label);
const parsed = parseBody(match[2]);
blocks.push({
label,
data: base64_js_1.base64.decode(parsed.base64Text),
headers: parsed.headers,
lineLength: parsed.base64Lines[0]?.length ?? 64,
newline: detectNewline(match[0])
});
}
if (options.strict && blocks.length === 0) throw new TypeError(requestedLabel ? `No PEM block with label '${requestedLabel}' was found` : "No PEM blocks were found");
return blocks;
}
function encode(label, data, options = {}) {
assertLabel(label);
const lineLength = options.lineLength ?? 64;
if (!Number.isInteger(lineLength) || lineLength < 1) throw new RangeError("PEM lineLength must be a positive integer");
const newline = options.newline ?? "\n";
const lines = [`-----BEGIN ${label}-----`];
if (options.headers) {
for (const [name, value] of Object.entries(options.headers)) lines.push(`${name}: ${value}`);
lines.push("");
}
lines.push(...wrap(base64_js_1.base64.encode(data), lineLength));
lines.push(`-----END ${label}-----`);
return `${lines.join(newline)}${newline}`;
}
function encodeMany(blocks, options = {}) {
return blocks.map((block) => encode(block.label, block.data, {
...options,
headers: block.headers ?? options.headers
})).join("");
}
function decode(text, options = {}) {
return collectBlocks(text, options).map(({ lineLength: _lineLength, newline: _newline, ...block }) => block);
}
function find(text, label) {
return decode(text, { label })[0];
}
function findAll(text, label) {
return decode(text, { label });
}
function decodeFirst(text, label) {
const [block] = decode(text, {
label,
strict: true
});
return block.data;
}
function parse(text, options = {}) {
const [block] = collectBlocks(text, {
...options,
strict: true
});
const format = {
label: block.label,
headers: block.headers,
lineLength: block.lineLength,
newline: block.newline
};
return {
bytes: block.data,
format,
normalized: encode(block.label, block.data, format)
};
}
function format(data, value) {
return encode(value.label, data, value);
}
exports.pem = {
decode,
decodeFirst,
encode,
encodeMany,
find,
findAll,
format,
parse
};
exports.pemConverter = {
name: "pem",
encode: (data, options) => {
if (!options?.label) throw new TypeError("PEM label is required");
return encode(options.label, data, options);
},
decode: (text, options) => decodeFirst(text, options?.label),
format,
is: (text) => typeof text === "string" && /-----BEGIN [^-]+-----/.test(text),
parse
};
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/pem/index.js
var require_pem = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.pemConverter = exports.pem = exports.parse = exports.format = exports.findAll = exports.find = exports.encodeMany = exports.encode = exports.decodeFirst = exports.decode = void 0;
var pem_js_1 = require_pem$1();
Object.defineProperty(exports, "decode", {
enumerable: true,
get: function() {
return pem_js_1.decode;
}
});
Object.defineProperty(exports, "decodeFirst", {
enumerable: true,
get: function() {
return pem_js_1.decodeFirst;
}
});
Object.defineProperty(exports, "encode", {
enumerable: true,
get: function() {
return pem_js_1.encode;
}
});
Object.defineProperty(exports, "encodeMany", {
enumerable: true,
get: function() {
return pem_js_1.encodeMany;
}
});
Object.defineProperty(exports, "find", {
enumerable: true,
get: function() {
return pem_js_1.find;
}
});
Object.defineProperty(exports, "findAll", {
enumerable: true,
get: function() {
return pem_js_1.findAll;
}
});
Object.defineProperty(exports, "format", {
enumerable: true,
get: function() {
return pem_js_1.format;
}
});
Object.defineProperty(exports, "parse", {
enumerable: true,
get: function() {
return pem_js_1.parse;
}
});
Object.defineProperty(exports, "pem", {
enumerable: true,
get: function() {
return pem_js_1.pem;
}
});
Object.defineProperty(exports, "pemConverter", {
enumerable: true,
get: function() {
return pem_js_1.pemConverter;
}
});
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/converters/registry.js
var require_registry$2 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.createConverterRegistry = createConverterRegistry;
function keyOf(name) {
return name.trim().toLowerCase();
}
function toError(error) {
return error instanceof Error ? error : new Error(String(error));
}
function removeConverter(converters, primaryNames, converter) {
for (const alias of [converter.name, ...converter.aliases ?? []]) converters.delete(keyOf(alias));
primaryNames.delete(keyOf(converter.name));
}
function requireCapability(converter, name, capability) {
const method = converter[capability];
if (typeof method !== "function") throw new Error(`Converter '${name}' does not support ${capability}()`);
return method;
}
function detectConfidence(name, text, converter) {
const normalizedName = keyOf(converter.name || name);
const trimmed = text.trim();
if (!trimmed) return 0;
let accepted = false;
if (converter.is) accepted = converter.is(text);
let decodable = false;
try {
converter.decode(text);
decodable = true;
} catch {
decodable = false;
}
if (!accepted && !decodable) return 0;
switch (normalizedName) {
case "pem": return /-----BEGIN [^-]+-----/.test(text) ? 1 : 0;
case "hex": {
const compact = trimmed.replace(/^0x/i, "").replace(/[\s:.-]/g, "");
if (!compact || /[^0-9a-f]/i.test(compact) || compact.length % 2 !== 0) return 0;
if (/^0x/i.test(trimmed) || /[:\s.-]/.test(trimmed)) return .95;
if (/[a-f]/.test(trimmed) || /[A-F]/.test(trimmed)) return .8;
return .45;
}
case "base64url":
if (/[-_]/.test(trimmed)) return .95;
if (/=/.test(trimmed)) return .1;
return .6;
case "base64":
if (/[+/=]/.test(trimmed)) return .9;
return .55;
case "binary":
case "utf8":
case "utf16be":
case "utf16le": return 0;
default: return accepted && decodable ? .75 : .5;
}
}
function createConverterRegistry(initialConverters = []) {
const converters = /* @__PURE__ */ new Map();
const primaryNames = /* @__PURE__ */ new Set();
const api = {
register(converter, options = {}) {
if (!converter.name || !keyOf(converter.name)) throw new TypeError("Converter name is required");
const names = [...new Set([converter.name, ...converter.aliases ?? []].map(keyOf))];
const conflicts = /* @__PURE__ */ new Set();
for (const name of names) {
const existing = converters.get(name);
if (!existing) continue;
if (!options.override) throw new Error(`Converter '${name}' is already registered`);
conflicts.add(existing);
}
for (const conflicting of conflicts) removeConverter(converters, primaryNames, conflicting);
for (const name of names) converters.set(name, converter);
primaryNames.add(keyOf(converter.name));
return this;
},
unregister(name) {
const converter = converters.get(keyOf(name));
if (!converter) return false;
removeConverter(converters, primaryNames, converter);
return true;
},
has(name) {
return converters.has(keyOf(name));
},
get(name) {
const converter = converters.get(keyOf(name));
if (!converter) throw new Error(`Converter '${name}' is not registered`);
return converter;
},
list() {
return [...primaryNames].map((name) => this.get(name));
},
encode(name, data, options) {
return this.get(name).encode(data, options);
},
decode(name, text, options) {
return this.get(name).decode(text, options);
},
tryDecode(name, text, options) {
try {
return {
ok: true,
bytes: this.decode(name, text, options)
};
} catch (error) {
return {
ok: false,
error: toError(error)
};
}
},
normalize(name, text, options) {
const converter = this.get(name);
return requireCapability(converter, name, "normalize").call(converter, text, options);
},
parse(name, text, options) {
const converter = this.get(name);
return requireCapability(converter, name, "parse").call(converter, text, options);
},
format(name, data, format) {
const converter = this.get(name);
return requireCapability(converter, name, "format").call(converter, data, format);
},
transcode(text, options) {
const bytes = this.decode(options.from, text, options.fromOptions);
return this.encode(options.to, bytes, options.toOptions);
},
detect(text, options = {}) {
const formatNames = options.formats?.length ? options.formats.map((name) => String(name)) : this.list().map((converter) => converter.name).filter((name) => ![
"binary",
"utf8",
"utf16be",
"utf16le"
].includes(keyOf(name)));
const detections = /* @__PURE__ */ new Map();
for (const requestedName of formatNames) {
const converter = this.get(requestedName);
const confidence = detectConfidence(requestedName, text, converter);
if (confidence <= 0) continue;
const format = converter.name;
const current = detections.get(format);
if (!current || confidence > current.confidence) detections.set(format, {
format,
confidence
});
}
return [...detections.values()].sort((left, right) => right.confidence - left.confidence);
}
};
for (const converter of initialConverters) api.register(converter);
return api;
}
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/converters/defaults.js
var require_defaults = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaultConverterRegistry = exports.defaultConverters = exports.utf16leConverter = exports.utf16beConverter = exports.utf8Converter = exports.base64urlConverter = exports.base64Converter = exports.hexConverter = exports.binaryConverter = exports.pemConverter = void 0;
const index_js_1 = require_encoding();
const index_js_2 = require_pem();
var index_js_3 = require_pem();
Object.defineProperty(exports, "pemConverter", {
enumerable: true,
get: function() {
return index_js_3.pemConverter;
}
});
const registry_js_1 = require_registry$2();
exports.binaryConverter = {
name: "binary",
aliases: ["latin1"],
encode: index_js_1.binary.encode,
decode: index_js_1.binary.decode,
is: index_js_1.binary.is
};
exports.hexConverter = {
name: "hex",
encode: index_js_1.hex.encode,
decode: index_js_1.hex.decode,
format: index_js_1.hex.format,
is: index_js_1.hex.is,
normalize: index_js_1.hex.normalize,
parse: index_js_1.hex.parse
};
exports.base64Converter = {
name: "base64",
aliases: ["b64"],
encode: index_js_1.base64.encode,
decode: index_js_1.base64.decode,
is: index_js_1.base64.is,
normalize: index_js_1.base64.normalize
};
exports.base64urlConverter = {
name: "base64url",
aliases: ["base64-url", "b64url"],
encode: index_js_1.base64url.encode,
decode: index_js_1.base64url.decode,
is: index_js_1.base64url.is,
normalize: index_js_1.base64url.normalize
};
exports.utf8Converter = {
name: "utf8",
aliases: ["utf-8"],
encode: (data) => index_js_1.utf8.decode(data),
decode: (text) => index_js_1.utf8.encode(text),
is: (text) => typeof text === "string"
};
exports.utf16beConverter = {
name: "utf16be",
aliases: [
"utf16",
"utf-16",
"utf-16be"
],
encode: (data) => index_js_1.utf16.decode(data),
decode: (text) => index_js_1.utf16.encode(text),
is: (text) => typeof text === "string"
};
exports.utf16leConverter = {
name: "utf16le",
aliases: [
"utf-16le",
"ucs2",
"usc2"
],
encode: (data) => index_js_1.utf16.decode(data, { littleEndian: true }),
decode: (text) => index_js_1.utf16.encode(text, { littleEndian: true }),
is: (text) => typeof text === "string"
};
exports.defaultConverters = [
exports.binaryConverter,
exports.hexConverter,
exports.base64Converter,
exports.base64urlConverter,
exports.utf8Converter,
exports.utf16beConverter,
exports.utf16leConverter,
index_js_2.pemConverter
];
exports.defaultConverterRegistry = (0, registry_js_1.createConverterRegistry)(exports.defaultConverters);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/converters/convert.js
var require_convert$2 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.convert = void 0;
const index_js_1 = require_bytes();
const index_js_2 = require_encoding();
const defaults_js_1 = require_defaults();
function encode(name, data, ...args) {
return defaults_js_1.defaultConverterRegistry.encode(name, data, ...args);
}
function decode(name, text, ...args) {
return defaults_js_1.defaultConverterRegistry.decode(name, text, ...args);
}
function tryDecode(name, text, ...args) {
return defaults_js_1.defaultConverterRegistry.tryDecode(name, text, ...args);
}
function normalize(name, text, ...args) {
return defaults_js_1.defaultConverterRegistry.normalize(name, text, ...args);
}
function parse(name, text, ...args) {
return defaults_js_1.defaultConverterRegistry.parse(name, text, ...args);
}
function format(name, data, value) {
return defaults_js_1.defaultConverterRegistry.format(name, data, value);
}
function transcode(text, options) {
return defaults_js_1.defaultConverterRegistry.transcode(text, options);
}
function detect(text, options) {
return defaults_js_1.defaultConverterRegistry.detect(text, options);
}
function normalizeEncodingName(encoding) {
return encoding.toLowerCase();
}
exports.convert = {
encode,
decode,
tryDecode,
normalize,
parse,
format,
transcode,
detect,
to(format, data, ...args) {
return encode(format, data, ...args);
},
from(format, text, ...args) {
return decode(format, text, ...args);
},
toString(data, encoding = "utf8") {
return encode(encoding, data);
},
fromString(text, encoding = "utf8") {
if (normalizeEncodingName(encoding) === "hex") return (0, index_js_1.toArrayBuffer)(index_js_2.hex.decode(text, { allowOddLength: true }));
return (0, index_js_1.toArrayBuffer)(decode(encoding, text));
},
toBase64: index_js_2.base64.encode,
fromBase64: (text) => (0, index_js_1.toArrayBuffer)(index_js_2.base64.decode(text)),
toBase64Url: index_js_2.base64url.encode,
fromBase64Url: (text) => (0, index_js_1.toArrayBuffer)(index_js_2.base64url.decode(text)),
toHex: index_js_2.hex.encode,
fromHex: (text) => (0, index_js_1.toArrayBuffer)(index_js_2.hex.decode(text, { allowOddLength: true })),
toBinary: index_js_2.binary.encode,
fromBinary: (text) => (0, index_js_1.toArrayBuffer)(index_js_2.binary.decode(text)),
toUtf8String: index_js_2.utf8.decode,
fromUtf8String: (text) => (0, index_js_1.toArrayBuffer)(index_js_2.utf8.encode(text)),
toUtf16String: (data, littleEndian = false) => index_js_2.utf16.decode(data, { littleEndian }),
fromUtf16String: (text, littleEndian = false) => (0, index_js_1.toArrayBuffer)(index_js_2.utf16.encode(text, { littleEndian })),
isHex: index_js_2.hex.is,
isBase64: index_js_2.base64.is,
isBase64Url: index_js_2.base64url.is,
formatString: index_js_2.base64.normalize
};
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/converters/index.js
var require_converters$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.convert = exports.utf8Converter = exports.utf16leConverter = exports.utf16beConverter = exports.pemConverter = exports.hexConverter = exports.defaultConverters = exports.defaultConverterRegistry = exports.binaryConverter = exports.base64urlConverter = exports.base64Converter = exports.createConverterRegistry = void 0;
var registry_js_1 = require_registry$2();
Object.defineProperty(exports, "createConverterRegistry", {
enumerable: true,
get: function() {
return registry_js_1.createConverterRegistry;
}
});
var defaults_js_1 = require_defaults();
Object.defineProperty(exports, "base64Converter", {
enumerable: true,
get: function() {
return defaults_js_1.base64Converter;
}
});
Object.defineProperty(exports, "base64urlConverter", {
enumerable: true,
get: function() {
return defaults_js_1.base64urlConverter;
}
});
Object.defineProperty(exports, "binaryConverter", {
enumerable: true,
get: function() {
return defaults_js_1.binaryConverter;
}
});
Object.defineProperty(exports, "defaultConverterRegistry", {
enumerable: true,
get: function() {
return defaults_js_1.defaultConverterRegistry;
}
});
Object.defineProperty(exports, "defaultConverters", {
enumerable: true,
get: function() {
return defaults_js_1.defaultConverters;
}
});
Object.defineProperty(exports, "hexConverter", {
enumerable: true,
get: function() {
return defaults_js_1.hexConverter;
}
});
Object.defineProperty(exports, "pemConverter", {
enumerable: true,
get: function() {
return defaults_js_1.pemConverter;
}
});
Object.defineProperty(exports, "utf16beConverter", {
enumerable: true,
get: function() {
return defaults_js_1.utf16beConverter;
}
});
Object.defineProperty(exports, "utf16leConverter", {
enumerable: true,
get: function() {
return defaults_js_1.utf16leConverter;
}
});
Object.defineProperty(exports, "utf8Converter", {
enumerable: true,
get: function() {
return defaults_js_1.utf8Converter;
}
});
var convert_js_1 = require_convert$2();
Object.defineProperty(exports, "convert", {
enumerable: true,
get: function() {
return convert_js_1.convert;
}
});
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/legacy/buffer-source-converter.js
var require_buffer_source_converter = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.BufferSourceConverter = void 0;
const index_js_1 = require_bytes();
var BufferSourceConverter = class {
static isArrayBuffer(data) {
return (0, index_js_1.isArrayBuffer)(data);
}
static toArrayBuffer(data) {
return (0, index_js_1.toArrayBuffer)(data);
}
static toUint8Array(data) {
return (0, index_js_1.toUint8Array)(data);
}
static toView(data, type) {
return (0, index_js_1.toView)(data, type);
}
static isBufferSource(data) {
return (0, index_js_1.isBufferSource)(data);
}
static isArrayBufferView(data) {
return (0, index_js_1.isArrayBufferView)(data);
}
static isEqual(a, b) {
return (0, index_js_1.equal)(a, b);
}
static concat(first, second, ...rest) {
if (Array.isArray(first)) return typeof second === "function" ? (0, index_js_1.concat)(first, second) : (0, index_js_1.concat)(first);
const buffers = [
first,
second,
...rest
].filter(Boolean);
return (0, index_js_1.concat)(buffers);
}
};
exports.BufferSourceConverter = BufferSourceConverter;
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/legacy/convert.js
var require_convert$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Convert = void 0;
const index_js_1 = require_converters$1();
function normalizeTextEncoding(encoding) {
return encoding === "ascii" ? "binary" : encoding;
}
exports.Convert = class Convert {
static DEFAULT_UTF8_ENCODING = "utf8";
static isHex(data) {
return index_js_1.convert.isHex(data);
}
static isBase64(data) {
return index_js_1.convert.isBase64(data);
}
static isBase64Url(data) {
return index_js_1.convert.isBase64Url(data);
}
static ToString(buffer, enc = "utf8") {
return index_js_1.convert.toString(buffer, enc);
}
static FromString(str, enc = "utf8") {
if (!str) return /* @__PURE__ */ new ArrayBuffer(0);
return index_js_1.convert.fromString(str, enc);
}
static ToBase64(buffer) {
return index_js_1.convert.toBase64(buffer);
}
static FromBase64(base64) {
return index_js_1.convert.fromBase64(base64);
}
static FromBase64Url(base64url) {
return index_js_1.convert.fromBase64Url(base64url);
}
static ToBase64Url(data) {
return index_js_1.convert.toBase64Url(data);
}
static FromUtf8String(text, encoding = Convert.DEFAULT_UTF8_ENCODING) {
return index_js_1.convert.fromString(text, normalizeTextEncoding(encoding));
}
static ToUtf8String(buffer, encoding = Convert.DEFAULT_UTF8_ENCODING) {
return index_js_1.convert.toString(buffer, normalizeTextEncoding(encoding));
}
static FromBinary(text) {
return index_js_1.convert.fromBinary(text);
}
static ToBinary(buffer) {
return index_js_1.convert.toBinary(buffer);
}
static ToHex(buffer) {
return index_js_1.convert.toHex(buffer);
}
static FromHex(hexString) {
return index_js_1.convert.fromHex(hexString);
}
static ToUtf16String(buffer, littleEndian = false) {
return index_js_1.convert.toUtf16String(buffer, littleEndian);
}
static FromUtf16String(text, littleEndian = false) {
return index_js_1.convert.fromUtf16String(text, littleEndian);
}
static Base64Padding(base64) {
const padCount = 4 - base64.length % 4;
return padCount < 4 ? base64 + "=".repeat(padCount) : base64;
}
static formatString(data) {
return index_js_1.convert.formatString(data);
}
};
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/legacy/functions.js
var require_functions = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.assign = assign;
exports.combine = combine;
exports.isEqual = isEqual;
const index_js_1 = require_bytes();
function assign(target, ...sources) {
for (const source of sources) {
if (!source) continue;
for (const prop in source) target[prop] = source[prop];
}
return target;
}
function combine(...buf) {
return (0, index_js_1.concat)(buf);
}
function isEqual(bytes1, bytes2) {
return (0, index_js_1.equal)(bytes1, bytes2);
}
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/legacy/index.js
var require_legacy = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.isEqual = exports.combine = exports.assign = exports.Convert = exports.BufferSourceConverter = void 0;
var buffer_source_converter_js_1 = require_buffer_source_converter();
Object.defineProperty(exports, "BufferSourceConverter", {
enumerable: true,
get: function() {
return buffer_source_converter_js_1.BufferSourceConverter;
}
});
var convert_js_1 = require_convert$1();
Object.defineProperty(exports, "Convert", {
enumerable: true,
get: function() {
return convert_js_1.Convert;
}
});
var functions_js_1 = require_functions();
Object.defineProperty(exports, "assign", {
enumerable: true,
get: function() {
return functions_js_1.assign;
}
});
Object.defineProperty(exports, "combine", {
enumerable: true,
get: function() {
return functions_js_1.combine;
}
});
Object.defineProperty(exports, "isEqual", {
enumerable: true,
get: function() {
return functions_js_1.isEqual;
}
});
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+utils@2.0.3/node_modules/@peculiar/utils/build/cjs/index.js
var require_cjs$11 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.bytes = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
tslib_1.__exportStar(require_bytes(), exports);
exports.bytes = tslib_1.__importStar(require_bytes());
tslib_1.__exportStar(require_encoding(), exports);
tslib_1.__exportStar(require_pem(), exports);
tslib_1.__exportStar(require_converters$1(), exports);
tslib_1.__exportStar(require_legacy(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-schema@2.9.4/node_modules/@peculiar/asn1-schema/build/cjs/enums.js
var require_enums = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.AsnPropTypes = exports.AsnTypeTypes = void 0;
var AsnTypeTypes;
(function(AsnTypeTypes) {
AsnTypeTypes[AsnTypeTypes["Sequence"] = 0] = "Sequence";
AsnTypeTypes[AsnTypeTypes["Set"] = 1] = "Set";
AsnTypeTypes[AsnTypeTypes["Choice"] = 2] = "Choice";
})(AsnTypeTypes || (exports.AsnTypeTypes = AsnTypeTypes = {}));
var AsnPropTypes;
(function(AsnPropTypes) {
AsnPropTypes[AsnPropTypes["Any"] = 1] = "Any";
AsnPropTypes[AsnPropTypes["Boolean"] = 2] = "Boolean";
AsnPropTypes[AsnPropTypes["OctetString"] = 3] = "OctetString";
AsnPropTypes[AsnPropTypes["BitString"] = 4] = "BitString";
AsnPropTypes[AsnPropTypes["Integer"] = 5] = "Integer";
AsnPropTypes[AsnPropTypes["Enumerated"] = 6] = "Enumerated";
AsnPropTypes[AsnPropTypes["ObjectIdentifier"] = 7] = "ObjectIdentifier";
AsnPropTypes[AsnPropTypes["Utf8String"] = 8] = "Utf8String";
AsnPropTypes[AsnPropTypes["BmpString"] = 9] = "BmpString";
AsnPropTypes[AsnPropTypes["UniversalString"] = 10] = "UniversalString";
AsnPropTypes[AsnPropTypes["NumericString"] = 11] = "NumericString";
AsnPropTypes[AsnPropTypes["PrintableString"] = 12] = "PrintableString";
AsnPropTypes[AsnPropTypes["TeletexString"] = 13] = "TeletexString";
AsnPropTypes[AsnPropTypes["VideotexString"] = 14] = "VideotexString";
AsnPropTypes[AsnPropTypes["IA5String"] = 15] = "IA5String";
AsnPropTypes[AsnPropTypes["GraphicString"] = 16] = "GraphicString";
AsnPropTypes[AsnPropTypes["VisibleString"] = 17] = "VisibleString";
AsnPropTypes[AsnPropTypes["GeneralString"] = 18] = "GeneralString";
AsnPropTypes[AsnPropTypes["CharacterString"] = 19] = "CharacterString";
AsnPropTypes[AsnPropTypes["UTCTime"] = 20] = "UTCTime";
AsnPropTypes[AsnPropTypes["GeneralizedTime"] = 21] = "GeneralizedTime";
AsnPropTypes[AsnPropTypes["DATE"] = 22] = "DATE";
AsnPropTypes[AsnPropTypes["TimeOfDay"] = 23] = "TimeOfDay";
AsnPropTypes[AsnPropTypes["DateTime"] = 24] = "DateTime";
AsnPropTypes[AsnPropTypes["Duration"] = 25] = "Duration";
AsnPropTypes[AsnPropTypes["TIME"] = 26] = "TIME";
AsnPropTypes[AsnPropTypes["Null"] = 27] = "Null";
AsnPropTypes[AsnPropTypes["RelativeObjectIdentifier"] = 28] = "RelativeObjectIdentifier";
})(AsnPropTypes || (exports.AsnPropTypes = AsnPropTypes = {}));
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-schema@2.9.4/node_modules/@peculiar/asn1-schema/build/cjs/types/bit_string.js
var require_bit_string = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.BitString = void 0;
const asn1js = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1)).__importStar(require_build$2());
const utils_1 = require_cjs$11();
var BitString = class {
unusedBits = 0;
value = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params, unusedBits = 0) {
if (params) {
if (typeof params === "number") this.fromNumber(params);
else if ((0, utils_1.isBufferSource)(params)) {
this.unusedBits = unusedBits;
this.value = (0, utils_1.toArrayBuffer)(params);
} else throw TypeError("Unsupported type of 'params' argument for BitString");
}
}
fromASN(asn) {
if (!(asn instanceof asn1js.BitString)) throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");
this.unusedBits = asn.valueBlock.unusedBits;
this.value = (0, utils_1.toArrayBuffer)(asn.valueBlock.valueHex);
return this;
}
toASN() {
return new asn1js.BitString({
unusedBits: this.unusedBits,
valueHex: this.value
});
}
toSchema(name) {
return new asn1js.BitString({ name });
}
toNumber() {
let res = "";
const uintArray = new Uint8Array(this.value);
for (const octet of uintArray) res += octet.toString(2).padStart(8, "0");
res = res.split("").reverse().join("");
if (this.unusedBits) res = res.slice(this.unusedBits).padStart(this.unusedBits, "0");
return parseInt(res, 2);
}
fromNumber(value) {
let bits = value.toString(2);
const octetSize = bits.length + 7 >> 3;
this.unusedBits = (octetSize << 3) - bits.length;
const octets = new Uint8Array(octetSize);
bits = bits.padStart(octetSize << 3, "0").split("").reverse().join("");
let index = 0;
while (index < octetSize) {
octets[index] = parseInt(bits.slice(index << 3, (index << 3) + 8), 2);
index++;
}
this.value = octets.buffer;
}
};
exports.BitString = BitString;
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-schema@2.9.4/node_modules/@peculiar/asn1-schema/build/cjs/types/octet_string.js
var require_octet_string = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.OctetString = void 0;
const asn1js = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1)).__importStar(require_build$2());
const utils_1 = require_cjs$11();
var OctetString = class {
buffer;
get byteLength() {
return this.buffer.byteLength;
}
get byteOffset() {
return 0;
}
constructor(param) {
if (typeof param === "number") this.buffer = new ArrayBuffer(param);
else if ((0, utils_1.isBufferSource)(param)) this.buffer = (0, utils_1.toArrayBuffer)(param);
else if (Array.isArray(param)) this.buffer = new Uint8Array(param).buffer;
else this.buffer = /* @__PURE__ */ new ArrayBuffer(0);
}
fromASN(asn) {
if (!(asn instanceof asn1js.OctetString)) throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");
this.buffer = (0, utils_1.toArrayBuffer)(asn.valueBlock.valueHex);
return this;
}
toASN() {
return new asn1js.OctetString({ valueHex: this.buffer });
}
toSchema(name) {
return new asn1js.OctetString({ name });
}
};
exports.OctetString = OctetString;
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-schema@2.9.4/node_modules/@peculiar/asn1-schema/build/cjs/types/index.js
var require_types$5 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
tslib_1.__exportStar(require_bit_string(), exports);
tslib_1.__exportStar(require_octet_string(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-schema@2.9.4/node_modules/@peculiar/asn1-schema/build/cjs/converters.js
var require_converters = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.AsnNullConverter = exports.AsnGeneralizedTimeConverter = exports.AsnUTCTimeConverter = exports.AsnCharacterStringConverter = exports.AsnGeneralStringConverter = exports.AsnVisibleStringConverter = exports.AsnGraphicStringConverter = exports.AsnIA5StringConverter = exports.AsnVideotexStringConverter = exports.AsnTeletexStringConverter = exports.AsnPrintableStringConverter = exports.AsnNumericStringConverter = exports.AsnUniversalStringConverter = exports.AsnBmpStringConverter = exports.AsnUtf8StringConverter = exports.AsnConstructedOctetStringConverter = exports.AsnOctetStringConverter = exports.AsnBooleanConverter = exports.AsnRelativeObjectIdentifierConverter = exports.AsnObjectIdentifierConverter = exports.AsnBitStringConverter = exports.AsnIntegerBigIntConverter = exports.AsnIntegerArrayBufferConverter = exports.AsnEnumeratedConverter = exports.AsnIntegerConverter = exports.AsnAnyConverter = void 0;
exports.defaultConverter = defaultConverter;
const asn1js = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1)).__importStar(require_build$2());
const utils_1 = require_cjs$11();
const enums_1 = require_enums();
const index_1 = require_types$5();
exports.AsnAnyConverter = {
fromASN: (value) => value instanceof asn1js.Null ? null : (0, utils_1.toArrayBuffer)(value.valueBeforeDecodeView),
toASN: (value) => {
if (value === null) return new asn1js.Null();
const schema = asn1js.fromBER(value);
if (schema.result.error) throw new Error(schema.result.error);
return schema.result;
}
};
exports.AsnIntegerConverter = {
fromASN: (value) => value.valueBlock.valueHexView.byteLength >= 4 ? value.valueBlock.toString() : value.valueBlock.valueDec,
toASN: (value) => new asn1js.Integer({ value: +value })
};
exports.AsnEnumeratedConverter = {
fromASN: (value) => value.valueBlock.valueDec,
toASN: (value) => new asn1js.Enumerated({ value })
};
exports.AsnIntegerArrayBufferConverter = {
fromASN: (value) => (0, utils_1.toArrayBuffer)(value.valueBlock.valueHexView),
toASN: (value) => new asn1js.Integer({ valueHex: value })
};
exports.AsnIntegerBigIntConverter = {
fromASN: (value) => value.toBigInt(),
toASN: (value) => asn1js.Integer.fromBigInt(value)
};
exports.AsnBitStringConverter = {
fromASN: (value) => (0, utils_1.toArrayBuffer)(value.valueBlock.valueHexView),
toASN: (value) => new asn1js.BitString({ valueHex: value })
};
exports.AsnObjectIdentifierConverter = {
fromASN: (value) => value.valueBlock.toString(),
toASN: (value) => new asn1js.ObjectIdentifier({ value })
};
exports.AsnRelativeObjectIdentifierConverter = {
fromASN: (value) => value.valueBlock.toString(),
toASN: (value) => new asn1js.RelativeObjectIdentifier({ value })
};
exports.AsnBooleanConverter = {
fromASN: (value) => value.valueBlock.value,
toASN: (value) => new asn1js.Boolean({ value })
};
exports.AsnOctetStringConverter = {
fromASN: (value) => (0, utils_1.toArrayBuffer)(value.valueBlock.valueHexView),
toASN: (value) => new asn1js.OctetString({ valueHex: value })
};
exports.AsnConstructedOctetStringConverter = {
fromASN: (value) => new index_1.OctetString(value.getValue()),
toASN: (value) => value.toASN()
};
function createStringConverter(Asn1Type) {
return {
fromASN: (value) => value.valueBlock.value,
toASN: (value) => new Asn1Type({ value })
};
}
exports.AsnUtf8StringConverter = createStringConverter(asn1js.Utf8String);
exports.AsnBmpStringConverter = createStringConverter(asn1js.BmpString);
exports.AsnUniversalStringConverter = createStringConverter(asn1js.UniversalString);
exports.AsnNumericStringConverter = createStringConverter(asn1js.NumericString);
exports.AsnPrintableStringConverter = createStringConverter(asn1js.PrintableString);
exports.AsnTeletexStringConverter = createStringConverter(asn1js.TeletexString);
exports.AsnVideotexStringConverter = createStringConverter(asn1js.VideotexString);
exports.AsnIA5StringConverter = createStringConverter(asn1js.IA5String);
exports.AsnGraphicStringConverter = createStringConverter(asn1js.GraphicString);
exports.AsnVisibleStringConverter = createStringConverter(asn1js.VisibleString);
exports.AsnGeneralStringConverter = createStringConverter(asn1js.GeneralString);
exports.AsnCharacterStringConverter = createStringConverter(asn1js.CharacterString);
exports.AsnUTCTimeConverter = {
fromASN: (value) => value.toDate(),
toASN: (value) => new asn1js.UTCTime({ valueDate: value })
};
exports.AsnGeneralizedTimeConverter = {
fromASN: (value) => value.toDate(),
toASN: (value) => new asn1js.GeneralizedTime({ valueDate: value })
};
exports.AsnNullConverter = {
fromASN: () => null,
toASN: () => {
return new asn1js.Null();
}
};
function defaultConverter(type) {
switch (type) {
case enums_1.AsnPropTypes.Any: return exports.AsnAnyConverter;
case enums_1.AsnPropTypes.BitString: return exports.AsnBitStringConverter;
case enums_1.AsnPropTypes.BmpString: return exports.AsnBmpStringConverter;
case enums_1.AsnPropTypes.Boolean: return exports.AsnBooleanConverter;
case enums_1.AsnPropTypes.CharacterString: return exports.AsnCharacterStringConverter;
case enums_1.AsnPropTypes.Enumerated: return exports.AsnEnumeratedConverter;
case enums_1.AsnPropTypes.GeneralString: return exports.AsnGeneralStringConverter;
case enums_1.AsnPropTypes.GeneralizedTime: return exports.AsnGeneralizedTimeConverter;
case enums_1.AsnPropTypes.GraphicString: return exports.AsnGraphicStringConverter;
case enums_1.AsnPropTypes.IA5String: return exports.AsnIA5StringConverter;
case enums_1.AsnPropTypes.Integer: return exports.AsnIntegerConverter;
case enums_1.AsnPropTypes.Null: return exports.AsnNullConverter;
case enums_1.AsnPropTypes.NumericString: return exports.AsnNumericStringConverter;
case enums_1.AsnPropTypes.ObjectIdentifier: return exports.AsnObjectIdentifierConverter;
case enums_1.AsnPropTypes.RelativeObjectIdentifier: return exports.AsnRelativeObjectIdentifierConverter;
case enums_1.AsnPropTypes.OctetString: return exports.AsnOctetStringConverter;
case enums_1.AsnPropTypes.PrintableString: return exports.AsnPrintableStringConverter;
case enums_1.AsnPropTypes.TeletexString: return exports.AsnTeletexStringConverter;
case enums_1.AsnPropTypes.UTCTime: return exports.AsnUTCTimeConverter;
case enums_1.AsnPropTypes.UniversalString: return exports.AsnUniversalStringConverter;
case enums_1.AsnPropTypes.Utf8String: return exports.AsnUtf8StringConverter;
case enums_1.AsnPropTypes.VideotexString: return exports.AsnVideotexStringConverter;
case enums_1.AsnPropTypes.VisibleString: return exports.AsnVisibleStringConverter;
default: return null;
}
}
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-schema@2.9.4/node_modules/@peculiar/asn1-schema/build/cjs/helper.js
var require_helper = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.isConvertible = isConvertible;
exports.isTypeOfArray = isTypeOfArray;
exports.isArrayEqual = isArrayEqual;
function isConvertible(target) {
if (typeof target === "function" && target.prototype) {
if (target.prototype.toASN && target.prototype.fromASN) return true;
else return isConvertible(target.prototype);
} else return !!(target && typeof target === "object" && "toASN" in target && "fromASN" in target);
}
function isTypeOfArray(target) {
if (target) {
const proto = Object.getPrototypeOf(target);
if (proto?.prototype?.constructor === Array) return true;
return isTypeOfArray(proto);
}
return false;
}
function isArrayEqual(bytes1, bytes2) {
if (!(bytes1 && bytes2)) return false;
if (bytes1.byteLength !== bytes2.byteLength) return false;
const b1 = new Uint8Array(bytes1);
const b2 = new Uint8Array(bytes2);
for (let i = 0; i < bytes1.byteLength; i++) if (b1[i] !== b2[i]) return false;
return true;
}
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-schema@2.9.4/node_modules/@peculiar/asn1-schema/build/cjs/schema.js
var require_schema = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.AsnSchemaStorage = void 0;
const asn1js = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1)).__importStar(require_build$2());
const enums_1 = require_enums();
const helper_1 = require_helper();
var AsnSchemaStorage = class {
items = /* @__PURE__ */ new WeakMap();
has(target) {
return this.items.has(target);
}
get(target, checkSchema = false) {
const schema = this.items.get(target);
if (!schema) throw new Error(`Cannot get schema for '${target.prototype.constructor.name}' target`);
if (checkSchema && !schema.schema) throw new Error(`Schema '${target.prototype.constructor.name}' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'.`);
return schema;
}
cache(target) {
const schema = this.get(target);
if (!schema.schema) schema.schema = this.create(target, true);
}
createDefault(target) {
const schema = {
type: enums_1.AsnTypeTypes.Sequence,
items: {}
};
const parentSchema = this.findParentSchema(target);
if (parentSchema) {
Object.assign(schema, parentSchema);
schema.items = Object.assign({}, schema.items, parentSchema.items);
}
return schema;
}
create(target, useNames) {
const schema = this.items.get(target) || this.createDefault(target);
const asn1Value = [];
for (const key in schema.items) {
const item = schema.items[key];
const name = useNames ? key : "";
let asn1Item;
if (typeof item.type === "number") {
const Asn1TypeName = enums_1.AsnPropTypes[item.type];
const Asn1Type = asn1js[Asn1TypeName];
if (!Asn1Type) throw new Error(`Cannot get ASN1 class by name '${Asn1TypeName}'`);
asn1Item = new Asn1Type({ name });
} else if ((0, helper_1.isConvertible)(item.type)) asn1Item = new item.type().toSchema(name);
else if (item.optional) {
if (this.get(item.type).type === enums_1.AsnTypeTypes.Choice) asn1Item = new asn1js.Any({ name });
else {
asn1Item = this.create(item.type, false);
asn1Item.name = name;
}
} else asn1Item = new asn1js.Any({ name });
const optional = !!item.optional || item.defaultValue !== void 0;
if (item.repeated) {
asn1Item.name = "";
asn1Item = new (item.repeated === "set" ? asn1js.Set : asn1js.Sequence)({
name: "",
value: [new asn1js.Repeated({
name,
value: asn1Item
})]
});
}
if (item.context !== null && item.context !== void 0) {
if (item.implicit) {
if (typeof item.type === "number" || (0, helper_1.isConvertible)(item.type)) {
const Container = item.repeated ? asn1js.Constructed : asn1js.Primitive;
asn1Value.push(new Container({
name,
optional,
idBlock: {
tagClass: 3,
tagNumber: item.context
}
}));
} else {
this.cache(item.type);
const isRepeated = !!item.repeated;
let value = !isRepeated ? this.get(item.type, true).schema : asn1Item;
value = "valueBlock" in value ? value.valueBlock.value : value.value;
asn1Value.push(new asn1js.Constructed({
name: !isRepeated ? name : "",
optional,
idBlock: {
tagClass: 3,
tagNumber: item.context
},
value
}));
}
} else asn1Value.push(new asn1js.Constructed({
optional,
idBlock: {
tagClass: 3,
tagNumber: item.context
},
value: [asn1Item]
}));
} else {
asn1Item.optional = optional;
asn1Value.push(asn1Item);
}
}
switch (schema.type) {
case enums_1.AsnTypeTypes.Sequence: return new asn1js.Sequence({
value: asn1Value,
name: ""
});
case enums_1.AsnTypeTypes.Set: return new asn1js.Set({
value: asn1Value,
name: ""
});
case enums_1.AsnTypeTypes.Choice: return new asn1js.Choice({
value: asn1Value,
name: ""
});
default: throw new Error("Unsupported ASN1 type in use");
}
}
set(target, schema) {
this.items.set(target, schema);
return this;
}
findParentSchema(target) {
const parent = Object.getPrototypeOf(target);
if (parent) return this.items.get(parent) || this.findParentSchema(parent);
return null;
}
};
exports.AsnSchemaStorage = AsnSchemaStorage;
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-schema@2.9.4/node_modules/@peculiar/asn1-schema/build/cjs/storage.js
var require_storage = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.schemaStorage = void 0;
exports.schemaStorage = new (require_schema()).AsnSchemaStorage();
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-schema@2.9.4/node_modules/@peculiar/asn1-schema/build/cjs/decorators.js
var require_decorators$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.AsnProp = exports.AsnSequenceType = exports.AsnSetType = exports.AsnChoiceType = exports.AsnType = void 0;
const converters = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1)).__importStar(require_converters());
const enums_1 = require_enums();
const storage_1 = require_storage();
const AsnType = (options) => (target) => {
let schema;
if (!storage_1.schemaStorage.has(target)) {
schema = storage_1.schemaStorage.createDefault(target);
storage_1.schemaStorage.set(target, schema);
} else schema = storage_1.schemaStorage.get(target);
Object.assign(schema, options);
};
exports.AsnType = AsnType;
const AsnChoiceType = () => (0, exports.AsnType)({ type: enums_1.AsnTypeTypes.Choice });
exports.AsnChoiceType = AsnChoiceType;
const AsnSetType = (options) => (0, exports.AsnType)({
type: enums_1.AsnTypeTypes.Set,
...options
});
exports.AsnSetType = AsnSetType;
const AsnSequenceType = (options) => (0, exports.AsnType)({
type: enums_1.AsnTypeTypes.Sequence,
...options
});
exports.AsnSequenceType = AsnSequenceType;
const AsnProp = (options) => (target, propertyKey) => {
let schema;
if (!storage_1.schemaStorage.has(target.constructor)) {
schema = storage_1.schemaStorage.createDefault(target.constructor);
storage_1.schemaStorage.set(target.constructor, schema);
} else schema = storage_1.schemaStorage.get(target.constructor);
const copyOptions = Object.assign({}, options);
if (typeof copyOptions.type === "number" && !copyOptions.converter) {
const defaultConverter = converters.defaultConverter(options.type);
if (!defaultConverter) throw new Error(`Cannot get default converter for property '${propertyKey}' of ${target.constructor.name}`);
copyOptions.converter = defaultConverter;
}
copyOptions.raw = options.raw;
schema.items[propertyKey] = copyOptions;
};
exports.AsnProp = AsnProp;
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-schema@2.9.4/node_modules/@peculiar/asn1-schema/build/cjs/errors/schema_validation.js
var require_schema_validation = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.AsnSchemaValidationError = void 0;
var AsnSchemaValidationError = class extends Error {
schemas = [];
};
exports.AsnSchemaValidationError = AsnSchemaValidationError;
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-schema@2.9.4/node_modules/@peculiar/asn1-schema/build/cjs/errors/index.js
var require_errors = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
(init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1)).__exportStar(require_schema_validation(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-schema@2.9.4/node_modules/@peculiar/asn1-schema/build/cjs/parser.js
var require_parser = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.AsnParser = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1js = tslib_1.__importStar(require_build$2());
const utils_1 = require_cjs$11();
const enums_1 = require_enums();
const converters = tslib_1.__importStar(require_converters());
const errors_1 = require_errors();
const helper_1 = require_helper();
const storage_1 = require_storage();
var AsnParser = class {
static parse(data, target, options) {
const asn1Parsed = asn1js.fromBER((0, utils_1.toArrayBuffer)(data), options?.berOptions);
if (asn1Parsed.result.error) throw new Error(asn1Parsed.result.error);
return this.fromASN(asn1Parsed.result, target, options);
}
static fromASN(asn1Schema, target, options) {
try {
if ((0, helper_1.isConvertible)(target)) return new target().fromASN(asn1Schema);
const schema = storage_1.schemaStorage.get(target);
storage_1.schemaStorage.cache(target);
let targetSchema = schema.schema;
const choiceResult = this.handleChoiceTypes(asn1Schema, schema, target, targetSchema, options);
if (choiceResult?.result) return choiceResult.result;
if (choiceResult?.targetSchema) targetSchema = choiceResult.targetSchema;
const sequenceResult = this.handleSequenceTypes(asn1Schema, schema, target, targetSchema);
const res = new target();
if ((0, helper_1.isTypeOfArray)(target)) return this.handleArrayTypes(asn1Schema, schema, target, options);
this.processSchemaItems(schema, sequenceResult, res, options);
return res;
} catch (error) {
if (error instanceof errors_1.AsnSchemaValidationError) error.schemas.push(target.name);
throw error;
}
}
static handleChoiceTypes(asn1Schema, schema, target, targetSchema, options) {
if (asn1Schema.constructor === asn1js.Constructed && schema.type === enums_1.AsnTypeTypes.Choice && asn1Schema.idBlock.tagClass === 3) for (const key in schema.items) {
const schemaItem = schema.items[key];
if (schemaItem.context === asn1Schema.idBlock.tagNumber && schemaItem.implicit) {
if (typeof schemaItem.type === "function" && storage_1.schemaStorage.has(schemaItem.type)) {
const fieldSchema = storage_1.schemaStorage.get(schemaItem.type);
if (fieldSchema && fieldSchema.type === enums_1.AsnTypeTypes.Sequence) {
const newSeq = new asn1js.Sequence();
if ("value" in asn1Schema.valueBlock && Array.isArray(asn1Schema.valueBlock.value) && "value" in newSeq.valueBlock) {
newSeq.valueBlock.value = asn1Schema.valueBlock.value;
const fieldValue = this.fromASN(newSeq, schemaItem.type, options);
const res = new target();
res[key] = fieldValue;
return { result: res };
}
}
}
}
}
else if (asn1Schema.constructor === asn1js.Constructed && schema.type !== enums_1.AsnTypeTypes.Choice) {
const newTargetSchema = new asn1js.Constructed({
idBlock: {
tagClass: 3,
tagNumber: asn1Schema.idBlock.tagNumber
},
value: schema.schema.valueBlock.value
});
for (const key in schema.items) delete asn1Schema[key];
return { targetSchema: newTargetSchema };
}
return null;
}
static handleSequenceTypes(asn1Schema, schema, target, targetSchema) {
if (schema.type === enums_1.AsnTypeTypes.Sequence) {
const asn1ComparedSchema = asn1js.compareSchema({}, asn1Schema, targetSchema);
if (!asn1ComparedSchema.verified) throw new errors_1.AsnSchemaValidationError(`Data does not match to ${target.name} ASN1 schema.${asn1ComparedSchema.result.error ? ` ${asn1ComparedSchema.result.error}` : ""}`);
return asn1ComparedSchema;
} else {
const asn1ComparedSchema = asn1js.compareSchema({}, asn1Schema, targetSchema);
if (!asn1ComparedSchema.verified) throw new errors_1.AsnSchemaValidationError(`Data does not match to ${target.name} ASN1 schema.${asn1ComparedSchema.result.error ? ` ${asn1ComparedSchema.result.error}` : ""}`);
return asn1ComparedSchema;
}
}
static processRepeatedField(asn1Elements, asn1Index, schemaItem) {
let elementsToProcess = asn1Elements.slice(asn1Index);
if (elementsToProcess.length === 1 && elementsToProcess[0].constructor.name === "Sequence") {
const seq = elementsToProcess[0];
if (seq.valueBlock && seq.valueBlock.value && Array.isArray(seq.valueBlock.value)) elementsToProcess = seq.valueBlock.value;
}
if (typeof schemaItem.type === "number") {
const converter = converters.defaultConverter(schemaItem.type);
if (!converter) throw new Error(`No converter for ASN.1 type ${schemaItem.type}`);
return elementsToProcess.filter((el) => el && el.valueBlock).map((el) => {
try {
return converter.fromASN(el);
} catch {
return;
}
}).filter((v) => v !== void 0);
} else return elementsToProcess.filter((el) => el && el.valueBlock).map((el) => {
try {
return this.fromASN(el, schemaItem.type);
} catch {
return;
}
}).filter((v) => v !== void 0);
}
static processPrimitiveField(asn1Element, schemaItem) {
const converter = converters.defaultConverter(schemaItem.type);
if (!converter) throw new Error(`No converter for ASN.1 type ${schemaItem.type}`);
return converter.fromASN(asn1Element);
}
static isOptionalChoiceField(schemaItem) {
return schemaItem.optional && typeof schemaItem.type === "function" && storage_1.schemaStorage.has(schemaItem.type) && storage_1.schemaStorage.get(schemaItem.type).type === enums_1.AsnTypeTypes.Choice;
}
static processOptionalChoiceField(asn1Element, schemaItem) {
try {
return {
processed: true,
value: this.fromASN(asn1Element, schemaItem.type)
};
} catch (err) {
if (err instanceof errors_1.AsnSchemaValidationError && /Wrong values for Choice type/.test(err.message)) return { processed: false };
throw err;
}
}
static handleArrayTypes(asn1Schema, schema, target, options) {
if (!("value" in asn1Schema.valueBlock && Array.isArray(asn1Schema.valueBlock.value))) throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");
const itemType = schema.itemType;
if (typeof itemType === "number") {
const converter = converters.defaultConverter(itemType);
if (!converter) throw new Error(`Cannot get default converter for array item of ${target.name} ASN1 schema`);
return target.from(asn1Schema.valueBlock.value, (element) => converter.fromASN(element));
} else return target.from(asn1Schema.valueBlock.value, (element) => this.fromASN(element, itemType, options));
}
static processSchemaItems(schema, asn1ComparedSchema, res, options) {
for (const key in schema.items) {
const asn1SchemaValue = asn1ComparedSchema.result[key];
if (!asn1SchemaValue) continue;
const schemaItem = schema.items[key];
const schemaItemType = schemaItem.type;
let parsedValue;
if (typeof schemaItemType === "number" || (0, helper_1.isConvertible)(schemaItemType)) parsedValue = this.processPrimitiveSchemaItem(asn1SchemaValue, schemaItem, schemaItemType, options);
else parsedValue = this.processComplexSchemaItem(asn1SchemaValue, schemaItem, schemaItemType, options);
if (parsedValue && typeof parsedValue === "object" && "value" in parsedValue && "raw" in parsedValue) {
res[key] = parsedValue.value;
res[`${key}Raw`] = parsedValue.raw;
} else res[key] = parsedValue;
}
}
static processPrimitiveSchemaItem(asn1SchemaValue, schemaItem, schemaItemType, options) {
const converter = schemaItem.converter ?? ((0, helper_1.isConvertible)(schemaItemType) ? new schemaItemType() : null);
if (!converter) throw new Error("Converter is empty");
if (schemaItem.repeated) return this.processRepeatedPrimitiveItem(asn1SchemaValue, schemaItem, converter, options);
else return this.processSinglePrimitiveItem(asn1SchemaValue, schemaItem, schemaItemType, converter, options);
}
static processRepeatedPrimitiveItem(asn1SchemaValue, schemaItem, converter, options) {
if (schemaItem.implicit) {
const newItem = new (schemaItem.repeated === "sequence" ? asn1js.Sequence : asn1js.Set)();
newItem.valueBlock = asn1SchemaValue.valueBlock;
const newItemAsn = asn1js.fromBER(newItem.toBER(false), options?.berOptions);
if (newItemAsn.offset === -1) throw new Error(`Cannot parse the child item. ${newItemAsn.result.error}`);
if (!("value" in newItemAsn.result.valueBlock && Array.isArray(newItemAsn.result.valueBlock.value))) throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");
const value = newItemAsn.result.valueBlock.value;
return Array.from(value, (element) => converter.fromASN(element));
} else return Array.from(asn1SchemaValue, (element) => converter.fromASN(element));
}
static processSinglePrimitiveItem(asn1SchemaValue, schemaItem, schemaItemType, converter, options) {
let value = asn1SchemaValue;
if (schemaItem.implicit) {
let newItem;
if ((0, helper_1.isConvertible)(schemaItemType)) newItem = new schemaItemType().toSchema("");
else {
const Asn1TypeName = enums_1.AsnPropTypes[schemaItemType];
const Asn1Type = asn1js[Asn1TypeName];
if (!Asn1Type) throw new Error(`Cannot get '${Asn1TypeName}' class from asn1js module`);
newItem = new Asn1Type();
}
newItem.valueBlock = value.valueBlock;
value = asn1js.fromBER(newItem.toBER(false), options?.berOptions).result;
}
return converter.fromASN(value);
}
static processComplexSchemaItem(asn1SchemaValue, schemaItem, schemaItemType, options) {
if (schemaItem.repeated) {
if (!Array.isArray(asn1SchemaValue)) throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");
return Array.from(asn1SchemaValue, (element) => this.fromASN(element, schemaItemType, options));
} else {
const valueToProcess = this.handleImplicitTagging(asn1SchemaValue, schemaItem, schemaItemType);
if (this.isOptionalChoiceField(schemaItem)) try {
return this.fromASN(valueToProcess, schemaItemType, options);
} catch (err) {
if (err instanceof errors_1.AsnSchemaValidationError && /Wrong values for Choice type/.test(err.message)) return;
throw err;
}
else {
const parsedValue = this.fromASN(valueToProcess, schemaItemType, options);
if (schemaItem.raw) return {
value: parsedValue,
raw: asn1SchemaValue.valueBeforeDecodeView
};
return parsedValue;
}
}
}
static handleImplicitTagging(asn1SchemaValue, schemaItem, schemaItemType) {
if (schemaItem.implicit && typeof schemaItem.context === "number") {
const schema = storage_1.schemaStorage.get(schemaItemType);
if (schema.type === enums_1.AsnTypeTypes.Sequence) {
const newSeq = new asn1js.Sequence();
if ("value" in asn1SchemaValue.valueBlock && Array.isArray(asn1SchemaValue.valueBlock.value) && "value" in newSeq.valueBlock) {
newSeq.valueBlock.value = asn1SchemaValue.valueBlock.value;
return newSeq;
}
} else if (schema.type === enums_1.AsnTypeTypes.Set) {
const newSet = new asn1js.Set();
if ("value" in asn1SchemaValue.valueBlock && Array.isArray(asn1SchemaValue.valueBlock.value) && "value" in newSet.valueBlock) {
newSet.valueBlock.value = asn1SchemaValue.valueBlock.value;
return newSet;
}
}
}
return asn1SchemaValue;
}
};
exports.AsnParser = AsnParser;
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-schema@2.9.4/node_modules/@peculiar/asn1-schema/build/cjs/serializer.js
var require_serializer = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.AsnSerializer = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1js = tslib_1.__importStar(require_build$2());
const utils_1 = require_cjs$11();
const converters = tslib_1.__importStar(require_converters());
const enums_1 = require_enums();
const helper_1 = require_helper();
const storage_1 = require_storage();
exports.AsnSerializer = class AsnSerializer {
static serialize(obj) {
if (obj instanceof asn1js.BaseBlock) return obj.toBER(false);
return this.toASN(obj).toBER(false);
}
static toASN(obj) {
if (obj && typeof obj === "object" && (0, helper_1.isConvertible)(obj)) return obj.toASN();
if (!(obj && typeof obj === "object")) throw new TypeError("Parameter 1 should be type of Object.");
const target = obj.constructor;
const schema = storage_1.schemaStorage.get(target);
storage_1.schemaStorage.cache(target);
let asn1Value = [];
if (schema.itemType) {
if (!Array.isArray(obj)) throw new TypeError("Parameter 1 should be type of Array.");
if (typeof schema.itemType === "number") {
const converter = converters.defaultConverter(schema.itemType);
if (!converter) throw new Error(`Cannot get default converter for array item of ${target.name} ASN1 schema`);
asn1Value = obj.map((o) => converter.toASN(o));
} else asn1Value = obj.map((o) => this.toAsnItem({ type: schema.itemType }, "[]", target, o));
} else for (const key in schema.items) {
const schemaItem = schema.items[key];
const objProp = obj[key];
if (objProp === void 0 || schemaItem.defaultValue === objProp || typeof schemaItem.defaultValue === "object" && typeof objProp === "object" && (0, helper_1.isArrayEqual)(this.serialize(schemaItem.defaultValue), this.serialize(objProp))) continue;
const asn1Item = AsnSerializer.toAsnItem(schemaItem, key, target, objProp);
if (typeof schemaItem.context === "number") {
if (schemaItem.implicit) {
if (!schemaItem.repeated && (typeof schemaItem.type === "number" || (0, helper_1.isConvertible)(schemaItem.type))) {
const value = {};
value.valueHex = asn1Item instanceof asn1js.Null ? (0, utils_1.toArrayBuffer)(asn1Item.valueBeforeDecodeView) : asn1Item.valueBlock.toBER();
asn1Value.push(new asn1js.Primitive({
optional: schemaItem.optional,
idBlock: {
tagClass: 3,
tagNumber: schemaItem.context
},
...value
}));
} else asn1Value.push(new asn1js.Constructed({
optional: schemaItem.optional,
idBlock: {
tagClass: 3,
tagNumber: schemaItem.context
},
value: asn1Item.valueBlock.value
}));
} else asn1Value.push(new asn1js.Constructed({
optional: schemaItem.optional,
idBlock: {
tagClass: 3,
tagNumber: schemaItem.context
},
value: [asn1Item]
}));
} else if (schemaItem.repeated) asn1Value = asn1Value.concat(asn1Item);
else asn1Value.push(asn1Item);
}
let asnSchema;
switch (schema.type) {
case enums_1.AsnTypeTypes.Sequence:
asnSchema = new asn1js.Sequence({ value: asn1Value });
break;
case enums_1.AsnTypeTypes.Set:
asnSchema = new asn1js.Set({ value: asn1Value });
break;
case enums_1.AsnTypeTypes.Choice:
if (!asn1Value[0]) throw new Error(`Schema '${target.name}' has wrong data. Choice cannot be empty.`);
asnSchema = asn1Value[0];
}
return asnSchema;
}
static toAsnItem(schemaItem, key, target, objProp) {
let asn1Item;
if (typeof schemaItem.type === "number") {
const converter = schemaItem.converter;
if (!converter) throw new Error(`Property '${key}' doesn't have converter for type ${enums_1.AsnPropTypes[schemaItem.type]} in schema '${target.name}'`);
if (schemaItem.repeated) {
if (!Array.isArray(objProp)) throw new TypeError("Parameter 'objProp' should be type of Array.");
const items = Array.from(objProp, (element) => converter.toASN(element));
asn1Item = new (schemaItem.repeated === "sequence" ? asn1js.Sequence : asn1js.Set)({ value: items });
} else asn1Item = converter.toASN(objProp);
} else if (schemaItem.repeated) {
if (!Array.isArray(objProp)) throw new TypeError("Parameter 'objProp' should be type of Array.");
const items = Array.from(objProp, (element) => this.toASN(element));
asn1Item = new (schemaItem.repeated === "sequence" ? asn1js.Sequence : asn1js.Set)({ value: items });
} else asn1Item = this.toASN(objProp);
return asn1Item;
}
};
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-schema@2.9.4/node_modules/@peculiar/asn1-schema/build/cjs/objects.js
var require_objects = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.AsnArray = void 0;
var AsnArray = class extends Array {
constructor(items = []) {
if (typeof items === "number") super(items);
else {
super();
for (const item of items) this.push(item);
}
}
};
exports.AsnArray = AsnArray;
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-schema@2.9.4/node_modules/@peculiar/asn1-schema/build/cjs/convert.js
var require_convert = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.AsnConvert = void 0;
const asn1js = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1)).__importStar(require_build$2());
const utils_1 = require_cjs$11();
const parser_1 = require_parser();
const serializer_1 = require_serializer();
exports.AsnConvert = class AsnConvert {
static serialize(obj) {
return serializer_1.AsnSerializer.serialize(obj);
}
static parse(data, target, options) {
return parser_1.AsnParser.parse(data, target, options);
}
static toString(data, options) {
const buf = (0, utils_1.isBufferSource)(data) ? (0, utils_1.toArrayBuffer)(data) : AsnConvert.serialize(data);
const asn = asn1js.fromBER(buf, options?.berOptions);
if (asn.offset === -1) throw new Error(`Cannot decode ASN.1 data. ${asn.result.error}`);
return asn.result.toString();
}
};
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-schema@2.9.4/node_modules/@peculiar/asn1-schema/build/cjs/index.js
var require_cjs$10 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.AsnSerializer = exports.AsnParser = exports.AsnPropTypes = exports.AsnTypeTypes = exports.AsnSetType = exports.AsnSequenceType = exports.AsnChoiceType = exports.AsnType = exports.AsnProp = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
tslib_1.__exportStar(require_converters(), exports);
tslib_1.__exportStar(require_types$5(), exports);
var decorators_1 = require_decorators$1();
Object.defineProperty(exports, "AsnProp", {
enumerable: true,
get: function() {
return decorators_1.AsnProp;
}
});
Object.defineProperty(exports, "AsnType", {
enumerable: true,
get: function() {
return decorators_1.AsnType;
}
});
Object.defineProperty(exports, "AsnChoiceType", {
enumerable: true,
get: function() {
return decorators_1.AsnChoiceType;
}
});
Object.defineProperty(exports, "AsnSequenceType", {
enumerable: true,
get: function() {
return decorators_1.AsnSequenceType;
}
});
Object.defineProperty(exports, "AsnSetType", {
enumerable: true,
get: function() {
return decorators_1.AsnSetType;
}
});
var enums_1 = require_enums();
Object.defineProperty(exports, "AsnTypeTypes", {
enumerable: true,
get: function() {
return enums_1.AsnTypeTypes;
}
});
Object.defineProperty(exports, "AsnPropTypes", {
enumerable: true,
get: function() {
return enums_1.AsnPropTypes;
}
});
var parser_1 = require_parser();
Object.defineProperty(exports, "AsnParser", {
enumerable: true,
get: function() {
return parser_1.AsnParser;
}
});
var serializer_1 = require_serializer();
Object.defineProperty(exports, "AsnSerializer", {
enumerable: true,
get: function() {
return serializer_1.AsnSerializer;
}
});
tslib_1.__exportStar(require_errors(), exports);
tslib_1.__exportStar(require_objects(), exports);
tslib_1.__exportStar(require_convert(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/ip_converter.js
var require_ip_converter = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.IpConverter = void 0;
const encoding_1 = require_encoding();
var IpConverter = class {
static isIPv4(ip) {
return /^(\d{1,3}\.){3}\d{1,3}$/.test(ip);
}
static parseIPv4(ip) {
const parts = ip.split(".");
if (parts.length !== 4) throw new Error("Invalid IPv4 address");
return parts.map((part) => {
const num = parseInt(part, 10);
if (isNaN(num) || num < 0 || num > 255) throw new Error("Invalid IPv4 address part");
return num;
});
}
static parseIPv6(ip) {
const parts = this.expandIPv6(ip).split(":");
if (parts.length !== 8) throw new Error("Invalid IPv6 address");
return parts.reduce((bytes, part) => {
const num = parseInt(part, 16);
if (isNaN(num) || num < 0 || num > 65535) throw new Error("Invalid IPv6 address part");
bytes.push(num >> 8 & 255);
bytes.push(num & 255);
return bytes;
}, []);
}
static expandIPv6(ip) {
if (!ip.includes("::")) return ip;
const parts = ip.split("::");
if (parts.length > 2) throw new Error("Invalid IPv6 address");
const left = parts[0] ? parts[0].split(":") : [];
const right = parts[1] ? parts[1].split(":") : [];
const missing = 8 - (left.length + right.length);
if (missing < 0) throw new Error("Invalid IPv6 address");
return [
...left,
...Array(missing).fill("0"),
...right
].join(":");
}
static formatIPv6(bytes) {
const parts = [];
for (let i = 0; i < 16; i += 2) parts.push((bytes[i] << 8 | bytes[i + 1]).toString(16));
return this.compressIPv6(parts.join(":"));
}
static compressIPv6(ip) {
const parts = ip.split(":");
let longestZeroStart = -1;
let longestZeroLength = 0;
let currentZeroStart = -1;
let currentZeroLength = 0;
for (let i = 0; i < parts.length; i++) if (parts[i] === "0") {
if (currentZeroStart === -1) currentZeroStart = i;
currentZeroLength++;
} else {
if (currentZeroLength > longestZeroLength) {
longestZeroStart = currentZeroStart;
longestZeroLength = currentZeroLength;
}
currentZeroStart = -1;
currentZeroLength = 0;
}
if (currentZeroLength > longestZeroLength) {
longestZeroStart = currentZeroStart;
longestZeroLength = currentZeroLength;
}
if (longestZeroLength > 1) return `${parts.slice(0, longestZeroStart).join(":")}::${parts.slice(longestZeroStart + longestZeroLength).join(":")}`;
return ip;
}
static parseCIDR(text) {
const [addr, prefixStr] = text.split("/");
const prefix = parseInt(prefixStr, 10);
if (this.isIPv4(addr)) {
if (prefix < 0 || prefix > 32) throw new Error("Invalid IPv4 prefix length");
return [this.parseIPv4(addr), prefix];
} else {
if (prefix < 0 || prefix > 128) throw new Error("Invalid IPv6 prefix length");
return [this.parseIPv6(addr), prefix];
}
}
static decodeIP(value) {
if (value.length === 64 && parseInt(value, 16) === 0) return "::/0";
if (value.length !== 16) return value;
const mask = parseInt(value.slice(8), 16).toString(2).split("").reduce((a, k) => a + +k, 0);
let ip = value.slice(0, 8).replace(/(.{2})/g, (match) => `${parseInt(match, 16)}.`);
ip = ip.slice(0, -1);
return `${ip}/${mask}`;
}
static toString(buf) {
const uint8 = new Uint8Array(buf);
if (uint8.length === 4) return Array.from(uint8).join(".");
if (uint8.length === 16) return this.formatIPv6(uint8);
if (uint8.length === 8 || uint8.length === 32) {
const half = uint8.length / 2;
const addrBytes = uint8.slice(0, half);
const maskBytes = uint8.slice(half);
if (uint8.every((byte) => byte === 0)) return uint8.length === 8 ? "0.0.0.0/0" : "::/0";
const prefixLen = maskBytes.reduce((a, b) => a + (b.toString(2).match(/1/g) || []).length, 0);
if (uint8.length === 8) return `${Array.from(addrBytes).join(".")}/${prefixLen}`;
else return `${this.formatIPv6(addrBytes)}/${prefixLen}`;
}
return this.decodeIP(encoding_1.hex.encode(buf));
}
static fromString(text) {
if (text.includes("/")) {
const [addr, prefix] = this.parseCIDR(text);
const maskBytes = new Uint8Array(addr.length);
let bitsLeft = prefix;
for (let i = 0; i < maskBytes.length; i++) if (bitsLeft >= 8) {
maskBytes[i] = 255;
bitsLeft -= 8;
} else if (bitsLeft > 0) {
maskBytes[i] = 255 << 8 - bitsLeft;
bitsLeft = 0;
}
const out = new Uint8Array(addr.length * 2);
out.set(addr, 0);
out.set(maskBytes, addr.length);
return out.buffer;
}
const bytes = this.isIPv4(text) ? this.parseIPv4(text) : this.parseIPv6(text);
return new Uint8Array(bytes).buffer;
}
};
exports.IpConverter = IpConverter;
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/name.js
var require_name = /* @__PURE__ */ __commonJSMin(((exports) => {
var RelativeDistinguishedName_1;
var RDNSequence_1;
var Name_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Name = exports.RDNSequence = exports.RelativeDistinguishedName = exports.AttributeTypeAndValue = exports.AttributeValue = exports.DirectoryString = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const encoding_1 = require_encoding();
let DirectoryString = class DirectoryString {
teletexString;
printableString;
universalString;
utf8String;
bmpString;
constructor(params = {}) {
Object.assign(this, params);
}
toString() {
return this.bmpString || this.printableString || this.teletexString || this.universalString || this.utf8String || "";
}
};
exports.DirectoryString = DirectoryString;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.TeletexString })], DirectoryString.prototype, "teletexString", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.PrintableString })], DirectoryString.prototype, "printableString", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.UniversalString })], DirectoryString.prototype, "universalString", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Utf8String })], DirectoryString.prototype, "utf8String", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.BmpString })], DirectoryString.prototype, "bmpString", void 0);
exports.DirectoryString = DirectoryString = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], DirectoryString);
let AttributeValue = class AttributeValue extends DirectoryString {
ia5String;
anyValue;
constructor(params = {}) {
super(params);
Object.assign(this, params);
}
toString() {
return this.ia5String || (this.anyValue ? encoding_1.hex.encode(this.anyValue) : super.toString());
}
};
exports.AttributeValue = AttributeValue;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.IA5String })], AttributeValue.prototype, "ia5String", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Any })], AttributeValue.prototype, "anyValue", void 0);
exports.AttributeValue = AttributeValue = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], AttributeValue);
var AttributeTypeAndValue = class {
type = "";
value = new AttributeValue();
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.AttributeTypeAndValue = AttributeTypeAndValue;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], AttributeTypeAndValue.prototype, "type", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: AttributeValue })], AttributeTypeAndValue.prototype, "value", void 0);
let RelativeDistinguishedName = RelativeDistinguishedName_1 = class RelativeDistinguishedName extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, RelativeDistinguishedName_1.prototype);
}
};
exports.RelativeDistinguishedName = RelativeDistinguishedName;
exports.RelativeDistinguishedName = RelativeDistinguishedName = RelativeDistinguishedName_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Set,
itemType: AttributeTypeAndValue
})], RelativeDistinguishedName);
let RDNSequence = RDNSequence_1 = class RDNSequence extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, RDNSequence_1.prototype);
}
};
exports.RDNSequence = RDNSequence;
exports.RDNSequence = RDNSequence = RDNSequence_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: RelativeDistinguishedName
})], RDNSequence);
let Name = Name_1 = class Name extends RDNSequence {
constructor(items) {
super(items);
Object.setPrototypeOf(this, Name_1.prototype);
}
};
exports.Name = Name;
exports.Name = Name = Name_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], Name);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/general_name.js
var require_general_name = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.GeneralName = exports.EDIPartyName = exports.OtherName = exports.AsnIpConverter = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const ip_converter_1 = require_ip_converter();
const name_1 = require_name();
exports.AsnIpConverter = {
fromASN: (value) => ip_converter_1.IpConverter.toString(asn1_schema_1.AsnOctetStringConverter.fromASN(value)),
toASN: (value) => asn1_schema_1.AsnOctetStringConverter.toASN(ip_converter_1.IpConverter.fromString(value))
};
var OtherName = class {
typeId = "";
value = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.OtherName = OtherName;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], OtherName.prototype, "typeId", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Any,
context: 0
})], OtherName.prototype, "value", void 0);
var EDIPartyName = class {
nameAssigner;
partyName = new name_1.DirectoryString();
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.EDIPartyName = EDIPartyName;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: name_1.DirectoryString,
optional: true,
context: 0,
implicit: true
})], EDIPartyName.prototype, "nameAssigner", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: name_1.DirectoryString,
context: 1,
implicit: true
})], EDIPartyName.prototype, "partyName", void 0);
let GeneralName = class GeneralName {
otherName;
rfc822Name;
dNSName;
x400Address;
directoryName;
ediPartyName;
uniformResourceIdentifier;
iPAddress;
registeredID;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.GeneralName = GeneralName;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: OtherName,
context: 0,
implicit: true
})], GeneralName.prototype, "otherName", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.IA5String,
context: 1,
implicit: true
})], GeneralName.prototype, "rfc822Name", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.IA5String,
context: 2,
implicit: true
})], GeneralName.prototype, "dNSName", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Any,
context: 3,
implicit: true
})], GeneralName.prototype, "x400Address", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: name_1.Name,
context: 4,
implicit: false
})], GeneralName.prototype, "directoryName", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: EDIPartyName,
context: 5
})], GeneralName.prototype, "ediPartyName", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.IA5String,
context: 6,
implicit: true
})], GeneralName.prototype, "uniformResourceIdentifier", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.OctetString,
context: 7,
implicit: true,
converter: exports.AsnIpConverter
})], GeneralName.prototype, "iPAddress", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.ObjectIdentifier,
context: 8,
implicit: true
})], GeneralName.prototype, "registeredID", void 0);
exports.GeneralName = GeneralName = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], GeneralName);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/object_identifiers.js
var require_object_identifiers$5 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.id_alg_unsigned = exports.id_ce = exports.id_ad_caRepository = exports.id_ad_timeStamping = exports.id_ad_caIssuers = exports.id_ad_ocsp = exports.id_qt_unotice = exports.id_qt_csp = exports.id_ad = exports.id_kp = exports.id_qt = exports.id_pe = exports.id_pkix = void 0;
exports.id_pkix = "1.3.6.1.5.5.7";
exports.id_pe = `${exports.id_pkix}.1`;
exports.id_qt = `${exports.id_pkix}.2`;
exports.id_kp = `${exports.id_pkix}.3`;
exports.id_ad = `${exports.id_pkix}.48`;
exports.id_qt_csp = `${exports.id_qt}.1`;
exports.id_qt_unotice = `${exports.id_qt}.2`;
exports.id_ad_ocsp = `${exports.id_ad}.1`;
exports.id_ad_caIssuers = `${exports.id_ad}.2`;
exports.id_ad_timeStamping = `${exports.id_ad}.3`;
exports.id_ad_caRepository = `${exports.id_ad}.5`;
exports.id_ce = "2.5.29";
exports.id_alg_unsigned = "1.3.6.1.5.5.7.6.36";
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/authority_information_access.js
var require_authority_information_access = /* @__PURE__ */ __commonJSMin(((exports) => {
var AuthorityInfoAccessSyntax_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthorityInfoAccessSyntax = exports.AccessDescription = exports.id_pe_authorityInfoAccess = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const general_name_1 = require_general_name();
exports.id_pe_authorityInfoAccess = `${require_object_identifiers$5().id_pe}.1`;
var AccessDescription = class {
accessMethod = "";
accessLocation = new general_name_1.GeneralName();
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.AccessDescription = AccessDescription;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], AccessDescription.prototype, "accessMethod", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: general_name_1.GeneralName })], AccessDescription.prototype, "accessLocation", void 0);
let AuthorityInfoAccessSyntax = AuthorityInfoAccessSyntax_1 = class AuthorityInfoAccessSyntax extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, AuthorityInfoAccessSyntax_1.prototype);
}
};
exports.AuthorityInfoAccessSyntax = AuthorityInfoAccessSyntax;
exports.AuthorityInfoAccessSyntax = AuthorityInfoAccessSyntax = AuthorityInfoAccessSyntax_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: AccessDescription
})], AuthorityInfoAccessSyntax);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/authority_key_identifier.js
var require_authority_key_identifier = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthorityKeyIdentifier = exports.KeyIdentifier = exports.id_ce_authorityKeyIdentifier = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const general_name_1 = require_general_name();
exports.id_ce_authorityKeyIdentifier = `${require_object_identifiers$5().id_ce}.35`;
var KeyIdentifier = class extends asn1_schema_1.OctetString {};
exports.KeyIdentifier = KeyIdentifier;
var AuthorityKeyIdentifier = class {
keyIdentifier;
authorityCertIssuer;
authorityCertSerialNumber;
constructor(params = {}) {
if (params) Object.assign(this, params);
}
};
exports.AuthorityKeyIdentifier = AuthorityKeyIdentifier;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: KeyIdentifier,
context: 0,
optional: true,
implicit: true
})], AuthorityKeyIdentifier.prototype, "keyIdentifier", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: general_name_1.GeneralName,
context: 1,
optional: true,
implicit: true,
repeated: "sequence"
})], AuthorityKeyIdentifier.prototype, "authorityCertIssuer", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
context: 2,
optional: true,
implicit: true,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], AuthorityKeyIdentifier.prototype, "authorityCertSerialNumber", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/basic_constraints.js
var require_basic_constraints = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.BasicConstraints = exports.id_ce_basicConstraints = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
exports.id_ce_basicConstraints = `${require_object_identifiers$5().id_ce}.19`;
var BasicConstraints = class {
cA = false;
pathLenConstraint;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.BasicConstraints = BasicConstraints;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Boolean,
defaultValue: false
})], BasicConstraints.prototype, "cA", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
optional: true
})], BasicConstraints.prototype, "pathLenConstraint", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/general_names.js
var require_general_names = /* @__PURE__ */ __commonJSMin(((exports) => {
var GeneralNames_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.GeneralNames = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const general_name_1 = require_general_name();
let GeneralNames = GeneralNames_1 = class GeneralNames extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, GeneralNames_1.prototype);
}
};
exports.GeneralNames = GeneralNames;
exports.GeneralNames = GeneralNames = GeneralNames_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: general_name_1.GeneralName
})], GeneralNames);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/certificate_issuer.js
var require_certificate_issuer = /* @__PURE__ */ __commonJSMin(((exports) => {
var CertificateIssuer_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CertificateIssuer = exports.id_ce_certificateIssuer = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const general_names_1 = require_general_names();
exports.id_ce_certificateIssuer = `${require_object_identifiers$5().id_ce}.29`;
let CertificateIssuer = CertificateIssuer_1 = class CertificateIssuer extends general_names_1.GeneralNames {
constructor(items) {
super(items);
Object.setPrototypeOf(this, CertificateIssuer_1.prototype);
}
};
exports.CertificateIssuer = CertificateIssuer;
exports.CertificateIssuer = CertificateIssuer = CertificateIssuer_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], CertificateIssuer);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/certificate_policies.js
var require_certificate_policies = /* @__PURE__ */ __commonJSMin(((exports) => {
var CertificatePolicies_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CertificatePolicies = exports.PolicyInformation = exports.PolicyQualifierInfo = exports.Qualifier = exports.UserNotice = exports.NoticeReference = exports.DisplayText = exports.id_ce_certificatePolicies_anyPolicy = exports.id_ce_certificatePolicies = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
exports.id_ce_certificatePolicies = `${require_object_identifiers$5().id_ce}.32`;
exports.id_ce_certificatePolicies_anyPolicy = `${exports.id_ce_certificatePolicies}.0`;
let DisplayText = class DisplayText {
ia5String;
visibleString;
bmpString;
utf8String;
constructor(params = {}) {
Object.assign(this, params);
}
toString() {
return this.ia5String || this.visibleString || this.bmpString || this.utf8String || "";
}
};
exports.DisplayText = DisplayText;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.IA5String })], DisplayText.prototype, "ia5String", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.VisibleString })], DisplayText.prototype, "visibleString", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.BmpString })], DisplayText.prototype, "bmpString", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Utf8String })], DisplayText.prototype, "utf8String", void 0);
exports.DisplayText = DisplayText = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], DisplayText);
var NoticeReference = class {
organization = new DisplayText();
noticeNumbers = [];
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.NoticeReference = NoticeReference;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: DisplayText })], NoticeReference.prototype, "organization", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
repeated: "sequence"
})], NoticeReference.prototype, "noticeNumbers", void 0);
var UserNotice = class {
noticeRef;
explicitText;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.UserNotice = UserNotice;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: NoticeReference,
optional: true
})], UserNotice.prototype, "noticeRef", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: DisplayText,
optional: true
})], UserNotice.prototype, "explicitText", void 0);
let Qualifier = class Qualifier {
cPSuri;
userNotice;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.Qualifier = Qualifier;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.IA5String })], Qualifier.prototype, "cPSuri", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: UserNotice })], Qualifier.prototype, "userNotice", void 0);
exports.Qualifier = Qualifier = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], Qualifier);
var PolicyQualifierInfo = class {
policyQualifierId = "";
qualifier = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.PolicyQualifierInfo = PolicyQualifierInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], PolicyQualifierInfo.prototype, "policyQualifierId", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Any })], PolicyQualifierInfo.prototype, "qualifier", void 0);
var PolicyInformation = class {
policyIdentifier = "";
policyQualifiers;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.PolicyInformation = PolicyInformation;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], PolicyInformation.prototype, "policyIdentifier", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: PolicyQualifierInfo,
repeated: "sequence",
optional: true
})], PolicyInformation.prototype, "policyQualifiers", void 0);
let CertificatePolicies = CertificatePolicies_1 = class CertificatePolicies extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, CertificatePolicies_1.prototype);
}
};
exports.CertificatePolicies = CertificatePolicies;
exports.CertificatePolicies = CertificatePolicies = CertificatePolicies_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: PolicyInformation
})], CertificatePolicies);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/crl_number.js
var require_crl_number = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.CRLNumber = exports.id_ce_cRLNumber = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
exports.id_ce_cRLNumber = `${require_object_identifiers$5().id_ce}.20`;
let CRLNumber = class CRLNumber {
value;
constructor(value = 0) {
this.value = value;
}
};
exports.CRLNumber = CRLNumber;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Integer })], CRLNumber.prototype, "value", void 0);
exports.CRLNumber = CRLNumber = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], CRLNumber);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/crl_delta_indicator.js
var require_crl_delta_indicator = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseCRLNumber = exports.id_ce_deltaCRLIndicator = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const object_identifiers_1 = require_object_identifiers$5();
const crl_number_1 = require_crl_number();
exports.id_ce_deltaCRLIndicator = `${object_identifiers_1.id_ce}.27`;
let BaseCRLNumber = class BaseCRLNumber extends crl_number_1.CRLNumber {};
exports.BaseCRLNumber = BaseCRLNumber;
exports.BaseCRLNumber = BaseCRLNumber = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], BaseCRLNumber);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/crl_distribution_points.js
var require_crl_distribution_points = /* @__PURE__ */ __commonJSMin(((exports) => {
var CRLDistributionPoints_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CRLDistributionPoints = exports.DistributionPoint = exports.DistributionPointName = exports.Reason = exports.ReasonFlags = exports.id_ce_cRLDistributionPoints = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const name_1 = require_name();
const general_name_1 = require_general_name();
exports.id_ce_cRLDistributionPoints = `${require_object_identifiers$5().id_ce}.31`;
var ReasonFlags;
(function(ReasonFlags) {
ReasonFlags[ReasonFlags["unused"] = 1] = "unused";
ReasonFlags[ReasonFlags["keyCompromise"] = 2] = "keyCompromise";
ReasonFlags[ReasonFlags["cACompromise"] = 4] = "cACompromise";
ReasonFlags[ReasonFlags["affiliationChanged"] = 8] = "affiliationChanged";
ReasonFlags[ReasonFlags["superseded"] = 16] = "superseded";
ReasonFlags[ReasonFlags["cessationOfOperation"] = 32] = "cessationOfOperation";
ReasonFlags[ReasonFlags["certificateHold"] = 64] = "certificateHold";
ReasonFlags[ReasonFlags["privilegeWithdrawn"] = 128] = "privilegeWithdrawn";
ReasonFlags[ReasonFlags["aACompromise"] = 256] = "aACompromise";
})(ReasonFlags || (exports.ReasonFlags = ReasonFlags = {}));
var Reason = class extends asn1_schema_1.BitString {
toJSON() {
const res = [];
const flags = this.toNumber();
if (flags & ReasonFlags.aACompromise) res.push("aACompromise");
if (flags & ReasonFlags.affiliationChanged) res.push("affiliationChanged");
if (flags & ReasonFlags.cACompromise) res.push("cACompromise");
if (flags & ReasonFlags.certificateHold) res.push("certificateHold");
if (flags & ReasonFlags.cessationOfOperation) res.push("cessationOfOperation");
if (flags & ReasonFlags.keyCompromise) res.push("keyCompromise");
if (flags & ReasonFlags.privilegeWithdrawn) res.push("privilegeWithdrawn");
if (flags & ReasonFlags.superseded) res.push("superseded");
if (flags & ReasonFlags.unused) res.push("unused");
return res;
}
toString() {
return `[${this.toJSON().join(", ")}]`;
}
};
exports.Reason = Reason;
let DistributionPointName = class DistributionPointName {
fullName;
nameRelativeToCRLIssuer;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.DistributionPointName = DistributionPointName;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: general_name_1.GeneralName,
context: 0,
repeated: "sequence",
implicit: true
})], DistributionPointName.prototype, "fullName", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: name_1.RelativeDistinguishedName,
context: 1,
implicit: true
})], DistributionPointName.prototype, "nameRelativeToCRLIssuer", void 0);
exports.DistributionPointName = DistributionPointName = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], DistributionPointName);
var DistributionPoint = class {
distributionPoint;
reasons;
cRLIssuer;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.DistributionPoint = DistributionPoint;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: DistributionPointName,
context: 0,
optional: true
})], DistributionPoint.prototype, "distributionPoint", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: Reason,
context: 1,
optional: true,
implicit: true
})], DistributionPoint.prototype, "reasons", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: general_name_1.GeneralName,
context: 2,
optional: true,
repeated: "sequence",
implicit: true
})], DistributionPoint.prototype, "cRLIssuer", void 0);
let CRLDistributionPoints = CRLDistributionPoints_1 = class CRLDistributionPoints extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, CRLDistributionPoints_1.prototype);
}
};
exports.CRLDistributionPoints = CRLDistributionPoints;
exports.CRLDistributionPoints = CRLDistributionPoints = CRLDistributionPoints_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: DistributionPoint
})], CRLDistributionPoints);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/crl_freshest.js
var require_crl_freshest = /* @__PURE__ */ __commonJSMin(((exports) => {
var FreshestCRL_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.FreshestCRL = exports.id_ce_freshestCRL = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const object_identifiers_1 = require_object_identifiers$5();
const crl_distribution_points_1 = require_crl_distribution_points();
exports.id_ce_freshestCRL = `${object_identifiers_1.id_ce}.46`;
let FreshestCRL = FreshestCRL_1 = class FreshestCRL extends crl_distribution_points_1.CRLDistributionPoints {
constructor(items) {
super(items);
Object.setPrototypeOf(this, FreshestCRL_1.prototype);
}
};
exports.FreshestCRL = FreshestCRL;
exports.FreshestCRL = FreshestCRL = FreshestCRL_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: crl_distribution_points_1.DistributionPoint
})], FreshestCRL);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/crl_issuing_distribution_point.js
var require_crl_issuing_distribution_point = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.IssuingDistributionPoint = exports.id_ce_issuingDistributionPoint = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const object_identifiers_1 = require_object_identifiers$5();
const crl_distribution_points_1 = require_crl_distribution_points();
exports.id_ce_issuingDistributionPoint = `${object_identifiers_1.id_ce}.28`;
var IssuingDistributionPoint = class IssuingDistributionPoint {
static ONLY = false;
distributionPoint;
onlyContainsUserCerts = IssuingDistributionPoint.ONLY;
onlyContainsCACerts = IssuingDistributionPoint.ONLY;
onlySomeReasons;
indirectCRL = IssuingDistributionPoint.ONLY;
onlyContainsAttributeCerts = IssuingDistributionPoint.ONLY;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.IssuingDistributionPoint = IssuingDistributionPoint;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: crl_distribution_points_1.DistributionPointName,
context: 0,
optional: true
})], IssuingDistributionPoint.prototype, "distributionPoint", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Boolean,
context: 1,
defaultValue: IssuingDistributionPoint.ONLY,
implicit: true
})], IssuingDistributionPoint.prototype, "onlyContainsUserCerts", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Boolean,
context: 2,
defaultValue: IssuingDistributionPoint.ONLY,
implicit: true
})], IssuingDistributionPoint.prototype, "onlyContainsCACerts", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: crl_distribution_points_1.Reason,
context: 3,
optional: true,
implicit: true
})], IssuingDistributionPoint.prototype, "onlySomeReasons", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Boolean,
context: 4,
defaultValue: IssuingDistributionPoint.ONLY,
implicit: true
})], IssuingDistributionPoint.prototype, "indirectCRL", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Boolean,
context: 5,
defaultValue: IssuingDistributionPoint.ONLY,
implicit: true
})], IssuingDistributionPoint.prototype, "onlyContainsAttributeCerts", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/crl_reason.js
var require_crl_reason = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.CRLReason = exports.CRLReasons = exports.id_ce_cRLReasons = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
exports.id_ce_cRLReasons = `${require_object_identifiers$5().id_ce}.21`;
var CRLReasons;
(function(CRLReasons) {
CRLReasons[CRLReasons["unspecified"] = 0] = "unspecified";
CRLReasons[CRLReasons["keyCompromise"] = 1] = "keyCompromise";
CRLReasons[CRLReasons["cACompromise"] = 2] = "cACompromise";
CRLReasons[CRLReasons["affiliationChanged"] = 3] = "affiliationChanged";
CRLReasons[CRLReasons["superseded"] = 4] = "superseded";
CRLReasons[CRLReasons["cessationOfOperation"] = 5] = "cessationOfOperation";
CRLReasons[CRLReasons["certificateHold"] = 6] = "certificateHold";
CRLReasons[CRLReasons["removeFromCRL"] = 8] = "removeFromCRL";
CRLReasons[CRLReasons["privilegeWithdrawn"] = 9] = "privilegeWithdrawn";
CRLReasons[CRLReasons["aACompromise"] = 10] = "aACompromise";
})(CRLReasons || (exports.CRLReasons = CRLReasons = {}));
let CRLReason = class CRLReason {
reason = CRLReasons.unspecified;
constructor(reason = CRLReasons.unspecified) {
this.reason = reason;
}
toJSON() {
return CRLReasons[this.reason];
}
toString() {
return this.toJSON();
}
};
exports.CRLReason = CRLReason;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Enumerated })], CRLReason.prototype, "reason", void 0);
exports.CRLReason = CRLReason = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], CRLReason);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/extended_key_usage.js
var require_extended_key_usage = /* @__PURE__ */ __commonJSMin(((exports) => {
var ExtendedKeyUsage_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.id_kp_OCSPSigning = exports.id_kp_timeStamping = exports.id_kp_emailProtection = exports.id_kp_codeSigning = exports.id_kp_clientAuth = exports.id_kp_serverAuth = exports.anyExtendedKeyUsage = exports.ExtendedKeyUsage = exports.id_ce_extKeyUsage = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const object_identifiers_1 = require_object_identifiers$5();
exports.id_ce_extKeyUsage = `${object_identifiers_1.id_ce}.37`;
let ExtendedKeyUsage = ExtendedKeyUsage_1 = class ExtendedKeyUsage extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, ExtendedKeyUsage_1.prototype);
}
};
exports.ExtendedKeyUsage = ExtendedKeyUsage;
exports.ExtendedKeyUsage = ExtendedKeyUsage = ExtendedKeyUsage_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: asn1_schema_1.AsnPropTypes.ObjectIdentifier
})], ExtendedKeyUsage);
exports.anyExtendedKeyUsage = `${exports.id_ce_extKeyUsage}.0`;
exports.id_kp_serverAuth = `${object_identifiers_1.id_kp}.1`;
exports.id_kp_clientAuth = `${object_identifiers_1.id_kp}.2`;
exports.id_kp_codeSigning = `${object_identifiers_1.id_kp}.3`;
exports.id_kp_emailProtection = `${object_identifiers_1.id_kp}.4`;
exports.id_kp_timeStamping = `${object_identifiers_1.id_kp}.8`;
exports.id_kp_OCSPSigning = `${object_identifiers_1.id_kp}.9`;
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/inhibit_any_policy.js
var require_inhibit_any_policy = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.InhibitAnyPolicy = exports.id_ce_inhibitAnyPolicy = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
exports.id_ce_inhibitAnyPolicy = `${require_object_identifiers$5().id_ce}.54`;
let InhibitAnyPolicy = class InhibitAnyPolicy {
value;
constructor(value = /* @__PURE__ */ new ArrayBuffer(0)) {
this.value = value;
}
};
exports.InhibitAnyPolicy = InhibitAnyPolicy;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], InhibitAnyPolicy.prototype, "value", void 0);
exports.InhibitAnyPolicy = InhibitAnyPolicy = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], InhibitAnyPolicy);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/invalidity_date.js
var require_invalidity_date = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.InvalidityDate = exports.id_ce_invalidityDate = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
exports.id_ce_invalidityDate = `${require_object_identifiers$5().id_ce}.24`;
let InvalidityDate = class InvalidityDate {
value = /* @__PURE__ */ new Date();
constructor(value) {
if (value) this.value = value;
}
};
exports.InvalidityDate = InvalidityDate;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.GeneralizedTime })], InvalidityDate.prototype, "value", void 0);
exports.InvalidityDate = InvalidityDate = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], InvalidityDate);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/issuer_alternative_name.js
var require_issuer_alternative_name = /* @__PURE__ */ __commonJSMin(((exports) => {
var IssueAlternativeName_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.IssueAlternativeName = exports.id_ce_issuerAltName = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const general_names_1 = require_general_names();
exports.id_ce_issuerAltName = `${require_object_identifiers$5().id_ce}.18`;
let IssueAlternativeName = IssueAlternativeName_1 = class IssueAlternativeName extends general_names_1.GeneralNames {
constructor(items) {
super(items);
Object.setPrototypeOf(this, IssueAlternativeName_1.prototype);
}
};
exports.IssueAlternativeName = IssueAlternativeName;
exports.IssueAlternativeName = IssueAlternativeName = IssueAlternativeName_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], IssueAlternativeName);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/key_usage.js
var require_key_usage = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeyUsage = exports.KeyUsageFlags = exports.id_ce_keyUsage = void 0;
const asn1_schema_1 = require_cjs$10();
exports.id_ce_keyUsage = `${require_object_identifiers$5().id_ce}.15`;
var KeyUsageFlags;
(function(KeyUsageFlags) {
KeyUsageFlags[KeyUsageFlags["digitalSignature"] = 1] = "digitalSignature";
KeyUsageFlags[KeyUsageFlags["nonRepudiation"] = 2] = "nonRepudiation";
KeyUsageFlags[KeyUsageFlags["keyEncipherment"] = 4] = "keyEncipherment";
KeyUsageFlags[KeyUsageFlags["dataEncipherment"] = 8] = "dataEncipherment";
KeyUsageFlags[KeyUsageFlags["keyAgreement"] = 16] = "keyAgreement";
KeyUsageFlags[KeyUsageFlags["keyCertSign"] = 32] = "keyCertSign";
KeyUsageFlags[KeyUsageFlags["cRLSign"] = 64] = "cRLSign";
KeyUsageFlags[KeyUsageFlags["encipherOnly"] = 128] = "encipherOnly";
KeyUsageFlags[KeyUsageFlags["decipherOnly"] = 256] = "decipherOnly";
})(KeyUsageFlags || (exports.KeyUsageFlags = KeyUsageFlags = {}));
var KeyUsage = class extends asn1_schema_1.BitString {
toJSON() {
const flag = this.toNumber();
const res = [];
if (flag & KeyUsageFlags.cRLSign) res.push("crlSign");
if (flag & KeyUsageFlags.dataEncipherment) res.push("dataEncipherment");
if (flag & KeyUsageFlags.decipherOnly) res.push("decipherOnly");
if (flag & KeyUsageFlags.digitalSignature) res.push("digitalSignature");
if (flag & KeyUsageFlags.encipherOnly) res.push("encipherOnly");
if (flag & KeyUsageFlags.keyAgreement) res.push("keyAgreement");
if (flag & KeyUsageFlags.keyCertSign) res.push("keyCertSign");
if (flag & KeyUsageFlags.keyEncipherment) res.push("keyEncipherment");
if (flag & KeyUsageFlags.nonRepudiation) res.push("nonRepudiation");
return res;
}
toString() {
return `[${this.toJSON().join(", ")}]`;
}
};
exports.KeyUsage = KeyUsage;
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/name_constraints.js
var require_name_constraints = /* @__PURE__ */ __commonJSMin(((exports) => {
var GeneralSubtrees_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.NameConstraints = exports.GeneralSubtrees = exports.GeneralSubtree = exports.id_ce_nameConstraints = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const general_name_1 = require_general_name();
exports.id_ce_nameConstraints = `${require_object_identifiers$5().id_ce}.30`;
var GeneralSubtree = class {
base = new general_name_1.GeneralName();
minimum = 0;
maximum;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.GeneralSubtree = GeneralSubtree;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: general_name_1.GeneralName })], GeneralSubtree.prototype, "base", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
context: 0,
defaultValue: 0,
implicit: true
})], GeneralSubtree.prototype, "minimum", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
context: 1,
optional: true,
implicit: true
})], GeneralSubtree.prototype, "maximum", void 0);
let GeneralSubtrees = GeneralSubtrees_1 = class GeneralSubtrees extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, GeneralSubtrees_1.prototype);
}
};
exports.GeneralSubtrees = GeneralSubtrees;
exports.GeneralSubtrees = GeneralSubtrees = GeneralSubtrees_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: GeneralSubtree
})], GeneralSubtrees);
var NameConstraints = class {
permittedSubtrees;
excludedSubtrees;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.NameConstraints = NameConstraints;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: GeneralSubtrees,
context: 0,
optional: true,
implicit: true
})], NameConstraints.prototype, "permittedSubtrees", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: GeneralSubtrees,
context: 1,
optional: true,
implicit: true
})], NameConstraints.prototype, "excludedSubtrees", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/policy_constraints.js
var require_policy_constraints = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.PolicyConstraints = exports.id_ce_policyConstraints = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
exports.id_ce_policyConstraints = `${require_object_identifiers$5().id_ce}.36`;
var PolicyConstraints = class {
requireExplicitPolicy;
inhibitPolicyMapping;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.PolicyConstraints = PolicyConstraints;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
context: 0,
implicit: true,
optional: true,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], PolicyConstraints.prototype, "requireExplicitPolicy", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
context: 1,
implicit: true,
optional: true,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], PolicyConstraints.prototype, "inhibitPolicyMapping", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/policy_mappings.js
var require_policy_mappings = /* @__PURE__ */ __commonJSMin(((exports) => {
var PolicyMappings_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PolicyMappings = exports.PolicyMapping = exports.id_ce_policyMappings = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
exports.id_ce_policyMappings = `${require_object_identifiers$5().id_ce}.33`;
var PolicyMapping = class {
issuerDomainPolicy = "";
subjectDomainPolicy = "";
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.PolicyMapping = PolicyMapping;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], PolicyMapping.prototype, "issuerDomainPolicy", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], PolicyMapping.prototype, "subjectDomainPolicy", void 0);
let PolicyMappings = PolicyMappings_1 = class PolicyMappings extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, PolicyMappings_1.prototype);
}
};
exports.PolicyMappings = PolicyMappings;
exports.PolicyMappings = PolicyMappings = PolicyMappings_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: PolicyMapping
})], PolicyMappings);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/subject_alternative_name.js
var require_subject_alternative_name = /* @__PURE__ */ __commonJSMin(((exports) => {
var SubjectAlternativeName_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SubjectAlternativeName = exports.id_ce_subjectAltName = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const general_names_1 = require_general_names();
exports.id_ce_subjectAltName = `${require_object_identifiers$5().id_ce}.17`;
let SubjectAlternativeName = SubjectAlternativeName_1 = class SubjectAlternativeName extends general_names_1.GeneralNames {
constructor(items) {
super(items);
Object.setPrototypeOf(this, SubjectAlternativeName_1.prototype);
}
};
exports.SubjectAlternativeName = SubjectAlternativeName;
exports.SubjectAlternativeName = SubjectAlternativeName = SubjectAlternativeName_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], SubjectAlternativeName);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/attribute.js
var require_attribute$2 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Attribute = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
var Attribute = class {
type = "";
values = [];
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.Attribute = Attribute;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], Attribute.prototype, "type", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Any,
repeated: "set"
})], Attribute.prototype, "values", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/subject_directory_attributes.js
var require_subject_directory_attributes = /* @__PURE__ */ __commonJSMin(((exports) => {
var SubjectDirectoryAttributes_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SubjectDirectoryAttributes = exports.id_ce_subjectDirectoryAttributes = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const attribute_1 = require_attribute$2();
exports.id_ce_subjectDirectoryAttributes = `${require_object_identifiers$5().id_ce}.9`;
let SubjectDirectoryAttributes = SubjectDirectoryAttributes_1 = class SubjectDirectoryAttributes extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, SubjectDirectoryAttributes_1.prototype);
}
};
exports.SubjectDirectoryAttributes = SubjectDirectoryAttributes;
exports.SubjectDirectoryAttributes = SubjectDirectoryAttributes = SubjectDirectoryAttributes_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: attribute_1.Attribute
})], SubjectDirectoryAttributes);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/subject_key_identifier.js
var require_subject_key_identifier = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.SubjectKeyIdentifier = exports.id_ce_subjectKeyIdentifier = void 0;
const object_identifiers_1 = require_object_identifiers$5();
const authority_key_identifier_1 = require_authority_key_identifier();
exports.id_ce_subjectKeyIdentifier = `${object_identifiers_1.id_ce}.14`;
var SubjectKeyIdentifier = class extends authority_key_identifier_1.KeyIdentifier {};
exports.SubjectKeyIdentifier = SubjectKeyIdentifier;
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/private_key_usage_period.js
var require_private_key_usage_period = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.PrivateKeyUsagePeriod = exports.id_ce_privateKeyUsagePeriod = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
exports.id_ce_privateKeyUsagePeriod = `${require_object_identifiers$5().id_ce}.16`;
var PrivateKeyUsagePeriod = class {
notBefore;
notAfter;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.PrivateKeyUsagePeriod = PrivateKeyUsagePeriod;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.GeneralizedTime,
context: 0,
implicit: true,
optional: true
})], PrivateKeyUsagePeriod.prototype, "notBefore", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.GeneralizedTime,
context: 1,
implicit: true,
optional: true
})], PrivateKeyUsagePeriod.prototype, "notAfter", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/entrust_version_info.js
var require_entrust_version_info = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.EntrustVersionInfo = exports.EntrustInfo = exports.EntrustInfoFlags = exports.id_entrust_entrustVersInfo = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
exports.id_entrust_entrustVersInfo = "1.2.840.113533.7.65.0";
var EntrustInfoFlags;
(function(EntrustInfoFlags) {
EntrustInfoFlags[EntrustInfoFlags["keyUpdateAllowed"] = 1] = "keyUpdateAllowed";
EntrustInfoFlags[EntrustInfoFlags["newExtensions"] = 2] = "newExtensions";
EntrustInfoFlags[EntrustInfoFlags["pKIXCertificate"] = 4] = "pKIXCertificate";
})(EntrustInfoFlags || (exports.EntrustInfoFlags = EntrustInfoFlags = {}));
var EntrustInfo = class extends asn1_schema_1.BitString {
toJSON() {
const res = [];
const flags = this.toNumber();
if (flags & EntrustInfoFlags.pKIXCertificate) res.push("pKIXCertificate");
if (flags & EntrustInfoFlags.newExtensions) res.push("newExtensions");
if (flags & EntrustInfoFlags.keyUpdateAllowed) res.push("keyUpdateAllowed");
return res;
}
toString() {
return `[${this.toJSON().join(", ")}]`;
}
};
exports.EntrustInfo = EntrustInfo;
var EntrustVersionInfo = class {
entrustVers = "";
entrustInfoFlags = new EntrustInfo();
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.EntrustVersionInfo = EntrustVersionInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.GeneralString })], EntrustVersionInfo.prototype, "entrustVers", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: EntrustInfo })], EntrustVersionInfo.prototype, "entrustInfoFlags", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/subject_info_access.js
var require_subject_info_access = /* @__PURE__ */ __commonJSMin(((exports) => {
var SubjectInfoAccessSyntax_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SubjectInfoAccessSyntax = exports.id_pe_subjectInfoAccess = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const object_identifiers_1 = require_object_identifiers$5();
const authority_information_access_1 = require_authority_information_access();
exports.id_pe_subjectInfoAccess = `${object_identifiers_1.id_pe}.11`;
let SubjectInfoAccessSyntax = SubjectInfoAccessSyntax_1 = class SubjectInfoAccessSyntax extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, SubjectInfoAccessSyntax_1.prototype);
}
};
exports.SubjectInfoAccessSyntax = SubjectInfoAccessSyntax;
exports.SubjectInfoAccessSyntax = SubjectInfoAccessSyntax = SubjectInfoAccessSyntax_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: authority_information_access_1.AccessDescription
})], SubjectInfoAccessSyntax);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extensions/index.js
var require_extensions = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
tslib_1.__exportStar(require_authority_information_access(), exports);
tslib_1.__exportStar(require_authority_key_identifier(), exports);
tslib_1.__exportStar(require_basic_constraints(), exports);
tslib_1.__exportStar(require_certificate_issuer(), exports);
tslib_1.__exportStar(require_certificate_policies(), exports);
tslib_1.__exportStar(require_crl_delta_indicator(), exports);
tslib_1.__exportStar(require_crl_distribution_points(), exports);
tslib_1.__exportStar(require_crl_freshest(), exports);
tslib_1.__exportStar(require_crl_issuing_distribution_point(), exports);
tslib_1.__exportStar(require_crl_number(), exports);
tslib_1.__exportStar(require_crl_reason(), exports);
tslib_1.__exportStar(require_extended_key_usage(), exports);
tslib_1.__exportStar(require_inhibit_any_policy(), exports);
tslib_1.__exportStar(require_invalidity_date(), exports);
tslib_1.__exportStar(require_issuer_alternative_name(), exports);
tslib_1.__exportStar(require_key_usage(), exports);
tslib_1.__exportStar(require_name_constraints(), exports);
tslib_1.__exportStar(require_policy_constraints(), exports);
tslib_1.__exportStar(require_policy_mappings(), exports);
tslib_1.__exportStar(require_subject_alternative_name(), exports);
tslib_1.__exportStar(require_subject_directory_attributes(), exports);
tslib_1.__exportStar(require_subject_key_identifier(), exports);
tslib_1.__exportStar(require_private_key_usage_period(), exports);
tslib_1.__exportStar(require_entrust_version_info(), exports);
tslib_1.__exportStar(require_subject_info_access(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/algorithm_identifier.js
var require_algorithm_identifier = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.AlgorithmIdentifier = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const bytes_1 = require_bytes();
var AlgorithmIdentifier = class AlgorithmIdentifier {
algorithm = "";
parameters;
constructor(params = {}) {
Object.assign(this, params);
}
isEqual(data) {
return data instanceof AlgorithmIdentifier && data.algorithm == this.algorithm && (data.parameters && this.parameters && (0, bytes_1.equal)(data.parameters, this.parameters) || data.parameters === this.parameters);
}
};
exports.AlgorithmIdentifier = AlgorithmIdentifier;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], AlgorithmIdentifier.prototype, "algorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Any,
optional: true
})], AlgorithmIdentifier.prototype, "parameters", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/subject_public_key_info.js
var require_subject_public_key_info = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.SubjectPublicKeyInfo = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const algorithm_identifier_1 = require_algorithm_identifier();
var SubjectPublicKeyInfo = class {
algorithm = new algorithm_identifier_1.AlgorithmIdentifier();
subjectPublicKey = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.SubjectPublicKeyInfo = SubjectPublicKeyInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: algorithm_identifier_1.AlgorithmIdentifier })], SubjectPublicKeyInfo.prototype, "algorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.BitString })], SubjectPublicKeyInfo.prototype, "subjectPublicKey", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/time.js
var require_time = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Time = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
let Time = class Time {
utcTime;
generalTime;
constructor(time) {
if (time) {
if (typeof time === "string" || typeof time === "number" || time instanceof Date) {
const date = new Date(time);
date.setMilliseconds(0);
if (date.getUTCFullYear() > 2049) this.generalTime = date;
else this.utcTime = date;
} else Object.assign(this, time);
}
}
getTime() {
const time = this.utcTime || this.generalTime;
if (!time) throw new Error("Cannot get time from CHOICE object");
return time;
}
};
exports.Time = Time;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.UTCTime })], Time.prototype, "utcTime", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.GeneralizedTime })], Time.prototype, "generalTime", void 0);
exports.Time = Time = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], Time);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/validity.js
var require_validity = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Validity = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const time_1 = require_time();
var Validity = class {
notBefore = new time_1.Time(/* @__PURE__ */ new Date());
notAfter = new time_1.Time(/* @__PURE__ */ new Date());
constructor(params) {
if (params) {
this.notBefore = new time_1.Time(params.notBefore);
this.notAfter = new time_1.Time(params.notAfter);
}
}
};
exports.Validity = Validity;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: time_1.Time })], Validity.prototype, "notBefore", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: time_1.Time })], Validity.prototype, "notAfter", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/extension.js
var require_extension = /* @__PURE__ */ __commonJSMin(((exports) => {
var Extensions_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Extensions = exports.Extension = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
var Extension = class Extension {
static CRITICAL = false;
extnID = "";
critical = Extension.CRITICAL;
extnValue = new asn1_schema_1.OctetString();
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.Extension = Extension;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], Extension.prototype, "extnID", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Boolean,
defaultValue: Extension.CRITICAL
})], Extension.prototype, "critical", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.OctetString })], Extension.prototype, "extnValue", void 0);
let Extensions = Extensions_1 = class Extensions extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, Extensions_1.prototype);
}
};
exports.Extensions = Extensions;
exports.Extensions = Extensions = Extensions_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: Extension
})], Extensions);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/types.js
var require_types$4 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Version = void 0;
var Version;
(function(Version) {
Version[Version["v1"] = 0] = "v1";
Version[Version["v2"] = 1] = "v2";
Version[Version["v3"] = 2] = "v3";
})(Version || (exports.Version = Version = {}));
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/tbs_certificate.js
var require_tbs_certificate = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.TBSCertificate = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const algorithm_identifier_1 = require_algorithm_identifier();
const name_1 = require_name();
const subject_public_key_info_1 = require_subject_public_key_info();
const validity_1 = require_validity();
const extension_1 = require_extension();
const types_1 = require_types$4();
var TBSCertificate = class {
version = types_1.Version.v1;
serialNumber = /* @__PURE__ */ new ArrayBuffer(0);
signature = new algorithm_identifier_1.AlgorithmIdentifier();
issuer = new name_1.Name();
validity = new validity_1.Validity();
subject = new name_1.Name();
subjectPublicKeyInfo = new subject_public_key_info_1.SubjectPublicKeyInfo();
issuerUniqueID;
subjectUniqueID;
extensions;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.TBSCertificate = TBSCertificate;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
context: 0,
defaultValue: types_1.Version.v1
})], TBSCertificate.prototype, "version", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], TBSCertificate.prototype, "serialNumber", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: algorithm_identifier_1.AlgorithmIdentifier })], TBSCertificate.prototype, "signature", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: name_1.Name })], TBSCertificate.prototype, "issuer", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: validity_1.Validity })], TBSCertificate.prototype, "validity", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: name_1.Name })], TBSCertificate.prototype, "subject", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: subject_public_key_info_1.SubjectPublicKeyInfo })], TBSCertificate.prototype, "subjectPublicKeyInfo", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.BitString,
context: 1,
implicit: true,
optional: true
})], TBSCertificate.prototype, "issuerUniqueID", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.BitString,
context: 2,
implicit: true,
optional: true
})], TBSCertificate.prototype, "subjectUniqueID", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: extension_1.Extensions,
context: 3,
optional: true
})], TBSCertificate.prototype, "extensions", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/certificate.js
var require_certificate = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Certificate = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const algorithm_identifier_1 = require_algorithm_identifier();
const tbs_certificate_1 = require_tbs_certificate();
var Certificate = class {
tbsCertificate = new tbs_certificate_1.TBSCertificate();
tbsCertificateRaw;
signatureAlgorithm = new algorithm_identifier_1.AlgorithmIdentifier();
signatureValue = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.Certificate = Certificate;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: tbs_certificate_1.TBSCertificate,
raw: true
})], Certificate.prototype, "tbsCertificate", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: algorithm_identifier_1.AlgorithmIdentifier })], Certificate.prototype, "signatureAlgorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.BitString })], Certificate.prototype, "signatureValue", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/tbs_cert_list.js
var require_tbs_cert_list = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.TBSCertList = exports.RevokedCertificate = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const algorithm_identifier_1 = require_algorithm_identifier();
const name_1 = require_name();
const time_1 = require_time();
const extension_1 = require_extension();
var RevokedCertificate = class {
userCertificate = /* @__PURE__ */ new ArrayBuffer(0);
revocationDate = new time_1.Time();
crlEntryExtensions;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.RevokedCertificate = RevokedCertificate;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], RevokedCertificate.prototype, "userCertificate", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: time_1.Time })], RevokedCertificate.prototype, "revocationDate", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: extension_1.Extension,
optional: true,
repeated: "sequence"
})], RevokedCertificate.prototype, "crlEntryExtensions", void 0);
var TBSCertList = class {
version;
signature = new algorithm_identifier_1.AlgorithmIdentifier();
issuer = new name_1.Name();
thisUpdate = new time_1.Time();
nextUpdate;
revokedCertificates;
crlExtensions;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.TBSCertList = TBSCertList;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
optional: true
})], TBSCertList.prototype, "version", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: algorithm_identifier_1.AlgorithmIdentifier })], TBSCertList.prototype, "signature", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: name_1.Name })], TBSCertList.prototype, "issuer", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: time_1.Time })], TBSCertList.prototype, "thisUpdate", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: time_1.Time,
optional: true
})], TBSCertList.prototype, "nextUpdate", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: RevokedCertificate,
repeated: "sequence",
optional: true
})], TBSCertList.prototype, "revokedCertificates", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: extension_1.Extension,
optional: true,
context: 0,
repeated: "sequence"
})], TBSCertList.prototype, "crlExtensions", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/certificate_list.js
var require_certificate_list = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.CertificateList = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const algorithm_identifier_1 = require_algorithm_identifier();
const tbs_cert_list_1 = require_tbs_cert_list();
var CertificateList = class {
tbsCertList = new tbs_cert_list_1.TBSCertList();
tbsCertListRaw;
signatureAlgorithm = new algorithm_identifier_1.AlgorithmIdentifier();
signature = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.CertificateList = CertificateList;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: tbs_cert_list_1.TBSCertList,
raw: true
})], CertificateList.prototype, "tbsCertList", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: algorithm_identifier_1.AlgorithmIdentifier })], CertificateList.prototype, "signatureAlgorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.BitString })], CertificateList.prototype, "signature", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509@2.9.4/node_modules/@peculiar/asn1-x509/build/cjs/index.js
var require_cjs$9 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
tslib_1.__exportStar(require_extensions(), exports);
tslib_1.__exportStar(require_algorithm_identifier(), exports);
tslib_1.__exportStar(require_attribute$2(), exports);
tslib_1.__exportStar(require_certificate(), exports);
tslib_1.__exportStar(require_certificate_list(), exports);
tslib_1.__exportStar(require_extension(), exports);
tslib_1.__exportStar(require_general_name(), exports);
tslib_1.__exportStar(require_general_names(), exports);
tslib_1.__exportStar(require_name(), exports);
tslib_1.__exportStar(require_object_identifiers$5(), exports);
tslib_1.__exportStar(require_subject_public_key_info(), exports);
tslib_1.__exportStar(require_tbs_cert_list(), exports);
tslib_1.__exportStar(require_tbs_certificate(), exports);
tslib_1.__exportStar(require_time(), exports);
tslib_1.__exportStar(require_types$4(), exports);
tslib_1.__exportStar(require_validity(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/issuer_and_serial_number.js
var require_issuer_and_serial_number = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.IssuerAndSerialNumber = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
var IssuerAndSerialNumber = class {
issuer = new asn1_x509_1.Name();
serialNumber = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.IssuerAndSerialNumber = IssuerAndSerialNumber;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_x509_1.Name })], IssuerAndSerialNumber.prototype, "issuer", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], IssuerAndSerialNumber.prototype, "serialNumber", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/signer_identifier.js
var require_signer_identifier = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.SignerIdentifier = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
const issuer_and_serial_number_1 = require_issuer_and_serial_number();
let SignerIdentifier = class SignerIdentifier {
subjectKeyIdentifier;
issuerAndSerialNumber;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.SignerIdentifier = SignerIdentifier;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_1.SubjectKeyIdentifier,
context: 0,
implicit: true
})], SignerIdentifier.prototype, "subjectKeyIdentifier", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: issuer_and_serial_number_1.IssuerAndSerialNumber })], SignerIdentifier.prototype, "issuerAndSerialNumber", void 0);
exports.SignerIdentifier = SignerIdentifier = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], SignerIdentifier);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/types.js
var require_types$3 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeyDerivationAlgorithmIdentifier = exports.MessageAuthenticationCodeAlgorithm = exports.ContentEncryptionAlgorithmIdentifier = exports.KeyEncryptionAlgorithmIdentifier = exports.SignatureAlgorithmIdentifier = exports.DigestAlgorithmIdentifier = exports.CMSVersion = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_x509_1 = require_cjs$9();
const asn1_schema_1 = require_cjs$10();
var CMSVersion;
(function(CMSVersion) {
CMSVersion[CMSVersion["v0"] = 0] = "v0";
CMSVersion[CMSVersion["v1"] = 1] = "v1";
CMSVersion[CMSVersion["v2"] = 2] = "v2";
CMSVersion[CMSVersion["v3"] = 3] = "v3";
CMSVersion[CMSVersion["v4"] = 4] = "v4";
CMSVersion[CMSVersion["v5"] = 5] = "v5";
})(CMSVersion || (exports.CMSVersion = CMSVersion = {}));
let DigestAlgorithmIdentifier = class DigestAlgorithmIdentifier extends asn1_x509_1.AlgorithmIdentifier {};
exports.DigestAlgorithmIdentifier = DigestAlgorithmIdentifier;
exports.DigestAlgorithmIdentifier = DigestAlgorithmIdentifier = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], DigestAlgorithmIdentifier);
let SignatureAlgorithmIdentifier = class SignatureAlgorithmIdentifier extends asn1_x509_1.AlgorithmIdentifier {};
exports.SignatureAlgorithmIdentifier = SignatureAlgorithmIdentifier;
exports.SignatureAlgorithmIdentifier = SignatureAlgorithmIdentifier = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], SignatureAlgorithmIdentifier);
let KeyEncryptionAlgorithmIdentifier = class KeyEncryptionAlgorithmIdentifier extends asn1_x509_1.AlgorithmIdentifier {};
exports.KeyEncryptionAlgorithmIdentifier = KeyEncryptionAlgorithmIdentifier;
exports.KeyEncryptionAlgorithmIdentifier = KeyEncryptionAlgorithmIdentifier = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], KeyEncryptionAlgorithmIdentifier);
let ContentEncryptionAlgorithmIdentifier = class ContentEncryptionAlgorithmIdentifier extends asn1_x509_1.AlgorithmIdentifier {};
exports.ContentEncryptionAlgorithmIdentifier = ContentEncryptionAlgorithmIdentifier;
exports.ContentEncryptionAlgorithmIdentifier = ContentEncryptionAlgorithmIdentifier = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], ContentEncryptionAlgorithmIdentifier);
let MessageAuthenticationCodeAlgorithm = class MessageAuthenticationCodeAlgorithm extends asn1_x509_1.AlgorithmIdentifier {};
exports.MessageAuthenticationCodeAlgorithm = MessageAuthenticationCodeAlgorithm;
exports.MessageAuthenticationCodeAlgorithm = MessageAuthenticationCodeAlgorithm = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], MessageAuthenticationCodeAlgorithm);
let KeyDerivationAlgorithmIdentifier = class KeyDerivationAlgorithmIdentifier extends asn1_x509_1.AlgorithmIdentifier {};
exports.KeyDerivationAlgorithmIdentifier = KeyDerivationAlgorithmIdentifier;
exports.KeyDerivationAlgorithmIdentifier = KeyDerivationAlgorithmIdentifier = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], KeyDerivationAlgorithmIdentifier);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/attribute.js
var require_attribute$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Attribute = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
var Attribute = class {
attrType = "";
attrValues = [];
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.Attribute = Attribute;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], Attribute.prototype, "attrType", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Any,
repeated: "set"
})], Attribute.prototype, "attrValues", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/signer_info.js
var require_signer_info = /* @__PURE__ */ __commonJSMin(((exports) => {
var SignerInfos_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SignerInfos = exports.SignerInfo = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const signer_identifier_1 = require_signer_identifier();
const types_1 = require_types$3();
const attribute_1 = require_attribute$1();
var SignerInfo = class {
version = types_1.CMSVersion.v0;
sid = new signer_identifier_1.SignerIdentifier();
digestAlgorithm = new types_1.DigestAlgorithmIdentifier();
signedAttrs;
signedAttrsRaw;
signatureAlgorithm = new types_1.SignatureAlgorithmIdentifier();
signature = new asn1_schema_1.OctetString();
unsignedAttrs;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.SignerInfo = SignerInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Integer })], SignerInfo.prototype, "version", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: signer_identifier_1.SignerIdentifier })], SignerInfo.prototype, "sid", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: types_1.DigestAlgorithmIdentifier })], SignerInfo.prototype, "digestAlgorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: attribute_1.Attribute,
repeated: "set",
context: 0,
implicit: true,
optional: true,
raw: true
})], SignerInfo.prototype, "signedAttrs", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: types_1.SignatureAlgorithmIdentifier })], SignerInfo.prototype, "signatureAlgorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.OctetString })], SignerInfo.prototype, "signature", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: attribute_1.Attribute,
repeated: "set",
context: 1,
implicit: true,
optional: true
})], SignerInfo.prototype, "unsignedAttrs", void 0);
let SignerInfos = SignerInfos_1 = class SignerInfos extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, SignerInfos_1.prototype);
}
};
exports.SignerInfos = SignerInfos;
exports.SignerInfos = SignerInfos = SignerInfos_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Set,
itemType: SignerInfo
})], SignerInfos);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/attributes/counter_signature.js
var require_counter_signature = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.CounterSignature = exports.id_counterSignature = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const signer_info_1 = require_signer_info();
exports.id_counterSignature = "1.2.840.113549.1.9.6";
let CounterSignature = class CounterSignature extends signer_info_1.SignerInfo {};
exports.CounterSignature = CounterSignature;
exports.CounterSignature = CounterSignature = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], CounterSignature);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/attributes/message_digest.js
var require_message_digest = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.MessageDigest = exports.id_messageDigest = void 0;
const asn1_schema_1 = require_cjs$10();
exports.id_messageDigest = "1.2.840.113549.1.9.4";
var MessageDigest = class extends asn1_schema_1.OctetString {};
exports.MessageDigest = MessageDigest;
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/attributes/signing_time.js
var require_signing_time = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.SigningTime = exports.id_signingTime = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_x509_1 = require_cjs$9();
const asn1_schema_1 = require_cjs$10();
exports.id_signingTime = "1.2.840.113549.1.9.5";
let SigningTime = class SigningTime extends asn1_x509_1.Time {};
exports.SigningTime = SigningTime;
exports.SigningTime = SigningTime = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], SigningTime);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/attributes/index.js
var require_attributes$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.id_contentType = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
tslib_1.__exportStar(require_counter_signature(), exports);
tslib_1.__exportStar(require_message_digest(), exports);
tslib_1.__exportStar(require_signing_time(), exports);
exports.id_contentType = "1.2.840.113549.1.9.3";
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/aa_clear_attrs.js
var require_aa_clear_attrs = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ACClearAttrs = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
var ACClearAttrs = class {
acIssuer = new asn1_x509_1.GeneralName();
acSerial = 0;
attrs = [];
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.ACClearAttrs = ACClearAttrs;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_x509_1.GeneralName })], ACClearAttrs.prototype, "acIssuer", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Integer })], ACClearAttrs.prototype, "acSerial", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_1.Attribute,
repeated: "sequence"
})], ACClearAttrs.prototype, "attrs", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/attr_spec.js
var require_attr_spec = /* @__PURE__ */ __commonJSMin(((exports) => {
var AttrSpec_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AttrSpec = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
let AttrSpec = AttrSpec_1 = class AttrSpec extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, AttrSpec_1.prototype);
}
};
exports.AttrSpec = AttrSpec;
exports.AttrSpec = AttrSpec = AttrSpec_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: asn1_schema_1.AsnPropTypes.ObjectIdentifier
})], AttrSpec);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/aa_controls.js
var require_aa_controls = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.AAControls = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const attr_spec_1 = require_attr_spec();
var AAControls = class {
pathLenConstraint;
permittedAttrs;
excludedAttrs;
permitUnSpecified = true;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.AAControls = AAControls;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
optional: true
})], AAControls.prototype, "pathLenConstraint", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: attr_spec_1.AttrSpec,
implicit: true,
context: 0,
optional: true
})], AAControls.prototype, "permittedAttrs", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: attr_spec_1.AttrSpec,
implicit: true,
context: 1,
optional: true
})], AAControls.prototype, "excludedAttrs", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Boolean,
defaultValue: true
})], AAControls.prototype, "permitUnSpecified", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/issuer_serial.js
var require_issuer_serial = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.IssuerSerial = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
var IssuerSerial = class {
issuer = new asn1_x509_1.GeneralNames();
serial = /* @__PURE__ */ new ArrayBuffer(0);
issuerUID = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.IssuerSerial = IssuerSerial;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_x509_1.GeneralNames })], IssuerSerial.prototype, "issuer", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], IssuerSerial.prototype, "serial", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.BitString,
optional: true
})], IssuerSerial.prototype, "issuerUID", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/object_digest_info.js
var require_object_digest_info = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ObjectDigestInfo = exports.DigestedObjectType = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
var DigestedObjectType;
(function(DigestedObjectType) {
DigestedObjectType[DigestedObjectType["publicKey"] = 0] = "publicKey";
DigestedObjectType[DigestedObjectType["publicKeyCert"] = 1] = "publicKeyCert";
DigestedObjectType[DigestedObjectType["otherObjectTypes"] = 2] = "otherObjectTypes";
})(DigestedObjectType || (exports.DigestedObjectType = DigestedObjectType = {}));
var ObjectDigestInfo = class {
digestedObjectType = DigestedObjectType.publicKey;
otherObjectTypeID;
digestAlgorithm = new asn1_x509_1.AlgorithmIdentifier();
objectDigest = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.ObjectDigestInfo = ObjectDigestInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Enumerated })], ObjectDigestInfo.prototype, "digestedObjectType", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.ObjectIdentifier,
optional: true
})], ObjectDigestInfo.prototype, "otherObjectTypeID", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_x509_1.AlgorithmIdentifier })], ObjectDigestInfo.prototype, "digestAlgorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.BitString })], ObjectDigestInfo.prototype, "objectDigest", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/v2_form.js
var require_v2_form = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.V2Form = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
const issuer_serial_1 = require_issuer_serial();
const object_digest_info_1 = require_object_digest_info();
var V2Form = class {
issuerName;
baseCertificateID;
objectDigestInfo;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.V2Form = V2Form;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_1.GeneralNames,
optional: true
})], V2Form.prototype, "issuerName", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: issuer_serial_1.IssuerSerial,
context: 0,
implicit: true,
optional: true
})], V2Form.prototype, "baseCertificateID", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: object_digest_info_1.ObjectDigestInfo,
context: 1,
implicit: true,
optional: true
})], V2Form.prototype, "objectDigestInfo", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/attr_cert_issuer.js
var require_attr_cert_issuer = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.AttCertIssuer = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
const v2_form_1 = require_v2_form();
let AttCertIssuer = class AttCertIssuer {
v1Form;
v2Form;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.AttCertIssuer = AttCertIssuer;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_1.GeneralName,
repeated: "sequence"
})], AttCertIssuer.prototype, "v1Form", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: v2_form_1.V2Form,
context: 0,
implicit: true
})], AttCertIssuer.prototype, "v2Form", void 0);
exports.AttCertIssuer = AttCertIssuer = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], AttCertIssuer);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/attr_cert_validity_period.js
var require_attr_cert_validity_period = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.AttCertValidityPeriod = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
var AttCertValidityPeriod = class {
notBeforeTime = /* @__PURE__ */ new Date();
notAfterTime = /* @__PURE__ */ new Date();
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.AttCertValidityPeriod = AttCertValidityPeriod;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.GeneralizedTime })], AttCertValidityPeriod.prototype, "notBeforeTime", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.GeneralizedTime })], AttCertValidityPeriod.prototype, "notAfterTime", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/holder.js
var require_holder = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Holder = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
const issuer_serial_1 = require_issuer_serial();
const object_digest_info_1 = require_object_digest_info();
var Holder = class {
baseCertificateID;
entityName;
objectDigestInfo;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.Holder = Holder;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: issuer_serial_1.IssuerSerial,
implicit: true,
context: 0,
optional: true
})], Holder.prototype, "baseCertificateID", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_1.GeneralNames,
implicit: true,
context: 1,
optional: true
})], Holder.prototype, "entityName", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: object_digest_info_1.ObjectDigestInfo,
implicit: true,
context: 2,
optional: true
})], Holder.prototype, "objectDigestInfo", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/attribute_certificate_info.js
var require_attribute_certificate_info = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.AttributeCertificateInfo = exports.AttCertVersion = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
const holder_1 = require_holder();
const attr_cert_issuer_1 = require_attr_cert_issuer();
const attr_cert_validity_period_1 = require_attr_cert_validity_period();
var AttCertVersion;
(function(AttCertVersion) {
AttCertVersion[AttCertVersion["v2"] = 1] = "v2";
})(AttCertVersion || (exports.AttCertVersion = AttCertVersion = {}));
var AttributeCertificateInfo = class {
version = AttCertVersion.v2;
holder = new holder_1.Holder();
issuer = new attr_cert_issuer_1.AttCertIssuer();
signature = new asn1_x509_1.AlgorithmIdentifier();
serialNumber = /* @__PURE__ */ new ArrayBuffer(0);
attrCertValidityPeriod = new attr_cert_validity_period_1.AttCertValidityPeriod();
attributes = [];
issuerUniqueID;
extensions;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.AttributeCertificateInfo = AttributeCertificateInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Integer })], AttributeCertificateInfo.prototype, "version", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: holder_1.Holder })], AttributeCertificateInfo.prototype, "holder", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: attr_cert_issuer_1.AttCertIssuer })], AttributeCertificateInfo.prototype, "issuer", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_x509_1.AlgorithmIdentifier })], AttributeCertificateInfo.prototype, "signature", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], AttributeCertificateInfo.prototype, "serialNumber", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: attr_cert_validity_period_1.AttCertValidityPeriod })], AttributeCertificateInfo.prototype, "attrCertValidityPeriod", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_1.Attribute,
repeated: "sequence"
})], AttributeCertificateInfo.prototype, "attributes", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.BitString,
optional: true
})], AttributeCertificateInfo.prototype, "issuerUniqueID", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_1.Extensions,
optional: true
})], AttributeCertificateInfo.prototype, "extensions", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/attribute_certificate.js
var require_attribute_certificate = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.AttributeCertificate = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
const attribute_certificate_info_1 = require_attribute_certificate_info();
var AttributeCertificate = class {
acinfo = new attribute_certificate_info_1.AttributeCertificateInfo();
signatureAlgorithm = new asn1_x509_1.AlgorithmIdentifier();
signatureValue = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.AttributeCertificate = AttributeCertificate;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: attribute_certificate_info_1.AttributeCertificateInfo })], AttributeCertificate.prototype, "acinfo", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_x509_1.AlgorithmIdentifier })], AttributeCertificate.prototype, "signatureAlgorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.BitString })], AttributeCertificate.prototype, "signatureValue", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/class_list.js
var require_class_list = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClassList = exports.ClassListFlags = void 0;
const asn1_schema_1 = require_cjs$10();
var ClassListFlags;
(function(ClassListFlags) {
ClassListFlags[ClassListFlags["unmarked"] = 1] = "unmarked";
ClassListFlags[ClassListFlags["unclassified"] = 2] = "unclassified";
ClassListFlags[ClassListFlags["restricted"] = 4] = "restricted";
ClassListFlags[ClassListFlags["confidential"] = 8] = "confidential";
ClassListFlags[ClassListFlags["secret"] = 16] = "secret";
ClassListFlags[ClassListFlags["topSecret"] = 32] = "topSecret";
})(ClassListFlags || (exports.ClassListFlags = ClassListFlags = {}));
var ClassList = class extends asn1_schema_1.BitString {};
exports.ClassList = ClassList;
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/security_category.js
var require_security_category = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.SecurityCategory = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
var SecurityCategory = class {
type = "";
value = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.SecurityCategory = SecurityCategory;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.ObjectIdentifier,
implicit: true,
context: 0
})], SecurityCategory.prototype, "type", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Any,
implicit: true,
context: 1
})], SecurityCategory.prototype, "value", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/clearance.js
var require_clearance = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Clearance = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const class_list_1 = require_class_list();
const security_category_1 = require_security_category();
var Clearance = class {
policyId = "";
classList = new class_list_1.ClassList(class_list_1.ClassListFlags.unclassified);
securityCategories;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.Clearance = Clearance;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], Clearance.prototype, "policyId", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: class_list_1.ClassList,
defaultValue: new class_list_1.ClassList(class_list_1.ClassListFlags.unclassified)
})], Clearance.prototype, "classList", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: security_category_1.SecurityCategory,
repeated: "set"
})], Clearance.prototype, "securityCategories", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/ietf_attr_syntax.js
var require_ietf_attr_syntax = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.IetfAttrSyntax = exports.IetfAttrSyntaxValueChoices = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
var IetfAttrSyntaxValueChoices = class {
cotets;
oid;
string;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.IetfAttrSyntaxValueChoices = IetfAttrSyntaxValueChoices;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.OctetString })], IetfAttrSyntaxValueChoices.prototype, "cotets", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], IetfAttrSyntaxValueChoices.prototype, "oid", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Utf8String })], IetfAttrSyntaxValueChoices.prototype, "string", void 0);
var IetfAttrSyntax = class {
policyAuthority;
values = [];
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.IetfAttrSyntax = IetfAttrSyntax;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_1.GeneralNames,
implicit: true,
context: 0,
optional: true
})], IetfAttrSyntax.prototype, "policyAuthority", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: IetfAttrSyntaxValueChoices,
repeated: "sequence"
})], IetfAttrSyntax.prototype, "values", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/object_identifiers.js
var require_object_identifiers$4 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.id_at_clearance = exports.id_at_role = exports.id_at = exports.id_aca_encAttrs = exports.id_aca_group = exports.id_aca_chargingIdentity = exports.id_aca_accessIdentity = exports.id_aca_authenticationInfo = exports.id_aca = exports.id_ce_targetInformation = exports.id_pe_ac_proxying = exports.id_pe_aaControls = exports.id_pe_ac_auditIdentity = void 0;
const asn1_x509_1 = require_cjs$9();
exports.id_pe_ac_auditIdentity = `${asn1_x509_1.id_pe}.4`;
exports.id_pe_aaControls = `${asn1_x509_1.id_pe}.6`;
exports.id_pe_ac_proxying = `${asn1_x509_1.id_pe}.10`;
exports.id_ce_targetInformation = `${asn1_x509_1.id_ce}.55`;
exports.id_aca = `${asn1_x509_1.id_pkix}.10`;
exports.id_aca_authenticationInfo = `${exports.id_aca}.1`;
exports.id_aca_accessIdentity = `${exports.id_aca}.2`;
exports.id_aca_chargingIdentity = `${exports.id_aca}.3`;
exports.id_aca_group = `${exports.id_aca}.4`;
exports.id_aca_encAttrs = `${exports.id_aca}.6`;
exports.id_at = "2.5.4";
exports.id_at_role = `${exports.id_at}.72`;
exports.id_at_clearance = "2.5.1.5.55";
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/target.js
var require_target = /* @__PURE__ */ __commonJSMin(((exports) => {
var Targets_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Targets = exports.Target = exports.TargetCert = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
const issuer_serial_1 = require_issuer_serial();
const object_digest_info_1 = require_object_digest_info();
var TargetCert = class {
targetCertificate = new issuer_serial_1.IssuerSerial();
targetName;
certDigestInfo;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.TargetCert = TargetCert;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: issuer_serial_1.IssuerSerial })], TargetCert.prototype, "targetCertificate", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_1.GeneralName,
optional: true
})], TargetCert.prototype, "targetName", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: object_digest_info_1.ObjectDigestInfo,
optional: true
})], TargetCert.prototype, "certDigestInfo", void 0);
let Target = class Target {
targetName;
targetGroup;
targetCert;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.Target = Target;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_1.GeneralName,
context: 0,
implicit: true
})], Target.prototype, "targetName", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_1.GeneralName,
context: 1,
implicit: true
})], Target.prototype, "targetGroup", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: TargetCert,
context: 2,
implicit: true
})], Target.prototype, "targetCert", void 0);
exports.Target = Target = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], Target);
let Targets = Targets_1 = class Targets extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, Targets_1.prototype);
}
};
exports.Targets = Targets;
exports.Targets = Targets = Targets_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: Target
})], Targets);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/proxy_info.js
var require_proxy_info = /* @__PURE__ */ __commonJSMin(((exports) => {
var ProxyInfo_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProxyInfo = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const target_1 = require_target();
let ProxyInfo = ProxyInfo_1 = class ProxyInfo extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, ProxyInfo_1.prototype);
}
};
exports.ProxyInfo = ProxyInfo;
exports.ProxyInfo = ProxyInfo = ProxyInfo_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: target_1.Targets
})], ProxyInfo);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/role_syntax.js
var require_role_syntax = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.RoleSyntax = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
var RoleSyntax = class {
roleAuthority;
roleName;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.RoleSyntax = RoleSyntax;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_1.GeneralNames,
implicit: true,
context: 0,
optional: true
})], RoleSyntax.prototype, "roleAuthority", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_1.GeneralName,
implicit: true,
context: 1
})], RoleSyntax.prototype, "roleName", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/svce_auth_info.js
var require_svce_auth_info = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.SvceAuthInfo = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
var SvceAuthInfo = class {
service = new asn1_x509_1.GeneralName();
ident = new asn1_x509_1.GeneralName();
authInfo;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.SvceAuthInfo = SvceAuthInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_x509_1.GeneralName })], SvceAuthInfo.prototype, "service", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_x509_1.GeneralName })], SvceAuthInfo.prototype, "ident", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.OctetString,
optional: true
})], SvceAuthInfo.prototype, "authInfo", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-x509-attr@2.9.4/node_modules/@peculiar/asn1-x509-attr/build/cjs/index.js
var require_cjs$8 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
tslib_1.__exportStar(require_aa_clear_attrs(), exports);
tslib_1.__exportStar(require_aa_controls(), exports);
tslib_1.__exportStar(require_attr_cert_issuer(), exports);
tslib_1.__exportStar(require_attr_cert_validity_period(), exports);
tslib_1.__exportStar(require_attr_spec(), exports);
tslib_1.__exportStar(require_attribute_certificate(), exports);
tslib_1.__exportStar(require_attribute_certificate_info(), exports);
tslib_1.__exportStar(require_class_list(), exports);
tslib_1.__exportStar(require_clearance(), exports);
tslib_1.__exportStar(require_holder(), exports);
tslib_1.__exportStar(require_ietf_attr_syntax(), exports);
tslib_1.__exportStar(require_issuer_serial(), exports);
tslib_1.__exportStar(require_object_digest_info(), exports);
tslib_1.__exportStar(require_object_identifiers$4(), exports);
tslib_1.__exportStar(require_proxy_info(), exports);
tslib_1.__exportStar(require_role_syntax(), exports);
tslib_1.__exportStar(require_security_category(), exports);
tslib_1.__exportStar(require_svce_auth_info(), exports);
tslib_1.__exportStar(require_target(), exports);
tslib_1.__exportStar(require_v2_form(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/certificate_choices.js
var require_certificate_choices = /* @__PURE__ */ __commonJSMin(((exports) => {
var CertificateSet_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CertificateSet = exports.CertificateChoices = exports.OtherCertificateFormat = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
const asn1_x509_attr_1 = require_cjs$8();
var OtherCertificateFormat = class {
otherCertFormat = "";
otherCert = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.OtherCertificateFormat = OtherCertificateFormat;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], OtherCertificateFormat.prototype, "otherCertFormat", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Any })], OtherCertificateFormat.prototype, "otherCert", void 0);
let CertificateChoices = class CertificateChoices {
certificate;
v2AttrCert;
other;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.CertificateChoices = CertificateChoices;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_x509_1.Certificate })], CertificateChoices.prototype, "certificate", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_attr_1.AttributeCertificate,
context: 2,
implicit: true
})], CertificateChoices.prototype, "v2AttrCert", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: OtherCertificateFormat,
context: 3,
implicit: true
})], CertificateChoices.prototype, "other", void 0);
exports.CertificateChoices = CertificateChoices = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], CertificateChoices);
let CertificateSet = CertificateSet_1 = class CertificateSet extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, CertificateSet_1.prototype);
}
};
exports.CertificateSet = CertificateSet;
exports.CertificateSet = CertificateSet = CertificateSet_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Set,
itemType: CertificateChoices
})], CertificateSet);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/content_info.js
var require_content_info = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContentInfo = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
var ContentInfo = class {
contentType = "";
content = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.ContentInfo = ContentInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], ContentInfo.prototype, "contentType", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Any,
context: 0
})], ContentInfo.prototype, "content", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/encapsulated_content_info.js
var require_encapsulated_content_info = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.EncapsulatedContentInfo = exports.EncapsulatedContent = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
let EncapsulatedContent = class EncapsulatedContent {
single;
any;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.EncapsulatedContent = EncapsulatedContent;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.OctetString })], EncapsulatedContent.prototype, "single", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Any })], EncapsulatedContent.prototype, "any", void 0);
exports.EncapsulatedContent = EncapsulatedContent = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], EncapsulatedContent);
var EncapsulatedContentInfo = class {
eContentType = "";
eContent;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.EncapsulatedContentInfo = EncapsulatedContentInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], EncapsulatedContentInfo.prototype, "eContentType", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: EncapsulatedContent,
context: 0,
optional: true
})], EncapsulatedContentInfo.prototype, "eContent", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/encrypted_content_info.js
var require_encrypted_content_info = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.EncryptedContentInfo = exports.EncryptedContent = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const types_1 = require_types$3();
let EncryptedContent = class EncryptedContent {
value;
constructedValue;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.EncryptedContent = EncryptedContent;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.OctetString,
context: 0,
implicit: true,
optional: true
})], EncryptedContent.prototype, "value", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.OctetString,
converter: asn1_schema_1.AsnConstructedOctetStringConverter,
context: 0,
implicit: true,
optional: true,
repeated: "sequence"
})], EncryptedContent.prototype, "constructedValue", void 0);
exports.EncryptedContent = EncryptedContent = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], EncryptedContent);
var EncryptedContentInfo = class {
contentType = "";
contentEncryptionAlgorithm = new types_1.ContentEncryptionAlgorithmIdentifier();
encryptedContent;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.EncryptedContentInfo = EncryptedContentInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], EncryptedContentInfo.prototype, "contentType", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: types_1.ContentEncryptionAlgorithmIdentifier })], EncryptedContentInfo.prototype, "contentEncryptionAlgorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: EncryptedContent,
optional: true
})], EncryptedContentInfo.prototype, "encryptedContent", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/other_key_attribute.js
var require_other_key_attribute = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.OtherKeyAttribute = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
var OtherKeyAttribute = class {
keyAttrId = "";
keyAttr;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.OtherKeyAttribute = OtherKeyAttribute;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], OtherKeyAttribute.prototype, "keyAttrId", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Any,
optional: true
})], OtherKeyAttribute.prototype, "keyAttr", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/key_agree_recipient_info.js
var require_key_agree_recipient_info = /* @__PURE__ */ __commonJSMin(((exports) => {
var RecipientEncryptedKeys_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeyAgreeRecipientInfo = exports.OriginatorIdentifierOrKey = exports.OriginatorPublicKey = exports.RecipientEncryptedKeys = exports.RecipientEncryptedKey = exports.KeyAgreeRecipientIdentifier = exports.RecipientKeyIdentifier = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
const types_1 = require_types$3();
const issuer_and_serial_number_1 = require_issuer_and_serial_number();
const other_key_attribute_1 = require_other_key_attribute();
var RecipientKeyIdentifier = class {
subjectKeyIdentifier = new asn1_x509_1.SubjectKeyIdentifier();
date;
other;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.RecipientKeyIdentifier = RecipientKeyIdentifier;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_x509_1.SubjectKeyIdentifier })], RecipientKeyIdentifier.prototype, "subjectKeyIdentifier", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.GeneralizedTime,
optional: true
})], RecipientKeyIdentifier.prototype, "date", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: other_key_attribute_1.OtherKeyAttribute,
optional: true
})], RecipientKeyIdentifier.prototype, "other", void 0);
let KeyAgreeRecipientIdentifier = class KeyAgreeRecipientIdentifier {
rKeyId;
issuerAndSerialNumber;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.KeyAgreeRecipientIdentifier = KeyAgreeRecipientIdentifier;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: RecipientKeyIdentifier,
context: 0,
implicit: true,
optional: true
})], KeyAgreeRecipientIdentifier.prototype, "rKeyId", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: issuer_and_serial_number_1.IssuerAndSerialNumber,
optional: true
})], KeyAgreeRecipientIdentifier.prototype, "issuerAndSerialNumber", void 0);
exports.KeyAgreeRecipientIdentifier = KeyAgreeRecipientIdentifier = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], KeyAgreeRecipientIdentifier);
var RecipientEncryptedKey = class {
rid = new KeyAgreeRecipientIdentifier();
encryptedKey = new asn1_schema_1.OctetString();
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.RecipientEncryptedKey = RecipientEncryptedKey;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: KeyAgreeRecipientIdentifier })], RecipientEncryptedKey.prototype, "rid", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.OctetString })], RecipientEncryptedKey.prototype, "encryptedKey", void 0);
let RecipientEncryptedKeys = RecipientEncryptedKeys_1 = class RecipientEncryptedKeys extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, RecipientEncryptedKeys_1.prototype);
}
};
exports.RecipientEncryptedKeys = RecipientEncryptedKeys;
exports.RecipientEncryptedKeys = RecipientEncryptedKeys = RecipientEncryptedKeys_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: RecipientEncryptedKey
})], RecipientEncryptedKeys);
var OriginatorPublicKey = class {
algorithm = new asn1_x509_1.AlgorithmIdentifier();
publicKey = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.OriginatorPublicKey = OriginatorPublicKey;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_x509_1.AlgorithmIdentifier })], OriginatorPublicKey.prototype, "algorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.BitString })], OriginatorPublicKey.prototype, "publicKey", void 0);
let OriginatorIdentifierOrKey = class OriginatorIdentifierOrKey {
subjectKeyIdentifier;
originatorKey;
issuerAndSerialNumber;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.OriginatorIdentifierOrKey = OriginatorIdentifierOrKey;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_1.SubjectKeyIdentifier,
context: 0,
implicit: true,
optional: true
})], OriginatorIdentifierOrKey.prototype, "subjectKeyIdentifier", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: OriginatorPublicKey,
context: 1,
implicit: true,
optional: true
})], OriginatorIdentifierOrKey.prototype, "originatorKey", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: issuer_and_serial_number_1.IssuerAndSerialNumber,
optional: true
})], OriginatorIdentifierOrKey.prototype, "issuerAndSerialNumber", void 0);
exports.OriginatorIdentifierOrKey = OriginatorIdentifierOrKey = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], OriginatorIdentifierOrKey);
var KeyAgreeRecipientInfo = class {
version = types_1.CMSVersion.v3;
originator = new OriginatorIdentifierOrKey();
ukm;
keyEncryptionAlgorithm = new types_1.KeyEncryptionAlgorithmIdentifier();
recipientEncryptedKeys = new RecipientEncryptedKeys();
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.KeyAgreeRecipientInfo = KeyAgreeRecipientInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Integer })], KeyAgreeRecipientInfo.prototype, "version", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: OriginatorIdentifierOrKey,
context: 0
})], KeyAgreeRecipientInfo.prototype, "originator", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.OctetString,
context: 1,
optional: true
})], KeyAgreeRecipientInfo.prototype, "ukm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: types_1.KeyEncryptionAlgorithmIdentifier })], KeyAgreeRecipientInfo.prototype, "keyEncryptionAlgorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: RecipientEncryptedKeys })], KeyAgreeRecipientInfo.prototype, "recipientEncryptedKeys", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/key_trans_recipient_info.js
var require_key_trans_recipient_info = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeyTransRecipientInfo = exports.RecipientIdentifier = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
const types_1 = require_types$3();
const issuer_and_serial_number_1 = require_issuer_and_serial_number();
let RecipientIdentifier = class RecipientIdentifier {
subjectKeyIdentifier;
issuerAndSerialNumber;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.RecipientIdentifier = RecipientIdentifier;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_1.SubjectKeyIdentifier,
context: 0,
implicit: true
})], RecipientIdentifier.prototype, "subjectKeyIdentifier", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: issuer_and_serial_number_1.IssuerAndSerialNumber })], RecipientIdentifier.prototype, "issuerAndSerialNumber", void 0);
exports.RecipientIdentifier = RecipientIdentifier = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], RecipientIdentifier);
var KeyTransRecipientInfo = class {
version = types_1.CMSVersion.v0;
rid = new RecipientIdentifier();
keyEncryptionAlgorithm = new types_1.KeyEncryptionAlgorithmIdentifier();
encryptedKey = new asn1_schema_1.OctetString();
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.KeyTransRecipientInfo = KeyTransRecipientInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Integer })], KeyTransRecipientInfo.prototype, "version", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: RecipientIdentifier })], KeyTransRecipientInfo.prototype, "rid", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: types_1.KeyEncryptionAlgorithmIdentifier })], KeyTransRecipientInfo.prototype, "keyEncryptionAlgorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.OctetString })], KeyTransRecipientInfo.prototype, "encryptedKey", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/kek_recipient_info.js
var require_kek_recipient_info = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.KEKRecipientInfo = exports.KEKIdentifier = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const other_key_attribute_1 = require_other_key_attribute();
const types_1 = require_types$3();
var KEKIdentifier = class {
keyIdentifier = new asn1_schema_1.OctetString();
date;
other;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.KEKIdentifier = KEKIdentifier;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.OctetString })], KEKIdentifier.prototype, "keyIdentifier", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.GeneralizedTime,
optional: true
})], KEKIdentifier.prototype, "date", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: other_key_attribute_1.OtherKeyAttribute,
optional: true
})], KEKIdentifier.prototype, "other", void 0);
var KEKRecipientInfo = class {
version = types_1.CMSVersion.v4;
kekid = new KEKIdentifier();
keyEncryptionAlgorithm = new types_1.KeyEncryptionAlgorithmIdentifier();
encryptedKey = new asn1_schema_1.OctetString();
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.KEKRecipientInfo = KEKRecipientInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Integer })], KEKRecipientInfo.prototype, "version", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: KEKIdentifier })], KEKRecipientInfo.prototype, "kekid", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: types_1.KeyEncryptionAlgorithmIdentifier })], KEKRecipientInfo.prototype, "keyEncryptionAlgorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.OctetString })], KEKRecipientInfo.prototype, "encryptedKey", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/password_recipient_info.js
var require_password_recipient_info = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.PasswordRecipientInfo = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const types_1 = require_types$3();
var PasswordRecipientInfo = class {
version = types_1.CMSVersion.v0;
keyDerivationAlgorithm;
keyEncryptionAlgorithm = new types_1.KeyEncryptionAlgorithmIdentifier();
encryptedKey = new asn1_schema_1.OctetString();
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.PasswordRecipientInfo = PasswordRecipientInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Integer })], PasswordRecipientInfo.prototype, "version", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: types_1.KeyDerivationAlgorithmIdentifier,
context: 0,
optional: true
})], PasswordRecipientInfo.prototype, "keyDerivationAlgorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: types_1.KeyEncryptionAlgorithmIdentifier })], PasswordRecipientInfo.prototype, "keyEncryptionAlgorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.OctetString })], PasswordRecipientInfo.prototype, "encryptedKey", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/recipient_info.js
var require_recipient_info = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.RecipientInfo = exports.OtherRecipientInfo = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const key_agree_recipient_info_1 = require_key_agree_recipient_info();
const key_trans_recipient_info_1 = require_key_trans_recipient_info();
const kek_recipient_info_1 = require_kek_recipient_info();
const password_recipient_info_1 = require_password_recipient_info();
var OtherRecipientInfo = class {
oriType = "";
oriValue = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.OtherRecipientInfo = OtherRecipientInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], OtherRecipientInfo.prototype, "oriType", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Any })], OtherRecipientInfo.prototype, "oriValue", void 0);
let RecipientInfo = class RecipientInfo {
ktri;
kari;
kekri;
pwri;
ori;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.RecipientInfo = RecipientInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: key_trans_recipient_info_1.KeyTransRecipientInfo,
optional: true
})], RecipientInfo.prototype, "ktri", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: key_agree_recipient_info_1.KeyAgreeRecipientInfo,
context: 1,
implicit: true,
optional: true
})], RecipientInfo.prototype, "kari", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: kek_recipient_info_1.KEKRecipientInfo,
context: 2,
implicit: true,
optional: true
})], RecipientInfo.prototype, "kekri", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: password_recipient_info_1.PasswordRecipientInfo,
context: 3,
implicit: true,
optional: true
})], RecipientInfo.prototype, "pwri", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: OtherRecipientInfo,
context: 4,
implicit: true,
optional: true
})], RecipientInfo.prototype, "ori", void 0);
exports.RecipientInfo = RecipientInfo = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], RecipientInfo);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/recipient_infos.js
var require_recipient_infos = /* @__PURE__ */ __commonJSMin(((exports) => {
var RecipientInfos_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.RecipientInfos = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const recipient_info_1 = require_recipient_info();
let RecipientInfos = RecipientInfos_1 = class RecipientInfos extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, RecipientInfos_1.prototype);
}
};
exports.RecipientInfos = RecipientInfos;
exports.RecipientInfos = RecipientInfos = RecipientInfos_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Set,
itemType: recipient_info_1.RecipientInfo
})], RecipientInfos);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/revocation_info_choice.js
var require_revocation_info_choice = /* @__PURE__ */ __commonJSMin(((exports) => {
var RevocationInfoChoices_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.RevocationInfoChoices = exports.RevocationInfoChoice = exports.OtherRevocationInfoFormat = exports.id_ri_scvp = exports.id_ri_ocsp_response = exports.id_ri = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
exports.id_ri = `${require_cjs$9().id_pkix}.16`;
exports.id_ri_ocsp_response = `${exports.id_ri}.2`;
exports.id_ri_scvp = `${exports.id_ri}.4`;
var OtherRevocationInfoFormat = class {
otherRevInfoFormat = "";
otherRevInfo = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.OtherRevocationInfoFormat = OtherRevocationInfoFormat;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], OtherRevocationInfoFormat.prototype, "otherRevInfoFormat", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Any })], OtherRevocationInfoFormat.prototype, "otherRevInfo", void 0);
let RevocationInfoChoice = class RevocationInfoChoice {
other = new OtherRevocationInfoFormat();
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.RevocationInfoChoice = RevocationInfoChoice;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: OtherRevocationInfoFormat,
context: 1,
implicit: true
})], RevocationInfoChoice.prototype, "other", void 0);
exports.RevocationInfoChoice = RevocationInfoChoice = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], RevocationInfoChoice);
let RevocationInfoChoices = RevocationInfoChoices_1 = class RevocationInfoChoices extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, RevocationInfoChoices_1.prototype);
}
};
exports.RevocationInfoChoices = RevocationInfoChoices;
exports.RevocationInfoChoices = RevocationInfoChoices = RevocationInfoChoices_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Set,
itemType: RevocationInfoChoice
})], RevocationInfoChoices);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/originator_info.js
var require_originator_info = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.OriginatorInfo = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const certificate_choices_1 = require_certificate_choices();
const revocation_info_choice_1 = require_revocation_info_choice();
var OriginatorInfo = class {
certs;
crls;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.OriginatorInfo = OriginatorInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: certificate_choices_1.CertificateSet,
context: 0,
implicit: true,
optional: true
})], OriginatorInfo.prototype, "certs", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: revocation_info_choice_1.RevocationInfoChoices,
context: 1,
implicit: true,
optional: true
})], OriginatorInfo.prototype, "crls", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/enveloped_data.js
var require_enveloped_data = /* @__PURE__ */ __commonJSMin(((exports) => {
var UnprotectedAttributes_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.EnvelopedData = exports.UnprotectedAttributes = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const types_1 = require_types$3();
const attribute_1 = require_attribute$1();
const recipient_infos_1 = require_recipient_infos();
const originator_info_1 = require_originator_info();
const encrypted_content_info_1 = require_encrypted_content_info();
let UnprotectedAttributes = UnprotectedAttributes_1 = class UnprotectedAttributes extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, UnprotectedAttributes_1.prototype);
}
};
exports.UnprotectedAttributes = UnprotectedAttributes;
exports.UnprotectedAttributes = UnprotectedAttributes = UnprotectedAttributes_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Set,
itemType: attribute_1.Attribute
})], UnprotectedAttributes);
var EnvelopedData = class {
version = types_1.CMSVersion.v0;
originatorInfo;
recipientInfos = new recipient_infos_1.RecipientInfos();
encryptedContentInfo = new encrypted_content_info_1.EncryptedContentInfo();
unprotectedAttrs;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.EnvelopedData = EnvelopedData;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Integer })], EnvelopedData.prototype, "version", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: originator_info_1.OriginatorInfo,
context: 0,
implicit: true,
optional: true
})], EnvelopedData.prototype, "originatorInfo", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: recipient_infos_1.RecipientInfos })], EnvelopedData.prototype, "recipientInfos", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: encrypted_content_info_1.EncryptedContentInfo })], EnvelopedData.prototype, "encryptedContentInfo", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: UnprotectedAttributes,
context: 1,
implicit: true,
optional: true
})], EnvelopedData.prototype, "unprotectedAttrs", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/object_identifiers.js
var require_object_identifiers$3 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.id_authData = exports.id_encryptedData = exports.id_digestedData = exports.id_envelopedData = exports.id_signedData = exports.id_data = exports.id_ct_contentInfo = void 0;
exports.id_ct_contentInfo = "1.2.840.113549.1.9.16.1.6";
exports.id_data = "1.2.840.113549.1.7.1";
exports.id_signedData = "1.2.840.113549.1.7.2";
exports.id_envelopedData = "1.2.840.113549.1.7.3";
exports.id_digestedData = "1.2.840.113549.1.7.5";
exports.id_encryptedData = "1.2.840.113549.1.7.6";
exports.id_authData = "1.2.840.113549.1.9.16.1.2";
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/signed_data.js
var require_signed_data = /* @__PURE__ */ __commonJSMin(((exports) => {
var DigestAlgorithmIdentifiers_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SignedData = exports.DigestAlgorithmIdentifiers = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const certificate_choices_1 = require_certificate_choices();
const types_1 = require_types$3();
const encapsulated_content_info_1 = require_encapsulated_content_info();
const revocation_info_choice_1 = require_revocation_info_choice();
const signer_info_1 = require_signer_info();
let DigestAlgorithmIdentifiers = DigestAlgorithmIdentifiers_1 = class DigestAlgorithmIdentifiers extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, DigestAlgorithmIdentifiers_1.prototype);
}
};
exports.DigestAlgorithmIdentifiers = DigestAlgorithmIdentifiers;
exports.DigestAlgorithmIdentifiers = DigestAlgorithmIdentifiers = DigestAlgorithmIdentifiers_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Set,
itemType: types_1.DigestAlgorithmIdentifier
})], DigestAlgorithmIdentifiers);
var SignedData = class {
version = types_1.CMSVersion.v0;
digestAlgorithms = new DigestAlgorithmIdentifiers();
encapContentInfo = new encapsulated_content_info_1.EncapsulatedContentInfo();
certificates;
crls;
signerInfos = new signer_info_1.SignerInfos();
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.SignedData = SignedData;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Integer })], SignedData.prototype, "version", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: DigestAlgorithmIdentifiers })], SignedData.prototype, "digestAlgorithms", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: encapsulated_content_info_1.EncapsulatedContentInfo })], SignedData.prototype, "encapContentInfo", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: certificate_choices_1.CertificateSet,
context: 0,
implicit: true,
optional: true
})], SignedData.prototype, "certificates", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: revocation_info_choice_1.RevocationInfoChoices,
context: 1,
implicit: true,
optional: true
})], SignedData.prototype, "crls", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: signer_info_1.SignerInfos })], SignedData.prototype, "signerInfos", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-cms@2.9.4/node_modules/@peculiar/asn1-cms/build/cjs/index.js
var require_cjs$7 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
tslib_1.__exportStar(require_attributes$1(), exports);
tslib_1.__exportStar(require_attribute$1(), exports);
tslib_1.__exportStar(require_certificate_choices(), exports);
tslib_1.__exportStar(require_content_info(), exports);
tslib_1.__exportStar(require_encapsulated_content_info(), exports);
tslib_1.__exportStar(require_encrypted_content_info(), exports);
tslib_1.__exportStar(require_enveloped_data(), exports);
tslib_1.__exportStar(require_issuer_and_serial_number(), exports);
tslib_1.__exportStar(require_kek_recipient_info(), exports);
tslib_1.__exportStar(require_key_agree_recipient_info(), exports);
tslib_1.__exportStar(require_key_trans_recipient_info(), exports);
tslib_1.__exportStar(require_object_identifiers$3(), exports);
tslib_1.__exportStar(require_originator_info(), exports);
tslib_1.__exportStar(require_password_recipient_info(), exports);
tslib_1.__exportStar(require_recipient_info(), exports);
tslib_1.__exportStar(require_recipient_infos(), exports);
tslib_1.__exportStar(require_revocation_info_choice(), exports);
tslib_1.__exportStar(require_signed_data(), exports);
tslib_1.__exportStar(require_signer_identifier(), exports);
tslib_1.__exportStar(require_signer_info(), exports);
tslib_1.__exportStar(require_types$3(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-ecc@2.9.4/node_modules/@peculiar/asn1-ecc/build/cjs/object_identifiers.js
var require_object_identifiers$2 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.id_sect571r1 = exports.id_sect571k1 = exports.id_secp521r1 = exports.id_sect409r1 = exports.id_sect409k1 = exports.id_secp384r1 = exports.id_sect283r1 = exports.id_sect283k1 = exports.id_secp256r1 = exports.id_sect233r1 = exports.id_sect233k1 = exports.id_secp224r1 = exports.id_sect163r2 = exports.id_sect163k1 = exports.id_secp192r1 = exports.id_ecdsaWithSHA512 = exports.id_ecdsaWithSHA384 = exports.id_ecdsaWithSHA256 = exports.id_ecdsaWithSHA224 = exports.id_ecdsaWithSHA1 = exports.id_ecMQV = exports.id_ecDH = exports.id_ecPublicKey = void 0;
exports.id_ecPublicKey = "1.2.840.10045.2.1";
exports.id_ecDH = "1.3.132.1.12";
exports.id_ecMQV = "1.3.132.1.13";
exports.id_ecdsaWithSHA1 = "1.2.840.10045.4.1";
exports.id_ecdsaWithSHA224 = "1.2.840.10045.4.3.1";
exports.id_ecdsaWithSHA256 = "1.2.840.10045.4.3.2";
exports.id_ecdsaWithSHA384 = "1.2.840.10045.4.3.3";
exports.id_ecdsaWithSHA512 = "1.2.840.10045.4.3.4";
exports.id_secp192r1 = "1.2.840.10045.3.1.1";
exports.id_sect163k1 = "1.3.132.0.1";
exports.id_sect163r2 = "1.3.132.0.15";
exports.id_secp224r1 = "1.3.132.0.33";
exports.id_sect233k1 = "1.3.132.0.26";
exports.id_sect233r1 = "1.3.132.0.27";
exports.id_secp256r1 = "1.2.840.10045.3.1.7";
exports.id_sect283k1 = "1.3.132.0.16";
exports.id_sect283r1 = "1.3.132.0.17";
exports.id_secp384r1 = "1.3.132.0.34";
exports.id_sect409k1 = "1.3.132.0.36";
exports.id_sect409r1 = "1.3.132.0.37";
exports.id_secp521r1 = "1.3.132.0.35";
exports.id_sect571k1 = "1.3.132.0.38";
exports.id_sect571r1 = "1.3.132.0.39";
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-ecc@2.9.4/node_modules/@peculiar/asn1-ecc/build/cjs/algorithms.js
var require_algorithms$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ecdsaWithSHA512 = exports.ecdsaWithSHA384 = exports.ecdsaWithSHA256 = exports.ecdsaWithSHA224 = exports.ecdsaWithSHA1 = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_x509_1 = require_cjs$9();
const oid = tslib_1.__importStar(require_object_identifiers$2());
function create(algorithm) {
return new asn1_x509_1.AlgorithmIdentifier({ algorithm });
}
exports.ecdsaWithSHA1 = create(oid.id_ecdsaWithSHA1);
exports.ecdsaWithSHA224 = create(oid.id_ecdsaWithSHA224);
exports.ecdsaWithSHA256 = create(oid.id_ecdsaWithSHA256);
exports.ecdsaWithSHA384 = create(oid.id_ecdsaWithSHA384);
exports.ecdsaWithSHA512 = create(oid.id_ecdsaWithSHA512);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-ecc@2.9.4/node_modules/@peculiar/asn1-ecc/build/cjs/rfc3279.js
var require_rfc3279 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.SpecifiedECDomain = exports.ECPVer = exports.Curve = exports.FieldElement = exports.ECPoint = exports.FieldID = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
let FieldID = class FieldID {
fieldType;
parameters;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.FieldID = FieldID;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], FieldID.prototype, "fieldType", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Any })], FieldID.prototype, "parameters", void 0);
exports.FieldID = FieldID = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], FieldID);
var ECPoint = class extends asn1_schema_1.OctetString {};
exports.ECPoint = ECPoint;
var FieldElement = class extends asn1_schema_1.OctetString {};
exports.FieldElement = FieldElement;
let Curve = class Curve {
a;
b;
seed;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.Curve = Curve;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.OctetString })], Curve.prototype, "a", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.OctetString })], Curve.prototype, "b", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.BitString,
optional: true
})], Curve.prototype, "seed", void 0);
exports.Curve = Curve = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], Curve);
var ECPVer;
(function(ECPVer) {
ECPVer[ECPVer["ecpVer1"] = 1] = "ecpVer1";
})(ECPVer || (exports.ECPVer = ECPVer = {}));
let SpecifiedECDomain = class SpecifiedECDomain {
version = ECPVer.ecpVer1;
fieldID;
curve;
base;
order;
cofactor;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.SpecifiedECDomain = SpecifiedECDomain;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Integer })], SpecifiedECDomain.prototype, "version", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: FieldID })], SpecifiedECDomain.prototype, "fieldID", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: Curve })], SpecifiedECDomain.prototype, "curve", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: ECPoint })], SpecifiedECDomain.prototype, "base", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], SpecifiedECDomain.prototype, "order", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
optional: true
})], SpecifiedECDomain.prototype, "cofactor", void 0);
exports.SpecifiedECDomain = SpecifiedECDomain = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], SpecifiedECDomain);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-ecc@2.9.4/node_modules/@peculiar/asn1-ecc/build/cjs/ec_parameters.js
var require_ec_parameters = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ECParameters = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const rfc3279_1 = require_rfc3279();
let ECParameters = class ECParameters {
namedCurve;
implicitCurve;
specifiedCurve;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.ECParameters = ECParameters;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], ECParameters.prototype, "namedCurve", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Null })], ECParameters.prototype, "implicitCurve", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: rfc3279_1.SpecifiedECDomain })], ECParameters.prototype, "specifiedCurve", void 0);
exports.ECParameters = ECParameters = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], ECParameters);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-ecc@2.9.4/node_modules/@peculiar/asn1-ecc/build/cjs/ec_private_key.js
var require_ec_private_key = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ECPrivateKey = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const ec_parameters_1 = require_ec_parameters();
var ECPrivateKey = class {
version = 1;
privateKey = new asn1_schema_1.OctetString();
parameters;
publicKey;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.ECPrivateKey = ECPrivateKey;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Integer })], ECPrivateKey.prototype, "version", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.OctetString })], ECPrivateKey.prototype, "privateKey", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: ec_parameters_1.ECParameters,
context: 0,
optional: true
})], ECPrivateKey.prototype, "parameters", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.BitString,
context: 1,
optional: true
})], ECPrivateKey.prototype, "publicKey", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-ecc@2.9.4/node_modules/@peculiar/asn1-ecc/build/cjs/ec_signature_value.js
var require_ec_signature_value = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ECDSASigValue = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
var ECDSASigValue = class {
r = /* @__PURE__ */ new ArrayBuffer(0);
s = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.ECDSASigValue = ECDSASigValue;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], ECDSASigValue.prototype, "r", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], ECDSASigValue.prototype, "s", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-ecc@2.9.4/node_modules/@peculiar/asn1-ecc/build/cjs/index.js
var require_cjs$6 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
tslib_1.__exportStar(require_algorithms$1(), exports);
tslib_1.__exportStar(require_ec_parameters(), exports);
tslib_1.__exportStar(require_ec_private_key(), exports);
tslib_1.__exportStar(require_ec_signature_value(), exports);
tslib_1.__exportStar(require_object_identifiers$2(), exports);
tslib_1.__exportStar(require_rfc3279(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-rsa@2.9.4/node_modules/@peculiar/asn1-rsa/build/cjs/object_identifiers.js
var require_object_identifiers$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.id_mgf1 = exports.id_md5 = exports.id_md2 = exports.id_sha512_256 = exports.id_sha512_224 = exports.id_sha512 = exports.id_sha384 = exports.id_sha256 = exports.id_sha224 = exports.id_sha1 = exports.id_sha512_256WithRSAEncryption = exports.id_sha512_224WithRSAEncryption = exports.id_sha512WithRSAEncryption = exports.id_sha384WithRSAEncryption = exports.id_sha256WithRSAEncryption = exports.id_ssha224WithRSAEncryption = exports.id_sha224WithRSAEncryption = exports.id_sha1WithRSAEncryption = exports.id_md5WithRSAEncryption = exports.id_md2WithRSAEncryption = exports.id_RSASSA_PSS = exports.id_pSpecified = exports.id_RSAES_OAEP = exports.id_rsaEncryption = exports.id_pkcs_1 = void 0;
exports.id_pkcs_1 = "1.2.840.113549.1.1";
exports.id_rsaEncryption = `${exports.id_pkcs_1}.1`;
exports.id_RSAES_OAEP = `${exports.id_pkcs_1}.7`;
exports.id_pSpecified = `${exports.id_pkcs_1}.9`;
exports.id_RSASSA_PSS = `${exports.id_pkcs_1}.10`;
exports.id_md2WithRSAEncryption = `${exports.id_pkcs_1}.2`;
exports.id_md5WithRSAEncryption = `${exports.id_pkcs_1}.4`;
exports.id_sha1WithRSAEncryption = `${exports.id_pkcs_1}.5`;
exports.id_sha224WithRSAEncryption = `${exports.id_pkcs_1}.14`;
exports.id_ssha224WithRSAEncryption = exports.id_sha224WithRSAEncryption;
exports.id_sha256WithRSAEncryption = `${exports.id_pkcs_1}.11`;
exports.id_sha384WithRSAEncryption = `${exports.id_pkcs_1}.12`;
exports.id_sha512WithRSAEncryption = `${exports.id_pkcs_1}.13`;
exports.id_sha512_224WithRSAEncryption = `${exports.id_pkcs_1}.15`;
exports.id_sha512_256WithRSAEncryption = `${exports.id_pkcs_1}.16`;
exports.id_sha1 = "1.3.14.3.2.26";
exports.id_sha224 = "2.16.840.1.101.3.4.2.4";
exports.id_sha256 = "2.16.840.1.101.3.4.2.1";
exports.id_sha384 = "2.16.840.1.101.3.4.2.2";
exports.id_sha512 = "2.16.840.1.101.3.4.2.3";
exports.id_sha512_224 = "2.16.840.1.101.3.4.2.5";
exports.id_sha512_256 = "2.16.840.1.101.3.4.2.6";
exports.id_md2 = "1.2.840.113549.2.2";
exports.id_md5 = "1.2.840.113549.2.5";
exports.id_mgf1 = `${exports.id_pkcs_1}.8`;
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-rsa@2.9.4/node_modules/@peculiar/asn1-rsa/build/cjs/algorithms.js
var require_algorithms = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.sha512_256WithRSAEncryption = exports.sha512_224WithRSAEncryption = exports.sha512WithRSAEncryption = exports.sha384WithRSAEncryption = exports.sha256WithRSAEncryption = exports.sha224WithRSAEncryption = exports.sha1WithRSAEncryption = exports.md5WithRSAEncryption = exports.md2WithRSAEncryption = exports.rsaEncryption = exports.pSpecifiedEmpty = exports.mgf1SHA1 = exports.sha512_256 = exports.sha512_224 = exports.sha512 = exports.sha384 = exports.sha256 = exports.sha224 = exports.sha1 = exports.md4 = exports.md2 = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
const oid = tslib_1.__importStar(require_object_identifiers$1());
function create(algorithm) {
return new asn1_x509_1.AlgorithmIdentifier({
algorithm,
parameters: null
});
}
exports.md2 = create(oid.id_md2);
exports.md4 = create(oid.id_md5);
exports.sha1 = create(oid.id_sha1);
exports.sha224 = create(oid.id_sha224);
exports.sha256 = create(oid.id_sha256);
exports.sha384 = create(oid.id_sha384);
exports.sha512 = create(oid.id_sha512);
exports.sha512_224 = create(oid.id_sha512_224);
exports.sha512_256 = create(oid.id_sha512_256);
exports.mgf1SHA1 = new asn1_x509_1.AlgorithmIdentifier({
algorithm: oid.id_mgf1,
parameters: asn1_schema_1.AsnConvert.serialize(exports.sha1)
});
exports.pSpecifiedEmpty = new asn1_x509_1.AlgorithmIdentifier({
algorithm: oid.id_pSpecified,
parameters: asn1_schema_1.AsnConvert.serialize(asn1_schema_1.AsnOctetStringConverter.toASN(new Uint8Array([
218,
57,
163,
238,
94,
107,
75,
13,
50,
85,
191,
239,
149,
96,
24,
144,
175,
216,
7,
9
]).buffer))
});
exports.rsaEncryption = create(oid.id_rsaEncryption);
exports.md2WithRSAEncryption = create(oid.id_md2WithRSAEncryption);
exports.md5WithRSAEncryption = create(oid.id_md5WithRSAEncryption);
exports.sha1WithRSAEncryption = create(oid.id_sha1WithRSAEncryption);
exports.sha224WithRSAEncryption = create(oid.id_sha512_224WithRSAEncryption);
exports.sha256WithRSAEncryption = create(oid.id_sha512_256WithRSAEncryption);
exports.sha384WithRSAEncryption = create(oid.id_sha384WithRSAEncryption);
exports.sha512WithRSAEncryption = create(oid.id_sha512WithRSAEncryption);
exports.sha512_224WithRSAEncryption = create(oid.id_sha512_224WithRSAEncryption);
exports.sha512_256WithRSAEncryption = create(oid.id_sha512_256WithRSAEncryption);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-rsa@2.9.4/node_modules/@peculiar/asn1-rsa/build/cjs/parameters/rsaes_oaep.js
var require_rsaes_oaep = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.RSAES_OAEP = exports.RsaEsOaepParams = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
const object_identifiers_1 = require_object_identifiers$1();
const algorithms_1 = require_algorithms();
var RsaEsOaepParams = class {
hashAlgorithm = new asn1_x509_1.AlgorithmIdentifier(algorithms_1.sha1);
maskGenAlgorithm = new asn1_x509_1.AlgorithmIdentifier({
algorithm: object_identifiers_1.id_mgf1,
parameters: asn1_schema_1.AsnConvert.serialize(algorithms_1.sha1)
});
pSourceAlgorithm = new asn1_x509_1.AlgorithmIdentifier(algorithms_1.pSpecifiedEmpty);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.RsaEsOaepParams = RsaEsOaepParams;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_1.AlgorithmIdentifier,
context: 0,
defaultValue: algorithms_1.sha1
})], RsaEsOaepParams.prototype, "hashAlgorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_1.AlgorithmIdentifier,
context: 1,
defaultValue: algorithms_1.mgf1SHA1
})], RsaEsOaepParams.prototype, "maskGenAlgorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_1.AlgorithmIdentifier,
context: 2,
defaultValue: algorithms_1.pSpecifiedEmpty
})], RsaEsOaepParams.prototype, "pSourceAlgorithm", void 0);
exports.RSAES_OAEP = new asn1_x509_1.AlgorithmIdentifier({
algorithm: object_identifiers_1.id_RSAES_OAEP,
parameters: asn1_schema_1.AsnConvert.serialize(new RsaEsOaepParams())
});
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-rsa@2.9.4/node_modules/@peculiar/asn1-rsa/build/cjs/parameters/rsassa_pss.js
var require_rsassa_pss = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.RSASSA_PSS = exports.RsaSaPssParams = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
const object_identifiers_1 = require_object_identifiers$1();
const algorithms_1 = require_algorithms();
var RsaSaPssParams = class {
hashAlgorithm = new asn1_x509_1.AlgorithmIdentifier(algorithms_1.sha1);
maskGenAlgorithm = new asn1_x509_1.AlgorithmIdentifier({
algorithm: object_identifiers_1.id_mgf1,
parameters: asn1_schema_1.AsnConvert.serialize(algorithms_1.sha1)
});
saltLength = 20;
trailerField = 1;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.RsaSaPssParams = RsaSaPssParams;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_1.AlgorithmIdentifier,
context: 0,
defaultValue: algorithms_1.sha1
})], RsaSaPssParams.prototype, "hashAlgorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_x509_1.AlgorithmIdentifier,
context: 1,
defaultValue: algorithms_1.mgf1SHA1
})], RsaSaPssParams.prototype, "maskGenAlgorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
context: 2,
defaultValue: 20
})], RsaSaPssParams.prototype, "saltLength", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
context: 3,
defaultValue: 1
})], RsaSaPssParams.prototype, "trailerField", void 0);
exports.RSASSA_PSS = new asn1_x509_1.AlgorithmIdentifier({
algorithm: object_identifiers_1.id_RSASSA_PSS,
parameters: asn1_schema_1.AsnConvert.serialize(new RsaSaPssParams())
});
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-rsa@2.9.4/node_modules/@peculiar/asn1-rsa/build/cjs/parameters/rsassa_pkcs1_v1_5.js
var require_rsassa_pkcs1_v1_5 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.DigestInfo = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_x509_1 = require_cjs$9();
const asn1_schema_1 = require_cjs$10();
var DigestInfo = class {
digestAlgorithm = new asn1_x509_1.AlgorithmIdentifier();
digest = new asn1_schema_1.OctetString();
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.DigestInfo = DigestInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_x509_1.AlgorithmIdentifier })], DigestInfo.prototype, "digestAlgorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.OctetString })], DigestInfo.prototype, "digest", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-rsa@2.9.4/node_modules/@peculiar/asn1-rsa/build/cjs/parameters/index.js
var require_parameters = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
tslib_1.__exportStar(require_rsaes_oaep(), exports);
tslib_1.__exportStar(require_rsassa_pss(), exports);
tslib_1.__exportStar(require_rsassa_pkcs1_v1_5(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-rsa@2.9.4/node_modules/@peculiar/asn1-rsa/build/cjs/other_prime_info.js
var require_other_prime_info = /* @__PURE__ */ __commonJSMin(((exports) => {
var OtherPrimeInfos_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.OtherPrimeInfos = exports.OtherPrimeInfo = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
var OtherPrimeInfo = class {
prime = /* @__PURE__ */ new ArrayBuffer(0);
exponent = /* @__PURE__ */ new ArrayBuffer(0);
coefficient = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.OtherPrimeInfo = OtherPrimeInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], OtherPrimeInfo.prototype, "prime", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], OtherPrimeInfo.prototype, "exponent", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], OtherPrimeInfo.prototype, "coefficient", void 0);
let OtherPrimeInfos = OtherPrimeInfos_1 = class OtherPrimeInfos extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, OtherPrimeInfos_1.prototype);
}
};
exports.OtherPrimeInfos = OtherPrimeInfos;
exports.OtherPrimeInfos = OtherPrimeInfos = OtherPrimeInfos_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: OtherPrimeInfo
})], OtherPrimeInfos);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-rsa@2.9.4/node_modules/@peculiar/asn1-rsa/build/cjs/rsa_private_key.js
var require_rsa_private_key = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.RSAPrivateKey = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const other_prime_info_1 = require_other_prime_info();
var RSAPrivateKey = class {
version = 0;
modulus = /* @__PURE__ */ new ArrayBuffer(0);
publicExponent = /* @__PURE__ */ new ArrayBuffer(0);
privateExponent = /* @__PURE__ */ new ArrayBuffer(0);
prime1 = /* @__PURE__ */ new ArrayBuffer(0);
prime2 = /* @__PURE__ */ new ArrayBuffer(0);
exponent1 = /* @__PURE__ */ new ArrayBuffer(0);
exponent2 = /* @__PURE__ */ new ArrayBuffer(0);
coefficient = /* @__PURE__ */ new ArrayBuffer(0);
otherPrimeInfos;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.RSAPrivateKey = RSAPrivateKey;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Integer })], RSAPrivateKey.prototype, "version", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], RSAPrivateKey.prototype, "modulus", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], RSAPrivateKey.prototype, "publicExponent", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], RSAPrivateKey.prototype, "privateExponent", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], RSAPrivateKey.prototype, "prime1", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], RSAPrivateKey.prototype, "prime2", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], RSAPrivateKey.prototype, "exponent1", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], RSAPrivateKey.prototype, "exponent2", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], RSAPrivateKey.prototype, "coefficient", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: other_prime_info_1.OtherPrimeInfos,
optional: true
})], RSAPrivateKey.prototype, "otherPrimeInfos", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-rsa@2.9.4/node_modules/@peculiar/asn1-rsa/build/cjs/rsa_public_key.js
var require_rsa_public_key = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.RSAPublicKey = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
var RSAPublicKey = class {
modulus = /* @__PURE__ */ new ArrayBuffer(0);
publicExponent = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.RSAPublicKey = RSAPublicKey;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], RSAPublicKey.prototype, "modulus", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
converter: asn1_schema_1.AsnIntegerArrayBufferConverter
})], RSAPublicKey.prototype, "publicExponent", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-rsa@2.9.4/node_modules/@peculiar/asn1-rsa/build/cjs/index.js
var require_cjs$5 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
tslib_1.__exportStar(require_parameters(), exports);
tslib_1.__exportStar(require_algorithms(), exports);
tslib_1.__exportStar(require_object_identifiers$1(), exports);
tslib_1.__exportStar(require_other_prime_info(), exports);
tslib_1.__exportStar(require_rsa_private_key(), exports);
tslib_1.__exportStar(require_rsa_public_key(), exports);
}));
//#endregion
//#region node_modules/.pnpm/tslib@1.14.1/node_modules/tslib/tslib.es6.js
var tslib_es6_exports = /* @__PURE__ */ __exportAll({
__assign: () => __assign,
__asyncDelegator: () => __asyncDelegator,
__asyncGenerator: () => __asyncGenerator,
__asyncValues: () => __asyncValues,
__await: () => __await,
__awaiter: () => __awaiter,
__classPrivateFieldGet: () => __classPrivateFieldGet,
__classPrivateFieldSet: () => __classPrivateFieldSet,
__createBinding: () => __createBinding,
__decorate: () => __decorate,
__exportStar: () => __exportStar,
__extends: () => __extends,
__generator: () => __generator,
__importDefault: () => __importDefault,
__importStar: () => __importStar,
__makeTemplateObject: () => __makeTemplateObject,
__metadata: () => __metadata,
__param: () => __param,
__read: () => __read,
__rest: () => __rest,
__spread: () => __spread,
__spreadArrays: () => __spreadArrays,
__values: () => __values
});
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __extends(d, b) {
extendStatics(d, b);
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function") {
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function(target, key) {
decorator(target, key, paramIndex);
};
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function(resolve, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = {
label: 0,
sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
}, f, y, t, g;
return g = {
next: verb(0),
"throw": verb(1),
"return": verb(2)
}, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
return this;
}), g;
function verb(n) {
return function(v) {
return step([n, v]);
};
}
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return {
value: op[1],
done: false
};
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f = t = 0;
}
if (op[0] & 5) throw op[1];
return {
value: op[0] ? op[1] : void 0,
done: true
};
}
}
function __createBinding(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
}
function __exportStar(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p];
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return { next: function() {
if (o && i >= o.length) o = void 0;
return {
value: o && o[i++],
done: !o
};
} };
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
} catch (error) {
e = { error };
} finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
} finally {
if (e) throw e.error;
}
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j];
return r;
}
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
return this;
}, i;
function verb(n) {
if (g[n]) i[n] = function(v) {
return new Promise(function(a, b) {
q.push([
n,
v,
a,
b
]) > 1 || resume(n, v);
});
};
}
function resume(n, v) {
try {
step(g[n](v));
} catch (e) {
settle(q[0][3], e);
}
}
function step(r) {
r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
}
function fulfill(value) {
resume("next", value);
}
function reject(value) {
resume("throw", value);
}
function settle(f, v) {
if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
}
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function(e) {
throw e;
}), verb("return"), i[Symbol.iterator] = function() {
return this;
}, i;
function verb(n, f) {
i[n] = o[n] ? function(v) {
return (p = !p) ? {
value: __await(o[n](v)),
done: n === "return"
} : f ? f(v) : v;
} : f;
}
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
return this;
}, i);
function verb(n) {
i[n] = o[n] && function(v) {
return new Promise(function(resolve, reject) {
v = o[n](v), settle(resolve, reject, v.done, v.value);
});
};
}
function settle(resolve, reject, d, v) {
Promise.resolve(v).then(function(v) {
resolve({
value: v,
done: d
});
}, reject);
}
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) Object.defineProperty(cooked, "raw", { value: raw });
else cooked.raw = raw;
return cooked;
}
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
}
result.default = mod;
return result;
}
function __importDefault(mod) {
return mod && mod.__esModule ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, privateMap) {
if (!privateMap.has(receiver)) throw new TypeError("attempted to get private field on non-instance");
return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
if (!privateMap.has(receiver)) throw new TypeError("attempted to set private field on non-instance");
privateMap.set(receiver, value);
return value;
}
var extendStatics, __assign;
var init_tslib_es6 = __esmMin((() => {
extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d, b) {
d.__proto__ = b;
} || function(d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
};
return extendStatics(d, b);
};
__assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/types/lifecycle.js
var require_lifecycle = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
var Lifecycle;
(function(Lifecycle) {
Lifecycle[Lifecycle["Transient"] = 0] = "Transient";
Lifecycle[Lifecycle["Singleton"] = 1] = "Singleton";
Lifecycle[Lifecycle["ResolutionScoped"] = 2] = "ResolutionScoped";
Lifecycle[Lifecycle["ContainerScoped"] = 3] = "ContainerScoped";
})(Lifecycle || (Lifecycle = {}));
exports.default = Lifecycle;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/types/index.js
var require_types$2 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
var lifecycle_1 = require_lifecycle();
Object.defineProperty(exports, "Lifecycle", {
enumerable: true,
get: function() {
return lifecycle_1.default;
}
});
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/reflection-helpers.js
var require_reflection_helpers = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.defineInjectionTokenMetadata = exports.getParamInfo = exports.INJECTION_TOKEN_METADATA_KEY = void 0;
exports.INJECTION_TOKEN_METADATA_KEY = "injectionTokens";
function getParamInfo(target) {
const params = Reflect.getMetadata("design:paramtypes", target) || [];
const injectionTokens = Reflect.getOwnMetadata(exports.INJECTION_TOKEN_METADATA_KEY, target) || {};
Object.keys(injectionTokens).forEach((key) => {
params[+key] = injectionTokens[key];
});
return params;
}
exports.getParamInfo = getParamInfo;
function defineInjectionTokenMetadata(data, transform) {
return function(target, _propertyKey, parameterIndex) {
const descriptors = Reflect.getOwnMetadata(exports.INJECTION_TOKEN_METADATA_KEY, target) || {};
descriptors[parameterIndex] = transform ? {
token: data,
transform: transform.transformToken,
transformArgs: transform.args || []
} : data;
Reflect.defineMetadata(exports.INJECTION_TOKEN_METADATA_KEY, descriptors, target);
};
}
exports.defineInjectionTokenMetadata = defineInjectionTokenMetadata;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/providers/class-provider.js
var require_class_provider = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.isClassProvider = void 0;
function isClassProvider(provider) {
return !!provider.useClass;
}
exports.isClassProvider = isClassProvider;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/providers/factory-provider.js
var require_factory_provider = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.isFactoryProvider = void 0;
function isFactoryProvider(provider) {
return !!provider.useFactory;
}
exports.isFactoryProvider = isFactoryProvider;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/lazy-helpers.js
var require_lazy_helpers = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.delay = exports.DelayedConstructor = void 0;
var DelayedConstructor = class {
constructor(wrap) {
this.wrap = wrap;
this.reflectMethods = [
"get",
"getPrototypeOf",
"setPrototypeOf",
"getOwnPropertyDescriptor",
"defineProperty",
"has",
"set",
"deleteProperty",
"apply",
"construct",
"ownKeys"
];
}
createProxy(createObject) {
const target = {};
let init = false;
let value;
const delayedObject = () => {
if (!init) {
value = createObject(this.wrap());
init = true;
}
return value;
};
return new Proxy(target, this.createHandler(delayedObject));
}
createHandler(delayedObject) {
const handler = {};
const install = (name) => {
handler[name] = (...args) => {
args[0] = delayedObject();
const method = Reflect[name];
return method(...args);
};
};
this.reflectMethods.forEach(install);
return handler;
}
};
exports.DelayedConstructor = DelayedConstructor;
function delay(wrappedConstructor) {
if (typeof wrappedConstructor === "undefined") throw new Error("Attempt to `delay` undefined. Constructor must be wrapped in a callback");
return new DelayedConstructor(wrappedConstructor);
}
exports.delay = delay;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/providers/injection-token.js
var require_injection_token = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.isConstructorToken = exports.isTransformDescriptor = exports.isTokenDescriptor = exports.isNormalToken = void 0;
const lazy_helpers_1 = require_lazy_helpers();
function isNormalToken(token) {
return typeof token === "string" || typeof token === "symbol";
}
exports.isNormalToken = isNormalToken;
function isTokenDescriptor(descriptor) {
return typeof descriptor === "object" && "token" in descriptor && "multiple" in descriptor;
}
exports.isTokenDescriptor = isTokenDescriptor;
function isTransformDescriptor(descriptor) {
return typeof descriptor === "object" && "token" in descriptor && "transform" in descriptor;
}
exports.isTransformDescriptor = isTransformDescriptor;
function isConstructorToken(token) {
return typeof token === "function" || token instanceof lazy_helpers_1.DelayedConstructor;
}
exports.isConstructorToken = isConstructorToken;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/providers/token-provider.js
var require_token_provider = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.isTokenProvider = void 0;
function isTokenProvider(provider) {
return !!provider.useToken;
}
exports.isTokenProvider = isTokenProvider;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/providers/value-provider.js
var require_value_provider = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.isValueProvider = void 0;
function isValueProvider(provider) {
return provider.useValue != void 0;
}
exports.isValueProvider = isValueProvider;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/providers/index.js
var require_providers = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
var class_provider_1 = require_class_provider();
Object.defineProperty(exports, "isClassProvider", {
enumerable: true,
get: function() {
return class_provider_1.isClassProvider;
}
});
var factory_provider_1 = require_factory_provider();
Object.defineProperty(exports, "isFactoryProvider", {
enumerable: true,
get: function() {
return factory_provider_1.isFactoryProvider;
}
});
var injection_token_1 = require_injection_token();
Object.defineProperty(exports, "isNormalToken", {
enumerable: true,
get: function() {
return injection_token_1.isNormalToken;
}
});
var token_provider_1 = require_token_provider();
Object.defineProperty(exports, "isTokenProvider", {
enumerable: true,
get: function() {
return token_provider_1.isTokenProvider;
}
});
var value_provider_1 = require_value_provider();
Object.defineProperty(exports, "isValueProvider", {
enumerable: true,
get: function() {
return value_provider_1.isValueProvider;
}
});
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/providers/provider.js
var require_provider = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.isProvider = void 0;
const class_provider_1 = require_class_provider();
const value_provider_1 = require_value_provider();
const token_provider_1 = require_token_provider();
const factory_provider_1 = require_factory_provider();
function isProvider(provider) {
return class_provider_1.isClassProvider(provider) || value_provider_1.isValueProvider(provider) || token_provider_1.isTokenProvider(provider) || factory_provider_1.isFactoryProvider(provider);
}
exports.isProvider = isProvider;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/registry-base.js
var require_registry_base = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
var RegistryBase = class {
constructor() {
this._registryMap = /* @__PURE__ */ new Map();
}
entries() {
return this._registryMap.entries();
}
getAll(key) {
this.ensure(key);
return this._registryMap.get(key);
}
get(key) {
this.ensure(key);
const value = this._registryMap.get(key);
return value[value.length - 1] || null;
}
set(key, value) {
this.ensure(key);
this._registryMap.get(key).push(value);
}
setAll(key, value) {
this._registryMap.set(key, value);
}
has(key) {
this.ensure(key);
return this._registryMap.get(key).length > 0;
}
clear() {
this._registryMap.clear();
}
ensure(key) {
if (!this._registryMap.has(key)) this._registryMap.set(key, []);
}
};
exports.default = RegistryBase;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/registry.js
var require_registry$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const registry_base_1 = require_registry_base();
var Registry = class extends registry_base_1.default {};
exports.default = Registry;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/resolution-context.js
var require_resolution_context = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
var ResolutionContext = class {
constructor() {
this.scopedResolutions = /* @__PURE__ */ new Map();
}
};
exports.default = ResolutionContext;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/error-helpers.js
var require_error_helpers = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatErrorCtor = void 0;
function formatDependency(params, idx) {
if (params === null) return `at position #${idx}`;
return `"${params.split(",")[idx].trim()}" at position #${idx}`;
}
function composeErrorMessage(msg, e, indent = " ") {
return [msg, ...e.message.split("\n").map((l) => indent + l)].join("\n");
}
function formatErrorCtor(ctor, paramIdx, error) {
const [, params = null] = ctor.toString().match(/constructor\(([\w, ]+)\)/) || [];
return composeErrorMessage(`Cannot inject the dependency ${formatDependency(params, paramIdx)} of "${ctor.name}" constructor. Reason:`, error);
}
exports.formatErrorCtor = formatErrorCtor;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/types/disposable.js
var require_disposable = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.isDisposable = void 0;
function isDisposable(value) {
if (typeof value.dispose !== "function") return false;
if (value.dispose.length > 0) return false;
return true;
}
exports.isDisposable = isDisposable;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/interceptors.js
var require_interceptors = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.PostResolutionInterceptors = exports.PreResolutionInterceptors = void 0;
const registry_base_1 = require_registry_base();
var PreResolutionInterceptors = class extends registry_base_1.default {};
exports.PreResolutionInterceptors = PreResolutionInterceptors;
var PostResolutionInterceptors = class extends registry_base_1.default {};
exports.PostResolutionInterceptors = PostResolutionInterceptors;
var Interceptors = class {
constructor() {
this.preResolution = new PreResolutionInterceptors();
this.postResolution = new PostResolutionInterceptors();
}
};
exports.default = Interceptors;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/dependency-container.js
var require_dependency_container = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.instance = exports.typeInfo = void 0;
const tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
const providers_1 = require_providers();
const provider_1 = require_provider();
const injection_token_1 = require_injection_token();
const registry_1 = require_registry$1();
const lifecycle_1 = require_lifecycle();
const resolution_context_1 = require_resolution_context();
const error_helpers_1 = require_error_helpers();
const lazy_helpers_1 = require_lazy_helpers();
const disposable_1 = require_disposable();
const interceptors_1 = require_interceptors();
exports.typeInfo = /* @__PURE__ */ new Map();
exports.instance = new class InternalDependencyContainer {
constructor(parent) {
this.parent = parent;
this._registry = new registry_1.default();
this.interceptors = new interceptors_1.default();
this.disposed = false;
this.disposables = /* @__PURE__ */ new Set();
}
register(token, providerOrConstructor, options = { lifecycle: lifecycle_1.default.Transient }) {
this.ensureNotDisposed();
let provider;
if (!provider_1.isProvider(providerOrConstructor)) provider = { useClass: providerOrConstructor };
else provider = providerOrConstructor;
if (providers_1.isTokenProvider(provider)) {
const path = [token];
let tokenProvider = provider;
while (tokenProvider != null) {
const currentToken = tokenProvider.useToken;
if (path.includes(currentToken)) throw new Error(`Token registration cycle detected! ${[...path, currentToken].join(" -> ")}`);
path.push(currentToken);
const registration = this._registry.get(currentToken);
if (registration && providers_1.isTokenProvider(registration.provider)) tokenProvider = registration.provider;
else tokenProvider = null;
}
}
if (options.lifecycle === lifecycle_1.default.Singleton || options.lifecycle == lifecycle_1.default.ContainerScoped || options.lifecycle == lifecycle_1.default.ResolutionScoped) {
if (providers_1.isValueProvider(provider) || providers_1.isFactoryProvider(provider)) throw new Error(`Cannot use lifecycle "${lifecycle_1.default[options.lifecycle]}" with ValueProviders or FactoryProviders`);
}
this._registry.set(token, {
provider,
options
});
return this;
}
registerType(from, to) {
this.ensureNotDisposed();
if (providers_1.isNormalToken(to)) return this.register(from, { useToken: to });
return this.register(from, { useClass: to });
}
registerInstance(token, instance) {
this.ensureNotDisposed();
return this.register(token, { useValue: instance });
}
registerSingleton(from, to) {
this.ensureNotDisposed();
if (providers_1.isNormalToken(from)) {
if (providers_1.isNormalToken(to)) return this.register(from, { useToken: to }, { lifecycle: lifecycle_1.default.Singleton });
else if (to) return this.register(from, { useClass: to }, { lifecycle: lifecycle_1.default.Singleton });
throw new Error("Cannot register a type name as a singleton without a \"to\" token");
}
let useClass = from;
if (to && !providers_1.isNormalToken(to)) useClass = to;
return this.register(from, { useClass }, { lifecycle: lifecycle_1.default.Singleton });
}
resolve(token, context = new resolution_context_1.default(), isOptional = false) {
this.ensureNotDisposed();
const registration = this.getRegistration(token);
if (!registration && providers_1.isNormalToken(token)) {
if (isOptional) return;
throw new Error(`Attempted to resolve unregistered dependency token: "${token.toString()}"`);
}
this.executePreResolutionInterceptor(token, "Single");
if (registration) {
const result = this.resolveRegistration(registration, context);
this.executePostResolutionInterceptor(token, result, "Single");
return result;
}
if (injection_token_1.isConstructorToken(token)) {
const result = this.construct(token, context);
this.executePostResolutionInterceptor(token, result, "Single");
return result;
}
throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.");
}
executePreResolutionInterceptor(token, resolutionType) {
if (this.interceptors.preResolution.has(token)) {
const remainingInterceptors = [];
for (const interceptor of this.interceptors.preResolution.getAll(token)) {
if (interceptor.options.frequency != "Once") remainingInterceptors.push(interceptor);
interceptor.callback(token, resolutionType);
}
this.interceptors.preResolution.setAll(token, remainingInterceptors);
}
}
executePostResolutionInterceptor(token, result, resolutionType) {
if (this.interceptors.postResolution.has(token)) {
const remainingInterceptors = [];
for (const interceptor of this.interceptors.postResolution.getAll(token)) {
if (interceptor.options.frequency != "Once") remainingInterceptors.push(interceptor);
interceptor.callback(token, result, resolutionType);
}
this.interceptors.postResolution.setAll(token, remainingInterceptors);
}
}
resolveRegistration(registration, context) {
this.ensureNotDisposed();
if (registration.options.lifecycle === lifecycle_1.default.ResolutionScoped && context.scopedResolutions.has(registration)) return context.scopedResolutions.get(registration);
const isSingleton = registration.options.lifecycle === lifecycle_1.default.Singleton;
const isContainerScoped = registration.options.lifecycle === lifecycle_1.default.ContainerScoped;
const returnInstance = isSingleton || isContainerScoped;
let resolved;
if (providers_1.isValueProvider(registration.provider)) resolved = registration.provider.useValue;
else if (providers_1.isTokenProvider(registration.provider)) resolved = returnInstance ? registration.instance || (registration.instance = this.resolve(registration.provider.useToken, context)) : this.resolve(registration.provider.useToken, context);
else if (providers_1.isClassProvider(registration.provider)) resolved = returnInstance ? registration.instance || (registration.instance = this.construct(registration.provider.useClass, context)) : this.construct(registration.provider.useClass, context);
else if (providers_1.isFactoryProvider(registration.provider)) resolved = registration.provider.useFactory(this);
else resolved = this.construct(registration.provider, context);
if (registration.options.lifecycle === lifecycle_1.default.ResolutionScoped) context.scopedResolutions.set(registration, resolved);
return resolved;
}
resolveAll(token, context = new resolution_context_1.default(), isOptional = false) {
this.ensureNotDisposed();
const registrations = this.getAllRegistrations(token);
if (!registrations && providers_1.isNormalToken(token)) {
if (isOptional) return [];
throw new Error(`Attempted to resolve unregistered dependency token: "${token.toString()}"`);
}
this.executePreResolutionInterceptor(token, "All");
if (registrations) {
const result = registrations.map((item) => this.resolveRegistration(item, context));
this.executePostResolutionInterceptor(token, result, "All");
return result;
}
const result = [this.construct(token, context)];
this.executePostResolutionInterceptor(token, result, "All");
return result;
}
isRegistered(token, recursive = false) {
this.ensureNotDisposed();
return this._registry.has(token) || recursive && (this.parent || false) && this.parent.isRegistered(token, true);
}
reset() {
this.ensureNotDisposed();
this._registry.clear();
this.interceptors.preResolution.clear();
this.interceptors.postResolution.clear();
}
clearInstances() {
this.ensureNotDisposed();
for (const [token, registrations] of this._registry.entries()) this._registry.setAll(token, registrations.filter((registration) => !providers_1.isValueProvider(registration.provider)).map((registration) => {
registration.instance = void 0;
return registration;
}));
}
createChildContainer() {
this.ensureNotDisposed();
const childContainer = new InternalDependencyContainer(this);
for (const [token, registrations] of this._registry.entries()) if (registrations.some(({ options }) => options.lifecycle === lifecycle_1.default.ContainerScoped)) childContainer._registry.setAll(token, registrations.map((registration) => {
if (registration.options.lifecycle === lifecycle_1.default.ContainerScoped) return {
provider: registration.provider,
options: registration.options
};
return registration;
}));
return childContainer;
}
beforeResolution(token, callback, options = { frequency: "Always" }) {
this.interceptors.preResolution.set(token, {
callback,
options
});
}
afterResolution(token, callback, options = { frequency: "Always" }) {
this.interceptors.postResolution.set(token, {
callback,
options
});
}
dispose() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
this.disposed = true;
const promises = [];
this.disposables.forEach((disposable) => {
const maybePromise = disposable.dispose();
if (maybePromise) promises.push(maybePromise);
});
yield Promise.all(promises);
});
}
getRegistration(token) {
if (this.isRegistered(token)) return this._registry.get(token);
if (this.parent) return this.parent.getRegistration(token);
return null;
}
getAllRegistrations(token) {
if (this.isRegistered(token)) return this._registry.getAll(token);
if (this.parent) return this.parent.getAllRegistrations(token);
return null;
}
construct(ctor, context) {
if (ctor instanceof lazy_helpers_1.DelayedConstructor) return ctor.createProxy((target) => this.resolve(target, context));
const instance = (() => {
const paramInfo = exports.typeInfo.get(ctor);
if (!paramInfo || paramInfo.length === 0) {
if (ctor.length === 0) return new ctor();
else throw new Error(`TypeInfo not known for "${ctor.name}"`);
}
return new ctor(...paramInfo.map(this.resolveParams(context, ctor)));
})();
if (disposable_1.isDisposable(instance)) this.disposables.add(instance);
return instance;
}
resolveParams(context, ctor) {
return (param, idx) => {
try {
if (injection_token_1.isTokenDescriptor(param)) {
if (injection_token_1.isTransformDescriptor(param)) return param.multiple ? this.resolve(param.transform).transform(this.resolveAll(param.token, new resolution_context_1.default(), param.isOptional), ...param.transformArgs) : this.resolve(param.transform).transform(this.resolve(param.token, context, param.isOptional), ...param.transformArgs);
else return param.multiple ? this.resolveAll(param.token, new resolution_context_1.default(), param.isOptional) : this.resolve(param.token, context, param.isOptional);
} else if (injection_token_1.isTransformDescriptor(param)) return this.resolve(param.transform, context).transform(this.resolve(param.token, context), ...param.transformArgs);
return this.resolve(param, context);
} catch (e) {
throw new Error(error_helpers_1.formatErrorCtor(ctor, idx, e));
}
};
}
ensureNotDisposed() {
if (this.disposed) throw new Error("This container has been disposed, you cannot interact with a disposed container");
}
}();
exports.default = exports.instance;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/decorators/auto-injectable.js
var require_auto_injectable = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const reflection_helpers_1 = require_reflection_helpers();
const dependency_container_1 = require_dependency_container();
const injection_token_1 = require_injection_token();
const error_helpers_1 = require_error_helpers();
function autoInjectable() {
return function(target) {
const paramInfo = reflection_helpers_1.getParamInfo(target);
return class extends target {
constructor(...args) {
super(...args.concat(paramInfo.slice(args.length).map((type, index) => {
try {
if (injection_token_1.isTokenDescriptor(type)) {
if (injection_token_1.isTransformDescriptor(type)) return type.multiple ? dependency_container_1.instance.resolve(type.transform).transform(dependency_container_1.instance.resolveAll(type.token), ...type.transformArgs) : dependency_container_1.instance.resolve(type.transform).transform(dependency_container_1.instance.resolve(type.token), ...type.transformArgs);
else return type.multiple ? dependency_container_1.instance.resolveAll(type.token) : dependency_container_1.instance.resolve(type.token);
} else if (injection_token_1.isTransformDescriptor(type)) return dependency_container_1.instance.resolve(type.transform).transform(dependency_container_1.instance.resolve(type.token), ...type.transformArgs);
return dependency_container_1.instance.resolve(type);
} catch (e) {
const argIndex = index + args.length;
throw new Error(error_helpers_1.formatErrorCtor(target, argIndex, e));
}
})));
}
};
};
}
exports.default = autoInjectable;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/decorators/inject.js
var require_inject = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const reflection_helpers_1 = require_reflection_helpers();
function inject(token, options) {
const data = {
token,
multiple: false,
isOptional: options && options.isOptional
};
return reflection_helpers_1.defineInjectionTokenMetadata(data);
}
exports.default = inject;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/decorators/injectable.js
var require_injectable = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const reflection_helpers_1 = require_reflection_helpers();
const dependency_container_1 = require_dependency_container();
const dependency_container_2 = require_dependency_container();
function injectable(options) {
return function(target) {
dependency_container_1.typeInfo.set(target, reflection_helpers_1.getParamInfo(target));
if (options && options.token) {
if (!Array.isArray(options.token)) dependency_container_2.instance.register(options.token, target);
else options.token.forEach((token) => {
dependency_container_2.instance.register(token, target);
});
}
};
}
exports.default = injectable;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/decorators/registry.js
var require_registry = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
const dependency_container_1 = require_dependency_container();
function registry(registrations = []) {
return function(target) {
registrations.forEach((_a) => {
var { token, options } = _a, provider = tslib_1.__rest(_a, ["token", "options"]);
return dependency_container_1.instance.register(token, provider, options);
});
return target;
};
}
exports.default = registry;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/decorators/singleton.js
var require_singleton = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const injectable_1 = require_injectable();
const dependency_container_1 = require_dependency_container();
function singleton() {
return function(target) {
injectable_1.default()(target);
dependency_container_1.instance.registerSingleton(target);
};
}
exports.default = singleton;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/decorators/inject-all.js
var require_inject_all = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const reflection_helpers_1 = require_reflection_helpers();
function injectAll(token, options) {
const data = {
token,
multiple: true,
isOptional: options && options.isOptional
};
return reflection_helpers_1.defineInjectionTokenMetadata(data);
}
exports.default = injectAll;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/decorators/inject-all-with-transform.js
var require_inject_all_with_transform = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const reflection_helpers_1 = require_reflection_helpers();
function injectAllWithTransform(token, transformer, ...args) {
const data = {
token,
multiple: true,
transform: transformer,
transformArgs: args
};
return reflection_helpers_1.defineInjectionTokenMetadata(data);
}
exports.default = injectAllWithTransform;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/decorators/inject-with-transform.js
var require_inject_with_transform = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const reflection_helpers_1 = require_reflection_helpers();
function injectWithTransform(token, transformer, ...args) {
return reflection_helpers_1.defineInjectionTokenMetadata(token, {
transformToken: transformer,
args
});
}
exports.default = injectWithTransform;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/decorators/scoped.js
var require_scoped = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const injectable_1 = require_injectable();
const dependency_container_1 = require_dependency_container();
function scoped(lifecycle, token) {
return function(target) {
injectable_1.default()(target);
dependency_container_1.instance.register(token || target, target, { lifecycle });
};
}
exports.default = scoped;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/decorators/index.js
var require_decorators = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
var auto_injectable_1 = require_auto_injectable();
Object.defineProperty(exports, "autoInjectable", {
enumerable: true,
get: function() {
return auto_injectable_1.default;
}
});
var inject_1 = require_inject();
Object.defineProperty(exports, "inject", {
enumerable: true,
get: function() {
return inject_1.default;
}
});
var injectable_1 = require_injectable();
Object.defineProperty(exports, "injectable", {
enumerable: true,
get: function() {
return injectable_1.default;
}
});
var registry_1 = require_registry();
Object.defineProperty(exports, "registry", {
enumerable: true,
get: function() {
return registry_1.default;
}
});
var singleton_1 = require_singleton();
Object.defineProperty(exports, "singleton", {
enumerable: true,
get: function() {
return singleton_1.default;
}
});
var inject_all_1 = require_inject_all();
Object.defineProperty(exports, "injectAll", {
enumerable: true,
get: function() {
return inject_all_1.default;
}
});
var inject_all_with_transform_1 = require_inject_all_with_transform();
Object.defineProperty(exports, "injectAllWithTransform", {
enumerable: true,
get: function() {
return inject_all_with_transform_1.default;
}
});
var inject_with_transform_1 = require_inject_with_transform();
Object.defineProperty(exports, "injectWithTransform", {
enumerable: true,
get: function() {
return inject_with_transform_1.default;
}
});
var scoped_1 = require_scoped();
Object.defineProperty(exports, "scoped", {
enumerable: true,
get: function() {
return scoped_1.default;
}
});
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/factories/instance-caching-factory.js
var require_instance_caching_factory = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
function instanceCachingFactory(factoryFunc) {
let instance;
return (dependencyContainer) => {
if (instance == void 0) instance = factoryFunc(dependencyContainer);
return instance;
};
}
exports.default = instanceCachingFactory;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/factories/instance-per-container-caching-factory.js
var require_instance_per_container_caching_factory = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
function instancePerContainerCachingFactory(factoryFunc) {
const cache = /* @__PURE__ */ new WeakMap();
return (dependencyContainer) => {
let instance = cache.get(dependencyContainer);
if (instance == void 0) {
instance = factoryFunc(dependencyContainer);
cache.set(dependencyContainer, instance);
}
return instance;
};
}
exports.default = instancePerContainerCachingFactory;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/factories/predicate-aware-class-factory.js
var require_predicate_aware_class_factory = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
function predicateAwareClassFactory(predicate, trueConstructor, falseConstructor, useCaching = true) {
let instance;
let previousPredicate;
return (dependencyContainer) => {
const currentPredicate = predicate(dependencyContainer);
if (!useCaching || previousPredicate !== currentPredicate) {
if (previousPredicate = currentPredicate) instance = dependencyContainer.resolve(trueConstructor);
else instance = dependencyContainer.resolve(falseConstructor);
}
return instance;
};
}
exports.default = predicateAwareClassFactory;
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/factories/index.js
var require_factories = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
var instance_caching_factory_1 = require_instance_caching_factory();
Object.defineProperty(exports, "instanceCachingFactory", {
enumerable: true,
get: function() {
return instance_caching_factory_1.default;
}
});
var instance_per_container_caching_factory_1 = require_instance_per_container_caching_factory();
Object.defineProperty(exports, "instancePerContainerCachingFactory", {
enumerable: true,
get: function() {
return instance_per_container_caching_factory_1.default;
}
});
var predicate_aware_class_factory_1 = require_predicate_aware_class_factory();
Object.defineProperty(exports, "predicateAwareClassFactory", {
enumerable: true,
get: function() {
return predicate_aware_class_factory_1.default;
}
});
}));
//#endregion
//#region node_modules/.pnpm/tsyringe@4.10.0/node_modules/tsyringe/dist/cjs/index.js
var require_cjs$4 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = (init_tslib_es6(), __toCommonJS(tslib_es6_exports));
if (typeof Reflect === "undefined" || !Reflect.getMetadata) throw new Error(`tsyringe requires a reflect polyfill. Please add 'import "reflect-metadata"' to the top of your entry point.`);
var types_1 = require_types$2();
Object.defineProperty(exports, "Lifecycle", {
enumerable: true,
get: function() {
return types_1.Lifecycle;
}
});
tslib_1.__exportStar(require_decorators(), exports);
tslib_1.__exportStar(require_factories(), exports);
tslib_1.__exportStar(require_providers(), exports);
var lazy_helpers_1 = require_lazy_helpers();
Object.defineProperty(exports, "delay", {
enumerable: true,
get: function() {
return lazy_helpers_1.delay;
}
});
var dependency_container_1 = require_dependency_container();
Object.defineProperty(exports, "container", {
enumerable: true,
get: function() {
return dependency_container_1.instance;
}
});
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-pfx@2.9.4/node_modules/@peculiar/asn1-pfx/build/cjs/attribute.js
var require_attribute = /* @__PURE__ */ __commonJSMin(((exports) => {
var PKCS12AttrSet_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PKCS12AttrSet = exports.PKCS12Attribute = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
var PKCS12Attribute = class {
attrId = "";
attrValues = [];
constructor(params = {}) {
Object.assign(params);
}
};
exports.PKCS12Attribute = PKCS12Attribute;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], PKCS12Attribute.prototype, "attrId", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Any,
repeated: "set"
})], PKCS12Attribute.prototype, "attrValues", void 0);
let PKCS12AttrSet = PKCS12AttrSet_1 = class PKCS12AttrSet extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, PKCS12AttrSet_1.prototype);
}
};
exports.PKCS12AttrSet = PKCS12AttrSet;
exports.PKCS12AttrSet = PKCS12AttrSet = PKCS12AttrSet_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: PKCS12Attribute
})], PKCS12AttrSet);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-pfx@2.9.4/node_modules/@peculiar/asn1-pfx/build/cjs/authenticated_safe.js
var require_authenticated_safe = /* @__PURE__ */ __commonJSMin(((exports) => {
var AuthenticatedSafe_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthenticatedSafe = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_cms_1 = require_cjs$7();
let AuthenticatedSafe = AuthenticatedSafe_1 = class AuthenticatedSafe extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, AuthenticatedSafe_1.prototype);
}
};
exports.AuthenticatedSafe = AuthenticatedSafe;
exports.AuthenticatedSafe = AuthenticatedSafe = AuthenticatedSafe_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: asn1_cms_1.ContentInfo
})], AuthenticatedSafe);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-pfx@2.9.4/node_modules/@peculiar/asn1-pfx/build/cjs/object_identifiers.js
var require_object_identifiers = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.id_bagtypes = exports.id_pbewithSHAAnd40BitRC2_CBC = exports.id_pbeWithSHAAnd128BitRC2_CBC = exports.id_pbeWithSHAAnd2_KeyTripleDES_CBC = exports.id_pbeWithSHAAnd3_KeyTripleDES_CBC = exports.id_pbeWithSHAAnd40BitRC4 = exports.id_pbeWithSHAAnd128BitRC4 = exports.id_pkcs_12PbeIds = exports.id_pkcs_12 = exports.id_pkcs = exports.id_rsadsi = void 0;
exports.id_rsadsi = "1.2.840.113549";
exports.id_pkcs = `${exports.id_rsadsi}.1`;
exports.id_pkcs_12 = `${exports.id_pkcs}.12`;
exports.id_pkcs_12PbeIds = `${exports.id_pkcs_12}.1`;
exports.id_pbeWithSHAAnd128BitRC4 = `${exports.id_pkcs_12PbeIds}.1`;
exports.id_pbeWithSHAAnd40BitRC4 = `${exports.id_pkcs_12PbeIds}.2`;
exports.id_pbeWithSHAAnd3_KeyTripleDES_CBC = `${exports.id_pkcs_12PbeIds}.3`;
exports.id_pbeWithSHAAnd2_KeyTripleDES_CBC = `${exports.id_pkcs_12PbeIds}.4`;
exports.id_pbeWithSHAAnd128BitRC2_CBC = `${exports.id_pkcs_12PbeIds}.5`;
exports.id_pbewithSHAAnd40BitRC2_CBC = `${exports.id_pkcs_12PbeIds}.6`;
exports.id_bagtypes = `${exports.id_pkcs_12}.10.1`;
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-pfx@2.9.4/node_modules/@peculiar/asn1-pfx/build/cjs/bags/types.js
var require_types$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.id_pkcs_9 = exports.id_SafeContents = exports.id_SecretBag = exports.id_CRLBag = exports.id_certBag = exports.id_pkcs8ShroudedKeyBag = exports.id_keyBag = void 0;
const object_identifiers_1 = require_object_identifiers();
exports.id_keyBag = `${object_identifiers_1.id_bagtypes}.1`;
exports.id_pkcs8ShroudedKeyBag = `${object_identifiers_1.id_bagtypes}.2`;
exports.id_certBag = `${object_identifiers_1.id_bagtypes}.3`;
exports.id_CRLBag = `${object_identifiers_1.id_bagtypes}.4`;
exports.id_SecretBag = `${object_identifiers_1.id_bagtypes}.5`;
exports.id_SafeContents = `${object_identifiers_1.id_bagtypes}.6`;
exports.id_pkcs_9 = "1.2.840.113549.1.9";
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-pfx@2.9.4/node_modules/@peculiar/asn1-pfx/build/cjs/bags/cert_bag.js
var require_cert_bag = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.id_sdsiCertificate = exports.id_x509Certificate = exports.id_certTypes = exports.CertBag = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const types_1 = require_types$1();
var CertBag = class {
certId = "";
certValue = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.CertBag = CertBag;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], CertBag.prototype, "certId", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Any,
context: 0
})], CertBag.prototype, "certValue", void 0);
exports.id_certTypes = `${types_1.id_pkcs_9}.22`;
exports.id_x509Certificate = `${exports.id_certTypes}.1`;
exports.id_sdsiCertificate = `${exports.id_certTypes}.2`;
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-pfx@2.9.4/node_modules/@peculiar/asn1-pfx/build/cjs/bags/crl_bag.js
var require_crl_bag = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.id_x509CRL = exports.id_crlTypes = exports.CRLBag = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const types_1 = require_types$1();
var CRLBag = class {
crlId = "";
crltValue = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.CRLBag = CRLBag;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], CRLBag.prototype, "crlId", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Any,
context: 0
})], CRLBag.prototype, "crltValue", void 0);
exports.id_crlTypes = `${types_1.id_pkcs_9}.23`;
exports.id_x509CRL = `${exports.id_crlTypes}.1`;
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-pkcs8@2.9.4/node_modules/@peculiar/asn1-pkcs8/build/cjs/encrypted_private_key_info.js
var require_encrypted_private_key_info = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.EncryptedPrivateKeyInfo = exports.EncryptedData = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
var EncryptedData = class extends asn1_schema_1.OctetString {};
exports.EncryptedData = EncryptedData;
var EncryptedPrivateKeyInfo = class {
encryptionAlgorithm = new asn1_x509_1.AlgorithmIdentifier();
encryptedData = new EncryptedData();
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.EncryptedPrivateKeyInfo = EncryptedPrivateKeyInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_x509_1.AlgorithmIdentifier })], EncryptedPrivateKeyInfo.prototype, "encryptionAlgorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: EncryptedData })], EncryptedPrivateKeyInfo.prototype, "encryptedData", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-pkcs8@2.9.4/node_modules/@peculiar/asn1-pkcs8/build/cjs/private_key_info.js
var require_private_key_info = /* @__PURE__ */ __commonJSMin(((exports) => {
var Attributes_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PrivateKeyInfo = exports.Attributes = exports.PrivateKey = exports.Version = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
var Version;
(function(Version) {
Version[Version["v1"] = 0] = "v1";
})(Version || (exports.Version = Version = {}));
var PrivateKey = class extends asn1_schema_1.OctetString {};
exports.PrivateKey = PrivateKey;
let Attributes = Attributes_1 = class Attributes extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, Attributes_1.prototype);
}
};
exports.Attributes = Attributes;
exports.Attributes = Attributes = Attributes_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: asn1_x509_1.Attribute
})], Attributes);
var PrivateKeyInfo = class {
version = Version.v1;
privateKeyAlgorithm = new asn1_x509_1.AlgorithmIdentifier();
privateKey = new PrivateKey();
attributes;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.PrivateKeyInfo = PrivateKeyInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Integer })], PrivateKeyInfo.prototype, "version", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_x509_1.AlgorithmIdentifier })], PrivateKeyInfo.prototype, "privateKeyAlgorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: PrivateKey })], PrivateKeyInfo.prototype, "privateKey", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: Attributes,
implicit: true,
context: 0,
optional: true
})], PrivateKeyInfo.prototype, "attributes", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-pkcs8@2.9.4/node_modules/@peculiar/asn1-pkcs8/build/cjs/index.js
var require_cjs$3 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
tslib_1.__exportStar(require_encrypted_private_key_info(), exports);
tslib_1.__exportStar(require_private_key_info(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-pfx@2.9.4/node_modules/@peculiar/asn1-pfx/build/cjs/bags/key_bag.js
var require_key_bag = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.KeyBag = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_pkcs8_1 = require_cjs$3();
const asn1_schema_1 = require_cjs$10();
let KeyBag = class KeyBag extends asn1_pkcs8_1.PrivateKeyInfo {};
exports.KeyBag = KeyBag;
exports.KeyBag = KeyBag = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], KeyBag);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-pfx@2.9.4/node_modules/@peculiar/asn1-pfx/build/cjs/bags/pkcs8_shrouded_key_bag.js
var require_pkcs8_shrouded_key_bag = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.PKCS8ShroudedKeyBag = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_pkcs8_1 = require_cjs$3();
const asn1_schema_1 = require_cjs$10();
let PKCS8ShroudedKeyBag = class PKCS8ShroudedKeyBag extends asn1_pkcs8_1.EncryptedPrivateKeyInfo {};
exports.PKCS8ShroudedKeyBag = PKCS8ShroudedKeyBag;
exports.PKCS8ShroudedKeyBag = PKCS8ShroudedKeyBag = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], PKCS8ShroudedKeyBag);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-pfx@2.9.4/node_modules/@peculiar/asn1-pfx/build/cjs/bags/secret_bag.js
var require_secret_bag = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.SecretBag = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
var SecretBag = class {
secretTypeId = "";
secretValue = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.SecretBag = SecretBag;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], SecretBag.prototype, "secretTypeId", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Any,
context: 0
})], SecretBag.prototype, "secretValue", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-pfx@2.9.4/node_modules/@peculiar/asn1-pfx/build/cjs/bags/index.js
var require_bags = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
tslib_1.__exportStar(require_cert_bag(), exports);
tslib_1.__exportStar(require_crl_bag(), exports);
tslib_1.__exportStar(require_key_bag(), exports);
tslib_1.__exportStar(require_pkcs8_shrouded_key_bag(), exports);
tslib_1.__exportStar(require_secret_bag(), exports);
tslib_1.__exportStar(require_types$1(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-pfx@2.9.4/node_modules/@peculiar/asn1-pfx/build/cjs/mac_data.js
var require_mac_data = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.MacData = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_rsa_1 = require_cjs$5();
const asn1_schema_1 = require_cjs$10();
var MacData = class {
mac = new asn1_rsa_1.DigestInfo();
macSalt = new asn1_schema_1.OctetString();
iterations = 1;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.MacData = MacData;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_rsa_1.DigestInfo })], MacData.prototype, "mac", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.OctetString })], MacData.prototype, "macSalt", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Integer,
defaultValue: 1
})], MacData.prototype, "iterations", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-pfx@2.9.4/node_modules/@peculiar/asn1-pfx/build/cjs/pfx.js
var require_pfx = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.PFX = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_cms_1 = require_cjs$7();
const mac_data_1 = require_mac_data();
var PFX = class {
version = 3;
authSafe = new asn1_cms_1.ContentInfo();
macData = new mac_data_1.MacData();
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.PFX = PFX;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Integer })], PFX.prototype, "version", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_cms_1.ContentInfo })], PFX.prototype, "authSafe", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: mac_data_1.MacData,
optional: true
})], PFX.prototype, "macData", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-pfx@2.9.4/node_modules/@peculiar/asn1-pfx/build/cjs/safe_bag.js
var require_safe_bag = /* @__PURE__ */ __commonJSMin(((exports) => {
var SafeContents_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SafeContents = exports.SafeBag = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const attribute_1 = require_attribute();
var SafeBag = class {
bagId = "";
bagValue = /* @__PURE__ */ new ArrayBuffer(0);
bagAttributes;
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.SafeBag = SafeBag;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], SafeBag.prototype, "bagId", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: asn1_schema_1.AsnPropTypes.Any,
context: 0
})], SafeBag.prototype, "bagValue", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: attribute_1.PKCS12Attribute,
repeated: "set",
optional: true
})], SafeBag.prototype, "bagAttributes", void 0);
let SafeContents = SafeContents_1 = class SafeContents extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, SafeContents_1.prototype);
}
};
exports.SafeContents = SafeContents;
exports.SafeContents = SafeContents = SafeContents_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: SafeBag
})], SafeContents);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-pfx@2.9.4/node_modules/@peculiar/asn1-pfx/build/cjs/index.js
var require_cjs$2 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
tslib_1.__exportStar(require_attribute(), exports);
tslib_1.__exportStar(require_authenticated_safe(), exports);
tslib_1.__exportStar(require_bags(), exports);
tslib_1.__exportStar(require_mac_data(), exports);
tslib_1.__exportStar(require_object_identifiers(), exports);
tslib_1.__exportStar(require_pfx(), exports);
tslib_1.__exportStar(require_safe_bag(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-pkcs9@2.9.4/node_modules/@peculiar/asn1-pkcs9/build/cjs/index.js
var require_cjs$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
var ExtensionRequest_1;
var ExtendedCertificateAttributes_1;
var SMIMECapabilities_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.DateOfBirth = exports.UnstructuredAddress = exports.UnstructuredName = exports.EmailAddress = exports.EncryptedPrivateKeyInfo = exports.UserPKCS12 = exports.Pkcs7PDU = exports.PKCS9String = exports.id_at_pseudonym = exports.crlTypes = exports.id_certTypes = exports.id_smime = exports.id_pkcs9_mr_signingTimeMatch = exports.id_pkcs9_mr_caseIgnoreMatch = exports.id_pkcs9_sx_signingTime = exports.id_pkcs9_sx_pkcs9String = exports.id_pkcs9_at_countryOfResidence = exports.id_pkcs9_at_countryOfCitizenship = exports.id_pkcs9_at_gender = exports.id_pkcs9_at_placeOfBirth = exports.id_pkcs9_at_dateOfBirth = exports.id_ietf_at = exports.id_pkcs9_at_pkcs7PDU = exports.id_pkcs9_at_sequenceNumber = exports.id_pkcs9_at_randomNonce = exports.id_pkcs9_at_encryptedPrivateKeyInfo = exports.id_pkcs9_at_pkcs15Token = exports.id_pkcs9_at_userPKCS12 = exports.id_pkcs9_at_localKeyId = exports.id_pkcs9_at_friendlyName = exports.id_pkcs9_at_smimeCapabilities = exports.id_pkcs9_at_extensionRequest = exports.id_pkcs9_at_signingDescription = exports.id_pkcs9_at_extendedCertificateAttributes = exports.id_pkcs9_at_unstructuredAddress = exports.id_pkcs9_at_challengePassword = exports.id_pkcs9_at_counterSignature = exports.id_pkcs9_at_signingTime = exports.id_pkcs9_at_messageDigest = exports.id_pkcs9_at_contentType = exports.id_pkcs9_at_unstructuredName = exports.id_pkcs9_at_emailAddress = exports.id_pkcs9_oc_naturalPerson = exports.id_pkcs9_oc_pkcsEntity = exports.id_pkcs9_mr = exports.id_pkcs9_sx = exports.id_pkcs9_at = exports.id_pkcs9_oc = exports.id_pkcs9_mo = exports.id_pkcs9 = void 0;
exports.SMIMECapabilities = exports.SMIMECapability = exports.SigningDescription = exports.LocalKeyId = exports.FriendlyName = exports.ExtendedCertificateAttributes = exports.ExtensionRequest = exports.ChallengePassword = exports.CounterSignature = exports.SequenceNumber = exports.RandomNonce = exports.SigningTime = exports.MessageDigest = exports.ContentType = exports.Pseudonym = exports.CountryOfResidence = exports.CountryOfCitizenship = exports.Gender = exports.PlaceOfBirth = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const cms = tslib_1.__importStar(require_cjs$7());
const pfx = tslib_1.__importStar(require_cjs$2());
const pkcs8 = tslib_1.__importStar(require_cjs$3());
const x509 = tslib_1.__importStar(require_cjs$9());
const attr = tslib_1.__importStar(require_cjs$8());
exports.id_pkcs9 = "1.2.840.113549.1.9";
exports.id_pkcs9_mo = `${exports.id_pkcs9}.0`;
exports.id_pkcs9_oc = `${exports.id_pkcs9}.24`;
exports.id_pkcs9_at = `${exports.id_pkcs9}.25`;
exports.id_pkcs9_sx = `${exports.id_pkcs9}.26`;
exports.id_pkcs9_mr = `${exports.id_pkcs9}.27`;
exports.id_pkcs9_oc_pkcsEntity = `${exports.id_pkcs9_oc}.1`;
exports.id_pkcs9_oc_naturalPerson = `${exports.id_pkcs9_oc}.2`;
exports.id_pkcs9_at_emailAddress = `${exports.id_pkcs9}.1`;
exports.id_pkcs9_at_unstructuredName = `${exports.id_pkcs9}.2`;
exports.id_pkcs9_at_contentType = `${exports.id_pkcs9}.3`;
exports.id_pkcs9_at_messageDigest = `${exports.id_pkcs9}.4`;
exports.id_pkcs9_at_signingTime = `${exports.id_pkcs9}.5`;
exports.id_pkcs9_at_counterSignature = `${exports.id_pkcs9}.6`;
exports.id_pkcs9_at_challengePassword = `${exports.id_pkcs9}.7`;
exports.id_pkcs9_at_unstructuredAddress = `${exports.id_pkcs9}.8`;
exports.id_pkcs9_at_extendedCertificateAttributes = `${exports.id_pkcs9}.9`;
exports.id_pkcs9_at_signingDescription = `${exports.id_pkcs9}.13`;
exports.id_pkcs9_at_extensionRequest = `${exports.id_pkcs9}.14`;
exports.id_pkcs9_at_smimeCapabilities = `${exports.id_pkcs9}.15`;
exports.id_pkcs9_at_friendlyName = `${exports.id_pkcs9}.20`;
exports.id_pkcs9_at_localKeyId = `${exports.id_pkcs9}.21`;
exports.id_pkcs9_at_userPKCS12 = "2.16.840.1.113730.3.1.216";
exports.id_pkcs9_at_pkcs15Token = `${exports.id_pkcs9_at}.1`;
exports.id_pkcs9_at_encryptedPrivateKeyInfo = `${exports.id_pkcs9_at}.2`;
exports.id_pkcs9_at_randomNonce = `${exports.id_pkcs9_at}.3`;
exports.id_pkcs9_at_sequenceNumber = `${exports.id_pkcs9_at}.4`;
exports.id_pkcs9_at_pkcs7PDU = `${exports.id_pkcs9_at}.5`;
exports.id_ietf_at = "1.3.6.1.5.5.7.9";
exports.id_pkcs9_at_dateOfBirth = `${exports.id_ietf_at}.1`;
exports.id_pkcs9_at_placeOfBirth = `${exports.id_ietf_at}.2`;
exports.id_pkcs9_at_gender = `${exports.id_ietf_at}.3`;
exports.id_pkcs9_at_countryOfCitizenship = `${exports.id_ietf_at}.4`;
exports.id_pkcs9_at_countryOfResidence = `${exports.id_ietf_at}.5`;
exports.id_pkcs9_sx_pkcs9String = `${exports.id_pkcs9_sx}.1`;
exports.id_pkcs9_sx_signingTime = `${exports.id_pkcs9_sx}.2`;
exports.id_pkcs9_mr_caseIgnoreMatch = `${exports.id_pkcs9_mr}.1`;
exports.id_pkcs9_mr_signingTimeMatch = `${exports.id_pkcs9_mr}.2`;
exports.id_smime = `${exports.id_pkcs9}.16`;
exports.id_certTypes = `${exports.id_pkcs9}.22`;
exports.crlTypes = `${exports.id_pkcs9}.23`;
exports.id_at_pseudonym = `${attr.id_at}.65`;
let PKCS9String = class PKCS9String extends x509.DirectoryString {
ia5String;
constructor(params = {}) {
super(params);
}
toString() {
({}).toString();
return this.ia5String || super.toString();
}
};
exports.PKCS9String = PKCS9String;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.IA5String })], PKCS9String.prototype, "ia5String", void 0);
exports.PKCS9String = PKCS9String = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], PKCS9String);
let Pkcs7PDU = class Pkcs7PDU extends cms.ContentInfo {};
exports.Pkcs7PDU = Pkcs7PDU;
exports.Pkcs7PDU = Pkcs7PDU = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], Pkcs7PDU);
let UserPKCS12 = class UserPKCS12 extends pfx.PFX {};
exports.UserPKCS12 = UserPKCS12;
exports.UserPKCS12 = UserPKCS12 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], UserPKCS12);
let EncryptedPrivateKeyInfo = class EncryptedPrivateKeyInfo extends pkcs8.EncryptedPrivateKeyInfo {};
exports.EncryptedPrivateKeyInfo = EncryptedPrivateKeyInfo;
exports.EncryptedPrivateKeyInfo = EncryptedPrivateKeyInfo = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], EncryptedPrivateKeyInfo);
let EmailAddress = class EmailAddress {
value;
constructor(value = "") {
this.value = value;
}
toString() {
return this.value;
}
};
exports.EmailAddress = EmailAddress;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.IA5String })], EmailAddress.prototype, "value", void 0);
exports.EmailAddress = EmailAddress = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], EmailAddress);
let UnstructuredName = class UnstructuredName extends PKCS9String {};
exports.UnstructuredName = UnstructuredName;
exports.UnstructuredName = UnstructuredName = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], UnstructuredName);
let UnstructuredAddress = class UnstructuredAddress extends x509.DirectoryString {};
exports.UnstructuredAddress = UnstructuredAddress;
exports.UnstructuredAddress = UnstructuredAddress = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], UnstructuredAddress);
let DateOfBirth = class DateOfBirth {
value;
constructor(value = /* @__PURE__ */ new Date()) {
this.value = value;
}
};
exports.DateOfBirth = DateOfBirth;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.GeneralizedTime })], DateOfBirth.prototype, "value", void 0);
exports.DateOfBirth = DateOfBirth = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], DateOfBirth);
let PlaceOfBirth = class PlaceOfBirth extends x509.DirectoryString {};
exports.PlaceOfBirth = PlaceOfBirth;
exports.PlaceOfBirth = PlaceOfBirth = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], PlaceOfBirth);
let Gender = class Gender {
value;
constructor(value = "M") {
this.value = value;
}
toString() {
return this.value;
}
};
exports.Gender = Gender;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.PrintableString })], Gender.prototype, "value", void 0);
exports.Gender = Gender = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], Gender);
let CountryOfCitizenship = class CountryOfCitizenship {
value;
constructor(value = "") {
this.value = value;
}
toString() {
return this.value;
}
};
exports.CountryOfCitizenship = CountryOfCitizenship;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.PrintableString })], CountryOfCitizenship.prototype, "value", void 0);
exports.CountryOfCitizenship = CountryOfCitizenship = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], CountryOfCitizenship);
let CountryOfResidence = class CountryOfResidence extends CountryOfCitizenship {};
exports.CountryOfResidence = CountryOfResidence;
exports.CountryOfResidence = CountryOfResidence = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], CountryOfResidence);
let Pseudonym = class Pseudonym extends x509.DirectoryString {};
exports.Pseudonym = Pseudonym;
exports.Pseudonym = Pseudonym = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], Pseudonym);
let ContentType = class ContentType {
value;
constructor(value = "") {
this.value = value;
}
toString() {
return this.value;
}
};
exports.ContentType = ContentType;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.ObjectIdentifier })], ContentType.prototype, "value", void 0);
exports.ContentType = ContentType = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], ContentType);
var MessageDigest = class extends asn1_schema_1.OctetString {};
exports.MessageDigest = MessageDigest;
let SigningTime = class SigningTime extends x509.Time {};
exports.SigningTime = SigningTime;
exports.SigningTime = SigningTime = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], SigningTime);
var RandomNonce = class extends asn1_schema_1.OctetString {};
exports.RandomNonce = RandomNonce;
let SequenceNumber = class SequenceNumber {
value;
constructor(value = 0) {
this.value = value;
}
toString() {
return this.value.toString();
}
};
exports.SequenceNumber = SequenceNumber;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Integer })], SequenceNumber.prototype, "value", void 0);
exports.SequenceNumber = SequenceNumber = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], SequenceNumber);
let CounterSignature = class CounterSignature extends cms.SignerInfo {};
exports.CounterSignature = CounterSignature;
exports.CounterSignature = CounterSignature = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], CounterSignature);
let ChallengePassword = class ChallengePassword extends x509.DirectoryString {};
exports.ChallengePassword = ChallengePassword;
exports.ChallengePassword = ChallengePassword = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], ChallengePassword);
let ExtensionRequest = ExtensionRequest_1 = class ExtensionRequest extends x509.Extensions {
constructor(items) {
super(items);
Object.setPrototypeOf(this, ExtensionRequest_1.prototype);
}
};
exports.ExtensionRequest = ExtensionRequest;
exports.ExtensionRequest = ExtensionRequest = ExtensionRequest_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], ExtensionRequest);
let ExtendedCertificateAttributes = ExtendedCertificateAttributes_1 = class ExtendedCertificateAttributes extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, ExtendedCertificateAttributes_1.prototype);
}
};
exports.ExtendedCertificateAttributes = ExtendedCertificateAttributes;
exports.ExtendedCertificateAttributes = ExtendedCertificateAttributes = ExtendedCertificateAttributes_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Set,
itemType: cms.Attribute
})], ExtendedCertificateAttributes);
let FriendlyName = class FriendlyName {
value;
constructor(value = "") {
this.value = value;
}
toString() {
return this.value;
}
};
exports.FriendlyName = FriendlyName;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.BmpString })], FriendlyName.prototype, "value", void 0);
exports.FriendlyName = FriendlyName = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })], FriendlyName);
var LocalKeyId = class extends asn1_schema_1.OctetString {};
exports.LocalKeyId = LocalKeyId;
var SigningDescription = class extends x509.DirectoryString {};
exports.SigningDescription = SigningDescription;
let SMIMECapability = class SMIMECapability extends x509.AlgorithmIdentifier {};
exports.SMIMECapability = SMIMECapability;
exports.SMIMECapability = SMIMECapability = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence })], SMIMECapability);
let SMIMECapabilities = SMIMECapabilities_1 = class SMIMECapabilities extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, SMIMECapabilities_1.prototype);
}
};
exports.SMIMECapabilities = SMIMECapabilities;
exports.SMIMECapabilities = SMIMECapabilities = SMIMECapabilities_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: SMIMECapability
})], SMIMECapabilities);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-csr@2.9.4/node_modules/@peculiar/asn1-csr/build/cjs/attributes.js
var require_attributes = /* @__PURE__ */ __commonJSMin(((exports) => {
var Attributes_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Attributes = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
let Attributes = Attributes_1 = class Attributes extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, Attributes_1.prototype);
}
};
exports.Attributes = Attributes;
exports.Attributes = Attributes = Attributes_1 = tslib_1.__decorate([(0, asn1_schema_1.AsnType)({
type: asn1_schema_1.AsnTypeTypes.Sequence,
itemType: asn1_x509_1.Attribute
})], Attributes);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-csr@2.9.4/node_modules/@peculiar/asn1-csr/build/cjs/certification_request_info.js
var require_certification_request_info = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.CertificationRequestInfo = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
const attributes_1 = require_attributes();
var CertificationRequestInfo = class {
version = 0;
subject = new asn1_x509_1.Name();
subjectPKInfo = new asn1_x509_1.SubjectPublicKeyInfo();
attributes = new attributes_1.Attributes();
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.CertificationRequestInfo = CertificationRequestInfo;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.Integer })], CertificationRequestInfo.prototype, "version", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_x509_1.Name })], CertificationRequestInfo.prototype, "subject", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_x509_1.SubjectPublicKeyInfo })], CertificationRequestInfo.prototype, "subjectPKInfo", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: attributes_1.Attributes,
implicit: true,
context: 0,
optional: true
})], CertificationRequestInfo.prototype, "attributes", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-csr@2.9.4/node_modules/@peculiar/asn1-csr/build/cjs/certification_request.js
var require_certification_request = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.CertificationRequest = void 0;
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
const asn1_schema_1 = require_cjs$10();
const asn1_x509_1 = require_cjs$9();
const certification_request_info_1 = require_certification_request_info();
var CertificationRequest = class {
certificationRequestInfo = new certification_request_info_1.CertificationRequestInfo();
certificationRequestInfoRaw;
signatureAlgorithm = new asn1_x509_1.AlgorithmIdentifier();
signature = /* @__PURE__ */ new ArrayBuffer(0);
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.CertificationRequest = CertificationRequest;
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({
type: certification_request_info_1.CertificationRequestInfo,
raw: true
})], CertificationRequest.prototype, "certificationRequestInfo", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_x509_1.AlgorithmIdentifier })], CertificationRequest.prototype, "signatureAlgorithm", void 0);
tslib_1.__decorate([(0, asn1_schema_1.AsnProp)({ type: asn1_schema_1.AsnPropTypes.BitString })], CertificationRequest.prototype, "signature", void 0);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+asn1-csr@2.9.4/node_modules/@peculiar/asn1-csr/build/cjs/index.js
var require_cjs = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
tslib_1.__exportStar(require_attributes(), exports);
tslib_1.__exportStar(require_certification_request(), exports);
tslib_1.__exportStar(require_certification_request_info(), exports);
}));
//#endregion
//#region node_modules/.pnpm/@peculiar+x509@1.14.3/node_modules/@peculiar/x509/build/x509.cjs.js
/*!
* MIT License
*
* Copyright (c) Peculiar Ventures. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
var require_x509_cjs = /* @__PURE__ */ __commonJSMin(((exports) => {
require_Reflect();
var asn1Schema = require_cjs$10();
var asn1X509 = require_cjs$9();
var pvtsutils = require_build$3();
var tslib = (init_tslib_es6$1(), __toCommonJS(tslib_es6_exports$1));
var asn1Cms = require_cjs$7();
var asn1Ecc = require_cjs$6();
var asn1Rsa = require_cjs$5();
var tsyringe = require_cjs$4();
var asnPkcs9 = require_cjs$1();
var asn1Csr = require_cjs();
function _interopNamespaceDefault(e) {
var n = Object.create(null);
if (e) Object.keys(e).forEach(function(k) {
if (k !== "default") {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function() {
return e[k];
}
});
}
});
n.default = e;
return Object.freeze(n);
}
var asn1X509__namespace = /*#__PURE__*/ _interopNamespaceDefault(asn1X509);
var asn1Cms__namespace = /*#__PURE__*/ _interopNamespaceDefault(asn1Cms);
var asn1Ecc__namespace = /*#__PURE__*/ _interopNamespaceDefault(asn1Ecc);
var asn1Rsa__namespace = /*#__PURE__*/ _interopNamespaceDefault(asn1Rsa);
var asnPkcs9__namespace = /*#__PURE__*/ _interopNamespaceDefault(asnPkcs9);
const diAlgorithm = "crypto.algorithm";
var AlgorithmProvider = class {
getAlgorithms() {
return tsyringe.container.resolveAll(diAlgorithm);
}
toAsnAlgorithm(alg) {
({ ...alg });
for (const algorithm of this.getAlgorithms()) {
const res = algorithm.toAsnAlgorithm(alg);
if (res) return res;
}
if (/^[0-9.]+$/.test(alg.name)) {
const res = new asn1X509.AlgorithmIdentifier({ algorithm: alg.name });
if ("parameters" in alg) res.parameters = alg.parameters;
return res;
}
throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm");
}
toWebAlgorithm(alg) {
for (const algorithm of this.getAlgorithms()) {
const res = algorithm.toWebAlgorithm(alg);
if (res) return res;
}
return {
name: alg.algorithm,
parameters: alg.parameters
};
}
};
const diAlgorithmProvider = "crypto.algorithmProvider";
tsyringe.container.registerSingleton(diAlgorithmProvider, AlgorithmProvider);
var EcAlgorithm_1;
const idVersionOne = "1.3.36.3.3.2.8.1.1";
const idBrainpoolP160r1 = `${idVersionOne}.1`;
const idBrainpoolP160t1 = `${idVersionOne}.2`;
const idBrainpoolP192r1 = `${idVersionOne}.3`;
const idBrainpoolP192t1 = `${idVersionOne}.4`;
const idBrainpoolP224r1 = `${idVersionOne}.5`;
const idBrainpoolP224t1 = `${idVersionOne}.6`;
const idBrainpoolP256r1 = `${idVersionOne}.7`;
const idBrainpoolP256t1 = `${idVersionOne}.8`;
const idBrainpoolP320r1 = `${idVersionOne}.9`;
const idBrainpoolP320t1 = `${idVersionOne}.10`;
const idBrainpoolP384r1 = `${idVersionOne}.11`;
const idBrainpoolP384t1 = `${idVersionOne}.12`;
const idBrainpoolP512r1 = `${idVersionOne}.13`;
const idBrainpoolP512t1 = `${idVersionOne}.14`;
const brainpoolP160r1 = "brainpoolP160r1";
const brainpoolP160t1 = "brainpoolP160t1";
const brainpoolP192r1 = "brainpoolP192r1";
const brainpoolP192t1 = "brainpoolP192t1";
const brainpoolP224r1 = "brainpoolP224r1";
const brainpoolP224t1 = "brainpoolP224t1";
const brainpoolP256r1 = "brainpoolP256r1";
const brainpoolP256t1 = "brainpoolP256t1";
const brainpoolP320r1 = "brainpoolP320r1";
const brainpoolP320t1 = "brainpoolP320t1";
const brainpoolP384r1 = "brainpoolP384r1";
const brainpoolP384t1 = "brainpoolP384t1";
const brainpoolP512r1 = "brainpoolP512r1";
const brainpoolP512t1 = "brainpoolP512t1";
const ECDSA = "ECDSA";
exports.EcAlgorithm = EcAlgorithm_1 = class EcAlgorithm {
toAsnAlgorithm(alg) {
switch (alg.name.toLowerCase()) {
case ECDSA.toLowerCase(): if ("hash" in alg) switch ((typeof alg.hash === "string" ? alg.hash : alg.hash.name).toLowerCase()) {
case "sha-1": return asn1Ecc__namespace.ecdsaWithSHA1;
case "sha-256": return asn1Ecc__namespace.ecdsaWithSHA256;
case "sha-384": return asn1Ecc__namespace.ecdsaWithSHA384;
case "sha-512": return asn1Ecc__namespace.ecdsaWithSHA512;
}
else if ("namedCurve" in alg) {
let parameters = "";
switch (alg.namedCurve) {
case "P-256":
parameters = asn1Ecc__namespace.id_secp256r1;
break;
case "K-256":
parameters = EcAlgorithm_1.SECP256K1;
break;
case "P-384":
parameters = asn1Ecc__namespace.id_secp384r1;
break;
case "P-521":
parameters = asn1Ecc__namespace.id_secp521r1;
break;
case brainpoolP160r1:
parameters = idBrainpoolP160r1;
break;
case brainpoolP160t1:
parameters = idBrainpoolP160t1;
break;
case brainpoolP192r1:
parameters = idBrainpoolP192r1;
break;
case brainpoolP192t1:
parameters = idBrainpoolP192t1;
break;
case brainpoolP224r1:
parameters = idBrainpoolP224r1;
break;
case brainpoolP224t1:
parameters = idBrainpoolP224t1;
break;
case brainpoolP256r1:
parameters = idBrainpoolP256r1;
break;
case brainpoolP256t1:
parameters = idBrainpoolP256t1;
break;
case brainpoolP320r1:
parameters = idBrainpoolP320r1;
break;
case brainpoolP320t1:
parameters = idBrainpoolP320t1;
break;
case brainpoolP384r1:
parameters = idBrainpoolP384r1;
break;
case brainpoolP384t1:
parameters = idBrainpoolP384t1;
break;
case brainpoolP512r1:
parameters = idBrainpoolP512r1;
break;
case brainpoolP512t1: parameters = idBrainpoolP512t1;
}
if (parameters) return new asn1X509.AlgorithmIdentifier({
algorithm: asn1Ecc__namespace.id_ecPublicKey,
parameters: asn1Schema.AsnConvert.serialize(new asn1Ecc__namespace.ECParameters({ namedCurve: parameters }))
});
}
}
return null;
}
toWebAlgorithm(alg) {
switch (alg.algorithm) {
case asn1Ecc__namespace.id_ecdsaWithSHA1: return {
name: ECDSA,
hash: { name: "SHA-1" }
};
case asn1Ecc__namespace.id_ecdsaWithSHA256: return {
name: ECDSA,
hash: { name: "SHA-256" }
};
case asn1Ecc__namespace.id_ecdsaWithSHA384: return {
name: ECDSA,
hash: { name: "SHA-384" }
};
case asn1Ecc__namespace.id_ecdsaWithSHA512: return {
name: ECDSA,
hash: { name: "SHA-512" }
};
case asn1Ecc__namespace.id_ecPublicKey:
if (!alg.parameters) throw new TypeError("Cannot get required parameters from EC algorithm");
switch (asn1Schema.AsnConvert.parse(alg.parameters, asn1Ecc__namespace.ECParameters).namedCurve) {
case asn1Ecc__namespace.id_secp256r1: return {
name: ECDSA,
namedCurve: "P-256"
};
case EcAlgorithm_1.SECP256K1: return {
name: ECDSA,
namedCurve: "K-256"
};
case asn1Ecc__namespace.id_secp384r1: return {
name: ECDSA,
namedCurve: "P-384"
};
case asn1Ecc__namespace.id_secp521r1: return {
name: ECDSA,
namedCurve: "P-521"
};
case idBrainpoolP160r1: return {
name: ECDSA,
namedCurve: brainpoolP160r1
};
case idBrainpoolP160t1: return {
name: ECDSA,
namedCurve: brainpoolP160t1
};
case idBrainpoolP192r1: return {
name: ECDSA,
namedCurve: brainpoolP192r1
};
case idBrainpoolP192t1: return {
name: ECDSA,
namedCurve: brainpoolP192t1
};
case idBrainpoolP224r1: return {
name: ECDSA,
namedCurve: brainpoolP224r1
};
case idBrainpoolP224t1: return {
name: ECDSA,
namedCurve: brainpoolP224t1
};
case idBrainpoolP256r1: return {
name: ECDSA,
namedCurve: brainpoolP256r1
};
case idBrainpoolP256t1: return {
name: ECDSA,
namedCurve: brainpoolP256t1
};
case idBrainpoolP320r1: return {
name: ECDSA,
namedCurve: brainpoolP320r1
};
case idBrainpoolP320t1: return {
name: ECDSA,
namedCurve: brainpoolP320t1
};
case idBrainpoolP384r1: return {
name: ECDSA,
namedCurve: brainpoolP384r1
};
case idBrainpoolP384t1: return {
name: ECDSA,
namedCurve: brainpoolP384t1
};
case idBrainpoolP512r1: return {
name: ECDSA,
namedCurve: brainpoolP512r1
};
case idBrainpoolP512t1: return {
name: ECDSA,
namedCurve: brainpoolP512t1
};
}
}
return null;
}
};
exports.EcAlgorithm.SECP256K1 = "1.3.132.0.10";
exports.EcAlgorithm = EcAlgorithm_1 = tslib.__decorate([tsyringe.injectable()], exports.EcAlgorithm);
tsyringe.container.registerSingleton(diAlgorithm, exports.EcAlgorithm);
const NAME = Symbol("name");
const VALUE = Symbol("value");
var TextObject = class {
constructor(name, items = {}, value = "") {
this[NAME] = name;
this[VALUE] = value;
for (const key in items) this[key] = items[key];
}
};
TextObject.NAME = NAME;
TextObject.VALUE = VALUE;
var DefaultAlgorithmSerializer = class {
static toTextObject(alg) {
const obj = new TextObject("Algorithm Identifier", {}, OidSerializer.toString(alg.algorithm));
if (alg.parameters) switch (alg.algorithm) {
case asn1Ecc__namespace.id_ecPublicKey: {
const ecAlg = new exports.EcAlgorithm().toWebAlgorithm(alg);
if (ecAlg && "namedCurve" in ecAlg) obj["Named Curve"] = ecAlg.namedCurve;
else obj["Parameters"] = alg.parameters;
break;
}
default: obj["Parameters"] = alg.parameters;
}
return obj;
}
};
var OidSerializer = class {
static toString(oid) {
const name = this.items[oid];
if (name) return name;
return oid;
}
};
OidSerializer.items = {
[asn1Rsa__namespace.id_sha1]: "sha1",
[asn1Rsa__namespace.id_sha224]: "sha224",
[asn1Rsa__namespace.id_sha256]: "sha256",
[asn1Rsa__namespace.id_sha384]: "sha384",
[asn1Rsa__namespace.id_sha512]: "sha512",
[asn1Rsa__namespace.id_rsaEncryption]: "rsaEncryption",
[asn1Rsa__namespace.id_sha1WithRSAEncryption]: "sha1WithRSAEncryption",
[asn1Rsa__namespace.id_sha224WithRSAEncryption]: "sha224WithRSAEncryption",
[asn1Rsa__namespace.id_sha256WithRSAEncryption]: "sha256WithRSAEncryption",
[asn1Rsa__namespace.id_sha384WithRSAEncryption]: "sha384WithRSAEncryption",
[asn1Rsa__namespace.id_sha512WithRSAEncryption]: "sha512WithRSAEncryption",
[asn1Ecc__namespace.id_ecPublicKey]: "ecPublicKey",
[asn1Ecc__namespace.id_ecdsaWithSHA1]: "ecdsaWithSHA1",
[asn1Ecc__namespace.id_ecdsaWithSHA224]: "ecdsaWithSHA224",
[asn1Ecc__namespace.id_ecdsaWithSHA256]: "ecdsaWithSHA256",
[asn1Ecc__namespace.id_ecdsaWithSHA384]: "ecdsaWithSHA384",
[asn1Ecc__namespace.id_ecdsaWithSHA512]: "ecdsaWithSHA512",
[asn1X509__namespace.id_kp_serverAuth]: "TLS WWW server authentication",
[asn1X509__namespace.id_kp_clientAuth]: "TLS WWW client authentication",
[asn1X509__namespace.id_kp_codeSigning]: "Code Signing",
[asn1X509__namespace.id_kp_emailProtection]: "E-mail Protection",
[asn1X509__namespace.id_kp_timeStamping]: "Time Stamping",
[asn1X509__namespace.id_kp_OCSPSigning]: "OCSP Signing",
[asn1Cms__namespace.id_signedData]: "Signed Data"
};
var TextConverter = class {
static serialize(obj) {
return this.serializeObj(obj).join("\n");
}
static pad(deep = 0) {
return "".padStart(2 * deep, " ");
}
static serializeObj(obj, deep = 0) {
const res = [];
let pad = this.pad(deep++);
let value = "";
const objValue = obj[TextObject.VALUE];
if (objValue) value = ` ${objValue}`;
res.push(`${pad}${obj[TextObject.NAME]}:${value}`);
pad = this.pad(deep);
for (const key in obj) {
if (typeof key === "symbol") continue;
const value = obj[key];
const keyValue = key ? `${key}: ` : "";
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") res.push(`${pad}${keyValue}${value}`);
else if (value instanceof Date) res.push(`${pad}${keyValue}${value.toUTCString()}`);
else if (Array.isArray(value)) for (const obj of value) {
obj[TextObject.NAME] = key;
res.push(...this.serializeObj(obj, deep));
}
else if (value instanceof TextObject) {
value[TextObject.NAME] = key;
res.push(...this.serializeObj(value, deep));
} else if (pvtsutils.BufferSourceConverter.isBufferSource(value)) {
if (key) {
res.push(`${pad}${keyValue}`);
res.push(...this.serializeBufferSource(value, deep + 1));
} else res.push(...this.serializeBufferSource(value, deep));
} else if ("toTextObject" in value) {
const obj = value.toTextObject();
obj[TextObject.NAME] = key;
res.push(...this.serializeObj(obj, deep));
} else throw new TypeError("Cannot serialize data in text format. Unsupported type.");
}
return res;
}
static serializeBufferSource(buffer, deep = 0) {
const pad = this.pad(deep);
const view = pvtsutils.BufferSourceConverter.toUint8Array(buffer);
const res = [];
for (let i = 0; i < view.length;) {
const row = [];
for (let j = 0; j < 16 && i < view.length; j++) {
if (j === 8) row.push("");
const hex = view[i++].toString(16).padStart(2, "0");
row.push(hex);
}
res.push(`${pad}${row.join(" ")}`);
}
return res;
}
static serializeAlgorithm(alg) {
return this.algorithmSerializer.toTextObject(alg);
}
};
TextConverter.oidSerializer = OidSerializer;
TextConverter.algorithmSerializer = DefaultAlgorithmSerializer;
var _AsnData_rawData;
var AsnData = class AsnData {
get rawData() {
if (!tslib.__classPrivateFieldGet(this, _AsnData_rawData, "f")) tslib.__classPrivateFieldSet(this, _AsnData_rawData, asn1Schema.AsnConvert.serialize(this.asn), "f");
return tslib.__classPrivateFieldGet(this, _AsnData_rawData, "f");
}
constructor(...args) {
_AsnData_rawData.set(this, void 0);
if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
this.asn = asn1Schema.AsnConvert.parse(args[0], args[1]);
tslib.__classPrivateFieldSet(this, _AsnData_rawData, pvtsutils.BufferSourceConverter.toArrayBuffer(args[0]), "f");
this.onInit(this.asn);
} else {
this.asn = args[0];
this.onInit(this.asn);
}
}
equal(data) {
if (data instanceof AsnData) return pvtsutils.isEqual(data.rawData, this.rawData);
return false;
}
toString(format = "text") {
switch (format) {
case "asn": return asn1Schema.AsnConvert.toString(this.rawData);
case "text": return TextConverter.serialize(this.toTextObject());
case "hex": return pvtsutils.Convert.ToHex(this.rawData);
case "base64": return pvtsutils.Convert.ToBase64(this.rawData);
case "base64url": return pvtsutils.Convert.ToBase64Url(this.rawData);
default: throw TypeError("Argument 'format' is unsupported value");
}
}
getTextName() {
return this.constructor.NAME;
}
toTextObject() {
const obj = this.toTextObjectEmpty();
obj[""] = this.rawData;
return obj;
}
toTextObjectEmpty(value) {
return new TextObject(this.getTextName(), {}, value);
}
};
_AsnData_rawData = /* @__PURE__ */ new WeakMap();
AsnData.NAME = "ASN";
var Extension = class Extension extends AsnData {
constructor(...args) {
let raw;
if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) raw = pvtsutils.BufferSourceConverter.toArrayBuffer(args[0]);
else raw = asn1Schema.AsnConvert.serialize(new asn1X509.Extension({
extnID: args[0],
critical: args[1],
extnValue: new asn1Schema.OctetString(pvtsutils.BufferSourceConverter.toArrayBuffer(args[2]))
}));
super(raw, asn1X509.Extension);
}
onInit(asn) {
this.type = asn.extnID;
this.critical = asn.critical;
this.value = asn.extnValue.buffer;
}
toTextObject() {
const obj = this.toTextObjectWithoutValue();
obj[""] = this.value;
return obj;
}
toTextObjectWithoutValue() {
const obj = this.toTextObjectEmpty(this.critical ? "critical" : void 0);
if (obj[TextObject.NAME] === Extension.NAME) obj[TextObject.NAME] = OidSerializer.toString(this.type);
return obj;
}
};
var _a;
var CryptoProvider = class CryptoProvider {
static isCryptoKeyPair(data) {
return data && data.privateKey && data.publicKey;
}
static isCryptoKey(data) {
return data && data.usages && data.type && data.algorithm && data.extractable !== void 0;
}
constructor() {
this.items = /* @__PURE__ */ new Map();
this[_a] = "CryptoProvider";
if (typeof self !== "undefined" && typeof crypto !== "undefined") this.set(CryptoProvider.DEFAULT, crypto);
else if (typeof global !== "undefined" && global.crypto && global.crypto.subtle) this.set(CryptoProvider.DEFAULT, global.crypto);
}
clear() {
this.items.clear();
}
delete(key) {
return this.items.delete(key);
}
forEach(callbackfn, thisArg) {
return this.items.forEach(callbackfn, thisArg);
}
has(key) {
return this.items.has(key);
}
get size() {
return this.items.size;
}
entries() {
return this.items.entries();
}
keys() {
return this.items.keys();
}
values() {
return this.items.values();
}
[Symbol.iterator]() {
return this.items[Symbol.iterator]();
}
get(key = CryptoProvider.DEFAULT) {
const crypto = this.items.get(key.toLowerCase());
if (!crypto) throw new Error(`Cannot get Crypto by name '${key}'`);
return crypto;
}
set(key, value) {
if (typeof key === "string") {
if (!value) throw new TypeError("Argument 'value' is required");
this.items.set(key.toLowerCase(), value);
} else this.items.set(CryptoProvider.DEFAULT, key);
return this;
}
};
_a = Symbol.toStringTag;
CryptoProvider.DEFAULT = "default";
const cryptoProvider = new CryptoProvider();
const OID_REGEX = /^[0-2](?:\.[1-9][0-9]*)+$/;
function isOID(id) {
return new RegExp(OID_REGEX).test(id);
}
var NameIdentifier = class {
constructor(names = {}) {
this.items = {};
for (const id in names) this.register(id, names[id]);
}
get(idOrName) {
return this.items[idOrName] || null;
}
findId(idOrName) {
if (!isOID(idOrName)) return this.get(idOrName);
return idOrName;
}
register(id, name) {
this.items[id] = name;
this.items[name] = id;
}
};
const names = new NameIdentifier();
names.register("CN", "2.5.4.3");
names.register("L", "2.5.4.7");
names.register("ST", "2.5.4.8");
names.register("O", "2.5.4.10");
names.register("OU", "2.5.4.11");
names.register("C", "2.5.4.6");
names.register("DC", "0.9.2342.19200300.100.1.25");
names.register("E", "1.2.840.113549.1.9.1");
names.register("G", "2.5.4.42");
names.register("I", "2.5.4.43");
names.register("SN", "2.5.4.4");
names.register("T", "2.5.4.12");
function replaceUnknownCharacter(text, char) {
return `\\${pvtsutils.Convert.ToHex(pvtsutils.Convert.FromUtf8String(char)).toUpperCase()}`;
}
function escape(data) {
return data.replace(/([,+"\\<>;])/g, "\\$1").replace(/^([ #])/, "\\$1").replace(/([ ]$)/, "\\$1").replace(/([\r\n\t])/, replaceUnknownCharacter);
}
var Name = class Name {
static isASCII(text) {
for (let i = 0; i < text.length; i++) if (text.charCodeAt(i) > 255) return false;
return true;
}
static isPrintableString(text) {
return /^[A-Za-z0-9 '()+,-./:=?]*$/g.test(text);
}
constructor(data, extraNames = {}) {
this.extraNames = new NameIdentifier();
this.asn = new asn1X509.Name();
for (const key in extraNames) if (Object.prototype.hasOwnProperty.call(extraNames, key)) {
const value = extraNames[key];
this.extraNames.register(key, value);
}
if (typeof data === "string") this.asn = this.fromString(data);
else if (data instanceof asn1X509.Name) this.asn = data;
else if (pvtsutils.BufferSourceConverter.isBufferSource(data)) this.asn = asn1Schema.AsnConvert.parse(data, asn1X509.Name);
else this.asn = this.fromJSON(data);
}
getField(idOrName) {
const id = this.extraNames.findId(idOrName) || names.findId(idOrName);
const res = [];
for (const name of this.asn) for (const rdn of name) if (rdn.type === id) res.push(rdn.value.toString());
return res;
}
getName(idOrName) {
return this.extraNames.get(idOrName) || names.get(idOrName);
}
toString() {
return this.asn.map((rdn) => rdn.map((o) => {
return `${this.getName(o.type) || o.type}=${o.value.anyValue ? `#${pvtsutils.Convert.ToHex(o.value.anyValue)}` : escape(o.value.toString())}`;
}).join("+")).join(", ");
}
toJSON() {
var _a;
const json = [];
for (const rdn of this.asn) {
const jsonItem = {};
for (const attr of rdn) {
const type = this.getName(attr.type) || attr.type;
(_a = jsonItem[type]) !== null && _a !== void 0 || (jsonItem[type] = []);
jsonItem[type].push(attr.value.anyValue ? `#${pvtsutils.Convert.ToHex(attr.value.anyValue)}` : attr.value.toString());
}
json.push(jsonItem);
}
return json;
}
fromString(data) {
const asn = new asn1X509.Name();
const regex = /(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+"\\](?=[,+]|$))|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;
let matches = null;
let level = ",";
while (matches = regex.exec(`${data},`)) {
let [, type, value] = matches;
const lastChar = value[value.length - 1];
if (lastChar === "," || lastChar === "+") {
value = value.slice(0, value.length - 1);
matches[3] = lastChar;
}
const next = matches[3];
type = this.getTypeOid(type);
const attr = this.createAttribute(type, value);
if (level === "+") asn[asn.length - 1].push(attr);
else asn.push(new asn1X509.RelativeDistinguishedName([attr]));
level = next;
}
return asn;
}
fromJSON(data) {
const asn = new asn1X509.Name();
for (const item of data) {
const asnRdn = new asn1X509.RelativeDistinguishedName();
for (const type in item) {
const typeId = this.getTypeOid(type);
const values = item[type];
for (const value of values) {
const asnAttr = this.createAttribute(typeId, value);
asnRdn.push(asnAttr);
}
}
asn.push(asnRdn);
}
return asn;
}
getTypeOid(type) {
if (!/[\d.]+/.test(type)) type = this.getName(type) || "";
if (!type) throw new Error(`Cannot get OID for name type '${type}'`);
return type;
}
createAttribute(type, value) {
const attr = new asn1X509.AttributeTypeAndValue({ type });
if (typeof value === "object") for (const key in value) switch (key) {
case "ia5String":
attr.value.ia5String = value[key];
break;
case "utf8String":
attr.value.utf8String = value[key];
break;
case "universalString":
attr.value.universalString = value[key];
break;
case "bmpString":
attr.value.bmpString = value[key];
break;
case "printableString": attr.value.printableString = value[key];
}
else if (value[0] === "#") attr.value.anyValue = pvtsutils.Convert.FromHex(value.slice(1));
else {
const processedValue = this.processStringValue(value);
if (type === this.getName("E") || type === this.getName("DC")) attr.value.ia5String = processedValue;
else if (Name.isPrintableString(processedValue)) attr.value.printableString = processedValue;
else attr.value.utf8String = processedValue;
}
return attr;
}
processStringValue(value) {
const quotedMatches = /"(.*?[^\\])?"/.exec(value);
if (quotedMatches) value = quotedMatches[1];
return value.replace(/\\0a/gi, "\n").replace(/\\0d/gi, "\r").replace(/\\0g/gi, " ").replace(/\\(.)/g, "$1");
}
toArrayBuffer() {
return asn1Schema.AsnConvert.serialize(this.asn);
}
async getThumbprint(...args) {
var _a;
let crypto;
let algorithm = "SHA-1";
if (args.length >= 1 && !((_a = args[0]) === null || _a === void 0 ? void 0 : _a.subtle)) {
algorithm = args[0] || algorithm;
crypto = args[1] || cryptoProvider.get();
} else crypto = args[0] || cryptoProvider.get();
return await crypto.subtle.digest(algorithm, this.toArrayBuffer());
}
};
const ERR_GN_CONSTRUCTOR = "Cannot initialize GeneralName from ASN.1 data.";
const ERR_GN_STRING_FORMAT = `${ERR_GN_CONSTRUCTOR} Unsupported string format in use.`;
const ERR_GUID = `${ERR_GN_CONSTRUCTOR} Value doesn't match to GUID regular expression.`;
const GUID_REGEX = /^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i;
const id_GUID = "1.3.6.1.4.1.311.25.1";
const id_UPN = "1.3.6.1.4.1.311.20.2.3";
const DNS = "dns";
const DN = "dn";
const EMAIL = "email";
const IP = "ip";
const URL = "url";
const GUID = "guid";
const UPN = "upn";
const REGISTERED_ID = "id";
var GeneralName = class extends AsnData {
constructor(...args) {
let name;
if (args.length === 2) switch (args[0]) {
case DN: {
const derName = new Name(args[1]).toArrayBuffer();
const asnName = asn1Schema.AsnConvert.parse(derName, asn1X509__namespace.Name);
name = new asn1X509__namespace.GeneralName({ directoryName: asnName });
break;
}
case DNS:
name = new asn1X509__namespace.GeneralName({ dNSName: args[1] });
break;
case EMAIL:
name = new asn1X509__namespace.GeneralName({ rfc822Name: args[1] });
break;
case GUID: {
const matches = new RegExp(GUID_REGEX, "i").exec(args[1]);
if (!matches) throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");
const hex = matches.slice(1).map((o, i) => {
if (i < 3) return pvtsutils.Convert.ToHex(new Uint8Array(pvtsutils.Convert.FromHex(o)).reverse());
return o;
}).join("");
name = new asn1X509__namespace.GeneralName({ otherName: new asn1X509__namespace.OtherName({
typeId: id_GUID,
value: asn1Schema.AsnConvert.serialize(new asn1Schema.OctetString(pvtsutils.Convert.FromHex(hex)))
}) });
break;
}
case IP:
name = new asn1X509__namespace.GeneralName({ iPAddress: args[1] });
break;
case REGISTERED_ID:
name = new asn1X509__namespace.GeneralName({ registeredID: args[1] });
break;
case UPN:
name = new asn1X509__namespace.GeneralName({ otherName: new asn1X509__namespace.OtherName({
typeId: id_UPN,
value: asn1Schema.AsnConvert.serialize(asn1Schema.AsnUtf8StringConverter.toASN(args[1]))
}) });
break;
case URL:
name = new asn1X509__namespace.GeneralName({ uniformResourceIdentifier: args[1] });
break;
default: throw new Error("Cannot create GeneralName. Unsupported type of the name");
}
else if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) name = asn1Schema.AsnConvert.parse(args[0], asn1X509__namespace.GeneralName);
else name = args[0];
super(name);
}
onInit(asn) {
if (asn.dNSName != void 0) {
this.type = DNS;
this.value = asn.dNSName;
} else if (asn.rfc822Name != void 0) {
this.type = EMAIL;
this.value = asn.rfc822Name;
} else if (asn.iPAddress != void 0) {
this.type = IP;
this.value = asn.iPAddress;
} else if (asn.uniformResourceIdentifier != void 0) {
this.type = URL;
this.value = asn.uniformResourceIdentifier;
} else if (asn.registeredID != void 0) {
this.type = REGISTERED_ID;
this.value = asn.registeredID;
} else if (asn.directoryName != void 0) {
this.type = DN;
this.value = new Name(asn.directoryName).toString();
} else if (asn.otherName != void 0) {
if (asn.otherName.typeId === id_GUID) {
this.type = GUID;
const guid = asn1Schema.AsnConvert.parse(asn.otherName.value, asn1Schema.OctetString);
const matches = new RegExp(GUID_REGEX, "i").exec(pvtsutils.Convert.ToHex(guid));
if (!matches) throw new Error(ERR_GUID);
this.value = matches.slice(1).map((o, i) => {
if (i < 3) return pvtsutils.Convert.ToHex(new Uint8Array(pvtsutils.Convert.FromHex(o)).reverse());
return o;
}).join("-");
} else if (asn.otherName.typeId === id_UPN) {
this.type = UPN;
this.value = asn1Schema.AsnConvert.parse(asn.otherName.value, asn1X509__namespace.DirectoryString).toString();
} else throw new Error(ERR_GN_STRING_FORMAT);
} else throw new Error(ERR_GN_STRING_FORMAT);
}
toJSON() {
return {
type: this.type,
value: this.value
};
}
toTextObject() {
let type;
switch (this.type) {
case DN:
case DNS:
case GUID:
case IP:
case REGISTERED_ID:
case UPN:
case URL:
type = this.type.toUpperCase();
break;
case EMAIL:
type = "Email";
break;
default: throw new Error("Unsupported GeneralName type");
}
let value = this.value;
if (this.type === REGISTERED_ID) value = OidSerializer.toString(value);
return new TextObject(type, void 0, value);
}
};
var GeneralNames = class extends AsnData {
constructor(params) {
let names;
if (params instanceof asn1X509__namespace.GeneralNames) names = params;
else if (Array.isArray(params)) {
const items = [];
for (const name of params) if (name instanceof asn1X509__namespace.GeneralName) items.push(name);
else {
const asnName = asn1Schema.AsnConvert.parse(new GeneralName(name.type, name.value).rawData, asn1X509__namespace.GeneralName);
items.push(asnName);
}
names = new asn1X509__namespace.GeneralNames(items);
} else if (pvtsutils.BufferSourceConverter.isBufferSource(params)) names = asn1Schema.AsnConvert.parse(params, asn1X509__namespace.GeneralNames);
else throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");
super(names);
}
onInit(asn) {
const items = [];
for (const asnName of asn) {
let name = null;
try {
name = new GeneralName(asnName);
} catch {
continue;
}
items.push(name);
}
this.items = items;
}
toJSON() {
return this.items.map((o) => o.toJSON());
}
toTextObject() {
const res = super.toTextObjectEmpty();
for (const name of this.items) {
const nameObj = name.toTextObject();
let field = res[nameObj[TextObject.NAME]];
if (!Array.isArray(field)) {
field = [];
res[nameObj[TextObject.NAME]] = field;
}
field.push(nameObj);
}
return res;
}
};
GeneralNames.NAME = "GeneralNames";
const rPaddingTag = "-{5}";
const rEolChars = "\\n";
const rBeginTag = `${rPaddingTag}BEGIN (${`[^${rEolChars}]+`}(?=${rPaddingTag}))${rPaddingTag}`;
const rEndTag = `${rPaddingTag}END \\1${rPaddingTag}`;
const rEolGroup = "\\n";
const rPem = `${rBeginTag}${rEolGroup}(?:((?:${`[^:${rEolChars}]+`}: ${`(?:[^${rEolChars}]+${rEolGroup}(?: +[^${rEolChars}]+${rEolGroup})*)`})+))?${rEolGroup}?(${`(?:[a-zA-Z0-9=+/]+${rEolGroup})+`})${rEndTag}`;
var PemConverter = class {
static isPem(data) {
return typeof data === "string" && new RegExp(rPem, "g").test(data.replace(/\r/g, ""));
}
static decodeWithHeaders(pem) {
pem = pem.replace(/\r/g, "");
const pattern = new RegExp(rPem, "g");
const res = [];
let matches = null;
while (matches = pattern.exec(pem)) {
const base64 = matches[3].replace(new RegExp(`[${rEolChars}]+`, "g"), "");
const pemStruct = {
type: matches[1],
headers: [],
rawData: pvtsutils.Convert.FromBase64(base64)
};
const headersString = matches[2];
if (headersString) {
const headers = headersString.split(new RegExp(rEolGroup, "g"));
let lastHeader = null;
for (const header of headers) {
const [key, value] = header.split(/:(.*)/);
if (value === void 0) {
if (!lastHeader) throw new Error("Cannot parse PEM string. Incorrect header value");
lastHeader.value += key.trim();
} else {
if (lastHeader) pemStruct.headers.push(lastHeader);
lastHeader = {
key,
value: value.trim()
};
}
}
if (lastHeader) pemStruct.headers.push(lastHeader);
}
res.push(pemStruct);
}
return res;
}
static decode(pem) {
return this.decodeWithHeaders(pem).map((o) => o.rawData);
}
static decodeFirst(pem) {
const items = this.decode(pem);
if (!items.length) throw new RangeError("PEM string doesn't contain any objects");
return items[0];
}
static encode(rawData, tag) {
if (Array.isArray(rawData)) {
const raws = new Array();
if (tag) rawData.forEach((element) => {
if (!pvtsutils.BufferSourceConverter.isBufferSource(element)) throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");
raws.push(this.encodeStruct({
type: tag,
rawData: pvtsutils.BufferSourceConverter.toArrayBuffer(element)
}));
});
else rawData.forEach((element) => {
if (!("type" in element)) throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");
raws.push(this.encodeStruct(element));
});
return raws.join("\n");
} else {
if (!tag) throw new Error("Required argument 'tag' is missed");
return this.encodeStruct({
type: tag,
rawData: pvtsutils.BufferSourceConverter.toArrayBuffer(rawData)
});
}
}
static encodeStruct(pem) {
var _a;
const upperCaseType = pem.type.toLocaleUpperCase();
const res = [];
res.push(`-----BEGIN ${upperCaseType}-----`);
if ((_a = pem.headers) === null || _a === void 0 ? void 0 : _a.length) {
for (const header of pem.headers) res.push(`${header.key}: ${header.value}`);
res.push("");
}
const base64 = pvtsutils.Convert.ToBase64(pem.rawData);
let sliced;
let offset = 0;
const rows = Array();
while (offset < base64.length) {
if (base64.length - offset < 64) sliced = base64.substring(offset);
else {
sliced = base64.substring(offset, offset + 64);
offset += 64;
}
if (sliced.length !== 0) {
rows.push(sliced);
if (sliced.length < 64) break;
} else break;
}
res.push(...rows);
res.push(`-----END ${upperCaseType}-----`);
return res.join("\n");
}
};
PemConverter.CertificateTag = "CERTIFICATE";
PemConverter.CrlTag = "CRL";
PemConverter.CertificateRequestTag = "CERTIFICATE REQUEST";
PemConverter.PublicKeyTag = "PUBLIC KEY";
PemConverter.PrivateKeyTag = "PRIVATE KEY";
var PemData = class PemData extends AsnData {
static isAsnEncoded(data) {
return pvtsutils.BufferSourceConverter.isBufferSource(data) || typeof data === "string";
}
static toArrayBuffer(raw) {
if (typeof raw === "string") {
if (PemConverter.isPem(raw)) return PemConverter.decode(raw)[0];
else if (pvtsutils.Convert.isHex(raw)) return pvtsutils.Convert.FromHex(raw);
else if (pvtsutils.Convert.isBase64(raw)) return pvtsutils.Convert.FromBase64(raw);
else if (pvtsutils.Convert.isBase64Url(raw)) return pvtsutils.Convert.FromBase64Url(raw);
else throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url");
} else {
const buffer = pvtsutils.BufferSourceConverter.toUint8Array(raw);
if (buffer.length > 0 && buffer[0] === 48) return pvtsutils.BufferSourceConverter.toArrayBuffer(raw);
const stringRaw = pvtsutils.Convert.ToBinary(raw);
if (PemConverter.isPem(stringRaw)) return PemConverter.decode(stringRaw)[0];
else if (pvtsutils.Convert.isHex(stringRaw)) return pvtsutils.Convert.FromHex(stringRaw);
else if (pvtsutils.Convert.isBase64(stringRaw)) return pvtsutils.Convert.FromBase64(stringRaw);
else if (pvtsutils.Convert.isBase64Url(stringRaw)) return pvtsutils.Convert.FromBase64Url(stringRaw);
throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url");
}
}
constructor(...args) {
if (PemData.isAsnEncoded(args[0])) super(PemData.toArrayBuffer(args[0]), args[1]);
else super(args[0]);
}
toString(format = "pem") {
switch (format) {
case "pem": return PemConverter.encode(this.rawData, this.tag);
default: return super.toString(format);
}
}
};
var PublicKey = class PublicKey extends PemData {
static async create(data, crypto = cryptoProvider.get()) {
if (data instanceof PublicKey) return data;
else if (CryptoProvider.isCryptoKey(data)) {
if (data.type !== "public") throw new TypeError("Public key is required");
const spki = await crypto.subtle.exportKey("spki", data);
return new PublicKey(spki);
} else if (data.publicKey) return data.publicKey;
else if (pvtsutils.BufferSourceConverter.isBufferSource(data)) return new PublicKey(data);
else throw new TypeError("Unsupported PublicKeyType");
}
constructor(param) {
if (PemData.isAsnEncoded(param)) super(param, asn1X509.SubjectPublicKeyInfo);
else super(param);
this.tag = PemConverter.PublicKeyTag;
}
async export(...args) {
let crypto;
let keyUsages = ["verify"];
let algorithm = {
hash: "SHA-256",
...this.algorithm
};
if (args.length > 1) {
algorithm = args[0] || algorithm;
keyUsages = args[1] || keyUsages;
crypto = args[2] || cryptoProvider.get();
} else crypto = args[0] || cryptoProvider.get();
let raw = this.rawData;
const asnSpki = asn1Schema.AsnConvert.parse(this.rawData, asn1X509.SubjectPublicKeyInfo);
if (asnSpki.algorithm.algorithm === asn1Rsa.id_RSASSA_PSS) raw = convertSpkiToRsaPkcs1(asnSpki, raw);
return crypto.subtle.importKey("spki", raw, algorithm, true, keyUsages);
}
onInit(asn) {
const algProv = tsyringe.container.resolve(diAlgorithmProvider);
const algorithm = this.algorithm = algProv.toWebAlgorithm(asn.algorithm);
switch (asn.algorithm.algorithm) {
case asn1Rsa.id_rsaEncryption: {
const rsaPublicKey = asn1Schema.AsnConvert.parse(asn.subjectPublicKey, asn1Rsa.RSAPublicKey);
const modulus = pvtsutils.BufferSourceConverter.toUint8Array(rsaPublicKey.modulus);
algorithm.publicExponent = pvtsutils.BufferSourceConverter.toUint8Array(rsaPublicKey.publicExponent);
algorithm.modulusLength = (!modulus[0] ? modulus.slice(1) : modulus).byteLength << 3;
break;
}
}
}
async getThumbprint(...args) {
var _a;
let crypto;
let algorithm = "SHA-1";
if (args.length >= 1 && !((_a = args[0]) === null || _a === void 0 ? void 0 : _a.subtle)) {
algorithm = args[0] || algorithm;
crypto = args[1] || cryptoProvider.get();
} else crypto = args[0] || cryptoProvider.get();
return await crypto.subtle.digest(algorithm, this.rawData);
}
async getKeyIdentifier(...args) {
let crypto;
let algorithm = "SHA-1";
if (args.length === 1) {
if (typeof args[0] === "string") {
algorithm = args[0];
crypto = cryptoProvider.get();
} else crypto = args[0];
} else if (args.length === 2) {
algorithm = args[0];
crypto = args[1];
} else crypto = cryptoProvider.get();
const asn = asn1Schema.AsnConvert.parse(this.rawData, asn1X509.SubjectPublicKeyInfo);
return await crypto.subtle.digest(algorithm, asn.subjectPublicKey);
}
toTextObject() {
const obj = this.toTextObjectEmpty();
const asn = asn1Schema.AsnConvert.parse(this.rawData, asn1X509.SubjectPublicKeyInfo);
obj["Algorithm"] = TextConverter.serializeAlgorithm(asn.algorithm);
switch (asn.algorithm.algorithm) {
case asn1Ecc.id_ecPublicKey:
obj["EC Point"] = asn.subjectPublicKey;
break;
case asn1Rsa.id_rsaEncryption:
default: obj["Raw Data"] = asn.subjectPublicKey;
}
return obj;
}
};
function convertSpkiToRsaPkcs1(asnSpki, raw) {
asnSpki.algorithm = new asn1X509.AlgorithmIdentifier({
algorithm: asn1Rsa.id_rsaEncryption,
parameters: null
});
raw = asn1Schema.AsnConvert.serialize(asnSpki);
return raw;
}
var AuthorityKeyIdentifierExtension = class AuthorityKeyIdentifierExtension extends Extension {
static async create(param, critical = false, crypto = cryptoProvider.get()) {
if ("name" in param && "serialNumber" in param) return new AuthorityKeyIdentifierExtension(param, critical);
const id = await (await PublicKey.create(param, crypto)).getKeyIdentifier(crypto);
return new AuthorityKeyIdentifierExtension(pvtsutils.Convert.ToHex(id), critical);
}
constructor(...args) {
if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) super(args[0]);
else if (typeof args[0] === "string") {
const value = new asn1X509__namespace.AuthorityKeyIdentifier({ keyIdentifier: new asn1X509__namespace.KeyIdentifier(pvtsutils.Convert.FromHex(args[0])) });
super(asn1X509__namespace.id_ce_authorityKeyIdentifier, args[1], asn1Schema.AsnConvert.serialize(value));
} else {
const certId = args[0];
const certIdName = certId.name instanceof GeneralNames ? asn1Schema.AsnConvert.parse(certId.name.rawData, asn1X509__namespace.GeneralNames) : certId.name;
const value = new asn1X509__namespace.AuthorityKeyIdentifier({
authorityCertIssuer: certIdName,
authorityCertSerialNumber: pvtsutils.Convert.FromHex(certId.serialNumber)
});
super(asn1X509__namespace.id_ce_authorityKeyIdentifier, args[1], asn1Schema.AsnConvert.serialize(value));
}
}
onInit(asn) {
super.onInit(asn);
const aki = asn1Schema.AsnConvert.parse(asn.extnValue, asn1X509__namespace.AuthorityKeyIdentifier);
if (aki.keyIdentifier) this.keyId = pvtsutils.Convert.ToHex(aki.keyIdentifier);
if (aki.authorityCertIssuer || aki.authorityCertSerialNumber) this.certId = {
name: aki.authorityCertIssuer || [],
serialNumber: aki.authorityCertSerialNumber ? pvtsutils.Convert.ToHex(aki.authorityCertSerialNumber) : ""
};
}
toTextObject() {
const obj = this.toTextObjectWithoutValue();
const asn = asn1Schema.AsnConvert.parse(this.value, asn1X509__namespace.AuthorityKeyIdentifier);
if (asn.authorityCertIssuer) obj["Authority Issuer"] = new GeneralNames(asn.authorityCertIssuer).toTextObject();
if (asn.authorityCertSerialNumber) obj["Authority Serial Number"] = asn.authorityCertSerialNumber;
if (asn.keyIdentifier) obj[""] = asn.keyIdentifier;
return obj;
}
};
AuthorityKeyIdentifierExtension.NAME = "Authority Key Identifier";
var BasicConstraintsExtension = class extends Extension {
constructor(...args) {
if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
super(args[0]);
const value = asn1Schema.AsnConvert.parse(this.value, asn1X509.BasicConstraints);
this.ca = value.cA;
this.pathLength = value.pathLenConstraint;
} else {
const value = new asn1X509.BasicConstraints({
cA: args[0],
pathLenConstraint: args[1]
});
super(asn1X509.id_ce_basicConstraints, args[2], asn1Schema.AsnConvert.serialize(value));
this.ca = args[0];
this.pathLength = args[1];
}
}
toTextObject() {
const obj = this.toTextObjectWithoutValue();
if (this.ca) obj["CA"] = this.ca;
if (this.pathLength !== void 0) obj["Path Length"] = this.pathLength;
return obj;
}
};
BasicConstraintsExtension.NAME = "Basic Constraints";
exports.ExtendedKeyUsage = void 0;
(function(ExtendedKeyUsage) {
ExtendedKeyUsage["serverAuth"] = "1.3.6.1.5.5.7.3.1";
ExtendedKeyUsage["clientAuth"] = "1.3.6.1.5.5.7.3.2";
ExtendedKeyUsage["codeSigning"] = "1.3.6.1.5.5.7.3.3";
ExtendedKeyUsage["emailProtection"] = "1.3.6.1.5.5.7.3.4";
ExtendedKeyUsage["timeStamping"] = "1.3.6.1.5.5.7.3.8";
ExtendedKeyUsage["ocspSigning"] = "1.3.6.1.5.5.7.3.9";
})(exports.ExtendedKeyUsage || (exports.ExtendedKeyUsage = {}));
var ExtendedKeyUsageExtension = class extends Extension {
constructor(...args) {
if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
super(args[0]);
const value = asn1Schema.AsnConvert.parse(this.value, asn1X509__namespace.ExtendedKeyUsage);
this.usages = value.map((o) => o);
} else {
const value = new asn1X509__namespace.ExtendedKeyUsage(args[0]);
super(asn1X509__namespace.id_ce_extKeyUsage, args[1], asn1Schema.AsnConvert.serialize(value));
this.usages = args[0];
}
}
toTextObject() {
const obj = this.toTextObjectWithoutValue();
obj[""] = this.usages.map((o) => OidSerializer.toString(o)).join(", ");
return obj;
}
};
ExtendedKeyUsageExtension.NAME = "Extended Key Usages";
exports.KeyUsageFlags = void 0;
(function(KeyUsageFlags) {
KeyUsageFlags[KeyUsageFlags["digitalSignature"] = 1] = "digitalSignature";
KeyUsageFlags[KeyUsageFlags["nonRepudiation"] = 2] = "nonRepudiation";
KeyUsageFlags[KeyUsageFlags["keyEncipherment"] = 4] = "keyEncipherment";
KeyUsageFlags[KeyUsageFlags["dataEncipherment"] = 8] = "dataEncipherment";
KeyUsageFlags[KeyUsageFlags["keyAgreement"] = 16] = "keyAgreement";
KeyUsageFlags[KeyUsageFlags["keyCertSign"] = 32] = "keyCertSign";
KeyUsageFlags[KeyUsageFlags["cRLSign"] = 64] = "cRLSign";
KeyUsageFlags[KeyUsageFlags["encipherOnly"] = 128] = "encipherOnly";
KeyUsageFlags[KeyUsageFlags["decipherOnly"] = 256] = "decipherOnly";
})(exports.KeyUsageFlags || (exports.KeyUsageFlags = {}));
var KeyUsagesExtension = class extends Extension {
constructor(...args) {
if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
super(args[0]);
const value = asn1Schema.AsnConvert.parse(this.value, asn1X509.KeyUsage);
this.usages = value.toNumber();
} else {
const value = new asn1X509.KeyUsage(args[0]);
super(asn1X509.id_ce_keyUsage, args[1], asn1Schema.AsnConvert.serialize(value));
this.usages = args[0];
}
}
toTextObject() {
const obj = this.toTextObjectWithoutValue();
obj[""] = asn1Schema.AsnConvert.parse(this.value, asn1X509.KeyUsage).toJSON().join(", ");
return obj;
}
};
KeyUsagesExtension.NAME = "Key Usages";
var SubjectKeyIdentifierExtension = class SubjectKeyIdentifierExtension extends Extension {
static async create(publicKey, critical = false, crypto = cryptoProvider.get()) {
const id = await (await PublicKey.create(publicKey, crypto)).getKeyIdentifier(crypto);
return new SubjectKeyIdentifierExtension(pvtsutils.Convert.ToHex(id), critical);
}
constructor(...args) {
if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
super(args[0]);
const value = asn1Schema.AsnConvert.parse(this.value, asn1X509__namespace.SubjectKeyIdentifier);
this.keyId = pvtsutils.Convert.ToHex(value);
} else {
const identifier = typeof args[0] === "string" ? pvtsutils.Convert.FromHex(args[0]) : args[0];
const value = new asn1X509__namespace.SubjectKeyIdentifier(identifier);
super(asn1X509__namespace.id_ce_subjectKeyIdentifier, args[1], asn1Schema.AsnConvert.serialize(value));
this.keyId = pvtsutils.Convert.ToHex(identifier);
}
}
toTextObject() {
const obj = this.toTextObjectWithoutValue();
obj[""] = asn1Schema.AsnConvert.parse(this.value, asn1X509__namespace.SubjectKeyIdentifier);
return obj;
}
};
SubjectKeyIdentifierExtension.NAME = "Subject Key Identifier";
var SubjectAlternativeNameExtension = class extends Extension {
constructor(...args) {
if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) super(args[0]);
else super(asn1X509__namespace.id_ce_subjectAltName, args[1], new GeneralNames(args[0] || []).rawData);
}
onInit(asn) {
super.onInit(asn);
const value = asn1Schema.AsnConvert.parse(asn.extnValue, asn1X509__namespace.SubjectAlternativeName);
this.names = new GeneralNames(value);
}
toTextObject() {
const obj = this.toTextObjectWithoutValue();
const namesObj = this.names.toTextObject();
for (const key in namesObj) obj[key] = namesObj[key];
return obj;
}
};
SubjectAlternativeNameExtension.NAME = "Subject Alternative Name";
var ExtensionFactory = class {
static register(id, type) {
this.items.set(id, type);
}
static create(data) {
const extension = new Extension(data);
const Type = this.items.get(extension.type);
if (Type) return new Type(data);
return extension;
}
};
ExtensionFactory.items = /* @__PURE__ */ new Map();
var CertificatePolicyExtension = class extends Extension {
constructor(...args) {
var _a;
if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) {
super(args[0]);
const asnPolicies = asn1Schema.AsnConvert.parse(this.value, asn1X509__namespace.CertificatePolicies);
this.policies = asnPolicies.map((o) => o.policyIdentifier);
} else {
const policies = args[0];
const critical = (_a = args[1]) !== null && _a !== void 0 ? _a : false;
const value = new asn1X509__namespace.CertificatePolicies(policies.map((o) => new asn1X509__namespace.PolicyInformation({ policyIdentifier: o })));
super(asn1X509__namespace.id_ce_certificatePolicies, critical, asn1Schema.AsnConvert.serialize(value));
this.policies = policies;
}
}
toTextObject() {
const obj = this.toTextObjectWithoutValue();
obj["Policy"] = this.policies.map((o) => new TextObject("", {}, OidSerializer.toString(o)));
return obj;
}
};
CertificatePolicyExtension.NAME = "Certificate Policies";
ExtensionFactory.register(asn1X509__namespace.id_ce_certificatePolicies, CertificatePolicyExtension);
var CRLDistributionPointsExtension = class extends Extension {
constructor(...args) {
var _a;
if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) super(args[0]);
else if (Array.isArray(args[0]) && typeof args[0][0] === "string") {
const dps = args[0].map((url) => {
return new asn1X509__namespace.DistributionPoint({ distributionPoint: new asn1X509__namespace.DistributionPointName({ fullName: [new asn1X509__namespace.GeneralName({ uniformResourceIdentifier: url })] }) });
});
const value = new asn1X509__namespace.CRLDistributionPoints(dps);
super(asn1X509__namespace.id_ce_cRLDistributionPoints, args[1], asn1Schema.AsnConvert.serialize(value));
} else {
const value = new asn1X509__namespace.CRLDistributionPoints(args[0]);
super(asn1X509__namespace.id_ce_cRLDistributionPoints, args[1], asn1Schema.AsnConvert.serialize(value));
}
(_a = this.distributionPoints) !== null && _a !== void 0 || (this.distributionPoints = []);
}
onInit(asn) {
super.onInit(asn);
const crlExt = asn1Schema.AsnConvert.parse(asn.extnValue, asn1X509__namespace.CRLDistributionPoints);
this.distributionPoints = crlExt;
}
toTextObject() {
const obj = this.toTextObjectWithoutValue();
obj["Distribution Point"] = this.distributionPoints.map((dp) => {
var _a;
const dpObj = {};
if (dp.distributionPoint) dpObj[""] = (_a = dp.distributionPoint.fullName) === null || _a === void 0 ? void 0 : _a.map((name) => new GeneralName(name).toString()).join(", ");
if (dp.reasons) dpObj["Reasons"] = dp.reasons.toString();
if (dp.cRLIssuer) dpObj["CRL Issuer"] = dp.cRLIssuer.map((issuer) => issuer.toString()).join(", ");
return dpObj;
});
return obj;
}
};
CRLDistributionPointsExtension.NAME = "CRL Distribution Points";
var AuthorityInfoAccessExtension = class extends Extension {
constructor(...args) {
var _a, _b, _c, _d;
if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) super(args[0]);
else if (args[0] instanceof asn1X509__namespace.AuthorityInfoAccessSyntax) {
const value = new asn1X509__namespace.AuthorityInfoAccessSyntax(args[0]);
super(asn1X509__namespace.id_pe_authorityInfoAccess, args[1], asn1Schema.AsnConvert.serialize(value));
} else {
const params = args[0];
const value = new asn1X509__namespace.AuthorityInfoAccessSyntax();
addAccessDescriptions(value, params, asn1X509__namespace.id_ad_ocsp, "ocsp");
addAccessDescriptions(value, params, asn1X509__namespace.id_ad_caIssuers, "caIssuers");
addAccessDescriptions(value, params, asn1X509__namespace.id_ad_timeStamping, "timeStamping");
addAccessDescriptions(value, params, asn1X509__namespace.id_ad_caRepository, "caRepository");
super(asn1X509__namespace.id_pe_authorityInfoAccess, args[1], asn1Schema.AsnConvert.serialize(value));
}
(_a = this.ocsp) !== null && _a !== void 0 || (this.ocsp = []);
(_b = this.caIssuers) !== null && _b !== void 0 || (this.caIssuers = []);
(_c = this.timeStamping) !== null && _c !== void 0 || (this.timeStamping = []);
(_d = this.caRepository) !== null && _d !== void 0 || (this.caRepository = []);
}
onInit(asn) {
super.onInit(asn);
this.ocsp = [];
this.caIssuers = [];
this.timeStamping = [];
this.caRepository = [];
asn1Schema.AsnConvert.parse(asn.extnValue, asn1X509__namespace.AuthorityInfoAccessSyntax).forEach((accessDescription) => {
switch (accessDescription.accessMethod) {
case asn1X509__namespace.id_ad_ocsp:
this.ocsp.push(new GeneralName(accessDescription.accessLocation));
break;
case asn1X509__namespace.id_ad_caIssuers:
this.caIssuers.push(new GeneralName(accessDescription.accessLocation));
break;
case asn1X509__namespace.id_ad_timeStamping:
this.timeStamping.push(new GeneralName(accessDescription.accessLocation));
break;
case asn1X509__namespace.id_ad_caRepository: this.caRepository.push(new GeneralName(accessDescription.accessLocation));
}
});
}
toTextObject() {
const obj = this.toTextObjectWithoutValue();
if (this.ocsp.length) addUrlsToObject(obj, "OCSP", this.ocsp);
if (this.caIssuers.length) addUrlsToObject(obj, "CA Issuers", this.caIssuers);
if (this.timeStamping.length) addUrlsToObject(obj, "Time Stamping", this.timeStamping);
if (this.caRepository.length) addUrlsToObject(obj, "CA Repository", this.caRepository);
return obj;
}
};
AuthorityInfoAccessExtension.NAME = "Authority Info Access";
function addUrlsToObject(obj, key, urls) {
if (urls.length === 1) obj[key] = urls[0].toTextObject();
else {
const names = new TextObject("");
urls.forEach((name, index) => {
const nameObj = name.toTextObject();
const indexedKey = `${nameObj[TextObject.NAME]} ${index + 1}`;
let field = names[indexedKey];
if (!Array.isArray(field)) {
field = [];
names[indexedKey] = field;
}
field.push(nameObj);
});
obj[key] = names;
}
}
function addAccessDescriptions(value, params, method, key) {
const items = params[key];
if (items) (Array.isArray(items) ? items : [items]).forEach((url) => {
if (typeof url === "string") url = new GeneralName("url", url);
value.push(new asn1X509__namespace.AccessDescription({
accessMethod: method,
accessLocation: asn1Schema.AsnConvert.parse(url.rawData, asn1X509__namespace.GeneralName)
}));
});
}
var IssuerAlternativeNameExtension = class extends Extension {
constructor(...args) {
if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) super(args[0]);
else super(asn1X509__namespace.id_ce_issuerAltName, args[1], new GeneralNames(args[0] || []).rawData);
}
onInit(asn) {
super.onInit(asn);
const value = asn1Schema.AsnConvert.parse(asn.extnValue, asn1X509__namespace.GeneralNames);
this.names = new GeneralNames(value);
}
toTextObject() {
const obj = this.toTextObjectWithoutValue();
const namesObj = this.names.toTextObject();
for (const key in namesObj) obj[key] = namesObj[key];
return obj;
}
};
IssuerAlternativeNameExtension.NAME = "Issuer Alternative Name";
var Attribute = class Attribute extends AsnData {
constructor(...args) {
let raw;
if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) raw = pvtsutils.BufferSourceConverter.toArrayBuffer(args[0]);
else {
const type = args[0];
const values = Array.isArray(args[1]) ? args[1].map((o) => pvtsutils.BufferSourceConverter.toArrayBuffer(o)) : [];
raw = asn1Schema.AsnConvert.serialize(new asn1X509.Attribute({
type,
values
}));
}
super(raw, asn1X509.Attribute);
}
onInit(asn) {
this.type = asn.type;
this.values = asn.values;
}
toTextObject() {
const obj = this.toTextObjectWithoutValue();
obj["Value"] = this.values.map((o) => new TextObject("", { "": o }));
return obj;
}
toTextObjectWithoutValue() {
const obj = this.toTextObjectEmpty();
if (obj[TextObject.NAME] === Attribute.NAME) obj[TextObject.NAME] = OidSerializer.toString(this.type);
return obj;
}
};
Attribute.NAME = "Attribute";
var ChallengePasswordAttribute = class extends Attribute {
constructor(...args) {
var _a;
if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) super(args[0]);
else {
const value = new asnPkcs9__namespace.ChallengePassword({ printableString: args[0] });
super(asnPkcs9__namespace.id_pkcs9_at_challengePassword, [asn1Schema.AsnConvert.serialize(value)]);
}
(_a = this.password) !== null && _a !== void 0 || (this.password = "");
}
onInit(asn) {
super.onInit(asn);
if (this.values[0]) {
const value = asn1Schema.AsnConvert.parse(this.values[0], asnPkcs9__namespace.ChallengePassword);
this.password = value.toString();
}
}
toTextObject() {
const obj = this.toTextObjectWithoutValue();
obj[TextObject.VALUE] = this.password;
return obj;
}
};
ChallengePasswordAttribute.NAME = "Challenge Password";
var ExtensionsAttribute = class extends Attribute {
constructor(...args) {
var _a;
if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) super(args[0]);
else {
const extensions = args[0];
const value = new asn1X509__namespace.Extensions();
for (const extension of extensions) value.push(asn1Schema.AsnConvert.parse(extension.rawData, asn1X509__namespace.Extension));
super(asnPkcs9__namespace.id_pkcs9_at_extensionRequest, [asn1Schema.AsnConvert.serialize(value)]);
}
(_a = this.items) !== null && _a !== void 0 || (this.items = []);
}
onInit(asn) {
super.onInit(asn);
if (this.values[0]) {
const value = asn1Schema.AsnConvert.parse(this.values[0], asn1X509__namespace.Extensions);
this.items = value.map((o) => ExtensionFactory.create(asn1Schema.AsnConvert.serialize(o)));
}
}
toTextObject() {
const obj = this.toTextObjectWithoutValue();
const extensions = this.items.map((o) => o.toTextObject());
for (const extension of extensions) obj[extension[TextObject.NAME]] = extension;
return obj;
}
};
ExtensionsAttribute.NAME = "Extensions";
var AttributeFactory = class {
static register(id, type) {
this.items.set(id, type);
}
static create(data) {
const attribute = new Attribute(data);
const Type = this.items.get(attribute.type);
if (Type) return new Type(data);
return attribute;
}
};
AttributeFactory.items = /* @__PURE__ */ new Map();
const diAsnSignatureFormatter = "crypto.signatureFormatter";
var AsnDefaultSignatureFormatter = class {
toAsnSignature(algorithm, signature) {
return pvtsutils.BufferSourceConverter.toArrayBuffer(signature);
}
toWebSignature(algorithm, signature) {
return pvtsutils.BufferSourceConverter.toArrayBuffer(signature);
}
};
var RsaAlgorithm_1;
exports.RsaAlgorithm = RsaAlgorithm_1 = class RsaAlgorithm {
static createPssParams(hash, saltLength) {
const hashAlgorithm = RsaAlgorithm_1.getHashAlgorithm(hash);
if (!hashAlgorithm) return null;
return new asn1Rsa__namespace.RsaSaPssParams({
hashAlgorithm,
maskGenAlgorithm: new asn1X509.AlgorithmIdentifier({
algorithm: asn1Rsa__namespace.id_mgf1,
parameters: asn1Schema.AsnConvert.serialize(hashAlgorithm)
}),
saltLength
});
}
static getHashAlgorithm(alg) {
const algProv = tsyringe.container.resolve(diAlgorithmProvider);
if (typeof alg === "string") return algProv.toAsnAlgorithm({ name: alg });
if (typeof alg === "object" && alg && "name" in alg) return algProv.toAsnAlgorithm(alg);
return null;
}
toAsnAlgorithm(alg) {
switch (alg.name.toLowerCase()) {
case "rsassa-pkcs1-v1_5":
if ("hash" in alg) {
let hash;
if (typeof alg.hash === "string") hash = alg.hash;
else if (alg.hash && typeof alg.hash === "object" && "name" in alg.hash && typeof alg.hash.name === "string") hash = alg.hash.name.toUpperCase();
else throw new Error("Cannot get hash algorithm name");
switch (hash.toLowerCase()) {
case "sha-1": return new asn1X509.AlgorithmIdentifier({
algorithm: asn1Rsa__namespace.id_sha1WithRSAEncryption,
parameters: null
});
case "sha-256": return new asn1X509.AlgorithmIdentifier({
algorithm: asn1Rsa__namespace.id_sha256WithRSAEncryption,
parameters: null
});
case "sha-384": return new asn1X509.AlgorithmIdentifier({
algorithm: asn1Rsa__namespace.id_sha384WithRSAEncryption,
parameters: null
});
case "sha-512": return new asn1X509.AlgorithmIdentifier({
algorithm: asn1Rsa__namespace.id_sha512WithRSAEncryption,
parameters: null
});
}
} else return new asn1X509.AlgorithmIdentifier({
algorithm: asn1Rsa__namespace.id_rsaEncryption,
parameters: null
});
break;
case "rsa-pss": if ("hash" in alg) {
if (!("saltLength" in alg && typeof alg.saltLength === "number")) throw new Error("Cannot get 'saltLength' from 'alg' argument");
const pssParams = RsaAlgorithm_1.createPssParams(alg.hash, alg.saltLength);
if (!pssParams) throw new Error("Cannot create PSS parameters");
return new asn1X509.AlgorithmIdentifier({
algorithm: asn1Rsa__namespace.id_RSASSA_PSS,
parameters: asn1Schema.AsnConvert.serialize(pssParams)
});
} else return new asn1X509.AlgorithmIdentifier({
algorithm: asn1Rsa__namespace.id_RSASSA_PSS,
parameters: null
});
}
return null;
}
toWebAlgorithm(alg) {
switch (alg.algorithm) {
case asn1Rsa__namespace.id_rsaEncryption: return { name: "RSASSA-PKCS1-v1_5" };
case asn1Rsa__namespace.id_sha1WithRSAEncryption: return {
name: "RSASSA-PKCS1-v1_5",
hash: { name: "SHA-1" }
};
case asn1Rsa__namespace.id_sha256WithRSAEncryption: return {
name: "RSASSA-PKCS1-v1_5",
hash: { name: "SHA-256" }
};
case asn1Rsa__namespace.id_sha384WithRSAEncryption: return {
name: "RSASSA-PKCS1-v1_5",
hash: { name: "SHA-384" }
};
case asn1Rsa__namespace.id_sha512WithRSAEncryption: return {
name: "RSASSA-PKCS1-v1_5",
hash: { name: "SHA-512" }
};
case asn1Rsa__namespace.id_RSASSA_PSS: if (alg.parameters) {
const pssParams = asn1Schema.AsnConvert.parse(alg.parameters, asn1Rsa__namespace.RsaSaPssParams);
return {
name: "RSA-PSS",
hash: tsyringe.container.resolve(diAlgorithmProvider).toWebAlgorithm(pssParams.hashAlgorithm),
saltLength: pssParams.saltLength
};
} else return { name: "RSA-PSS" };
}
return null;
}
};
exports.RsaAlgorithm = RsaAlgorithm_1 = tslib.__decorate([tsyringe.injectable()], exports.RsaAlgorithm);
tsyringe.container.registerSingleton(diAlgorithm, exports.RsaAlgorithm);
exports.ShaAlgorithm = class ShaAlgorithm {
toAsnAlgorithm(alg) {
switch (alg.name.toLowerCase()) {
case "sha-1": return new asn1X509.AlgorithmIdentifier({ algorithm: asn1Rsa.id_sha1 });
case "sha-256": return new asn1X509.AlgorithmIdentifier({ algorithm: asn1Rsa.id_sha256 });
case "sha-384": return new asn1X509.AlgorithmIdentifier({ algorithm: asn1Rsa.id_sha384 });
case "sha-512": return new asn1X509.AlgorithmIdentifier({ algorithm: asn1Rsa.id_sha512 });
}
return null;
}
toWebAlgorithm(alg) {
switch (alg.algorithm) {
case asn1Rsa.id_sha1: return { name: "SHA-1" };
case asn1Rsa.id_sha256: return { name: "SHA-256" };
case asn1Rsa.id_sha384: return { name: "SHA-384" };
case asn1Rsa.id_sha512: return { name: "SHA-512" };
}
return null;
}
};
exports.ShaAlgorithm = tslib.__decorate([tsyringe.injectable()], exports.ShaAlgorithm);
tsyringe.container.registerSingleton(diAlgorithm, exports.ShaAlgorithm);
var AsnEcSignatureFormatter = class AsnEcSignatureFormatter {
addPadding(pointSize, data) {
const bytes = pvtsutils.BufferSourceConverter.toUint8Array(data);
const res = new Uint8Array(pointSize);
res.set(bytes, pointSize - bytes.length);
return res.buffer;
}
removePadding(data, positive = false) {
let bytes = pvtsutils.BufferSourceConverter.toUint8Array(data);
for (let i = 0; i < bytes.length; i++) {
if (!bytes[i]) continue;
bytes = bytes.slice(i);
break;
}
if (positive && bytes[0] > 127) {
const result = new Uint8Array(bytes.length + 1);
result.set(bytes, 1);
return result.buffer;
}
return bytes.buffer;
}
toAsnSignature(algorithm, signature) {
if (algorithm.name === "ECDSA") {
const namedCurve = algorithm.namedCurve;
const pointSize = AsnEcSignatureFormatter.namedCurveSize.get(namedCurve) || AsnEcSignatureFormatter.defaultNamedCurveSize;
const ecSignature = new asn1Ecc.ECDSASigValue();
const uint8Signature = pvtsutils.BufferSourceConverter.toUint8Array(signature);
ecSignature.r = this.removePadding(uint8Signature.slice(0, pointSize), true);
ecSignature.s = this.removePadding(uint8Signature.slice(pointSize, pointSize + pointSize), true);
return asn1Schema.AsnConvert.serialize(ecSignature);
}
return null;
}
toWebSignature(algorithm, signature) {
if (algorithm.name === "ECDSA") {
const ecSigValue = asn1Schema.AsnConvert.parse(signature, asn1Ecc.ECDSASigValue);
const namedCurve = algorithm.namedCurve;
const pointSize = AsnEcSignatureFormatter.namedCurveSize.get(namedCurve) || AsnEcSignatureFormatter.defaultNamedCurveSize;
const r = this.addPadding(pointSize, this.removePadding(ecSigValue.r));
const s = this.addPadding(pointSize, this.removePadding(ecSigValue.s));
return pvtsutils.combine(r, s);
}
return null;
}
};
AsnEcSignatureFormatter.namedCurveSize = /* @__PURE__ */ new Map();
AsnEcSignatureFormatter.defaultNamedCurveSize = 32;
const idX25519 = "1.3.101.110";
const idX448 = "1.3.101.111";
const idEd25519 = "1.3.101.112";
const idEd448 = "1.3.101.113";
exports.EdAlgorithm = class EdAlgorithm {
toAsnAlgorithm(alg) {
let algorithm = null;
switch (alg.name.toLowerCase()) {
case "ed25519":
algorithm = idEd25519;
break;
case "x25519":
algorithm = idX25519;
break;
case "eddsa":
switch (alg.namedCurve.toLowerCase()) {
case "ed25519":
algorithm = idEd25519;
break;
case "ed448": algorithm = idEd448;
}
break;
case "ecdh-es": switch (alg.namedCurve.toLowerCase()) {
case "x25519":
algorithm = idX25519;
break;
case "x448": algorithm = idX448;
}
}
if (algorithm) return new asn1X509.AlgorithmIdentifier({ algorithm });
return null;
}
toWebAlgorithm(alg) {
switch (alg.algorithm) {
case idEd25519: return { name: "Ed25519" };
case idEd448: return {
name: "EdDSA",
namedCurve: "Ed448"
};
case idX25519: return { name: "X25519" };
case idX448: return {
name: "ECDH-ES",
namedCurve: "X448"
};
}
return null;
}
};
exports.EdAlgorithm = tslib.__decorate([tsyringe.injectable()], exports.EdAlgorithm);
tsyringe.container.registerSingleton(diAlgorithm, exports.EdAlgorithm);
var _Pkcs10CertificateRequest_tbs;
var _Pkcs10CertificateRequest_subjectName;
var _Pkcs10CertificateRequest_subject;
var _Pkcs10CertificateRequest_signatureAlgorithm;
var _Pkcs10CertificateRequest_signature;
var _Pkcs10CertificateRequest_publicKey;
var _Pkcs10CertificateRequest_attributes;
var _Pkcs10CertificateRequest_extensions;
var Pkcs10CertificateRequest = class extends PemData {
get subjectName() {
if (!tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_subjectName, "f")) tslib.__classPrivateFieldSet(this, _Pkcs10CertificateRequest_subjectName, new Name(this.asn.certificationRequestInfo.subject), "f");
return tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_subjectName, "f");
}
get subject() {
if (!tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_subject, "f")) tslib.__classPrivateFieldSet(this, _Pkcs10CertificateRequest_subject, this.subjectName.toString(), "f");
return tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_subject, "f");
}
get signatureAlgorithm() {
if (!tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_signatureAlgorithm, "f")) {
const algProv = tsyringe.container.resolve(diAlgorithmProvider);
tslib.__classPrivateFieldSet(this, _Pkcs10CertificateRequest_signatureAlgorithm, algProv.toWebAlgorithm(this.asn.signatureAlgorithm), "f");
}
return tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_signatureAlgorithm, "f");
}
get signature() {
if (!tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_signature, "f")) tslib.__classPrivateFieldSet(this, _Pkcs10CertificateRequest_signature, this.asn.signature, "f");
return tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_signature, "f");
}
get publicKey() {
if (!tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_publicKey, "f")) tslib.__classPrivateFieldSet(this, _Pkcs10CertificateRequest_publicKey, new PublicKey(this.asn.certificationRequestInfo.subjectPKInfo), "f");
return tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_publicKey, "f");
}
get attributes() {
if (!tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_attributes, "f")) tslib.__classPrivateFieldSet(this, _Pkcs10CertificateRequest_attributes, this.asn.certificationRequestInfo.attributes.map((o) => AttributeFactory.create(asn1Schema.AsnConvert.serialize(o))), "f");
return tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_attributes, "f");
}
get extensions() {
if (!tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_extensions, "f")) {
tslib.__classPrivateFieldSet(this, _Pkcs10CertificateRequest_extensions, [], "f");
const extensions = this.getAttribute(asnPkcs9.id_pkcs9_at_extensionRequest);
if (extensions instanceof ExtensionsAttribute) tslib.__classPrivateFieldSet(this, _Pkcs10CertificateRequest_extensions, extensions.items, "f");
}
return tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_extensions, "f");
}
get tbs() {
if (!tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_tbs, "f")) tslib.__classPrivateFieldSet(this, _Pkcs10CertificateRequest_tbs, this.asn.certificationRequestInfoRaw || asn1Schema.AsnConvert.serialize(this.asn.certificationRequestInfo), "f");
return tslib.__classPrivateFieldGet(this, _Pkcs10CertificateRequest_tbs, "f");
}
constructor(param) {
const args = PemData.isAsnEncoded(param) ? [param, asn1Csr.CertificationRequest] : [param];
super(args[0], args[1]);
_Pkcs10CertificateRequest_tbs.set(this, void 0);
_Pkcs10CertificateRequest_subjectName.set(this, void 0);
_Pkcs10CertificateRequest_subject.set(this, void 0);
_Pkcs10CertificateRequest_signatureAlgorithm.set(this, void 0);
_Pkcs10CertificateRequest_signature.set(this, void 0);
_Pkcs10CertificateRequest_publicKey.set(this, void 0);
_Pkcs10CertificateRequest_attributes.set(this, void 0);
_Pkcs10CertificateRequest_extensions.set(this, void 0);
this.tag = PemConverter.CertificateRequestTag;
}
onInit(_asn) {}
getAttribute(type) {
for (const attr of this.attributes) if (attr.type === type) return attr;
return null;
}
getAttributes(type) {
return this.attributes.filter((o) => o.type === type);
}
getExtension(type) {
for (const ext of this.extensions) if (ext.type === type) return ext;
return null;
}
getExtensions(type) {
return this.extensions.filter((o) => o.type === type);
}
async verify(crypto = cryptoProvider.get()) {
const algorithm = {
...this.publicKey.algorithm,
...this.signatureAlgorithm
};
const publicKey = await this.publicKey.export(algorithm, ["verify"], crypto);
const signatureFormatters = tsyringe.container.resolveAll(diAsnSignatureFormatter).reverse();
let signature = null;
for (const signatureFormatter of signatureFormatters) {
signature = signatureFormatter.toWebSignature(algorithm, this.signature);
if (signature) break;
}
if (!signature) throw Error("Cannot convert WebCrypto signature value to ASN.1 format");
return await crypto.subtle.verify(this.signatureAlgorithm, publicKey, signature, this.tbs);
}
toTextObject() {
const obj = this.toTextObjectEmpty();
const req = asn1Schema.AsnConvert.parse(this.rawData, asn1Csr.CertificationRequest);
const tbs = req.certificationRequestInfo;
const data = new TextObject("", {
Version: `${asn1X509.Version[tbs.version]} (${tbs.version})`,
Subject: this.subject,
"Subject Public Key Info": this.publicKey
});
if (this.attributes.length) {
const attrs = new TextObject("");
for (const ext of this.attributes) {
const attrObj = ext.toTextObject();
attrs[attrObj[TextObject.NAME]] = attrObj;
}
data["Attributes"] = attrs;
}
obj["Data"] = data;
obj["Signature"] = new TextObject("", {
Algorithm: TextConverter.serializeAlgorithm(req.signatureAlgorithm),
"": req.signature
});
return obj;
}
};
_Pkcs10CertificateRequest_tbs = /* @__PURE__ */ new WeakMap(), _Pkcs10CertificateRequest_subjectName = /* @__PURE__ */ new WeakMap(), _Pkcs10CertificateRequest_subject = /* @__PURE__ */ new WeakMap(), _Pkcs10CertificateRequest_signatureAlgorithm = /* @__PURE__ */ new WeakMap(), _Pkcs10CertificateRequest_signature = /* @__PURE__ */ new WeakMap(), _Pkcs10CertificateRequest_publicKey = /* @__PURE__ */ new WeakMap(), _Pkcs10CertificateRequest_attributes = /* @__PURE__ */ new WeakMap(), _Pkcs10CertificateRequest_extensions = /* @__PURE__ */ new WeakMap();
Pkcs10CertificateRequest.NAME = "PKCS#10 Certificate Request";
var Pkcs10CertificateRequestGenerator = class {
static async create(params, crypto = cryptoProvider.get()) {
if (!params.keys.privateKey) throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");
if (!params.keys.publicKey) throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");
const spki = await crypto.subtle.exportKey("spki", params.keys.publicKey);
const asnReq = new asn1Csr.CertificationRequest({ certificationRequestInfo: new asn1Csr.CertificationRequestInfo({ subjectPKInfo: asn1Schema.AsnConvert.parse(spki, asn1X509.SubjectPublicKeyInfo) }) });
if (params.name) {
const name = params.name instanceof Name ? params.name : new Name(params.name);
asnReq.certificationRequestInfo.subject = asn1Schema.AsnConvert.parse(name.toArrayBuffer(), asn1X509.Name);
}
if (params.attributes) for (const o of params.attributes) asnReq.certificationRequestInfo.attributes.push(asn1Schema.AsnConvert.parse(o.rawData, asn1X509.Attribute));
if (params.extensions && params.extensions.length) {
const attr = new asn1X509.Attribute({ type: asnPkcs9.id_pkcs9_at_extensionRequest });
const extensions = new asn1X509.Extensions();
for (const o of params.extensions) extensions.push(asn1Schema.AsnConvert.parse(o.rawData, asn1X509.Extension));
attr.values.push(asn1Schema.AsnConvert.serialize(extensions));
asnReq.certificationRequestInfo.attributes.push(attr);
}
const signingAlgorithm = {
...params.signingAlgorithm,
...params.keys.privateKey.algorithm
};
asnReq.signatureAlgorithm = tsyringe.container.resolve(diAlgorithmProvider).toAsnAlgorithm(signingAlgorithm);
const tbs = asn1Schema.AsnConvert.serialize(asnReq.certificationRequestInfo);
const signature = await crypto.subtle.sign(signingAlgorithm, params.keys.privateKey, tbs);
const signatureFormatters = tsyringe.container.resolveAll(diAsnSignatureFormatter).reverse();
let asnSignature = null;
for (const signatureFormatter of signatureFormatters) {
asnSignature = signatureFormatter.toAsnSignature(signingAlgorithm, signature);
if (asnSignature) break;
}
if (!asnSignature) throw Error("Cannot convert WebCrypto signature value to ASN.1 format");
asnReq.signature = asnSignature;
return new Pkcs10CertificateRequest(asn1Schema.AsnConvert.serialize(asnReq));
}
};
var _X509Certificate_tbs;
var _X509Certificate_serialNumber;
var _X509Certificate_subjectName;
var _X509Certificate_subject;
var _X509Certificate_issuerName;
var _X509Certificate_issuer;
var _X509Certificate_notBefore;
var _X509Certificate_notAfter;
var _X509Certificate_signatureAlgorithm;
var _X509Certificate_signature;
var _X509Certificate_extensions;
var _X509Certificate_publicKey;
var X509Certificate = class extends PemData {
get publicKey() {
if (!tslib.__classPrivateFieldGet(this, _X509Certificate_publicKey, "f")) tslib.__classPrivateFieldSet(this, _X509Certificate_publicKey, new PublicKey(this.asn.tbsCertificate.subjectPublicKeyInfo), "f");
return tslib.__classPrivateFieldGet(this, _X509Certificate_publicKey, "f");
}
get serialNumber() {
if (!tslib.__classPrivateFieldGet(this, _X509Certificate_serialNumber, "f")) {
const tbs = this.asn.tbsCertificate;
let serialNumberBytes = new Uint8Array(tbs.serialNumber);
if (serialNumberBytes.length > 1 && serialNumberBytes[0] === 0 && serialNumberBytes[1] > 127) serialNumberBytes = serialNumberBytes.slice(1);
tslib.__classPrivateFieldSet(this, _X509Certificate_serialNumber, pvtsutils.Convert.ToHex(serialNumberBytes), "f");
}
return tslib.__classPrivateFieldGet(this, _X509Certificate_serialNumber, "f");
}
get subjectName() {
if (!tslib.__classPrivateFieldGet(this, _X509Certificate_subjectName, "f")) tslib.__classPrivateFieldSet(this, _X509Certificate_subjectName, new Name(this.asn.tbsCertificate.subject), "f");
return tslib.__classPrivateFieldGet(this, _X509Certificate_subjectName, "f");
}
get subject() {
if (!tslib.__classPrivateFieldGet(this, _X509Certificate_subject, "f")) tslib.__classPrivateFieldSet(this, _X509Certificate_subject, this.subjectName.toString(), "f");
return tslib.__classPrivateFieldGet(this, _X509Certificate_subject, "f");
}
get issuerName() {
if (!tslib.__classPrivateFieldGet(this, _X509Certificate_issuerName, "f")) tslib.__classPrivateFieldSet(this, _X509Certificate_issuerName, new Name(this.asn.tbsCertificate.issuer), "f");
return tslib.__classPrivateFieldGet(this, _X509Certificate_issuerName, "f");
}
get issuer() {
if (!tslib.__classPrivateFieldGet(this, _X509Certificate_issuer, "f")) tslib.__classPrivateFieldSet(this, _X509Certificate_issuer, this.issuerName.toString(), "f");
return tslib.__classPrivateFieldGet(this, _X509Certificate_issuer, "f");
}
get notBefore() {
if (!tslib.__classPrivateFieldGet(this, _X509Certificate_notBefore, "f")) {
const notBefore = this.asn.tbsCertificate.validity.notBefore.utcTime || this.asn.tbsCertificate.validity.notBefore.generalTime;
if (!notBefore) throw new Error("Cannot get 'notBefore' value");
tslib.__classPrivateFieldSet(this, _X509Certificate_notBefore, notBefore, "f");
}
return tslib.__classPrivateFieldGet(this, _X509Certificate_notBefore, "f");
}
get notAfter() {
if (!tslib.__classPrivateFieldGet(this, _X509Certificate_notAfter, "f")) {
const notAfter = this.asn.tbsCertificate.validity.notAfter.utcTime || this.asn.tbsCertificate.validity.notAfter.generalTime;
if (!notAfter) throw new Error("Cannot get 'notAfter' value");
tslib.__classPrivateFieldSet(this, _X509Certificate_notAfter, notAfter, "f");
}
return tslib.__classPrivateFieldGet(this, _X509Certificate_notAfter, "f");
}
get signatureAlgorithm() {
if (!tslib.__classPrivateFieldGet(this, _X509Certificate_signatureAlgorithm, "f")) {
const algProv = tsyringe.container.resolve(diAlgorithmProvider);
tslib.__classPrivateFieldSet(this, _X509Certificate_signatureAlgorithm, algProv.toWebAlgorithm(this.asn.signatureAlgorithm), "f");
}
return tslib.__classPrivateFieldGet(this, _X509Certificate_signatureAlgorithm, "f");
}
get signature() {
if (!tslib.__classPrivateFieldGet(this, _X509Certificate_signature, "f")) tslib.__classPrivateFieldSet(this, _X509Certificate_signature, this.asn.signatureValue, "f");
return tslib.__classPrivateFieldGet(this, _X509Certificate_signature, "f");
}
get extensions() {
if (!tslib.__classPrivateFieldGet(this, _X509Certificate_extensions, "f")) {
tslib.__classPrivateFieldSet(this, _X509Certificate_extensions, [], "f");
if (this.asn.tbsCertificate.extensions) tslib.__classPrivateFieldSet(this, _X509Certificate_extensions, this.asn.tbsCertificate.extensions.map((o) => ExtensionFactory.create(asn1Schema.AsnConvert.serialize(o))), "f");
}
return tslib.__classPrivateFieldGet(this, _X509Certificate_extensions, "f");
}
get tbs() {
if (!tslib.__classPrivateFieldGet(this, _X509Certificate_tbs, "f")) tslib.__classPrivateFieldSet(this, _X509Certificate_tbs, this.asn.tbsCertificateRaw || asn1Schema.AsnConvert.serialize(this.asn.tbsCertificate), "f");
return tslib.__classPrivateFieldGet(this, _X509Certificate_tbs, "f");
}
constructor(param) {
const args = PemData.isAsnEncoded(param) ? [param, asn1X509.Certificate] : [param];
super(args[0], args[1]);
_X509Certificate_tbs.set(this, void 0);
_X509Certificate_serialNumber.set(this, void 0);
_X509Certificate_subjectName.set(this, void 0);
_X509Certificate_subject.set(this, void 0);
_X509Certificate_issuerName.set(this, void 0);
_X509Certificate_issuer.set(this, void 0);
_X509Certificate_notBefore.set(this, void 0);
_X509Certificate_notAfter.set(this, void 0);
_X509Certificate_signatureAlgorithm.set(this, void 0);
_X509Certificate_signature.set(this, void 0);
_X509Certificate_extensions.set(this, void 0);
_X509Certificate_publicKey.set(this, void 0);
this.tag = PemConverter.CertificateTag;
}
onInit(_asn) {}
getExtension(type) {
for (const ext of this.extensions) if (typeof type === "string") {
if (ext.type === type) return ext;
} else if (ext instanceof type) return ext;
return null;
}
getExtensions(type) {
return this.extensions.filter((o) => {
if (typeof type === "string") return o.type === type;
else return o instanceof type;
});
}
async verify(params = {}, crypto = cryptoProvider.get()) {
let keyAlgorithm;
let publicKey;
const paramsKey = params.publicKey;
try {
if (!paramsKey) {
keyAlgorithm = {
...this.publicKey.algorithm,
...this.signatureAlgorithm
};
publicKey = await this.publicKey.export(keyAlgorithm, ["verify"], crypto);
} else if ("publicKey" in paramsKey) {
keyAlgorithm = {
...paramsKey.publicKey.algorithm,
...this.signatureAlgorithm
};
publicKey = await paramsKey.publicKey.export(keyAlgorithm, ["verify"], crypto);
} else if (paramsKey instanceof PublicKey) {
keyAlgorithm = {
...paramsKey.algorithm,
...this.signatureAlgorithm
};
publicKey = await paramsKey.export(keyAlgorithm, ["verify"], crypto);
} else if (pvtsutils.BufferSourceConverter.isBufferSource(paramsKey)) {
const key = new PublicKey(paramsKey);
keyAlgorithm = {
...key.algorithm,
...this.signatureAlgorithm
};
publicKey = await key.export(keyAlgorithm, ["verify"], crypto);
} else {
keyAlgorithm = {
...paramsKey.algorithm,
...this.signatureAlgorithm
};
publicKey = paramsKey;
}
} catch {
return false;
}
const signatureFormatters = tsyringe.container.resolveAll(diAsnSignatureFormatter).reverse();
let signature = null;
for (const signatureFormatter of signatureFormatters) {
signature = signatureFormatter.toWebSignature(keyAlgorithm, this.signature);
if (signature) break;
}
if (!signature) throw Error("Cannot convert ASN.1 signature value to WebCrypto format");
const ok = await crypto.subtle.verify(this.signatureAlgorithm, publicKey, signature, this.tbs);
if (params.signatureOnly) return ok;
else {
const time = (params.date || /* @__PURE__ */ new Date()).getTime();
return ok && this.notBefore.getTime() < time && time < this.notAfter.getTime();
}
}
async getThumbprint(...args) {
let crypto;
let algorithm = "SHA-1";
if (args[0]) {
if (!args[0].subtle) {
algorithm = args[0] || algorithm;
crypto = args[1];
} else crypto = args[0];
}
crypto !== null && crypto !== void 0 || (crypto = cryptoProvider.get());
return await crypto.subtle.digest(algorithm, this.rawData);
}
async isSelfSigned(crypto = cryptoProvider.get()) {
return this.subject === this.issuer && await this.verify({ signatureOnly: true }, crypto);
}
toTextObject() {
const obj = this.toTextObjectEmpty();
const cert = asn1Schema.AsnConvert.parse(this.rawData, asn1X509.Certificate);
const tbs = cert.tbsCertificate;
const data = new TextObject("", {
Version: `${asn1X509.Version[tbs.version]} (${tbs.version})`,
"Serial Number": tbs.serialNumber,
"Signature Algorithm": TextConverter.serializeAlgorithm(tbs.signature),
Issuer: this.issuer,
Validity: new TextObject("", {
"Not Before": tbs.validity.notBefore.getTime(),
"Not After": tbs.validity.notAfter.getTime()
}),
Subject: this.subject,
"Subject Public Key Info": this.publicKey
});
if (tbs.issuerUniqueID) data["Issuer Unique ID"] = tbs.issuerUniqueID;
if (tbs.subjectUniqueID) data["Subject Unique ID"] = tbs.subjectUniqueID;
if (this.extensions.length) {
const extensions = new TextObject("");
for (const ext of this.extensions) {
const extObj = ext.toTextObject();
extensions[extObj[TextObject.NAME]] = extObj;
}
data["Extensions"] = extensions;
}
obj["Data"] = data;
obj["Signature"] = new TextObject("", {
Algorithm: TextConverter.serializeAlgorithm(cert.signatureAlgorithm),
"": cert.signatureValue
});
return obj;
}
};
_X509Certificate_tbs = /* @__PURE__ */ new WeakMap(), _X509Certificate_serialNumber = /* @__PURE__ */ new WeakMap(), _X509Certificate_subjectName = /* @__PURE__ */ new WeakMap(), _X509Certificate_subject = /* @__PURE__ */ new WeakMap(), _X509Certificate_issuerName = /* @__PURE__ */ new WeakMap(), _X509Certificate_issuer = /* @__PURE__ */ new WeakMap(), _X509Certificate_notBefore = /* @__PURE__ */ new WeakMap(), _X509Certificate_notAfter = /* @__PURE__ */ new WeakMap(), _X509Certificate_signatureAlgorithm = /* @__PURE__ */ new WeakMap(), _X509Certificate_signature = /* @__PURE__ */ new WeakMap(), _X509Certificate_extensions = /* @__PURE__ */ new WeakMap(), _X509Certificate_publicKey = /* @__PURE__ */ new WeakMap();
X509Certificate.NAME = "Certificate";
var X509Certificates = class extends Array {
constructor(param) {
super();
if (PemData.isAsnEncoded(param)) this.import(param);
else if (param instanceof X509Certificate) this.push(param);
else if (Array.isArray(param)) for (const item of param) this.push(item);
}
export(format) {
const signedData = new asn1Cms__namespace.SignedData();
signedData.version = 1;
signedData.encapContentInfo.eContentType = asn1Cms__namespace.id_data;
signedData.encapContentInfo.eContent = new asn1Cms__namespace.EncapsulatedContent({ single: new asn1Schema.OctetString() });
signedData.certificates = new asn1Cms__namespace.CertificateSet(this.map((o) => new asn1Cms__namespace.CertificateChoices({ certificate: asn1Schema.AsnConvert.parse(o.rawData, asn1X509.Certificate) })));
const cms = new asn1Cms__namespace.ContentInfo({
contentType: asn1Cms__namespace.id_signedData,
content: asn1Schema.AsnConvert.serialize(signedData)
});
const raw = asn1Schema.AsnConvert.serialize(cms);
if (format === "raw") return raw;
return this.toString(format);
}
import(data) {
const raw = PemData.toArrayBuffer(data);
const cms = asn1Schema.AsnConvert.parse(raw, asn1Cms__namespace.ContentInfo);
if (cms.contentType !== asn1Cms__namespace.id_signedData) throw new TypeError("Cannot parse CMS package. Incoming data is not a SignedData object.");
const signedData = asn1Schema.AsnConvert.parse(cms.content, asn1Cms__namespace.SignedData);
this.clear();
for (const item of signedData.certificates || []) if (item.certificate) this.push(new X509Certificate(item.certificate));
}
clear() {
while (this.pop());
}
toString(format = "pem") {
const raw = this.export("raw");
switch (format) {
case "pem": return PemConverter.encode(raw, "CMS");
case "pem-chain": return this.map((o) => o.toString("pem")).join("\n");
case "asn": return asn1Schema.AsnConvert.toString(raw);
case "hex": return pvtsutils.Convert.ToHex(raw);
case "base64": return pvtsutils.Convert.ToBase64(raw);
case "base64url": return pvtsutils.Convert.ToBase64Url(raw);
case "text": return TextConverter.serialize(this.toTextObject());
default: throw TypeError("Argument 'format' is unsupported value");
}
}
toTextObject() {
const contentInfo = asn1Schema.AsnConvert.parse(this.export("raw"), asn1Cms__namespace.ContentInfo);
const signedData = asn1Schema.AsnConvert.parse(contentInfo.content, asn1Cms__namespace.SignedData);
return new TextObject("X509Certificates", {
"Content Type": OidSerializer.toString(contentInfo.contentType),
Content: new TextObject("", {
Version: `${asn1Cms__namespace.CMSVersion[signedData.version]} (${signedData.version})`,
Certificates: new TextObject("", { Certificate: this.map((o) => o.toTextObject()) })
})
});
}
};
var X509ChainBuilder = class {
constructor(params = {}) {
this.certificates = [];
if (params.certificates) this.certificates = params.certificates;
}
async build(cert, crypto = cryptoProvider.get()) {
const chain = new X509Certificates(cert);
let current = cert;
while (current = await this.findIssuer(current, crypto)) {
const thumbprint = await current.getThumbprint(crypto);
for (const item of chain) {
const thumbprint2 = await item.getThumbprint(crypto);
if (pvtsutils.isEqual(thumbprint, thumbprint2)) throw new Error("Cannot build a certificate chain. Circular dependency.");
}
chain.push(current);
}
return chain;
}
async findIssuer(cert, crypto = cryptoProvider.get()) {
if (!await cert.isSelfSigned(crypto)) {
const akiExt = cert.getExtension(asn1X509__namespace.id_ce_authorityKeyIdentifier);
for (const item of this.certificates) {
if (item.subject !== cert.issuer) continue;
if (akiExt) {
if (akiExt.keyId) {
const skiExt = item.getExtension(asn1X509__namespace.id_ce_subjectKeyIdentifier);
if (skiExt && skiExt.keyId !== akiExt.keyId) continue;
} else if (akiExt.certId) {
const sanExt = item.getExtension(asn1X509__namespace.id_ce_subjectAltName);
if (sanExt && !(akiExt.certId.serialNumber === item.serialNumber && pvtsutils.isEqual(asn1Schema.AsnConvert.serialize(akiExt.certId.name), asn1Schema.AsnConvert.serialize(sanExt)))) continue;
}
}
try {
const algorithm = {
...item.publicKey.algorithm,
...cert.signatureAlgorithm
};
const publicKey = await item.publicKey.export(algorithm, ["verify"], crypto);
if (!await cert.verify({
publicKey,
signatureOnly: true
}, crypto)) continue;
} catch {
continue;
}
return item;
}
}
return null;
}
};
function generateCertificateSerialNumber(input, crypto = cryptoProvider.get()) {
const inputView = pvtsutils.BufferSourceConverter.toUint8Array(pvtsutils.Convert.FromHex(input || ""));
let serialNumber = inputView && inputView.length && inputView.some((o) => o > 0) ? new Uint8Array(inputView) : void 0;
if (!serialNumber) serialNumber = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
let firstNonZero = 0;
while (firstNonZero < serialNumber.length - 1 && serialNumber[firstNonZero] === 0) firstNonZero++;
serialNumber = serialNumber.slice(firstNonZero);
if (serialNumber[0] > 127) {
const newSerialNumber = new Uint8Array(serialNumber.length + 1);
newSerialNumber[0] = 0;
newSerialNumber.set(serialNumber, 1);
serialNumber = newSerialNumber;
}
return serialNumber.buffer;
}
var X509CertificateGenerator = class {
static async createSelfSigned(params, crypto = cryptoProvider.get()) {
if (!params.keys.privateKey) throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");
if (!params.keys.publicKey) throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");
return this.create({
serialNumber: params.serialNumber,
subject: params.name,
issuer: params.name,
notBefore: params.notBefore,
notAfter: params.notAfter,
publicKey: params.keys.publicKey,
signingKey: params.keys.privateKey,
signingAlgorithm: params.signingAlgorithm,
extensions: params.extensions
}, crypto);
}
static async create(params, crypto = cryptoProvider.get()) {
var _a;
let spki;
if (params.publicKey instanceof PublicKey) spki = params.publicKey.rawData;
else if ("publicKey" in params.publicKey) spki = params.publicKey.publicKey.rawData;
else if (pvtsutils.BufferSourceConverter.isBufferSource(params.publicKey)) spki = params.publicKey;
else spki = await crypto.subtle.exportKey("spki", params.publicKey);
const serialNumber = generateCertificateSerialNumber(params.serialNumber, crypto);
const notBefore = params.notBefore || /* @__PURE__ */ new Date();
const notAfter = params.notAfter || new Date(notBefore.getTime() + 31536e6);
const asnX509 = new asn1X509__namespace.Certificate({ tbsCertificate: new asn1X509__namespace.TBSCertificate({
version: asn1X509__namespace.Version.v3,
serialNumber,
validity: new asn1X509__namespace.Validity({
notBefore,
notAfter
}),
extensions: new asn1X509__namespace.Extensions(((_a = params.extensions) === null || _a === void 0 ? void 0 : _a.map((o) => asn1Schema.AsnConvert.parse(o.rawData, asn1X509__namespace.Extension))) || []),
subjectPublicKeyInfo: asn1Schema.AsnConvert.parse(spki, asn1X509__namespace.SubjectPublicKeyInfo)
}) });
if (params.subject) {
const name = params.subject instanceof Name ? params.subject : new Name(params.subject);
asnX509.tbsCertificate.subject = asn1Schema.AsnConvert.parse(name.toArrayBuffer(), asn1X509__namespace.Name);
}
if (params.issuer) {
const name = params.issuer instanceof Name ? params.issuer : new Name(params.issuer);
asnX509.tbsCertificate.issuer = asn1Schema.AsnConvert.parse(name.toArrayBuffer(), asn1X509__namespace.Name);
}
const defaultSigningAlgorithm = { hash: "SHA-256" };
const signatureAlgorithm = "signingKey" in params ? {
...defaultSigningAlgorithm,
...params.signingAlgorithm,
...params.signingKey.algorithm
} : {
...defaultSigningAlgorithm,
...params.signingAlgorithm
};
const algProv = tsyringe.container.resolve(diAlgorithmProvider);
asnX509.tbsCertificate.signature = asnX509.signatureAlgorithm = algProv.toAsnAlgorithm(signatureAlgorithm);
const tbs = asn1Schema.AsnConvert.serialize(asnX509.tbsCertificate);
const signatureValue = "signingKey" in params ? await crypto.subtle.sign(signatureAlgorithm, params.signingKey, tbs) : params.signature;
const signatureFormatters = tsyringe.container.resolveAll(diAsnSignatureFormatter).reverse();
let asnSignature = null;
for (const signatureFormatter of signatureFormatters) {
asnSignature = signatureFormatter.toAsnSignature(signatureAlgorithm, signatureValue);
if (asnSignature) break;
}
if (!asnSignature) throw Error("Cannot convert ASN.1 signature value to WebCrypto format");
asnX509.signatureValue = asnSignature;
return new X509Certificate(asn1Schema.AsnConvert.serialize(asnX509));
}
};
var _X509CrlEntry_serialNumber;
var _X509CrlEntry_revocationDate;
var _X509CrlEntry_reason;
var _X509CrlEntry_invalidity;
var _X509CrlEntry_extensions;
exports.X509CrlReason = void 0;
(function(X509CrlReason) {
X509CrlReason[X509CrlReason["unspecified"] = 0] = "unspecified";
X509CrlReason[X509CrlReason["keyCompromise"] = 1] = "keyCompromise";
X509CrlReason[X509CrlReason["cACompromise"] = 2] = "cACompromise";
X509CrlReason[X509CrlReason["affiliationChanged"] = 3] = "affiliationChanged";
X509CrlReason[X509CrlReason["superseded"] = 4] = "superseded";
X509CrlReason[X509CrlReason["cessationOfOperation"] = 5] = "cessationOfOperation";
X509CrlReason[X509CrlReason["certificateHold"] = 6] = "certificateHold";
X509CrlReason[X509CrlReason["removeFromCRL"] = 8] = "removeFromCRL";
X509CrlReason[X509CrlReason["privilegeWithdrawn"] = 9] = "privilegeWithdrawn";
X509CrlReason[X509CrlReason["aACompromise"] = 10] = "aACompromise";
})(exports.X509CrlReason || (exports.X509CrlReason = {}));
var X509CrlEntry = class extends AsnData {
get serialNumber() {
if (!tslib.__classPrivateFieldGet(this, _X509CrlEntry_serialNumber, "f")) tslib.__classPrivateFieldSet(this, _X509CrlEntry_serialNumber, pvtsutils.Convert.ToHex(this.asn.userCertificate), "f");
return tslib.__classPrivateFieldGet(this, _X509CrlEntry_serialNumber, "f");
}
get revocationDate() {
if (!tslib.__classPrivateFieldGet(this, _X509CrlEntry_revocationDate, "f")) tslib.__classPrivateFieldSet(this, _X509CrlEntry_revocationDate, this.asn.revocationDate.getTime(), "f");
return tslib.__classPrivateFieldGet(this, _X509CrlEntry_revocationDate, "f");
}
get reason() {
if (tslib.__classPrivateFieldGet(this, _X509CrlEntry_reason, "f") === void 0) this.extensions;
return tslib.__classPrivateFieldGet(this, _X509CrlEntry_reason, "f");
}
get invalidity() {
if (tslib.__classPrivateFieldGet(this, _X509CrlEntry_invalidity, "f") === void 0) this.extensions;
return tslib.__classPrivateFieldGet(this, _X509CrlEntry_invalidity, "f");
}
get extensions() {
if (!tslib.__classPrivateFieldGet(this, _X509CrlEntry_extensions, "f")) {
tslib.__classPrivateFieldSet(this, _X509CrlEntry_extensions, [], "f");
if (this.asn.crlEntryExtensions) tslib.__classPrivateFieldSet(this, _X509CrlEntry_extensions, this.asn.crlEntryExtensions.map((o) => {
const extension = ExtensionFactory.create(asn1Schema.AsnConvert.serialize(o));
switch (extension.type) {
case asn1X509.id_ce_cRLReasons:
if (tslib.__classPrivateFieldGet(this, _X509CrlEntry_reason, "f") === void 0) tslib.__classPrivateFieldSet(this, _X509CrlEntry_reason, asn1Schema.AsnConvert.parse(extension.value, asn1X509.CRLReason).reason, "f");
break;
case asn1X509.id_ce_invalidityDate: if (tslib.__classPrivateFieldGet(this, _X509CrlEntry_invalidity, "f") === void 0) tslib.__classPrivateFieldSet(this, _X509CrlEntry_invalidity, asn1Schema.AsnConvert.parse(extension.value, asn1X509.InvalidityDate).value, "f");
}
return extension;
}), "f");
}
return tslib.__classPrivateFieldGet(this, _X509CrlEntry_extensions, "f");
}
constructor(...args) {
let raw;
if (pvtsutils.BufferSourceConverter.isBufferSource(args[0])) raw = pvtsutils.BufferSourceConverter.toArrayBuffer(args[0]);
else if (typeof args[0] === "string") raw = asn1Schema.AsnConvert.serialize(new asn1X509.RevokedCertificate({
userCertificate: generateCertificateSerialNumber(args[0]),
revocationDate: new asn1X509.Time(args[1]),
crlEntryExtensions: args[2]
}));
else if (args[0] instanceof asn1X509.RevokedCertificate) raw = args[0];
if (!raw) throw new TypeError("Cannot create X509CrlEntry instance. Wrong constructor arguments.");
super(raw, asn1X509.RevokedCertificate);
_X509CrlEntry_serialNumber.set(this, void 0);
_X509CrlEntry_revocationDate.set(this, void 0);
_X509CrlEntry_reason.set(this, void 0);
_X509CrlEntry_invalidity.set(this, void 0);
_X509CrlEntry_extensions.set(this, void 0);
}
onInit(_asn) {}
};
_X509CrlEntry_serialNumber = /* @__PURE__ */ new WeakMap(), _X509CrlEntry_revocationDate = /* @__PURE__ */ new WeakMap(), _X509CrlEntry_reason = /* @__PURE__ */ new WeakMap(), _X509CrlEntry_invalidity = /* @__PURE__ */ new WeakMap(), _X509CrlEntry_extensions = /* @__PURE__ */ new WeakMap();
var _X509Crl_tbs;
var _X509Crl_signatureAlgorithm;
var _X509Crl_issuerName;
var _X509Crl_thisUpdate;
var _X509Crl_nextUpdate;
var _X509Crl_entries;
var _X509Crl_extensions;
var X509Crl = class extends PemData {
get version() {
return this.asn.tbsCertList.version;
}
get signatureAlgorithm() {
if (!tslib.__classPrivateFieldGet(this, _X509Crl_signatureAlgorithm, "f")) {
const algProv = tsyringe.container.resolve(diAlgorithmProvider);
tslib.__classPrivateFieldSet(this, _X509Crl_signatureAlgorithm, algProv.toWebAlgorithm(this.asn.signatureAlgorithm), "f");
}
return tslib.__classPrivateFieldGet(this, _X509Crl_signatureAlgorithm, "f");
}
get signature() {
return this.asn.signature;
}
get issuer() {
return this.issuerName.toString();
}
get issuerName() {
if (!tslib.__classPrivateFieldGet(this, _X509Crl_issuerName, "f")) tslib.__classPrivateFieldSet(this, _X509Crl_issuerName, new Name(this.asn.tbsCertList.issuer), "f");
return tslib.__classPrivateFieldGet(this, _X509Crl_issuerName, "f");
}
get thisUpdate() {
if (!tslib.__classPrivateFieldGet(this, _X509Crl_thisUpdate, "f")) {
const thisUpdate = this.asn.tbsCertList.thisUpdate.getTime();
if (!thisUpdate) throw new Error("Cannot get 'thisUpdate' value");
tslib.__classPrivateFieldSet(this, _X509Crl_thisUpdate, thisUpdate, "f");
}
return tslib.__classPrivateFieldGet(this, _X509Crl_thisUpdate, "f");
}
get nextUpdate() {
var _a;
if (tslib.__classPrivateFieldGet(this, _X509Crl_nextUpdate, "f") === void 0) tslib.__classPrivateFieldSet(this, _X509Crl_nextUpdate, ((_a = this.asn.tbsCertList.nextUpdate) === null || _a === void 0 ? void 0 : _a.getTime()) || void 0, "f");
return tslib.__classPrivateFieldGet(this, _X509Crl_nextUpdate, "f");
}
get entries() {
var _a;
if (!tslib.__classPrivateFieldGet(this, _X509Crl_entries, "f")) tslib.__classPrivateFieldSet(this, _X509Crl_entries, ((_a = this.asn.tbsCertList.revokedCertificates) === null || _a === void 0 ? void 0 : _a.map((o) => new X509CrlEntry(o))) || [], "f");
return tslib.__classPrivateFieldGet(this, _X509Crl_entries, "f");
}
get extensions() {
if (!tslib.__classPrivateFieldGet(this, _X509Crl_extensions, "f")) {
tslib.__classPrivateFieldSet(this, _X509Crl_extensions, [], "f");
if (this.asn.tbsCertList.crlExtensions) tslib.__classPrivateFieldSet(this, _X509Crl_extensions, this.asn.tbsCertList.crlExtensions.map((o) => ExtensionFactory.create(asn1Schema.AsnConvert.serialize(o))), "f");
}
return tslib.__classPrivateFieldGet(this, _X509Crl_extensions, "f");
}
get tbs() {
if (!tslib.__classPrivateFieldGet(this, _X509Crl_tbs, "f")) tslib.__classPrivateFieldSet(this, _X509Crl_tbs, this.asn.tbsCertListRaw || asn1Schema.AsnConvert.serialize(this.asn.tbsCertList), "f");
return tslib.__classPrivateFieldGet(this, _X509Crl_tbs, "f");
}
get tbsCertListSignatureAlgorithm() {
return this.asn.tbsCertList.signature;
}
get certListSignatureAlgorithm() {
return this.asn.signatureAlgorithm;
}
constructor(param) {
super(param, PemData.isAsnEncoded(param) ? asn1X509.CertificateList : void 0);
this.tag = PemConverter.CrlTag;
_X509Crl_tbs.set(this, void 0);
_X509Crl_signatureAlgorithm.set(this, void 0);
_X509Crl_issuerName.set(this, void 0);
_X509Crl_thisUpdate.set(this, void 0);
_X509Crl_nextUpdate.set(this, void 0);
_X509Crl_entries.set(this, void 0);
_X509Crl_extensions.set(this, void 0);
}
onInit(_asn) {}
getExtension(type) {
for (const ext of this.extensions) if (typeof type === "string") {
if (ext.type === type) return ext;
} else if (ext instanceof type) return ext;
return null;
}
getExtensions(type) {
return this.extensions.filter((o) => {
if (typeof type === "string") return o.type === type;
else return o instanceof type;
});
}
async verify(params, crypto = cryptoProvider.get()) {
if (!this.certListSignatureAlgorithm.isEqual(this.tbsCertListSignatureAlgorithm)) throw new Error("algorithm identifier in the sequence tbsCertList and CertificateList mismatch");
let keyAlgorithm;
let publicKey;
const paramsKey = params.publicKey;
try {
if (paramsKey instanceof X509Certificate) {
keyAlgorithm = {
...paramsKey.publicKey.algorithm,
...paramsKey.signatureAlgorithm
};
publicKey = await paramsKey.publicKey.export(keyAlgorithm, ["verify"]);
} else if (paramsKey instanceof PublicKey) {
keyAlgorithm = {
...paramsKey.algorithm,
...this.signatureAlgorithm
};
publicKey = await paramsKey.export(keyAlgorithm, ["verify"]);
} else {
keyAlgorithm = {
...paramsKey.algorithm,
...this.signatureAlgorithm
};
publicKey = paramsKey;
}
} catch {
return false;
}
const signatureFormatters = tsyringe.container.resolveAll(diAsnSignatureFormatter).reverse();
let signature = null;
for (const signatureFormatter of signatureFormatters) {
signature = signatureFormatter.toWebSignature(keyAlgorithm, this.signature);
if (signature) break;
}
if (!signature) throw Error("Cannot convert ASN.1 signature value to WebCrypto format");
return await crypto.subtle.verify(this.signatureAlgorithm, publicKey, signature, this.tbs);
}
async getThumbprint(...args) {
let crypto;
let algorithm = "SHA-1";
if (args[0]) {
if (!args[0].subtle) {
algorithm = args[0] || algorithm;
crypto = args[1];
} else crypto = args[0];
}
crypto !== null && crypto !== void 0 || (crypto = cryptoProvider.get());
return await crypto.subtle.digest(algorithm, this.rawData);
}
findRevoked(certOrSerialNumber) {
const serialBuffer = generateCertificateSerialNumber(typeof certOrSerialNumber === "string" ? certOrSerialNumber : certOrSerialNumber.serialNumber);
for (const revoked of this.asn.tbsCertList.revokedCertificates || []) if (pvtsutils.BufferSourceConverter.isEqual(revoked.userCertificate, serialBuffer)) return new X509CrlEntry(asn1Schema.AsnConvert.serialize(revoked));
return null;
}
};
_X509Crl_tbs = /* @__PURE__ */ new WeakMap(), _X509Crl_signatureAlgorithm = /* @__PURE__ */ new WeakMap(), _X509Crl_issuerName = /* @__PURE__ */ new WeakMap(), _X509Crl_thisUpdate = /* @__PURE__ */ new WeakMap(), _X509Crl_nextUpdate = /* @__PURE__ */ new WeakMap(), _X509Crl_entries = /* @__PURE__ */ new WeakMap(), _X509Crl_extensions = /* @__PURE__ */ new WeakMap();
var X509CrlGenerator = class {
static async create(params, crypto = cryptoProvider.get()) {
var _a;
const name = params.issuer instanceof Name ? params.issuer : new Name(params.issuer);
const asnX509Crl = new asn1X509__namespace.CertificateList({ tbsCertList: new asn1X509__namespace.TBSCertList({
version: asn1X509__namespace.Version.v2,
issuer: asn1Schema.AsnConvert.parse(name.toArrayBuffer(), asn1X509__namespace.Name),
thisUpdate: new asn1X509.Time(params.thisUpdate || /* @__PURE__ */ new Date())
}) });
if (params.nextUpdate) asnX509Crl.tbsCertList.nextUpdate = new asn1X509.Time(params.nextUpdate);
if (params.extensions && params.extensions.length) asnX509Crl.tbsCertList.crlExtensions = new asn1X509__namespace.Extensions(params.extensions.map((o) => asn1Schema.AsnConvert.parse(o.rawData, asn1X509__namespace.Extension)) || []);
if (params.entries && params.entries.length) {
asnX509Crl.tbsCertList.revokedCertificates = [];
for (const entry of params.entries) {
const userCertificate = PemData.toArrayBuffer(entry.serialNumber);
if (asnX509Crl.tbsCertList.revokedCertificates.findIndex((cert) => pvtsutils.isEqual(cert.userCertificate, userCertificate)) > -1) throw new Error(`Certificate serial number ${entry.serialNumber} already exists in tbsCertList`);
const revokedCert = new asn1X509.RevokedCertificate({
userCertificate,
revocationDate: new asn1X509.Time(entry.revocationDate || /* @__PURE__ */ new Date())
});
if ("extensions" in entry && ((_a = entry.extensions) === null || _a === void 0 ? void 0 : _a.length)) revokedCert.crlEntryExtensions = entry.extensions.map((o) => asn1Schema.AsnConvert.parse(o.rawData, asn1X509__namespace.Extension));
else revokedCert.crlEntryExtensions = [];
if (!(entry instanceof X509CrlEntry)) {
if (entry.reason) revokedCert.crlEntryExtensions.push(new asn1X509__namespace.Extension({
extnID: asn1X509__namespace.id_ce_cRLReasons,
critical: false,
extnValue: new asn1Schema.OctetString(asn1Schema.AsnConvert.serialize(new asn1X509__namespace.CRLReason(entry.reason)))
}));
if (entry.invalidity) revokedCert.crlEntryExtensions.push(new asn1X509__namespace.Extension({
extnID: asn1X509__namespace.id_ce_invalidityDate,
critical: false,
extnValue: new asn1Schema.OctetString(asn1Schema.AsnConvert.serialize(new asn1X509__namespace.InvalidityDate(entry.invalidity)))
}));
if (entry.issuer) {
const name = params.issuer instanceof Name ? params.issuer : new Name(params.issuer);
revokedCert.crlEntryExtensions.push(new asn1X509__namespace.Extension({
extnID: asn1X509__namespace.id_ce_certificateIssuer,
critical: false,
extnValue: new asn1Schema.OctetString(asn1Schema.AsnConvert.serialize(asn1Schema.AsnConvert.parse(name.toArrayBuffer(), asn1X509__namespace.Name)))
}));
}
}
asnX509Crl.tbsCertList.revokedCertificates.push(revokedCert);
}
}
const signingAlgorithm = {
...params.signingAlgorithm,
...params.signingKey.algorithm
};
const algProv = tsyringe.container.resolve(diAlgorithmProvider);
asnX509Crl.tbsCertList.signature = asnX509Crl.signatureAlgorithm = algProv.toAsnAlgorithm(signingAlgorithm);
const tbs = asn1Schema.AsnConvert.serialize(asnX509Crl.tbsCertList);
const signature = await crypto.subtle.sign(signingAlgorithm, params.signingKey, tbs);
const signatureFormatters = tsyringe.container.resolveAll(diAsnSignatureFormatter).reverse();
let asnSignature = null;
for (const signatureFormatter of signatureFormatters) {
asnSignature = signatureFormatter.toAsnSignature(signingAlgorithm, signature);
if (asnSignature) break;
}
if (!asnSignature) throw Error("Cannot convert ASN.1 signature value to WebCrypto format");
asnX509Crl.signature = asnSignature;
return new X509Crl(asn1Schema.AsnConvert.serialize(asnX509Crl));
}
};
ExtensionFactory.register(asn1X509__namespace.id_ce_basicConstraints, BasicConstraintsExtension);
ExtensionFactory.register(asn1X509__namespace.id_ce_extKeyUsage, ExtendedKeyUsageExtension);
ExtensionFactory.register(asn1X509__namespace.id_ce_keyUsage, KeyUsagesExtension);
ExtensionFactory.register(asn1X509__namespace.id_ce_subjectKeyIdentifier, SubjectKeyIdentifierExtension);
ExtensionFactory.register(asn1X509__namespace.id_ce_authorityKeyIdentifier, AuthorityKeyIdentifierExtension);
ExtensionFactory.register(asn1X509__namespace.id_ce_subjectAltName, SubjectAlternativeNameExtension);
ExtensionFactory.register(asn1X509__namespace.id_ce_cRLDistributionPoints, CRLDistributionPointsExtension);
ExtensionFactory.register(asn1X509__namespace.id_pe_authorityInfoAccess, AuthorityInfoAccessExtension);
ExtensionFactory.register(asn1X509__namespace.id_ce_issuerAltName, IssuerAlternativeNameExtension);
AttributeFactory.register(asnPkcs9__namespace.id_pkcs9_at_challengePassword, ChallengePasswordAttribute);
AttributeFactory.register(asnPkcs9__namespace.id_pkcs9_at_extensionRequest, ExtensionsAttribute);
tsyringe.container.registerSingleton(diAsnSignatureFormatter, AsnDefaultSignatureFormatter);
tsyringe.container.registerSingleton(diAsnSignatureFormatter, AsnEcSignatureFormatter);
AsnEcSignatureFormatter.namedCurveSize.set("P-256", 32);
AsnEcSignatureFormatter.namedCurveSize.set("K-256", 32);
AsnEcSignatureFormatter.namedCurveSize.set("P-384", 48);
AsnEcSignatureFormatter.namedCurveSize.set("P-521", 66);
exports.AlgorithmProvider = AlgorithmProvider;
exports.AsnData = AsnData;
exports.AsnDefaultSignatureFormatter = AsnDefaultSignatureFormatter;
exports.AsnEcSignatureFormatter = AsnEcSignatureFormatter;
exports.Attribute = Attribute;
exports.AttributeFactory = AttributeFactory;
exports.AuthorityInfoAccessExtension = AuthorityInfoAccessExtension;
exports.AuthorityKeyIdentifierExtension = AuthorityKeyIdentifierExtension;
exports.BasicConstraintsExtension = BasicConstraintsExtension;
exports.CRLDistributionPointsExtension = CRLDistributionPointsExtension;
exports.CertificatePolicyExtension = CertificatePolicyExtension;
exports.ChallengePasswordAttribute = ChallengePasswordAttribute;
exports.CryptoProvider = CryptoProvider;
exports.DN = DN;
exports.DNS = DNS;
exports.DefaultAlgorithmSerializer = DefaultAlgorithmSerializer;
exports.EMAIL = EMAIL;
exports.ExtendedKeyUsageExtension = ExtendedKeyUsageExtension;
exports.Extension = Extension;
exports.ExtensionFactory = ExtensionFactory;
exports.ExtensionsAttribute = ExtensionsAttribute;
exports.GUID = GUID;
exports.GeneralName = GeneralName;
exports.GeneralNames = GeneralNames;
exports.IP = IP;
exports.IssuerAlternativeNameExtension = IssuerAlternativeNameExtension;
exports.KeyUsagesExtension = KeyUsagesExtension;
exports.Name = Name;
exports.NameIdentifier = NameIdentifier;
exports.OidSerializer = OidSerializer;
exports.PemConverter = PemConverter;
exports.PemData = PemData;
exports.Pkcs10CertificateRequest = Pkcs10CertificateRequest;
exports.Pkcs10CertificateRequestGenerator = Pkcs10CertificateRequestGenerator;
exports.PublicKey = PublicKey;
exports.REGISTERED_ID = REGISTERED_ID;
exports.SubjectAlternativeNameExtension = SubjectAlternativeNameExtension;
exports.SubjectKeyIdentifierExtension = SubjectKeyIdentifierExtension;
exports.TextConverter = TextConverter;
exports.TextObject = TextObject;
exports.UPN = UPN;
exports.URL = URL;
exports.X509Certificate = X509Certificate;
exports.X509CertificateGenerator = X509CertificateGenerator;
exports.X509Certificates = X509Certificates;
exports.X509ChainBuilder = X509ChainBuilder;
exports.X509Crl = X509Crl;
exports.X509CrlEntry = X509CrlEntry;
exports.X509CrlGenerator = X509CrlGenerator;
exports.cryptoProvider = cryptoProvider;
exports.diAlgorithm = diAlgorithm;
exports.diAlgorithmProvider = diAlgorithmProvider;
exports.diAsnSignatureFormatter = diAsnSignatureFormatter;
exports.idEd25519 = idEd25519;
exports.idEd448 = idEd448;
exports.idX25519 = idX25519;
exports.idX448 = idX448;
}));
//#endregion
//#region node_modules/.pnpm/is-property@1.0.2/node_modules/is-property/is-property.js
var require_is_property = /* @__PURE__ */ __commonJSMin(((exports, module) => {
function isProperty(str) {
return /^[$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc][$A-Z\_a-z\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc0-9\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19d9\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1dc0-\u1de6\u1dfc-\u1dff\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f]*$/.test(str);
}
module.exports = isProperty;
}));
//#endregion
//#region node_modules/.pnpm/generate-function@2.3.1/node_modules/generate-function/index.js
var require_generate_function = /* @__PURE__ */ __commonJSMin(((exports, module) => {
var util = __require("util");
var isProperty = require_is_property();
var INDENT_START = /[\{\[]/;
var INDENT_END = /[\}\]]/;
var RESERVED = [
"do",
"if",
"in",
"for",
"let",
"new",
"try",
"var",
"case",
"else",
"enum",
"eval",
"null",
"this",
"true",
"void",
"with",
"await",
"break",
"catch",
"class",
"const",
"false",
"super",
"throw",
"while",
"yield",
"delete",
"export",
"import",
"public",
"return",
"static",
"switch",
"typeof",
"default",
"extends",
"finally",
"package",
"private",
"continue",
"debugger",
"function",
"arguments",
"interface",
"protected",
"implements",
"instanceof",
"NaN",
"undefined"
];
var RESERVED_MAP = {};
for (var i = 0; i < RESERVED.length; i++) RESERVED_MAP[RESERVED[i]] = true;
var isVariable = function(name) {
return isProperty(name) && !RESERVED_MAP.hasOwnProperty(name);
};
var formats = {
s: function(s) {
return "" + s;
},
d: function(d) {
return "" + Number(d);
},
o: function(o) {
return JSON.stringify(o);
}
};
var genfun = function() {
var lines = [];
var indent = 0;
var vars = {};
var push = function(str) {
var spaces = "";
while (spaces.length < indent * 2) spaces += " ";
lines.push(spaces + str);
};
var pushLine = function(line) {
if (INDENT_END.test(line.trim()[0]) && INDENT_START.test(line[line.length - 1])) {
indent--;
push(line);
indent++;
return;
}
if (INDENT_START.test(line[line.length - 1])) {
push(line);
indent++;
return;
}
if (INDENT_END.test(line.trim()[0])) {
indent--;
push(line);
return;
}
push(line);
};
var line = function(fmt) {
if (!fmt) return line;
if (arguments.length === 1 && fmt.indexOf("\n") > -1) {
var lines = fmt.trim().split("\n");
for (var i = 0; i < lines.length; i++) pushLine(lines[i].trim());
} else pushLine(util.format.apply(util, arguments));
return line;
};
line.scope = {};
line.formats = formats;
line.sym = function(name) {
if (!name || !isVariable(name)) name = "tmp";
if (!vars[name]) vars[name] = 0;
return name + (vars[name]++ || "");
};
line.property = function(obj, name) {
if (arguments.length === 1) {
name = obj;
obj = "";
}
name = name + "";
if (isProperty(name)) return obj ? obj + "." + name : name;
return obj ? obj + "[" + JSON.stringify(name) + "]" : JSON.stringify(name);
};
line.toString = function() {
return lines.join("\n");
};
line.toFunction = function(scope) {
if (!scope) scope = {};
var src = "return (" + line.toString() + ")";
Object.keys(line.scope).forEach(function(key) {
if (!scope[key]) scope[key] = line.scope[key];
});
var keys = Object.keys(scope).map(function(key) {
return key;
});
var vals = keys.map(function(key) {
return scope[key];
});
return Function.apply(null, keys.concat(src)).apply(null, vals);
};
if (arguments.length) line.apply(null, arguments);
return line;
};
genfun.formats = formats;
module.exports = genfun;
}));
//#endregion
//#region node_modules/.pnpm/@shinyoshiaki+binary-data@0.6.1/node_modules/@shinyoshiaki/binary-data/src/node_modules/internal/linked-list.js
var require_linked_list = /* @__PURE__ */ __commonJSMin(((exports, module) => {
/**
* A Leaf in a linked list.
*/
var Chunk = class {
/**
* @class Chunk
*/
constructor() {
/** @type {Chunk} */
this.next = null;
/** @type {Buffer} */
this.buffer = null;
}
};
/**
* Linked list for buffers.
*/
module.exports = class LinkedList {
/**
* @class LinkedList
*/
constructor() {
/** @type {Chunk} */
this.head = null;
/** @type {Chunk} */
this.tail = null;
this.length = 0;
this.count = 0;
}
/**
* Add a buffer to the end of the list.
* @param {Buffer} buf
*/
push(buf) {
const entry = new Chunk();
entry.buffer = buf;
if (this.length > 0) this.tail.next = entry;
else this.head = entry;
this.tail = entry;
this.length += buf.length;
this.count += 1;
}
/**
* Add a buffer to the start of the list.
* @param {Buffer} buf
*/
unshift(buf) {
const entry = new Chunk();
entry.buffer = buf;
entry.next = this.head;
if (this.isEmpty()) this.tail = entry;
this.head = entry;
this.length += buf.length;
this.count += 1;
}
/**
* Remove and return first element's buffer.
* @returns {Buffer|null}
*/
shift() {
if (this.isEmpty()) return null;
const ret = this.head.buffer;
if (this.head === this.tail) {
this.head = null;
this.tail = null;
} else this.head = this.head.next;
this.length -= ret.length;
this.length = Math.max(this.length, 0);
this.count -= 1;
return ret;
}
/**
* Get buffer of first element or null.
* @returns {Buffer|null}
*/
get first() {
if (this.isEmpty()) return null;
return this.head.buffer;
}
/**
* Get buffer of last element or null.
* @returns {Buffer|null}
*/
get last() {
if (this.isEmpty()) return null;
return this.tail.buffer;
}
/**
* Check if a list is empty.
* @returns {bool}
*/
isEmpty() {
return this.length === 0;
}
/**
* Remove all elements from a list.
*/
clear() {
this.head = null;
this.tail = null;
this.length = 0;
this.count = 0;
}
/**
* Return a subset of linked list.
* @param {number} start Offset bytes from start.
* @param {number} end Bytes count.
* @returns {LinkedList}
*/
slice(start, end) {
if (start < 0 || start >= this.length) return new LinkedList();
if (end < 0 || end > this.length || end < start) return new LinkedList();
const list = new LinkedList();
let leaf = this.head;
let offsetStart = start;
let offsetEnd = end;
while (leaf) {
if (leaf.buffer.length > offsetStart) {
if (offsetStart === 0 && leaf.buffer.length <= offsetEnd) list.push(leaf.buffer);
else if (leaf.buffer.length >= offsetEnd) list.push(leaf.buffer.slice(offsetStart, offsetEnd));
else list.push(leaf.buffer.slice(offsetStart));
break;
}
offsetStart -= leaf.buffer.length;
offsetEnd -= leaf.buffer.length;
leaf = leaf.next;
}
if (leaf.buffer.length < offsetEnd) while (leaf) {
if (leaf.buffer.length === offsetEnd) {
list.push(leaf.buffer);
break;
} else if (leaf.buffer.length > offsetEnd) {
list.push(leaf.buffer.slice(0, offsetEnd));
break;
} else if (offsetStart < 0 && leaf.buffer.length < offsetEnd) list.push(leaf.buffer);
offsetStart -= leaf.buffer.length;
offsetEnd -= leaf.buffer.length;
leaf = leaf.next;
}
return list;
}
};
}));
//#endregion
//#region node_modules/.pnpm/@shinyoshiaki+binary-data@0.6.1/node_modules/@shinyoshiaki/binary-data/src/node_modules/internal/buffer-list.js
var require_buffer_list = /* @__PURE__ */ __commonJSMin(((exports, module) => {
const createFunction = require_generate_function();
const LinkedList = require_linked_list();
/**
* An optimised partial implementation of Buffer list from `bl`.
*/
var BufferList = class BufferList {
/**
* @class
*/
constructor() {
this.queue = new LinkedList();
this.offset = 0;
}
/**
* The number of bytes in list.
* @returns {number}
*/
get length() {
return this.queue.length - this.offset;
}
/**
* Adds an additional buffer or BufferList to the internal list.
* @param {Buffer|Buffer[]|BufferList|BufferList[]} buf
*/
append(buf) {
if (Buffer.isBuffer(buf)) {
if (this.offset > 0) {
const head = this.queue.shift();
this.queue.unshift(head.slice(this.offset));
this.offset = 0;
}
this.queue.push(buf);
} else if (Array.isArray(buf)) for (let i = 0; i < buf.length; i += 1) this.append(buf[i]);
else if (buf instanceof BufferList) {
if (this.offset > 0) {
const head = this.queue.shift();
this.queue.unshift(head.slice(this.offset));
this.offset = 0;
}
if (buf.offset > 0) {
const head = buf.queue.shift();
buf.queue.unshift(head.slice(buf.offset));
buf.offset = 0;
}
let leaf = buf.queue.head;
while (leaf) {
this.queue.push(leaf.buffer);
leaf = leaf.next;
}
}
}
/**
* Return the byte at the specified index.
* @param {number} index Index of the byte in the Buffer list.
* @returns {number}
*/
get(index) {
let i = index;
while (i >= this.length) i -= this.length;
while (i < 0) i += this.length;
let leaf = this.queue.head;
let { offset } = this;
while (leaf) {
if (leaf.buffer.length - offset > i) return leaf.buffer[i + offset];
i -= leaf.buffer.length - offset;
offset = 0;
leaf = leaf.next;
}
}
/**
* Returns a new Buffer object containing the bytes within the range specified.
* @param {number} start
* @param {number} end
* @returns {Buffer}
*/
slice(start, end) {
if (typeof start !== "number") start = 0;
if (typeof end !== "number") end = this.length;
while (start < 0) start += this.length;
while (end < 0) end += this.length;
end = Math.min(end, this.length);
if (start >= this.length || end === 0) return Buffer.alloc(0);
const tmpStart = start;
start = Math.min(tmpStart, end);
end = Math.max(tmpStart, end);
const subset = this.queue.slice(start + this.offset, end + this.offset);
if (subset.count === 1) return subset.first;
let leaf = subset.head;
const target = Buffer.allocUnsafe(subset.length);
let offset = 0;
for (let i = 0; i < subset.count; i += 1) {
target.set(leaf.buffer, offset);
offset += leaf.buffer.length;
leaf = leaf.next;
}
return target;
}
/**
* Return a string representation of the buffer.
* @param {string} encoding
* @param {number} start
* @param {number} end
* @returns {string}
*/
toString(encoding, start, end) {
return this.slice(start, end).toString(encoding);
}
/**
* Shift bytes off the start of the list.
* @param {number} bytes
*/
consume(bytes) {
let remainder = bytes;
while (this.length > 0) {
const firstLength = this.queue.first.length - this.offset;
if (remainder >= firstLength) {
this.queue.shift();
remainder -= firstLength;
this.offset = 0;
} else {
this.offset += remainder;
break;
}
}
}
/**
* Returns the first (least) index of an element
* within the list equal to the specified value,
* or -1 if none is found.
* @param {number} byte
* @param {number} [offset]
* @returns {number}
*/
indexOf(byte, offset = 0) {
if (!Number.isInteger(byte)) throw new TypeError("Invalid argument 1");
if (byte < 0 || byte > 255) throw new Error("Invalid argument 1");
if (!Number.isInteger(offset)) offset = 0;
while (offset >= this.length) offset -= this.length;
while (offset < 0) offset += this.length;
let leaf = this.queue.head;
let bias = 0;
const next = () => {
bias += leaf.buffer.length;
leaf = leaf.next;
};
while (leaf) {
let byteOffset = 0;
if (leaf === this.queue.head) byteOffset += this.offset;
if (offset >= leaf.buffer.length - byteOffset) {
offset -= leaf.buffer.length - byteOffset;
next();
continue;
}
if (offset < leaf.buffer.length) byteOffset += offset;
const index = leaf.buffer.indexOf(byte, byteOffset);
if (index > -1) return index + bias - this.offset;
next();
if (byteOffset > this.offset) offset = 0;
}
return -1;
}
};
const fixedReadMethods = {
readDoubleBE: 8,
readDoubleLE: 8,
readFloatBE: 4,
readFloatLE: 4,
readInt32BE: 4,
readInt32LE: 4,
readUInt32BE: 4,
readUInt32LE: 4,
readInt16BE: 2,
readInt16LE: 2,
readUInt16BE: 2,
readUInt16LE: 2,
readInt8: 1,
readUInt8: 1
};
Object.keys(fixedReadMethods).forEach((method) => {
const gen = createFunction();
gen(`
function bufferlist_${method}(offset = 0) {
const start = offset + this.offset;
const head = this.queue.first;
const size = ${gen.formats.d(fixedReadMethods[method])};
const isFirtsChunkEnough = head.length - start >= size;
return isFirtsChunkEnough
? head.${method}(start)
: this.slice(offset, offset + size).${method}(0)
}
`);
BufferList.prototype[method] = gen.toFunction();
});
[
"readIntBE",
"readIntLE",
"readUIntBE",
"readUIntLE"
].forEach((method) => {
const gen = createFunction();
gen(`
function bufferlist_${method}(size, offset = 0) {
const start = offset + this.offset;
const head = this.queue.first;
const isFirtsChunkEnough = head.length - start >= size;
return isFirtsChunkEnough
? head.${method}(start, size)
: this.slice(offset, offset + size).${method}(0, size)
}
`);
BufferList.prototype[method] = gen.toFunction();
});
const fixedWriteMethods = {
writeDoubleBE: 8,
writeDoubleLE: 8,
writeFloatBE: 4,
writeFloatLE: 4,
writeInt32BE: 4,
writeInt32LE: 4,
writeUInt32BE: 4,
writeUInt32LE: 4,
writeInt16BE: 2,
writeInt16LE: 2,
writeUInt16BE: 2,
writeUInt16LE: 2,
writeInt8: 1,
writeUInt8: 1
};
Object.keys(fixedWriteMethods).forEach((method) => {
const gen = createFunction();
gen(`
function bufferlist_${method}(value) {
const size = ${gen.formats.d(fixedWriteMethods[method])};
const buf = Buffer.allocUnsafe(size);
buf.${method}(value, 0);
this.append(buf);
}
`);
BufferList.prototype[method] = gen.toFunction();
});
[
"writeIntBE",
"writeIntLE",
"writeUIntBE",
"writeUIntLE"
].forEach((method) => {
const gen = createFunction();
gen(`
function bufferlist_${method}(value, size) {
const buf = Buffer.allocUnsafe(size);
buf.${method}(value, 0, size);
this.append(buf);
}
`);
BufferList.prototype[method] = gen.toFunction();
});
module.exports = BufferList;
}));
//#endregion
//#region node_modules/.pnpm/@shinyoshiaki+binary-data@0.6.1/node_modules/@shinyoshiaki/binary-data/src/node_modules/lib/not-enough-data-error.js
var require_not_enough_data_error = /* @__PURE__ */ __commonJSMin(((exports, module) => {
/**
* Represent an unexpected end of decode stream.
*/
module.exports = class NotEnoughDataError extends Error {
/**
* @class NotEnoughDataError
* @param {number} expected The number of expected bytes.
* @param {number} received The number of received bytes.
*/
constructor(expected, received) {
const message = `requested ${expected} bytes but only ${received} available`;
super(message);
this.name = "NotEnoughDataError";
}
};
}));
//#endregion
//#region node_modules/.pnpm/@shinyoshiaki+binary-data@0.6.1/node_modules/@shinyoshiaki/binary-data/src/node_modules/lib/binary-stream.js
var require_binary_stream = /* @__PURE__ */ __commonJSMin(((exports, module) => {
const { Transform } = __require("stream");
const createFunction = require_generate_function();
const BufferList = require_buffer_list();
const NotEnoughDataError = require_not_enough_data_error();
const kbuffer = Symbol("buffer");
/**
* Binary data queue.
* Also represent a part of BufferList API.
*/
var BinaryStream = class extends Transform {
/**
* @class Binary
* @param {Object} options
*/
constructor(options = {}) {
super(options);
this[kbuffer] = new BufferList();
}
/**
* @returns {BufferList}
*/
get buffer() {
return this[kbuffer];
}
/**
* @returns {number}
*/
get length() {
return this.buffer.length;
}
/**
* @param {Buffer} buf
*/
append(buf) {
this.buffer.append(buf);
}
/**
* @param {number} i
* @returns {number}
*/
get(i) {
return this.buffer.get(i);
}
/**
* @param {number} [start]
* @param {number} [end]
* @returns {Buffer}
*/
slice(start, end) {
return this.buffer.slice(start, end);
}
/**
* @param {number} bytes
*/
consume(bytes) {
this.buffer.consume(bytes);
}
/**
* @param {string} encoding
* @param {number} [start]
* @param {number} [end]
* @returns {string}
*/
toString(encoding, start, end) {
return this.buffer.toString(encoding, start, end);
}
/**
* Returns the first (least) index of an element
* within the list equal to the specified value,
* or -1 if none is found.
* @param {number} byte
* @param {number} [offset]
* @returns {number}
*/
indexOf(byte, offset = 0) {
return this.buffer.indexOf(byte, offset);
}
/**
* Read provided amount of bytes from stream.
* @param {number} size
* @returns {Buffer}
*/
readBuffer(size) {
assertSize(size, this.length);
const buf = this.slice(0, size);
this.consume(size);
return buf;
}
/**
* Write provided chunk to the stream.
* @param {Buffer} chunk
*/
writeBuffer(chunk) {
this.append(chunk);
}
};
const fixedReadMethods = {
readDoubleBE: 8,
readDoubleLE: 8,
readFloatBE: 4,
readFloatLE: 4,
readInt32BE: 4,
readInt32LE: 4,
readUInt32BE: 4,
readUInt32LE: 4,
readInt16BE: 2,
readInt16LE: 2,
readUInt16BE: 2,
readUInt16LE: 2,
readInt8: 1,
readUInt8: 1
};
const metaReadMethods = [
"readIntBE",
"readIntLE",
"readUIntBE",
"readUIntLE"
];
Object.keys(fixedReadMethods).forEach((method) => {
const gen = createFunction();
gen(`
function binary_${method}() {
const bytes = ${gen.formats.d(fixedReadMethods[method])};
assertSize(bytes, this.length);
const res = this.buffer.${method}(0);
this.consume(bytes);
return res;
}
`);
BinaryStream.prototype[method] = gen.toFunction({ assertSize });
});
metaReadMethods.forEach((method) => {
const gen = createFunction();
gen(`
function binary_${method}(size) {
assertSize(size, this.length);
const res = this.buffer.${method}(size, 0);
this.consume(size);
return res;
}
`);
BinaryStream.prototype[method] = gen.toFunction({ assertSize });
});
[
"writeDoubleBE",
"writeDoubleLE",
"writeFloatBE",
"writeFloatLE",
"writeInt32BE",
"writeInt32LE",
"writeUInt32BE",
"writeUInt32LE",
"writeInt16BE",
"writeInt16LE",
"writeUInt16BE",
"writeUInt16LE",
"writeInt8",
"writeUInt8"
].forEach((method) => {
const gen = createFunction();
gen(`
function binary_${method}(value) {
this.buffer.${method}(value);
}
`);
BinaryStream.prototype[method] = gen.toFunction();
});
[
"writeIntBE",
"writeIntLE",
"writeUIntBE",
"writeUIntLE"
].forEach((method) => {
const gen = createFunction();
gen(`
function binary_${method}(value, size) {
this.buffer.${method}(value, size);
}
`);
BinaryStream.prototype[method] = gen.toFunction();
});
/**
* Check if stream is able to read requested amound of data.
* @param {number} size Requested data size to read.
* @param {number} length The number of bytes in stream.
*/
function assertSize(size, length) {
if (size > length) throw new NotEnoughDataError(size, length);
}
module.exports = BinaryStream;
}));
//#endregion
//#region node_modules/.pnpm/isobject@3.0.1/node_modules/isobject/index.js
/*!
* isobject <https://github.com/jonschlinkert/isobject>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
var require_isobject = /* @__PURE__ */ __commonJSMin(((exports, module) => {
module.exports = function isObject(val) {
return val != null && typeof val === "object" && Array.isArray(val) === false;
};
}));
//#endregion
//#region node_modules/.pnpm/is-plain-object@2.0.4/node_modules/is-plain-object/index.js
/*!
* is-plain-object <https://github.com/jonschlinkert/is-plain-object>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
var require_is_plain_object = /* @__PURE__ */ __commonJSMin(((exports, module) => {
var isObject = require_isobject();
function isObjectObject(o) {
return isObject(o) === true && Object.prototype.toString.call(o) === "[object Object]";
}
module.exports = function isPlainObject(o) {
var ctor, prot;
if (isObjectObject(o) === false) return false;
ctor = o.constructor;
if (typeof ctor !== "function") return false;
prot = ctor.prototype;
if (isObjectObject(prot) === false) return false;
if (prot.hasOwnProperty("isPrototypeOf") === false) return false;
return true;
};
}));
//#endregion
//#region node_modules/.pnpm/@shinyoshiaki+binary-data@0.6.1/node_modules/@shinyoshiaki/binary-data/src/node_modules/lib/util.js
var require_util = /* @__PURE__ */ __commonJSMin(((exports, module) => {
module.exports = {
isType,
isUserType: require_is_plain_object(),
isFunction,
isDecodeType,
isEncodeType
};
/**
* Check if argument is data type.
* @param {*} type
* @returns {bool}
*/
function isType(type) {
return isObject(type) && isFunction(type.encode) && isFunction(type.decode);
}
/**
* Check if argument is function.
* @param {*} value
* @returns {bool}
*/
function isFunction(value) {
return typeof value === "function";
}
/**
* Check if argument is object.
* @param {*} value
* @returns {bool}
*/
function isObject(value) {
return typeof value === "object" && value !== null;
}
/**
* Check if argument is data type and able to decode data.
* @param {*} type
* @returns {bool}
*/
function isDecodeType(type) {
return isObject(type) && isFunction(type.decode);
}
/**
* Check if argument is data type and able to encode data.
* @param {*} type
* @returns {bool}
*/
function isEncodeType(type) {
return isObject(type) && isFunction(type.encode);
}
}));
//#endregion
//#region node_modules/.pnpm/@shinyoshiaki+binary-data@0.6.1/node_modules/@shinyoshiaki/binary-data/src/node_modules/internal/symbols.js
var require_symbols = /* @__PURE__ */ __commonJSMin(((exports, module) => {
module.exports = {
skip: Symbol("skip"),
bytes: Symbol("bytes")
};
}));
//#endregion
//#region node_modules/.pnpm/@shinyoshiaki+binary-data@0.6.1/node_modules/@shinyoshiaki/binary-data/src/node_modules/internal/meta.js
var require_meta = /* @__PURE__ */ __commonJSMin(((exports, module) => {
const symbols = require_symbols();
/**
* Store extended info between encode/decode calls.
*/
module.exports = class Metadata {
/**
* @class Metadata
*/
constructor() {
this[symbols.bytes] = 0;
this.node = void 0;
this.current = void 0;
}
/**
* The number of bytes are processed.
* @returns {number}
*/
get bytes() {
return this[symbols.bytes];
}
/**
* Clone provided metadata.
* @param {Metadata} metadata
* @returns {Metadata}
*/
static clone(metadata) {
const meta = new Metadata();
if (metadata instanceof Metadata) {
meta.node = metadata.node;
meta.current = metadata.current;
}
return meta;
}
/**
* Remove internal references to processed nodes.
* @param {Metadata} metadata
*/
static clean(metadata) {
if (metadata instanceof Metadata) {
metadata.node = void 0;
metadata.current = void 0;
}
}
};
}));
//#endregion
//#region node_modules/.pnpm/@shinyoshiaki+binary-data@0.6.1/node_modules/@shinyoshiaki/binary-data/src/node_modules/lib/decode.js
var require_decode = /* @__PURE__ */ __commonJSMin(((exports, module) => {
const { isType, isUserType, isDecodeType } = require_util();
const BinaryStream = require_binary_stream();
const symbols = require_symbols();
const Metadata = require_meta();
module.exports = {
decode,
decodeCommon
};
/**
* Decode any data from provided stream using schema.
* @param {BinaryStream} rstream Read stream to decode.
* @param {Object} typeOrSchema Builtin data type or schema.
* @returns {*}
*/
function decode(rstream, typeOrSchema) {
let decodeStream = rstream;
if (Buffer.isBuffer(rstream)) {
decodeStream = new BinaryStream();
decodeStream.append(rstream);
}
const meta = new Metadata();
const value = decodeCommon(decodeStream, typeOrSchema, meta);
decode.bytes = meta.bytes;
Metadata.clean(meta);
return value;
}
/**
* @private
* @param {BinaryStream|Buffer} rstream
* @param {Object} typeOrSchema
* @param {Metadata} meta
* @returns {*}
*/
function decodeCommon(rstream, typeOrSchema, meta) {
if (isType(typeOrSchema)) {
const value = typeOrSchema.decode.call(meta, rstream);
meta[symbols.bytes] += typeOrSchema.decode.bytes;
return value;
}
return decodeSchema(rstream, typeOrSchema, meta);
}
/**
* @private
* @param {BinaryStream} rstream
* @param {Object} schema
* @param {Metadata} meta
* @returns {Object}
*/
function decodeSchema(rstream, schema, meta) {
assertSchema(schema);
const node = Object.create(null);
if (meta.node === void 0) {
meta.node = node;
meta.current = node;
} else meta.current = node;
const keys = Object.keys(schema);
for (let i = 0; i < keys.length; i += 1) {
const key = keys[i];
const type = schema[key];
if (!isDecodeType(type)) {
node[key] = decodeSchema(rstream, type, meta);
meta.current = node;
continue;
}
const value = type.decode.call(meta, rstream);
meta[symbols.bytes] += type.decode.bytes;
if (type[symbols.skip] === true) continue;
node[key] = value;
}
return node;
}
/**
* Check if argument is schema.
* @param {Object} schema
* @private
*/
function assertSchema(schema) {
if (!isUserType(schema)) throw new TypeError("Argument #2 should be a plain object.");
}
}));
//#endregion
//#region node_modules/.pnpm/@shinyoshiaki+binary-data@0.6.1/node_modules/@shinyoshiaki/binary-data/src/node_modules/lib/encode.js
var require_encode = /* @__PURE__ */ __commonJSMin(((exports, module) => {
const { isUserType, isEncodeType, isType } = require_util();
const symbols = require_symbols();
const Metadata = require_meta();
const BinaryStream = require_binary_stream();
module.exports = {
encode,
encodeCommon
};
/**
* @param {any} obj
* @param {any} type
* @param {BinaryStream} [target]
* @returns {BinaryStream}
*/
function encode(obj, type, target) {
const meta = new Metadata();
if (type instanceof BinaryStream) {
const tmp = target;
target = type;
type = tmp;
}
if (!(target instanceof BinaryStream)) target = new BinaryStream();
encodeCommon(obj, target, type, meta);
encode.bytes = meta.bytes;
Metadata.clean(meta);
return target;
}
/**
* @param {any} object
* @param {EncodeStream} wstream
* @param {any} typeOrSchema
* @param {Metadata} context
*/
function encodeCommon(object, wstream, typeOrSchema, context) {
if (isType(typeOrSchema)) {
typeOrSchema.encode.call(context, object, wstream);
context[symbols.bytes] += typeOrSchema.encode.bytes;
} else encodeSchema(object, wstream, typeOrSchema, context);
}
/**
* @param {any} object
* @param {EncodeStream} wstream
* @param {any} schema
* @param {Metadata} context
*/
function encodeSchema(object, wstream, schema, context) {
assertSchema(schema);
if (context.node === void 0) {
context.node = object;
context.current = object;
} else context.current = object;
const keys = Object.keys(schema);
for (let i = 0; i < keys.length; i += 1) {
const key = keys[i];
const type = schema[key];
const value = object[key];
if (!isEncodeType(type)) {
encodeSchema(value, wstream, type, context);
context.current = object;
continue;
}
type.encode.call(context, value, wstream);
context[symbols.bytes] += type.encode.bytes;
}
}
/**
* Check if argument is schema.
* @param {Object} schema
* @private
*/
function assertSchema(schema) {
if (!isUserType(schema)) throw new TypeError("Argument `schema` should be a plain object.");
}
}));
//#endregion
//#region node_modules/.pnpm/@shinyoshiaki+binary-data@0.6.1/node_modules/@shinyoshiaki/binary-data/src/node_modules/lib/encoding-length.js
var require_encoding_length = /* @__PURE__ */ __commonJSMin(((exports, module) => {
const { isUserType, isType } = require_util();
const Metadata = require_meta();
const symbols = require_symbols();
module.exports = {
encodingLength,
encodingLengthCommon
};
/**
* Get the number of bytes to encode `obj` using `schema`.
* @param {*} obj Any valid js object.
* @param {Object} schema
* @returns {number}
*/
function encodingLength(obj, schema) {
const context = new Metadata();
encodingLengthCommon(obj, schema, context);
Metadata.clean(context);
return context.bytes;
}
/**
* @param {any} item
* @param {Object} typeOrSchema
* @param {Metadata} context
*/
function encodingLengthCommon(item, typeOrSchema, context) {
if (isType(typeOrSchema)) context[symbols.bytes] += typeOrSchema.encodingLength.call(context, item);
else encodingLengthSchema(item, typeOrSchema, context);
}
/**
* @param {any} item
* @param {Object} schema
* @param {Metadata} context
*/
function encodingLengthSchema(item, schema, context) {
if (!isUserType(schema)) throw new TypeError("Argument `schema` should be a plain object.");
if (context.node === void 0) {
context.node = item;
context.current = item;
} else context.current = item;
const keys = Object.keys(schema);
for (let i = 0; i < keys.length; i += 1) {
const key = keys[i];
const type = schema[key];
const value = item[key];
if (!isType(type)) {
encodingLengthSchema(value, type, context);
context.current = item;
continue;
}
context[symbols.bytes] += type.encodingLength.call(context, value);
}
}
}));
//#endregion
//#region node_modules/.pnpm/@shinyoshiaki+binary-data@0.6.1/node_modules/@shinyoshiaki/binary-data/src/node_modules/types/array.js
var require_array = /* @__PURE__ */ __commonJSMin(((exports, module) => {
const { decodeCommon } = require_decode();
const { encodeCommon } = require_encode();
const { encodingLengthCommon } = require_encoding_length();
const { isType, isUserType, isFunction } = require_util();
const Metadata = require_meta();
module.exports = array;
/**
* Array type.
* @param {Object} type Any builtin type or schema.
* @param {Object|number} length Number type or number.
* @param {string} lengthType Method of calculate the length of array.
* @returns {Object}
*/
function array(type, length, lengthType = "count") {
if (!isType(type) && !isUserType(type)) throw new TypeError("Argument #1 should be a valid type.");
const isLengthInBytes = lengthType === "bytes";
const isnum = typeof length === "number";
const istype = isType(length);
const isfunc = isFunction(length);
if (!isnum && !istype && !isfunc) throw new TypeError("Unknown type of argument #1.");
return {
encode,
decode,
encodingLength
};
/**
* Encode array's items.
* @param {any[]} items Array of items to encode.
* @param {EncodeStream} wstream
*/
function encode(items, wstream) {
checkArray(items);
const context = Metadata.clone(this);
encode.bytes = 0;
let expectedSize = 0;
if (istype) expectedSize = items.length;
else if (isnum) expectedSize = length;
else if (isfunc) {
expectedSize = length(context);
checkArraySizeType(expectedSize);
}
if (!isLengthInBytes) checkArraySize(expectedSize, items.length);
if (isLengthInBytes) {
const lengthContext = Metadata.clone(context);
for (const item of items) encodingLengthCommon(item, type, lengthContext);
if (istype) expectedSize = lengthContext.bytes;
checkArraySize(lengthContext.bytes, expectedSize);
Metadata.clean(lengthContext);
}
if (istype) {
length.encode.call(context, expectedSize, wstream);
encode.bytes += length.encode.bytes;
}
items.forEach((item) => {
encodeCommon(item, wstream, type, context);
});
encode.bytes += context.bytes;
Metadata.clean(context);
}
/**
* Decode array from stream.
* @param {DecodeStream} rstream
* @returns {any[]}
*/
function decode(rstream) {
let expectedSize = 0;
decode.bytes = 0;
const context = Metadata.clone(this);
if (isnum) expectedSize = length;
else if (istype) {
expectedSize = length.decode.call(context, rstream);
decode.bytes += length.decode.bytes;
} else if (isfunc) expectedSize = length(context);
checkArraySizeType(expectedSize);
let values;
if (isLengthInBytes) values = decodeBytes(type, expectedSize, rstream, context);
else values = decodeCount(type, expectedSize, rstream, context);
decode.bytes += context.bytes;
Metadata.clean(context);
return values;
}
/**
* Returns the number of bytes of an encoded items.
* @param {any[]} items
* @returns {number}
*/
function encodingLength(items) {
checkArray(items);
const context = Metadata.clone(this);
let size = 0;
if (isnum && isLengthInBytes) return length;
if (istype && !isLengthInBytes) size = length.encodingLength(items.length);
for (const item of items) encodingLengthCommon(item, type, context);
Metadata.clean(context);
size += context.bytes;
if (istype && isLengthInBytes) size += length.encodingLength(size);
return size;
}
}
/**
* Check if argument is an Array.
* @param {*} items
* @private
*/
function checkArray(items) {
if (!Array.isArray(items)) throw new TypeError("Argument #1 should be an Array.");
}
/**
* Check if argument is a number.
* @param {*} length
* @private
*/
function checkArraySizeType(length) {
if (typeof length !== "number") throw new TypeError("Length of an array should be a number.");
}
/**
* Check the number of items in an Array.
* @param {number} requiredSize
* @param {number} havingSize
* @private
*/
function checkArraySize(requiredSize, havingSize) {
if (requiredSize !== havingSize) throw new Error(`Argument #1 required length ${requiredSize} instead of ${havingSize}`);
}
/**
* Decode items of an array when length is the number of bytes.
* @param {Object} type Type of each array's item - user schema builtin type.
* @param {number} lengthBytes
* @param {DecodeStream} rstream
* @param {Metadata} context
* @returns {any[]}
* @private
*/
function decodeBytes(type, lengthBytes, rstream, context) {
const items = [];
const before = context.bytes;
let bytes = 0;
while (bytes < lengthBytes) {
items.push(decodeCommon(rstream, type, context));
bytes = context.bytes - before;
}
if (bytes > lengthBytes) throw new Error("Incorrect length of an array.");
return items;
}
/**
* Decode items of an array when length is the number of items.
* @param {Object} type Type of each array's item - user schema builtin type.
* @param {number} length
* @param {DecodeStream} rstream
* @param {Metadata} context
* @returns {any[]}
* @private
*/
function decodeCount(type, length, rstream, context) {
const items = new Array(length);
for (let i = 0; i < length; i += 1) items[i] = decodeCommon(rstream, type, context);
return items;
}
}));
//#endregion
//#region node_modules/.pnpm/@shinyoshiaki+binary-data@0.6.1/node_modules/@shinyoshiaki/binary-data/src/node_modules/types/buffer.js
var require_buffer = /* @__PURE__ */ __commonJSMin(((exports, module) => {
const { isType, isFunction } = require_util();
const NotEnoughDataError = require_not_enough_data_error();
const BinaryStream = require_binary_stream();
module.exports = buffer;
/**
* Buffer type.
* @param {number|Object} length The number of bytes or type for size-prefixed buffers.
* @returns {Object}
*/
function buffer(length) {
const isnum = typeof length === "number";
const istype = isType(length);
const isfunc = isFunction(length);
const isNull = length === null;
if (!isnum && !istype && !isfunc && !isNull) throw new TypeError("Unknown type of argument #1.");
return {
encode,
decode,
encodingLength
};
/**
* Encode buffer.
* @param {Buffer} buf
* @param {EncodeStream} wstream
*/
function encode(buf, wstream) {
checkBuffer(buf);
encode.bytes = 0;
const context = this;
if (isnum) checkLength(length, buf.length);
if (istype) {
length.encode.call(context, buf.length, wstream);
encode.bytes += length.encode.bytes;
}
if (isfunc) {
const expectedLength = length(context);
checkLengthType(expectedLength);
checkLength(expectedLength, buf.length);
}
wstream.writeBuffer(Buffer.isBuffer(buf) ? buf : buf.buffer);
encode.bytes += buf.length;
if (isNull) {
wstream.writeUInt8(0);
encode.bytes += 1;
}
}
/**
* Read the buffer from the stream.
* @param {DecodeStream} rstream
* @returns {Buffer}
*/
function decode(rstream) {
let size = 0;
decode.bytes = 0;
const context = this;
if (isnum) size = length;
else if (istype) {
size = length.decode.call(context, rstream);
decode.bytes += length.decode.bytes;
checkLengthType(size);
} else if (isfunc) {
size = length(context);
checkLengthType(size);
} else if (isNull) {
size = rstream.indexOf(0);
if (size === -1) throw new NotEnoughDataError(rstream.length + 1, rstream.length);
}
const buf = rstream.readBuffer(size);
decode.bytes += size;
if (isNull) {
decode.bytes += 1;
rstream.consume(1);
}
return buf;
}
/**
* Get the number bytes of an encoded buffer.
* @param {Buffer} buf
* @returns {number}
*/
function encodingLength(buf) {
checkBuffer(buf);
let size = 0;
if (isnum) return length;
if (isNull) size = 1;
else if (istype) size = length.encodingLength(buf.length);
return size + buf.length;
}
}
/**
* Check if item is a Buffer.
* @param {any} buf
* @private
*/
function checkBuffer(buf) {
if (!Buffer.isBuffer(buf) && !(buf instanceof BinaryStream)) throw new TypeError("Argument 1 should be a Buffer or a BinaryStream.");
}
/**
* Check the length of a Buffer to encode.
* @param {number} requiredSize
* @param {number} havingSize
*/
function checkLength(requiredSize, havingSize) {
if (requiredSize !== havingSize) throw new Error(`Buffer required length ${requiredSize} instead of ${havingSize}`);
}
/**
* Check if the length type is a number.
* @param {any} length
*/
function checkLengthType(length) {
if (typeof length !== "number") throw new TypeError("Length of a buffer should be a number.");
}
}));
//#endregion
//#region node_modules/.pnpm/@shinyoshiaki+binary-data@0.6.1/node_modules/@shinyoshiaki/binary-data/src/node_modules/types/bool.js
var require_bool = /* @__PURE__ */ __commonJSMin(((exports, module) => {
const { isType } = require_util();
module.exports = bool;
/**
* Boolean type.
* @param {Object} type Any builtin type or schema.
* @returns {Object}
*/
function bool(type) {
if (!isType(type)) throw new TypeError("Argument #1 should be valid type.");
/**
* Decode element as boolean.
* @param {DecodeStream} rstream
* @returns {bool}
*/
function decode(rstream) {
const context = this;
const value = type.decode.call(context, rstream);
decode.bytes = type.decode.bytes;
return Boolean(value);
}
/**
* Encode boolean item.
* @param {bool} value
* @param {EncodeStream} wstream
*/
function encode(value, wstream) {
const context = this;
type.encode.call(context, value ? 1 : 0, wstream);
encode.bytes = type.encode.bytes;
}
return {
encode,
decode,
encodingLength: type.encodingLength
};
}
}));
//#endregion
//#region node_modules/.pnpm/@shinyoshiaki+binary-data@0.6.1/node_modules/@shinyoshiaki/binary-data/src/node_modules/types/reserved.js
var require_reserved = /* @__PURE__ */ __commonJSMin(((exports, module) => {
const { decodeCommon } = require_decode();
const { encodeCommon } = require_encode();
const { encodingLengthCommon } = require_encoding_length();
const { isType, isFunction } = require_util();
const symbols = require_symbols();
const Metadata = require_meta();
module.exports = reserved;
/**
* Type for reserved data.
* @param {Object} type Any builtin type or schema.
* @param {number} size The number of reserved items.
* @returns {Object}
*/
function reserved(type, size = 1) {
if (!isType(type)) throw new TypeError("Invalid data type.");
if (!Number.isInteger(size) && !isFunction(size)) throw new TypeError("Argument #2 should be a valid integer or function.");
return {
[symbols.skip]: true,
encodingLength,
decode,
encode
};
/**
* Get the number of bytes to encode value.
* @param {any} value
* @returns {number}
*/
function encodingLength(value) {
const context = Metadata.clone(this);
const count = isFunction(size) ? size(context) : size;
encodingLengthCommon(value, type, context);
Metadata.clean(context);
return context.bytes * count;
}
/**
* Silently decode items.
* @param {DecodeStream} rstream
*/
function decode(rstream) {
const context = Metadata.clone(this);
decode.bytes = 0;
const count = isFunction(size) ? size(context) : size;
if (count === 0) {
Metadata.clean(context);
return;
}
for (let i = count; i > 0; i -= 1) decodeCommon(rstream, type, context);
decode.bytes = context.bytes;
Metadata.clean(context);
}
/**
* Encode reserved data.
* Fill with zeros the number of required bytes.
* @param {any} value
* @param {EncodeStream} wstream
*/
function encode(value, wstream) {
encode.bytes = 0;
const context = Metadata.clone(this);
const count = isFunction(size) ? size(context) : size;
if (count === 0) {
Metadata.clean(context);
return;
}
for (let i = count; i > 0; i -= 1) encodeCommon(0, wstream, type, context);
encode.bytes = context.bytes;
Metadata.clean(context);
}
}
}));
//#endregion
//#region node_modules/.pnpm/@shinyoshiaki+binary-data@0.6.1/node_modules/@shinyoshiaki/binary-data/src/node_modules/types/string.js
var require_string = /* @__PURE__ */ __commonJSMin(((exports, module) => {
const { isType } = require_util();
const NotEnoughDataError = require_not_enough_data_error();
module.exports = string;
/**
* Type for strings.
* @param {Object|number|null} length The number of bytes or type for size-prefixed strings.
* @param {string} encoding
* @returns {Object}
*/
function string(length, encoding = "ascii") {
if (!Buffer.isEncoding(encoding)) throw new Error("Argument #2 should be an encoding name.");
if (typeof length === "number") return {
encode: encodeFixedString(length, encoding),
decode: decodeFixedString(length, encoding),
encodingLength: () => length
};
if (isType(length)) return {
encode: encodeSizePrefixedString(length, encoding),
decode: decodeSizePrefixedString(length, encoding),
encodingLength: encodingLengthSizePrefixedString(length, encoding)
};
if (length === null) return {
encode: encodeNullString(encoding),
decode: decodeNullString(encoding),
/**
* Get the number bytes to encode provided string.
* @param {string} value
* @returns {number}
*/
encodingLength(value) {
return Buffer.byteLength(value, encoding) + 1;
}
};
if (typeof length === "function") return {
encode: encodeCallback(length, encoding),
decode: decodeCallback(length, encoding),
/**
* Get the number bytes to encode provided string.
* @param {string} value
* @returns {number}
*/
encodingLength(value) {
return Buffer.byteLength(value, encoding);
}
};
throw new TypeError("Unknown type of argument #1.");
}
/**
* Encode null-terminated string.
* @param {string} encoding
* @returns {Function}
*/
function encodeNullString(encoding) {
return function encode(value, wstream) {
const buf = Buffer.from(value.toString(), encoding);
wstream.writeBuffer(buf);
wstream.writeInt8(0);
encode.bytes = buf.length + 1;
};
}
/**
* Decode null-terminated string.
* @param {string} encoding
* @returns {Function}
*/
function decodeNullString(encoding) {
return function decode(rstream) {
const bytes = rstream.indexOf(0);
if (bytes === -1) throw new NotEnoughDataError(rstream.length + 1, rstream.length);
const bytesWithNull = bytes + 1;
const buf = rstream.readBuffer(bytesWithNull);
decode.bytes = bytesWithNull;
return buf.toString(encoding, 0, bytes);
};
}
/**
* Encode fixed-length string.
* @param {number} size The length of the string.
* @param {string} encoding
* @returns {Function}
*/
function encodeFixedString(size, encoding) {
return function encode(value, wstream) {
value = value.toString();
if (Buffer.byteLength(value, encoding) !== size) throw new Error(`Size of string should be ${size} in bytes.`);
const buf = Buffer.from(value, encoding);
wstream.writeBuffer(buf);
encode.bytes = buf.length;
};
}
/**
* Decode fixed-length string.
* @param {number} size The length of the string.
* @param {string} encoding
* @returns {Function}
*/
function decodeFixedString(size, encoding) {
return function decode(rstream) {
const buf = rstream.readBuffer(size);
decode.bytes = size;
return buf.toString(encoding);
};
}
/**
* Encode size-prefixed string.
* @param {Object} type Number type.
* @param {string} encoding
* @returns {number}
*/
function encodeSizePrefixedString(type, encoding) {
return function encode(value, wstream) {
value = value.toString();
const context = this;
type.encode.call(context, Buffer.byteLength(value, encoding), wstream);
encode.bytes = type.encode.bytes;
const buf = Buffer.from(value, encoding);
wstream.writeBuffer(buf);
encode.bytes += buf.length;
};
}
/**
* Decode size-prefixed string.
* @param {Object} type Number type.
* @param {string} encoding
* @returns {number}
*/
function decodeSizePrefixedString(type, encoding) {
return function decode(rstream) {
const size = type.decode.call(this, rstream);
if (typeof size !== "number") throw new TypeError("Size of a string should be a number.");
const buf = rstream.readBuffer(size);
decode.bytes = type.decode.bytes + buf.length;
return buf.toString(encoding);
};
}
/**
* Get the number of bytes of size-prefixed string.
* @param {Object} type Number type.
* @param {string} encoding
* @returns {number}
*/
function encodingLengthSizePrefixedString(type, encoding) {
return function encodingLength(value) {
const size = Buffer.byteLength(value, encoding);
return type.encodingLength(size) + size;
};
}
/**
* Encode the string with dynamic evaluated size.
* @param {Function} callback Function that returns a number.
* @param {string} encoding
* @returns {number}
*/
function encodeCallback(callback, encoding) {
return function encode(value, wstream) {
encode.bytes = 0;
const expectedLength = callback(this);
const buf = Buffer.from(value.toString(), encoding);
checkLengthType(expectedLength);
checkLength(expectedLength, buf.length);
wstream.writeBuffer(buf);
encode.bytes += buf.length;
};
}
/**
* Decode the string with dynamic evaluated size.
* @param {Function} callback Function that returns a number.
* @param {string} encoding
* @returns {number}
*/
function decodeCallback(callback, encoding) {
return function decode(rstream) {
const size = callback(this);
checkLengthType(size);
const buf = rstream.readBuffer(size);
decode.bytes = size;
return buf.toString(encoding);
};
}
/**
* @param {any} length
*/
function checkLengthType(length) {
if (typeof length !== "number") throw new TypeError("Length of a buffer should be a number.");
}
/**
* @param {number} requiredSize
* @param {number} havingSize
*/
function checkLength(requiredSize, havingSize) {
if (requiredSize !== havingSize) throw new Error(`Buffer required length ${requiredSize} instead of ${havingSize}`);
}
}));
//#endregion
//#region node_modules/.pnpm/@shinyoshiaki+binary-data@0.6.1/node_modules/@shinyoshiaki/binary-data/src/node_modules/types/numbers.js
var require_numbers = /* @__PURE__ */ __commonJSMin(((exports, module) => {
const createFunction = require_generate_function();
module.exports = {
doublebe: createFastStub(8, "writeDoubleBE", "readDoubleBE"),
doublele: createFastStub(8, "writeDoubleLE", "readDoubleLE"),
floatbe: createFastStub(4, "writeFloatBE", "readFloatBE"),
floatle: createFastStub(4, "writeFloatLE", "readFloatLE"),
int8: createFastStub(1, "writeInt8", "readInt8"),
uint8: createFastStub(1, "writeUInt8", "readUInt8"),
int16be: createFastStub(2, "writeInt16BE", "readInt16BE"),
uint16be: createFastStub(2, "writeUInt16BE", "readUInt16BE"),
int16le: createFastStub(2, "writeInt16LE", "readInt16LE"),
uint16le: createFastStub(2, "writeUInt16LE", "readUInt16LE"),
int32be: createFastStub(4, "writeInt32BE", "readInt32BE"),
uint32be: createFastStub(4, "writeUInt32BE", "readUInt32BE"),
int32le: createFastStub(4, "writeInt32LE", "readInt32LE"),
uint32le: createFastStub(4, "writeUInt32LE", "readUInt32LE"),
int24be: createFastStubGeneric(3, "writeIntBE", "readIntBE"),
uint24be: createFastStubGeneric(3, "writeUIntBE", "readUIntBE"),
int24le: createFastStubGeneric(3, "writeIntLE", "readIntLE"),
uint24le: createFastStubGeneric(3, "writeUIntLE", "readUIntLE"),
int40be: createFastStubGeneric(5, "writeIntBE", "readIntBE"),
uint40be: createFastStubGeneric(5, "writeUIntBE", "readUIntBE"),
int40le: createFastStubGeneric(5, "writeIntLE", "readIntLE"),
uint40le: createFastStubGeneric(5, "writeUIntLE", "readUIntLE"),
int48be: createFastStubGeneric(6, "writeIntBE", "readIntBE"),
uint48be: createFastStubGeneric(6, "writeUIntBE", "readUIntBE"),
int48le: createFastStubGeneric(6, "writeIntLE", "readIntLE"),
uint48le: createFastStubGeneric(6, "writeUIntLE", "readUIntLE")
};
/**
* Generate number type for provided the number of bytes.
* @param {number} size
* @param {string} write
* @param {string} read
* @returns {Object}
* @private
*/
function createFastStub(size, write, read) {
const genread = createFunction();
const genwrite = createFunction();
genread(`
function decode_${read}(rstream) {
decode_${read}.bytes = ${genread.formats.d(size)};
return rstream.${read}()
}
`);
genwrite(`
function encode_${write}(value, wstream) {
wstream.${write}(value);
encode_${write}.bytes = ${genread.formats.d(size)};
}
`);
return {
encodingLength: () => size,
encode: genwrite.toFunction(),
decode: genread.toFunction()
};
}
/**
* Generate number type for provided the number of bytes.
* @param {number} size
* @param {string} write
* @param {string} read
* @returns {Object}
* @private
*/
function createFastStubGeneric(size, write, read) {
const genread = createFunction();
const genwrite = createFunction();
genread(`
function decode_${read}(rstream) {
decode_${read}.bytes = ${genread.formats.d(size)};
return rstream.${read}(${genread.formats.d(size)})
}
`);
genwrite(`
function encode_${write}(value, wstream) {
wstream.${write}(value, ${genread.formats.d(size)});
encode_${write}.bytes = ${genread.formats.d(size)};
}
`);
return {
encodingLength: () => size,
encode: genwrite.toFunction(),
decode: genread.toFunction()
};
}
}));
//#endregion
//#region node_modules/.pnpm/@shinyoshiaki+binary-data@0.6.1/node_modules/@shinyoshiaki/binary-data/src/node_modules/types/when.js
var require_when = /* @__PURE__ */ __commonJSMin(((exports, module) => {
const { isType, isFunction, isUserType } = require_util();
const symbols = require_symbols();
const { decodeCommon } = require_decode();
const { encodeCommon } = require_encode();
const { encodingLengthCommon } = require_encoding_length();
const Metadata = require_meta();
module.exports = when;
/**
* Type for conditions.
* @param {Function|bool} condition
* @param {Object} type Any builtin type or schema.
* @returns {Object}
*/
function when(condition, type) {
if (!isType(type) && !isUserType(type)) throw new TypeError("Argument #2 should be a valid type.");
const result = {
encode,
decode,
encodingLength,
[symbols.skip]: false
};
return result;
/**
* Encode value if condition is truthy.
* @param {any} value
* @param {EncodeStream} wstream
*/
function encode(value, wstream) {
const context = Metadata.clone(this);
encode.bytes = 0;
const status = isFunction(condition) ? Boolean(condition(context)) : Boolean(condition);
result[symbols.skip] = !status;
if (!status) {
Metadata.clean(context);
return;
}
encodeCommon(value, wstream, type, context);
encode.bytes = context.bytes;
Metadata.clean(context);
}
/**
* Decode value if condition is truthy.
* @param {DecodeStream} rstream
* @returns {any}
*/
function decode(rstream) {
const context = Metadata.clone(this);
decode.bytes = 0;
const status = isFunction(condition) ? Boolean(condition(context)) : Boolean(condition);
result[symbols.skip] = !status;
if (!status) {
Metadata.clean(context);
return;
}
const value = decodeCommon(rstream, type, context);
decode.bytes = context.bytes;
Metadata.clean(context);
return value;
}
/**
* Get the number bytes of an encoded value
* when condition is truthy or 0.
* @param {any} value
* @returns {number}
*/
function encodingLength(value) {
const context = Metadata.clone(this);
if (isFunction(condition) ? Boolean(condition(context)) : Boolean(condition)) encodingLengthCommon(value, type, context);
Metadata.clean(context);
return context.bytes;
}
}
}));
//#endregion
//#region node_modules/.pnpm/@shinyoshiaki+binary-data@0.6.1/node_modules/@shinyoshiaki/binary-data/src/node_modules/types/select.js
var require_select = /* @__PURE__ */ __commonJSMin(((exports, module) => {
const symbols = require_symbols();
const { decodeCommon } = require_decode();
const Metadata = require_meta();
module.exports = select;
/**
* Type for multiple conditions.
* Works almost like `switch` operator.
* @param {...any} whenTypes The `when` type.
* @returns {Object}
*/
function select(...whenTypes) {
if (whenTypes.length === 0) throw new TypeError("You should set at least one condition type.");
const result = {
decode,
encode: () => {},
[symbols.skip]: true
};
return result;
/**
* Decode data using a first success contifion.
* @param {DecodeStream} rstream
* @returns {any}
*/
function decode(rstream) {
decode.bytes = 0;
const context = Metadata.clone(this);
for (const when of whenTypes) {
const probalyValue = decodeCommon(rstream, when, context);
if (when[symbols.skip] === true) continue;
decode.bytes = context.bytes;
Metadata.clean(context);
result[symbols.skip] = false;
return probalyValue;
}
result[symbols.skip] = true;
}
}
}));
//#endregion
//#region node_modules/.pnpm/@shinyoshiaki+binary-data@0.6.1/node_modules/@shinyoshiaki/binary-data/src/node_modules/lib/transaction.js
var require_transaction = /* @__PURE__ */ __commonJSMin(((exports, module) => {
const createFunction = require_generate_function();
const NotEnoughDataError = require_not_enough_data_error();
/**
* Helps to read the whole data chunk.
*/
var Transaction = class {
/**
* @class Transaction
* @param {DecodeStream} stream
*/
constructor(stream) {
this.stream = stream;
this.index = 0;
}
/**
* @param {Buffer} buf
*/
append(buf) {
this.stream.append(buf);
}
/**
* Confirm reading and removes data from stream.
*/
commit() {
this.stream.consume(this.index);
}
/**
* Get byte from stream by index.
* @param {number} i
* @returns {number}
*/
get(i = 0) {
return this.stream.get(this.index + i);
}
/**
* Get the number of bytes in stream.
* @returns {number}
*/
get length() {
return this.stream.length;
}
/**
* @param {number} [start]
* @param {number} [end]
* @returns {Buffer}
*/
slice(start, end) {
return this.stream.slice(start, end);
}
/**
* @param {string} encoding
* @param {number} [start]
* @param {number} [end]
* @returns {string}
*/
toString(encoding, start, end) {
return this.stream.toString(encoding, start, end);
}
/**
* Read provided amount of bytes from stream.
* @param {number} size
* @returns {Buffer}
*/
readBuffer(size) {
assertSize(this.index + size, this.length);
const buf = this.stream.slice(this.index, this.index + size);
this.index += size;
return buf;
}
/**
* @param {number} byte
* @param {number} [offset]
* @returns {number}
*/
indexOf(byte, offset = 0) {
return this.stream.indexOf(byte, this.index + offset) - this.index;
}
};
const methods = {
readDoubleBE: 8,
readDoubleLE: 8,
readFloatBE: 4,
readFloatLE: 4,
readInt32BE: 4,
readInt32LE: 4,
readUInt32BE: 4,
readUInt32LE: 4,
readInt16BE: 2,
readInt16LE: 2,
readUInt16BE: 2,
readUInt16LE: 2,
readInt8: 1,
readUInt8: 1
};
Object.keys(methods).forEach((method) => {
const gen = createFunction();
const bytes = methods[method];
gen(`
function transaction_${method}() {
assertSize(this.index + ${gen.formats.d(bytes)}, this.length);
const value = this.stream.buffer.${method}(this.index);
this.index += ${gen.formats.d(bytes)};
return value;
}
`);
Transaction.prototype[method] = gen.toFunction({ assertSize });
});
[
"readIntBE",
"readIntLE",
"readUIntBE",
"readUIntLE"
].forEach((method) => {
const gen = createFunction();
gen(`
function transaction_${method}(bytes) {
assertSize(this.index + bytes, this.length);
const value = this.stream.buffer.${method}(bytes, this.index);
this.index += bytes;
return value;
}
`);
Transaction.prototype[method] = gen.toFunction({ assertSize });
});
module.exports = Transaction;
/**
* Check if stream is able to read requested amound of data.
* @param {number} size Requested data size to read.
* @param {number} length The number of bytes in stream.
*/
function assertSize(size, length) {
if (size > length) throw new NotEnoughDataError(size, length);
}
}));
//#endregion
//#region node_modules/.pnpm/@shinyoshiaki+binary-data@0.6.1/node_modules/@shinyoshiaki/binary-data/src/index.js
var require_src = /* @__PURE__ */ __commonJSMin(((exports, module) => {
const BinaryStream = require_binary_stream();
const array = require_array();
const buffer = require_buffer();
const bool = require_bool();
const reserved = require_reserved();
const string = require_string();
const numbers = require_numbers();
const when = require_when();
const select = require_select();
const { encode } = require_encode();
const { decode } = require_decode();
const { encodingLength } = require_encoding_length();
const Transaction = require_transaction();
const NotEnoughDataError = require_not_enough_data_error();
const types = {
array,
bool,
buffer,
reserved,
string,
when,
select
};
for (const type of Object.keys(numbers)) types[type] = numbers[type];
const kschema = Symbol("schema");
/**
* Create transform stream to encode objects into Buffer.
* @param {Object} [schema]
* @returns {EncodeStream}
*/
function createEncodeStream(schema) {
const stream = new BinaryStream({
readableObjectMode: false,
writableObjectMode: true,
transform: transformEncode
});
stream[kschema] = schema;
return stream;
}
/**
* Create transform stream to decode binary data into object.
* @param {Buffer|Object} [bufOrSchema]
* @returns {DecodeStream}
*/
function createDecodeStream(bufOrSchema) {
let schema = null;
const isBuffer = Buffer.isBuffer(bufOrSchema);
if (!isBuffer) schema = bufOrSchema;
const stream = new BinaryStream({
transform: transformDecode,
readableObjectMode: true,
writableObjectMode: false
});
stream[kschema] = schema;
if (isBuffer) stream.append(bufOrSchema);
return stream;
}
/**
* The `transform` function for transform stream.
* @param {*} chunk Any valid js data type.
* @param {string} encoding
* @param {Function} cb
*/
function transformEncode(chunk, encoding, cb) {
try {
encode(chunk, this[kschema], this);
const buf = this.slice();
this.consume(buf.length);
cb(null, buf);
} catch (error) {
cb(error);
}
}
/**
* The `transform` function for transform stream.
* @param {*} chunk Any valid js data type.
* @param {string} encoding
* @param {Function} cb
*/
function transformDecode(chunk, encoding, cb) {
this.append(chunk);
try {
while (this.length > 0) {
const transaction = new Transaction(this);
const data = decode(transaction, this[kschema]);
transaction.commit();
this.push(data);
}
cb();
} catch (error) {
if (error instanceof NotEnoughDataError) cb();
else cb(error);
}
}
module.exports = {
createEncodeStream,
createDecodeStream,
encode,
decode,
encodingLength,
createEncode: createEncodeStream,
createDecode: createDecodeStream,
types,
BinaryStream,
NotEnoughDataError
};
}));
//#endregion
//#region node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/cryptoNode.js
var import_src = /* @__PURE__ */ __toESM(require_src$1(), 1);
var import_nacl_fast = /* @__PURE__ */ __toESM(require_nacl_fast(), 1);
var import_build = require_build();
var import_x509_cjs = /* @__PURE__ */ __toESM(require_x509_cjs(), 1);
var import_src$1 = require_src();
/**
* Internal webcrypto alias.
* We prefer WebCrypto aka globalThis.crypto, which exists in node.js 16+.
* Falls back to Node.js built-in crypto for Node.js <=v14.
* See utils.ts for details.
* @module
*/
const crypto$3 = nc && typeof nc === "object" && "webcrypto" in nc ? nc.webcrypto : nc && typeof nc === "object" && "randomBytes" in nc ? nc : void 0;
//#endregion
//#region node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js
/**
* Utilities for hex, bytes, CSPRNG.
* @module
*/
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
function isBytes(a) {
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
}
/** Asserts something is positive integer. */
function anumber(n) {
if (!Number.isSafeInteger(n) || n < 0) throw new Error("positive integer expected, got " + n);
}
/** Asserts something is Uint8Array. */
function abytes(b, ...lengths) {
if (!isBytes(b)) throw new Error("Uint8Array expected");
if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
}
/** Asserts something is hash */
function ahash(h) {
if (typeof h !== "function" || typeof h.create !== "function") throw new Error("Hash should be wrapped by utils.createHasher");
anumber(h.outputLen);
anumber(h.blockLen);
}
/** Asserts a hash instance has not been destroyed / finished */
function aexists(instance, checkFinished = true) {
if (instance.destroyed) throw new Error("Hash instance has been destroyed");
if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called");
}
/** Asserts output is properly-sized byte array */
function aoutput(out, instance) {
abytes(out);
const min = instance.outputLen;
if (out.length < min) throw new Error("digestInto() expects output buffer of length at least " + min);
}
/** Zeroize a byte array. Warning: JS provides no guarantees. */
function clean(...arrays) {
for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
}
/** Create DataView of an array for easy byte-level manipulation. */
function createView(arr) {
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
}
/** The rotate right (circular right shift) operation for uint32 */
function rotr(word, shift) {
return word << 32 - shift | word >>> shift;
}
const hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
/**
* Convert byte array to hex string. Uses built-in function, when available.
* @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
*/
function bytesToHex(bytes) {
abytes(bytes);
if (hasHexBuiltin) return bytes.toHex();
let hex = "";
for (let i = 0; i < bytes.length; i++) hex += hexes[bytes[i]];
return hex;
}
const asciis = {
_0: 48,
_9: 57,
A: 65,
F: 70,
a: 97,
f: 102
};
function asciiToBase16(ch) {
if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0;
if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10);
if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10);
}
/**
* Convert hex string to byte array. Uses built-in function, when available.
* @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
*/
function hexToBytes(hex) {
if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex);
if (hasHexBuiltin) return Uint8Array.fromHex(hex);
const hl = hex.length;
const al = hl / 2;
if (hl % 2) throw new Error("hex string expected, got unpadded hex of length " + hl);
const array = new Uint8Array(al);
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
const n1 = asciiToBase16(hex.charCodeAt(hi));
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
if (n1 === void 0 || n2 === void 0) {
const char = hex[hi] + hex[hi + 1];
throw new Error("hex string expected, got non-hex character \"" + char + "\" at index " + hi);
}
array[ai] = n1 * 16 + n2;
}
return array;
}
/**
* Converts string to bytes using UTF8 encoding.
* @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
*/
function utf8ToBytes(str) {
if (typeof str !== "string") throw new Error("string expected");
return new Uint8Array(new TextEncoder().encode(str));
}
/**
* Normalizes (non-hex) string or Uint8Array to Uint8Array.
* Warning: when Uint8Array is passed, it would NOT get copied.
* Keep in mind for future mutable operations.
*/
function toBytes(data) {
if (typeof data === "string") data = utf8ToBytes(data);
abytes(data);
return data;
}
/** Copies several Uint8Arrays into one. */
function concatBytes(...arrays) {
let sum = 0;
for (let i = 0; i < arrays.length; i++) {
const a = arrays[i];
abytes(a);
sum += a.length;
}
const res = new Uint8Array(sum);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const a = arrays[i];
res.set(a, pad);
pad += a.length;
}
return res;
}
/** For runtime check if class implements interface */
var Hash = class {};
/** Wraps hash function, creating an interface on top of it */
function createHasher(hashCons) {
const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
const tmp = hashCons();
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = () => hashCons();
return hashC;
}
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
function randomBytes$2(bytesLength = 32) {
if (crypto$3 && typeof crypto$3.getRandomValues === "function") return crypto$3.getRandomValues(new Uint8Array(bytesLength));
if (crypto$3 && typeof crypto$3.randomBytes === "function") return Uint8Array.from(crypto$3.randomBytes(bytesLength));
throw new Error("crypto.getRandomValues must be defined");
}
//#endregion
//#region node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/utils.js
/**
* Hex, bytes and number utilities.
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const _0n$3 = /* @__PURE__ */ BigInt(0);
const _1n$3 = /* @__PURE__ */ BigInt(1);
function _abool2(value, title = "") {
if (typeof value !== "boolean") {
const prefix = title && `"${title}"`;
throw new Error(prefix + "expected boolean, got type=" + typeof value);
}
return value;
}
/** Asserts something is Uint8Array. */
function _abytes2(value, length, title = "") {
const bytes = isBytes(value);
const len = value?.length;
const needsLen = length !== void 0;
if (!bytes || needsLen && len !== length) {
const prefix = title && `"${title}" `;
const ofLen = needsLen ? ` of length ${length}` : "";
const got = bytes ? `length=${len}` : `type=${typeof value}`;
throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
}
return value;
}
function numberToHexUnpadded(num) {
const hex = num.toString(16);
return hex.length & 1 ? "0" + hex : hex;
}
function hexToNumber(hex) {
if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex);
return hex === "" ? _0n$3 : BigInt("0x" + hex);
}
function bytesToNumberBE(bytes) {
return hexToNumber(bytesToHex(bytes));
}
function bytesToNumberLE(bytes) {
abytes(bytes);
return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));
}
function numberToBytesBE(n, len) {
return hexToBytes(n.toString(16).padStart(len * 2, "0"));
}
function numberToBytesLE(n, len) {
return numberToBytesBE(n, len).reverse();
}
/**
* Takes hex string or Uint8Array, converts to Uint8Array.
* Validates output length.
* Will throw error for other types.
* @param title descriptive title for an error e.g. 'secret key'
* @param hex hex string or Uint8Array
* @param expectedLength optional, will compare to result array's length
* @returns
*/
function ensureBytes(title, hex, expectedLength) {
let res;
if (typeof hex === "string") try {
res = hexToBytes(hex);
} catch (e) {
throw new Error(title + " must be hex string or Uint8Array, cause: " + e);
}
else if (isBytes(hex)) res = Uint8Array.from(hex);
else throw new Error(title + " must be hex string or Uint8Array");
const len = res.length;
if (typeof expectedLength === "number" && len !== expectedLength) throw new Error(title + " of length " + expectedLength + " expected, got " + len);
return res;
}
/**
* @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
*/
/**
* Converts bytes to string using UTF8 encoding.
* @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
*/
const isPosBig = (n) => typeof n === "bigint" && _0n$3 <= n;
function inRange(n, min, max) {
return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;
}
/**
* Asserts min <= n < max. NOTE: It's < max and not <= max.
* @example
* aInRange('x', x, 1n, 256n); // would assume x is in (1n..255n)
*/
function aInRange(title, n, min, max) {
if (!inRange(n, min, max)) throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n);
}
/**
* Calculates amount of bits in a bigint.
* Same as `n.toString(2).length`
* TODO: merge with nLength in modular
*/
function bitLen(n) {
let len;
for (len = 0; n > _0n$3; n >>= _1n$3, len += 1);
return len;
}
/**
* Calculate mask for N bits. Not using ** operator with bigints because of old engines.
* Same as BigInt(`0b${Array(i).fill('1').join('')}`)
*/
const bitMask = (n) => (_1n$3 << BigInt(n)) - _1n$3;
/**
* Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.
* @returns function that will call DRBG until 2nd arg returns something meaningful
* @example
* const drbg = createHmacDRBG<Key>(32, 32, hmac);
* drbg(seed, bytesToKey); // bytesToKey must return Key or undefined
*/
function createHmacDrbg(hashLen, qByteLen, hmacFn) {
if (typeof hashLen !== "number" || hashLen < 2) throw new Error("hashLen must be a number");
if (typeof qByteLen !== "number" || qByteLen < 2) throw new Error("qByteLen must be a number");
if (typeof hmacFn !== "function") throw new Error("hmacFn must be a function");
const u8n = (len) => new Uint8Array(len);
const u8of = (byte) => Uint8Array.of(byte);
let v = u8n(hashLen);
let k = u8n(hashLen);
let i = 0;
const reset = () => {
v.fill(1);
k.fill(0);
i = 0;
};
const h = (...b) => hmacFn(k, v, ...b);
const reseed = (seed = u8n(0)) => {
k = h(u8of(0), seed);
v = h();
if (seed.length === 0) return;
k = h(u8of(1), seed);
v = h();
};
const gen = () => {
if (i++ >= 1e3) throw new Error("drbg: tried 1000 values");
let len = 0;
const out = [];
while (len < qByteLen) {
v = h();
const sl = v.slice();
out.push(sl);
len += v.length;
}
return concatBytes(...out);
};
const genUntil = (seed, pred) => {
reset();
reseed(seed);
let res = void 0;
while (!(res = pred(gen()))) reseed();
reset();
return res;
};
return genUntil;
}
function _validateObject(object, fields, optFields = {}) {
if (!object || typeof object !== "object") throw new Error("expected valid options object");
function checkField(fieldName, expectedType, isOpt) {
const val = object[fieldName];
if (isOpt && val === void 0) return;
const current = typeof val;
if (current !== expectedType || val === null) throw new Error(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`);
}
Object.entries(fields).forEach(([k, v]) => checkField(k, v, false));
Object.entries(optFields).forEach(([k, v]) => checkField(k, v, true));
}
/**
* Memoizes (caches) computation result.
* Uses WeakMap: the value is going auto-cleaned by GC after last reference is removed.
*/
function memoized(fn) {
const map = /* @__PURE__ */ new WeakMap();
return (arg, ...args) => {
const val = map.get(arg);
if (val !== void 0) return val;
const computed = fn(arg, ...args);
map.set(arg, computed);
return computed;
};
}
//#endregion
//#region node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/modular.js
/**
* Utils for modular division and fields.
* Field over 11 is a finite (Galois) field is integer number operations `mod 11`.
* There is no division: it is replaced by modular multiplicative inverse.
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const _0n$2 = BigInt(0);
const _1n$2 = BigInt(1);
const _2n$1 = /* @__PURE__ */ BigInt(2);
const _3n$1 = /* @__PURE__ */ BigInt(3);
const _4n$1 = /* @__PURE__ */ BigInt(4);
const _5n = /* @__PURE__ */ BigInt(5);
const _7n = /* @__PURE__ */ BigInt(7);
const _8n = /* @__PURE__ */ BigInt(8);
const _9n = /* @__PURE__ */ BigInt(9);
const _16n = /* @__PURE__ */ BigInt(16);
function mod(a, b) {
const result = a % b;
return result >= _0n$2 ? result : b + result;
}
/**
* Inverses number over modulo.
* Implemented using [Euclidean GCD](https://brilliant.org/wiki/extended-euclidean-algorithm/).
*/
function invert(number, modulo) {
if (number === _0n$2) throw new Error("invert: expected non-zero number");
if (modulo <= _0n$2) throw new Error("invert: expected positive modulus, got " + modulo);
let a = mod(number, modulo);
let b = modulo;
let x = _0n$2, y = _1n$2, u = _1n$2, v = _0n$2;
while (a !== _0n$2) {
const q = b / a;
const r = b % a;
const m = x - u * q;
const n = y - v * q;
b = a, a = r, x = u, y = v, u = m, v = n;
}
if (b !== _1n$2) throw new Error("invert: does not exist");
return mod(x, modulo);
}
function assertIsSquare(Fp, root, n) {
if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root");
}
function sqrt3mod4(Fp, n) {
const p1div4 = (Fp.ORDER + _1n$2) / _4n$1;
const root = Fp.pow(n, p1div4);
assertIsSquare(Fp, root, n);
return root;
}
function sqrt5mod8(Fp, n) {
const p5div8 = (Fp.ORDER - _5n) / _8n;
const n2 = Fp.mul(n, _2n$1);
const v = Fp.pow(n2, p5div8);
const nv = Fp.mul(n, v);
const i = Fp.mul(Fp.mul(nv, _2n$1), v);
const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
assertIsSquare(Fp, root, n);
return root;
}
function sqrt9mod16(P) {
const Fp_ = Field(P);
const tn = tonelliShanks(P);
const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));
const c2 = tn(Fp_, c1);
const c3 = tn(Fp_, Fp_.neg(c1));
const c4 = (P + _7n) / _16n;
return (Fp, n) => {
let tv1 = Fp.pow(n, c4);
let tv2 = Fp.mul(tv1, c1);
const tv3 = Fp.mul(tv1, c2);
const tv4 = Fp.mul(tv1, c3);
const e1 = Fp.eql(Fp.sqr(tv2), n);
const e2 = Fp.eql(Fp.sqr(tv3), n);
tv1 = Fp.cmov(tv1, tv2, e1);
tv2 = Fp.cmov(tv4, tv3, e2);
const e3 = Fp.eql(Fp.sqr(tv2), n);
const root = Fp.cmov(tv1, tv2, e3);
assertIsSquare(Fp, root, n);
return root;
};
}
/**
* Tonelli-Shanks square root search algorithm.
* 1. https://eprint.iacr.org/2012/685.pdf (page 12)
* 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
* @param P field order
* @returns function that takes field Fp (created from P) and number n
*/
function tonelliShanks(P) {
if (P < _3n$1) throw new Error("sqrt is not defined for small field");
let Q = P - _1n$2;
let S = 0;
while (Q % _2n$1 === _0n$2) {
Q /= _2n$1;
S++;
}
let Z = _2n$1;
const _Fp = Field(P);
while (FpLegendre(_Fp, Z) === 1) if (Z++ > 1e3) throw new Error("Cannot find square root: probably non-prime P");
if (S === 1) return sqrt3mod4;
let cc = _Fp.pow(Z, Q);
const Q1div2 = (Q + _1n$2) / _2n$1;
return function tonelliSlow(Fp, n) {
if (Fp.is0(n)) return n;
if (FpLegendre(Fp, n) !== 1) throw new Error("Cannot find square root");
let M = S;
let c = Fp.mul(Fp.ONE, cc);
let t = Fp.pow(n, Q);
let R = Fp.pow(n, Q1div2);
while (!Fp.eql(t, Fp.ONE)) {
if (Fp.is0(t)) return Fp.ZERO;
let i = 1;
let t_tmp = Fp.sqr(t);
while (!Fp.eql(t_tmp, Fp.ONE)) {
i++;
t_tmp = Fp.sqr(t_tmp);
if (i === M) throw new Error("Cannot find square root");
}
const exponent = _1n$2 << BigInt(M - i - 1);
const b = Fp.pow(c, exponent);
M = i;
c = Fp.sqr(b);
t = Fp.mul(t, c);
R = Fp.mul(R, b);
}
return R;
};
}
/**
* Square root for a finite field. Will try optimized versions first:
*
* 1. P ≡ 3 (mod 4)
* 2. P ≡ 5 (mod 8)
* 3. P ≡ 9 (mod 16)
* 4. Tonelli-Shanks algorithm
*
* Different algorithms can give different roots, it is up to user to decide which one they want.
* For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
*/
function FpSqrt(P) {
if (P % _4n$1 === _3n$1) return sqrt3mod4;
if (P % _8n === _5n) return sqrt5mod8;
if (P % _16n === _9n) return sqrt9mod16(P);
return tonelliShanks(P);
}
const FIELD_FIELDS = [
"create",
"isValid",
"is0",
"neg",
"inv",
"sqrt",
"sqr",
"eql",
"add",
"sub",
"mul",
"pow",
"div",
"addN",
"subN",
"mulN",
"sqrN"
];
function validateField(field) {
_validateObject(field, FIELD_FIELDS.reduce((map, val) => {
map[val] = "function";
return map;
}, {
ORDER: "bigint",
MASK: "bigint",
BYTES: "number",
BITS: "number"
}));
return field;
}
/**
* Same as `pow` but for Fp: non-constant-time.
* Unsafe in some contexts: uses ladder, so can expose bigint bits.
*/
function FpPow(Fp, num, power) {
if (power < _0n$2) throw new Error("invalid exponent, negatives unsupported");
if (power === _0n$2) return Fp.ONE;
if (power === _1n$2) return num;
let p = Fp.ONE;
let d = num;
while (power > _0n$2) {
if (power & _1n$2) p = Fp.mul(p, d);
d = Fp.sqr(d);
power >>= _1n$2;
}
return p;
}
/**
* Efficiently invert an array of Field elements.
* Exception-free. Will return `undefined` for 0 elements.
* @param passZero map 0 to 0 (instead of undefined)
*/
function FpInvertBatch(Fp, nums, passZero = false) {
const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : void 0);
const multipliedAcc = nums.reduce((acc, num, i) => {
if (Fp.is0(num)) return acc;
inverted[i] = acc;
return Fp.mul(acc, num);
}, Fp.ONE);
const invertedAcc = Fp.inv(multipliedAcc);
nums.reduceRight((acc, num, i) => {
if (Fp.is0(num)) return acc;
inverted[i] = Fp.mul(acc, inverted[i]);
return Fp.mul(acc, num);
}, invertedAcc);
return inverted;
}
/**
* Legendre symbol.
* Legendre constant is used to calculate Legendre symbol (a | p)
* which denotes the value of a^((p-1)/2) (mod p).
*
* * (a | p) ≡ 1 if a is a square (mod p), quadratic residue
* * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue
* * (a | p) ≡ 0 if a ≡ 0 (mod p)
*/
function FpLegendre(Fp, n) {
const p1mod2 = (Fp.ORDER - _1n$2) / _2n$1;
const powered = Fp.pow(n, p1mod2);
const yes = Fp.eql(powered, Fp.ONE);
const zero = Fp.eql(powered, Fp.ZERO);
const no = Fp.eql(powered, Fp.neg(Fp.ONE));
if (!yes && !zero && !no) throw new Error("invalid Legendre symbol result");
return yes ? 1 : zero ? 0 : -1;
}
function nLength(n, nBitLength) {
if (nBitLength !== void 0) anumber(nBitLength);
const _nBitLength = nBitLength !== void 0 ? nBitLength : n.toString(2).length;
return {
nBitLength: _nBitLength,
nByteLength: Math.ceil(_nBitLength / 8)
};
}
/**
* Creates a finite field. Major performance optimizations:
* * 1. Denormalized operations like mulN instead of mul.
* * 2. Identical object shape: never add or remove keys.
* * 3. `Object.freeze`.
* Fragile: always run a benchmark on a change.
* Security note: operations don't check 'isValid' for all elements for performance reasons,
* it is caller responsibility to check this.
* This is low-level code, please make sure you know what you're doing.
*
* Note about field properties:
* * CHARACTERISTIC p = prime number, number of elements in main subgroup.
* * ORDER q = similar to cofactor in curves, may be composite `q = p^m`.
*
* @param ORDER field order, probably prime, or could be composite
* @param bitLen how many bits the field consumes
* @param isLE (default: false) if encoding / decoding should be in little-endian
* @param redef optional faster redefinitions of sqrt and other methods
*/
function Field(ORDER, bitLenOrOpts, isLE = false, opts = {}) {
if (ORDER <= _0n$2) throw new Error("invalid field: expected ORDER > 0, got " + ORDER);
let _nbitLength = void 0;
let _sqrt = void 0;
let modFromBytes = false;
let allowedLengths = void 0;
if (typeof bitLenOrOpts === "object" && bitLenOrOpts != null) {
if (opts.sqrt || isLE) throw new Error("cannot specify opts in two arguments");
const _opts = bitLenOrOpts;
if (_opts.BITS) _nbitLength = _opts.BITS;
if (_opts.sqrt) _sqrt = _opts.sqrt;
if (typeof _opts.isLE === "boolean") isLE = _opts.isLE;
if (typeof _opts.modFromBytes === "boolean") modFromBytes = _opts.modFromBytes;
allowedLengths = _opts.allowedLengths;
} else {
if (typeof bitLenOrOpts === "number") _nbitLength = bitLenOrOpts;
if (opts.sqrt) _sqrt = opts.sqrt;
}
const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, _nbitLength);
if (BYTES > 2048) throw new Error("invalid field: expected ORDER of <= 2048 bytes");
let sqrtP;
const f = Object.freeze({
ORDER,
isLE,
BITS,
BYTES,
MASK: bitMask(BITS),
ZERO: _0n$2,
ONE: _1n$2,
allowedLengths,
create: (num) => mod(num, ORDER),
isValid: (num) => {
if (typeof num !== "bigint") throw new Error("invalid field element: expected bigint, got " + typeof num);
return _0n$2 <= num && num < ORDER;
},
is0: (num) => num === _0n$2,
isValidNot0: (num) => !f.is0(num) && f.isValid(num),
isOdd: (num) => (num & _1n$2) === _1n$2,
neg: (num) => mod(-num, ORDER),
eql: (lhs, rhs) => lhs === rhs,
sqr: (num) => mod(num * num, ORDER),
add: (lhs, rhs) => mod(lhs + rhs, ORDER),
sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
pow: (num, power) => FpPow(f, num, power),
div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
sqrN: (num) => num * num,
addN: (lhs, rhs) => lhs + rhs,
subN: (lhs, rhs) => lhs - rhs,
mulN: (lhs, rhs) => lhs * rhs,
inv: (num) => invert(num, ORDER),
sqrt: _sqrt || ((n) => {
if (!sqrtP) sqrtP = FpSqrt(ORDER);
return sqrtP(f, n);
}),
toBytes: (num) => isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES),
fromBytes: (bytes, skipValidation = true) => {
if (allowedLengths) {
if (!allowedLengths.includes(bytes.length) || bytes.length > BYTES) throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length);
const padded = new Uint8Array(BYTES);
padded.set(bytes, isLE ? 0 : padded.length - bytes.length);
bytes = padded;
}
if (bytes.length !== BYTES) throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length);
let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
if (modFromBytes) scalar = mod(scalar, ORDER);
if (!skipValidation) {
if (!f.isValid(scalar)) throw new Error("invalid field element: outside of range 0..ORDER");
}
return scalar;
},
invertBatch: (lst) => FpInvertBatch(f, lst),
cmov: (a, b, c) => c ? b : a
});
return Object.freeze(f);
}
/**
* Returns total number of bytes consumed by the field element.
* For example, 32 bytes for usual 256-bit weierstrass curve.
* @param fieldOrder number of field elements, usually CURVE.n
* @returns byte length of field
*/
function getFieldBytesLength(fieldOrder) {
if (typeof fieldOrder !== "bigint") throw new Error("field order must be bigint");
const bitLength = fieldOrder.toString(2).length;
return Math.ceil(bitLength / 8);
}
/**
* Returns minimal amount of bytes that can be safely reduced
* by field order.
* Should be 2^-128 for 128-bit curve such as P256.
* @param fieldOrder number of field elements, usually CURVE.n
* @returns byte length of target hash
*/
function getMinHashLength(fieldOrder) {
const length = getFieldBytesLength(fieldOrder);
return length + Math.ceil(length / 2);
}
/**
* "Constant-time" private key generation utility.
* Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
* and convert them into private scalar, with the modulo bias being negligible.
* Needs at least 48 bytes of input for 32-byte private key.
* https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
* FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
* RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
* @param hash hash output from SHA3 or a similar function
* @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
* @param isLE interpret hash bytes as LE num
* @returns valid private scalar
*/
function mapHashToField(key, fieldOrder, isLE = false) {
const len = key.length;
const fieldLen = getFieldBytesLength(fieldOrder);
const minLen = getMinHashLength(fieldOrder);
if (len < 16 || len < minLen || len > 1024) throw new Error("expected " + minLen + "-1024 bytes of input, got " + len);
const reduced = mod(isLE ? bytesToNumberLE(key) : bytesToNumberBE(key), fieldOrder - _1n$2) + _1n$2;
return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
}
//#endregion
//#region node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js
/**
* Internal Merkle-Damgard hash utils.
* @module
*/
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
function setBigUint64(view, byteOffset, value, isLE) {
if (typeof view.setBigUint64 === "function") return view.setBigUint64(byteOffset, value, isLE);
const _32n = BigInt(32);
const _u32_max = BigInt(4294967295);
const wh = Number(value >> _32n & _u32_max);
const wl = Number(value & _u32_max);
const h = isLE ? 4 : 0;
const l = isLE ? 0 : 4;
view.setUint32(byteOffset + h, wh, isLE);
view.setUint32(byteOffset + l, wl, isLE);
}
/** Choice: a ? b : c */
function Chi(a, b, c) {
return a & b ^ ~a & c;
}
/** Majority function, true if any two inputs is true. */
function Maj(a, b, c) {
return a & b ^ a & c ^ b & c;
}
/**
* Merkle-Damgard hash construction base class.
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
*/
var HashMD = class extends Hash {
constructor(blockLen, outputLen, padOffset, isLE) {
super();
this.finished = false;
this.length = 0;
this.pos = 0;
this.destroyed = false;
this.blockLen = blockLen;
this.outputLen = outputLen;
this.padOffset = padOffset;
this.isLE = isLE;
this.buffer = new Uint8Array(blockLen);
this.view = createView(this.buffer);
}
update(data) {
aexists(this);
data = toBytes(data);
abytes(data);
const { view, buffer, blockLen } = this;
const len = data.length;
for (let pos = 0; pos < len;) {
const take = Math.min(blockLen - this.pos, len - pos);
if (take === blockLen) {
const dataView = createView(data);
for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
pos += take;
if (this.pos === blockLen) {
this.process(view, 0);
this.pos = 0;
}
}
this.length += data.length;
this.roundClean();
return this;
}
digestInto(out) {
aexists(this);
aoutput(out, this);
this.finished = true;
const { buffer, view, blockLen, isLE } = this;
let { pos } = this;
buffer[pos++] = 128;
clean(this.buffer.subarray(pos));
if (this.padOffset > blockLen - pos) {
this.process(view, 0);
pos = 0;
}
for (let i = pos; i < blockLen; i++) buffer[i] = 0;
setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
this.process(view, 0);
const oview = createView(out);
const len = this.outputLen;
if (len % 4) throw new Error("_sha2: outputLen should be aligned to 32bit");
const outLen = len / 4;
const state = this.get();
if (outLen > state.length) throw new Error("_sha2: outputLen bigger than state");
for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
_cloneInto(to) {
to || (to = new this.constructor());
to.set(...this.get());
const { blockLen, buffer, length, finished, destroyed, pos } = this;
to.destroyed = destroyed;
to.finished = finished;
to.length = length;
to.pos = pos;
if (length % blockLen) to.buffer.set(buffer);
return to;
}
clone() {
return this._cloneInto();
}
};
/**
* Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
* Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
*/
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
1779033703,
3144134277,
1013904242,
2773480762,
1359893119,
2600822924,
528734635,
1541459225
]);
/** Initial SHA384 state. Bits 0..64 of frac part of sqrt of primes 23..53 */
const SHA384_IV = /* @__PURE__ */ Uint32Array.from([
3418070365,
3238371032,
1654270250,
914150663,
2438529370,
812702999,
355462360,
4144912697,
1731405415,
4290775857,
2394180231,
1750603025,
3675008525,
1694076839,
1203062813,
3204075428
]);
/** Initial SHA512 state. Bits 0..64 of frac part of sqrt of primes 2..19 */
const SHA512_IV = /* @__PURE__ */ Uint32Array.from([
1779033703,
4089235720,
3144134277,
2227873595,
1013904242,
4271175723,
2773480762,
1595750129,
1359893119,
2917565137,
2600822924,
725511199,
528734635,
4215389547,
1541459225,
327033209
]);
//#endregion
//#region node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_u64.js
/**
* Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
* @todo re-check https://issues.chromium.org/issues/42212588
* @module
*/
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
const _32n = /* @__PURE__ */ BigInt(32);
function fromBig(n, le = false) {
if (le) return {
h: Number(n & U32_MASK64),
l: Number(n >> _32n & U32_MASK64)
};
return {
h: Number(n >> _32n & U32_MASK64) | 0,
l: Number(n & U32_MASK64) | 0
};
}
function split(lst, le = false) {
const len = lst.length;
let Ah = new Uint32Array(len);
let Al = new Uint32Array(len);
for (let i = 0; i < len; i++) {
const { h, l } = fromBig(lst[i], le);
[Ah[i], Al[i]] = [h, l];
}
return [Ah, Al];
}
const shrSH = (h, _l, s) => h >>> s;
const shrSL = (h, l, s) => h << 32 - s | l >>> s;
const rotrSH = (h, l, s) => h >>> s | l << 32 - s;
const rotrSL = (h, l, s) => h << 32 - s | l >>> s;
const rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32;
const rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s;
function add(Ah, Al, Bh, Bl) {
const l = (Al >>> 0) + (Bl >>> 0);
return {
h: Ah + Bh + (l / 2 ** 32 | 0) | 0,
l: l | 0
};
}
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
const add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0;
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
const add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0;
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0;
//#endregion
//#region node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js
/**
* SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
* SHA256 is the fastest hash implementable in JS, even faster than Blake3.
* Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
* [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
* @module
*/
/**
* Round constants:
* First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
*/
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
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
]);
/** Reusable temporary buffer. "W" comes straight from spec. */
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
var SHA256 = class extends HashMD {
constructor(outputLen = 32) {
super(64, outputLen, 8, false);
this.A = SHA256_IV[0] | 0;
this.B = SHA256_IV[1] | 0;
this.C = SHA256_IV[2] | 0;
this.D = SHA256_IV[3] | 0;
this.E = SHA256_IV[4] | 0;
this.F = SHA256_IV[5] | 0;
this.G = SHA256_IV[6] | 0;
this.H = SHA256_IV[7] | 0;
}
get() {
const { A, B, C, D, E, F, G, H } = this;
return [
A,
B,
C,
D,
E,
F,
G,
H
];
}
set(A, B, C, D, E, F, G, H) {
this.A = A | 0;
this.B = B | 0;
this.C = C | 0;
this.D = D | 0;
this.E = E | 0;
this.F = F | 0;
this.G = G | 0;
this.H = H | 0;
}
process(view, offset) {
for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);
for (let i = 16; i < 64; i++) {
const W15 = SHA256_W[i - 15];
const W2 = SHA256_W[i - 2];
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
}
let { A, B, C, D, E, F, G, H } = this;
for (let i = 0; i < 64; i++) {
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
const T2 = (rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22)) + Maj(A, B, C) | 0;
H = G;
G = F;
F = E;
E = D + T1 | 0;
D = C;
C = B;
B = A;
A = T1 + T2 | 0;
}
A = A + this.A | 0;
B = B + this.B | 0;
C = C + this.C | 0;
D = D + this.D | 0;
E = E + this.E | 0;
F = F + this.F | 0;
G = G + this.G | 0;
H = H + this.H | 0;
this.set(A, B, C, D, E, F, G, H);
}
roundClean() {
clean(SHA256_W);
}
destroy() {
this.set(0, 0, 0, 0, 0, 0, 0, 0);
clean(this.buffer);
}
};
const K512 = /* @__PURE__ */ (() => split([
"0x428a2f98d728ae22",
"0x7137449123ef65cd",
"0xb5c0fbcfec4d3b2f",
"0xe9b5dba58189dbbc",
"0x3956c25bf348b538",
"0x59f111f1b605d019",
"0x923f82a4af194f9b",
"0xab1c5ed5da6d8118",
"0xd807aa98a3030242",
"0x12835b0145706fbe",
"0x243185be4ee4b28c",
"0x550c7dc3d5ffb4e2",
"0x72be5d74f27b896f",
"0x80deb1fe3b1696b1",
"0x9bdc06a725c71235",
"0xc19bf174cf692694",
"0xe49b69c19ef14ad2",
"0xefbe4786384f25e3",
"0x0fc19dc68b8cd5b5",
"0x240ca1cc77ac9c65",
"0x2de92c6f592b0275",
"0x4a7484aa6ea6e483",
"0x5cb0a9dcbd41fbd4",
"0x76f988da831153b5",
"0x983e5152ee66dfab",
"0xa831c66d2db43210",
"0xb00327c898fb213f",
"0xbf597fc7beef0ee4",
"0xc6e00bf33da88fc2",
"0xd5a79147930aa725",
"0x06ca6351e003826f",
"0x142929670a0e6e70",
"0x27b70a8546d22ffc",
"0x2e1b21385c26c926",
"0x4d2c6dfc5ac42aed",
"0x53380d139d95b3df",
"0x650a73548baf63de",
"0x766a0abb3c77b2a8",
"0x81c2c92e47edaee6",
"0x92722c851482353b",
"0xa2bfe8a14cf10364",
"0xa81a664bbc423001",
"0xc24b8b70d0f89791",
"0xc76c51a30654be30",
"0xd192e819d6ef5218",
"0xd69906245565a910",
"0xf40e35855771202a",
"0x106aa07032bbd1b8",
"0x19a4c116b8d2d0c8",
"0x1e376c085141ab53",
"0x2748774cdf8eeb99",
"0x34b0bcb5e19b48a8",
"0x391c0cb3c5c95a63",
"0x4ed8aa4ae3418acb",
"0x5b9cca4f7763e373",
"0x682e6ff3d6b2b8a3",
"0x748f82ee5defb2fc",
"0x78a5636f43172f60",
"0x84c87814a1f0ab72",
"0x8cc702081a6439ec",
"0x90befffa23631e28",
"0xa4506cebde82bde9",
"0xbef9a3f7b2c67915",
"0xc67178f2e372532b",
"0xca273eceea26619c",
"0xd186b8c721c0c207",
"0xeada7dd6cde0eb1e",
"0xf57d4f7fee6ed178",
"0x06f067aa72176fba",
"0x0a637dc5a2c898a6",
"0x113f9804bef90dae",
"0x1b710b35131c471b",
"0x28db77f523047d84",
"0x32caab7b40c72493",
"0x3c9ebe0a15c9bebc",
"0x431d67c49c100d4c",
"0x4cc5d4becb3e42b6",
"0x597f299cfc657e2a",
"0x5fcb6fab3ad6faec",
"0x6c44198c4a475817"
].map((n) => BigInt(n))))();
const SHA512_Kh = /* @__PURE__ */ (() => K512[0])();
const SHA512_Kl = /* @__PURE__ */ (() => K512[1])();
const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);
const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);
var SHA512 = class extends HashMD {
constructor(outputLen = 64) {
super(128, outputLen, 16, false);
this.Ah = SHA512_IV[0] | 0;
this.Al = SHA512_IV[1] | 0;
this.Bh = SHA512_IV[2] | 0;
this.Bl = SHA512_IV[3] | 0;
this.Ch = SHA512_IV[4] | 0;
this.Cl = SHA512_IV[5] | 0;
this.Dh = SHA512_IV[6] | 0;
this.Dl = SHA512_IV[7] | 0;
this.Eh = SHA512_IV[8] | 0;
this.El = SHA512_IV[9] | 0;
this.Fh = SHA512_IV[10] | 0;
this.Fl = SHA512_IV[11] | 0;
this.Gh = SHA512_IV[12] | 0;
this.Gl = SHA512_IV[13] | 0;
this.Hh = SHA512_IV[14] | 0;
this.Hl = SHA512_IV[15] | 0;
}
get() {
const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
return [
Ah,
Al,
Bh,
Bl,
Ch,
Cl,
Dh,
Dl,
Eh,
El,
Fh,
Fl,
Gh,
Gl,
Hh,
Hl
];
}
set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {
this.Ah = Ah | 0;
this.Al = Al | 0;
this.Bh = Bh | 0;
this.Bl = Bl | 0;
this.Ch = Ch | 0;
this.Cl = Cl | 0;
this.Dh = Dh | 0;
this.Dl = Dl | 0;
this.Eh = Eh | 0;
this.El = El | 0;
this.Fh = Fh | 0;
this.Fl = Fl | 0;
this.Gh = Gh | 0;
this.Gl = Gl | 0;
this.Hh = Hh | 0;
this.Hl = Hl | 0;
}
process(view, offset) {
for (let i = 0; i < 16; i++, offset += 4) {
SHA512_W_H[i] = view.getUint32(offset);
SHA512_W_L[i] = view.getUint32(offset += 4);
}
for (let i = 16; i < 80; i++) {
const W15h = SHA512_W_H[i - 15] | 0;
const W15l = SHA512_W_L[i - 15] | 0;
const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7);
const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7);
const W2h = SHA512_W_H[i - 2] | 0;
const W2l = SHA512_W_L[i - 2] | 0;
const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6);
const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6);
const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);
const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);
SHA512_W_H[i] = SUMh | 0;
SHA512_W_L[i] = SUMl | 0;
}
let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;
for (let i = 0; i < 80; i++) {
const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41);
const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41);
const CHIh = Eh & Fh ^ ~Eh & Gh;
const CHIl = El & Fl ^ ~El & Gl;
const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);
const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);
const T1l = T1ll | 0;
const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39);
const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39);
const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch;
const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl;
Hh = Gh | 0;
Hl = Gl | 0;
Gh = Fh | 0;
Gl = Fl | 0;
Fh = Eh | 0;
Fl = El | 0;
({h: Eh, l: El} = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));
Dh = Ch | 0;
Dl = Cl | 0;
Ch = Bh | 0;
Cl = Bl | 0;
Bh = Ah | 0;
Bl = Al | 0;
const All = add3L(T1l, sigma0l, MAJl);
Ah = add3H(All, T1h, sigma0h, MAJh);
Al = All | 0;
}
({h: Ah, l: Al} = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));
({h: Bh, l: Bl} = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));
({h: Ch, l: Cl} = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));
({h: Dh, l: Dl} = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));
({h: Eh, l: El} = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));
({h: Fh, l: Fl} = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));
({h: Gh, l: Gl} = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));
({h: Hh, l: Hl} = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));
this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);
}
roundClean() {
clean(SHA512_W_H, SHA512_W_L);
}
destroy() {
clean(this.buffer);
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
};
var SHA384 = class extends SHA512 {
constructor() {
super(48);
this.Ah = SHA384_IV[0] | 0;
this.Al = SHA384_IV[1] | 0;
this.Bh = SHA384_IV[2] | 0;
this.Bl = SHA384_IV[3] | 0;
this.Ch = SHA384_IV[4] | 0;
this.Cl = SHA384_IV[5] | 0;
this.Dh = SHA384_IV[6] | 0;
this.Dl = SHA384_IV[7] | 0;
this.Eh = SHA384_IV[8] | 0;
this.El = SHA384_IV[9] | 0;
this.Fh = SHA384_IV[10] | 0;
this.Fl = SHA384_IV[11] | 0;
this.Gh = SHA384_IV[12] | 0;
this.Gl = SHA384_IV[13] | 0;
this.Hh = SHA384_IV[14] | 0;
this.Hl = SHA384_IV[15] | 0;
}
};
/**
* SHA2-256 hash function from RFC 4634.
*
* It is the fastest JS hash, even faster than Blake3.
* To break sha256 using birthday attack, attackers need to try 2^128 hashes.
* BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
*/
const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
/** SHA2-512 hash function from RFC 4634. */
const sha512 = /* @__PURE__ */ createHasher(() => new SHA512());
/** SHA2-384 hash function from RFC 4634. */
const sha384 = /* @__PURE__ */ createHasher(() => new SHA384());
//#endregion
//#region node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js
/**
* HMAC: RFC2104 message authentication code.
* @module
*/
var HMAC = class extends Hash {
constructor(hash, _key) {
super();
this.finished = false;
this.destroyed = false;
ahash(hash);
const key = toBytes(_key);
this.iHash = hash.create();
if (typeof this.iHash.update !== "function") throw new Error("Expected instance of class which extends utils.Hash");
this.blockLen = this.iHash.blockLen;
this.outputLen = this.iHash.outputLen;
const blockLen = this.blockLen;
const pad = new Uint8Array(blockLen);
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
for (let i = 0; i < pad.length; i++) pad[i] ^= 54;
this.iHash.update(pad);
this.oHash = hash.create();
for (let i = 0; i < pad.length; i++) pad[i] ^= 106;
this.oHash.update(pad);
clean(pad);
}
update(buf) {
aexists(this);
this.iHash.update(buf);
return this;
}
digestInto(out) {
aexists(this);
abytes(out, this.outputLen);
this.finished = true;
this.iHash.digestInto(out);
this.oHash.update(out);
this.oHash.digestInto(out);
this.destroy();
}
digest() {
const out = new Uint8Array(this.oHash.outputLen);
this.digestInto(out);
return out;
}
_cloneInto(to) {
to || (to = Object.create(Object.getPrototypeOf(this), {}));
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
to = to;
to.finished = finished;
to.destroyed = destroyed;
to.blockLen = blockLen;
to.outputLen = outputLen;
to.oHash = oHash._cloneInto(to.oHash);
to.iHash = iHash._cloneInto(to.iHash);
return to;
}
clone() {
return this._cloneInto();
}
destroy() {
this.destroyed = true;
this.oHash.destroy();
this.iHash.destroy();
}
};
/**
* HMAC: RFC2104 message authentication code.
* @param hash - function that would be used e.g. sha256
* @param key - message key
* @param message - message data
* @example
* import { hmac } from '@noble/hashes/hmac';
* import { sha256 } from '@noble/hashes/sha2';
* const mac1 = hmac(sha256, 'key', 'message');
*/
const hmac$1 = (hash, key, message) => new HMAC(hash, key).update(message).digest();
hmac$1.create = (hash, key) => new HMAC(hash, key);
//#endregion
//#region node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/curve.js
/**
* Methods for elliptic curve multiplication by scalars.
* Contains wNAF, pippenger.
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const _0n$1 = BigInt(0);
const _1n$1 = BigInt(1);
function negateCt(condition, item) {
const neg = item.negate();
return condition ? neg : item;
}
/**
* Takes a bunch of Projective Points but executes only one
* inversion on all of them. Inversion is very slow operation,
* so this improves performance massively.
* Optimization: converts a list of projective points to a list of identical points with Z=1.
*/
function normalizeZ(c, points) {
const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z));
return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
}
function validateW(W, bits) {
if (!Number.isSafeInteger(W) || W <= 0 || W > bits) throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
}
function calcWOpts(W, scalarBits) {
validateW(W, scalarBits);
const windows = Math.ceil(scalarBits / W) + 1;
const windowSize = 2 ** (W - 1);
const maxNumber = 2 ** W;
return {
windows,
windowSize,
mask: bitMask(W),
maxNumber,
shiftBy: BigInt(W)
};
}
function calcOffsets(n, window, wOpts) {
const { windowSize, mask, maxNumber, shiftBy } = wOpts;
let wbits = Number(n & mask);
let nextN = n >> shiftBy;
if (wbits > windowSize) {
wbits -= maxNumber;
nextN += _1n$1;
}
const offsetStart = window * windowSize;
const offset = offsetStart + Math.abs(wbits) - 1;
const isZero = wbits === 0;
const isNeg = wbits < 0;
const isNegF = window % 2 !== 0;
return {
nextN,
offset,
isZero,
isNeg,
isNegF,
offsetF: offsetStart
};
}
function validateMSMPoints(points, c) {
if (!Array.isArray(points)) throw new Error("array expected");
points.forEach((p, i) => {
if (!(p instanceof c)) throw new Error("invalid point at index " + i);
});
}
function validateMSMScalars(scalars, field) {
if (!Array.isArray(scalars)) throw new Error("array of scalars expected");
scalars.forEach((s, i) => {
if (!field.isValid(s)) throw new Error("invalid scalar at index " + i);
});
}
const pointPrecomputes = /* @__PURE__ */ new WeakMap();
const pointWindowSizes = /* @__PURE__ */ new WeakMap();
function getW(P) {
return pointWindowSizes.get(P) || 1;
}
function assert0(n) {
if (n !== _0n$1) throw new Error("invalid wNAF");
}
/**
* Elliptic curve multiplication of Point by scalar. Fragile.
* Table generation takes **30MB of ram and 10ms on high-end CPU**,
* but may take much longer on slow devices. Actual generation will happen on
* first call of `multiply()`. By default, `BASE` point is precomputed.
*
* Scalars should always be less than curve order: this should be checked inside of a curve itself.
* Creates precomputation tables for fast multiplication:
* - private scalar is split by fixed size windows of W bits
* - every window point is collected from window's table & added to accumulator
* - since windows are different, same point inside tables won't be accessed more than once per calc
* - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
* - +1 window is neccessary for wNAF
* - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
*
* @todo Research returning 2d JS array of windows, instead of a single window.
* This would allow windows to be in different memory locations
*/
var wNAF = class {
constructor(Point, bits) {
this.BASE = Point.BASE;
this.ZERO = Point.ZERO;
this.Fn = Point.Fn;
this.bits = bits;
}
_unsafeLadder(elm, n, p = this.ZERO) {
let d = elm;
while (n > _0n$1) {
if (n & _1n$1) p = p.add(d);
d = d.double();
n >>= _1n$1;
}
return p;
}
/**
* Creates a wNAF precomputation window. Used for caching.
* Default window size is set by `utils.precompute()` and is equal to 8.
* Number of precomputed points depends on the curve size:
* 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
* - 𝑊 is the window size
* - 𝑛 is the bitlength of the curve order.
* For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
* @param point Point instance
* @param W window size
* @returns precomputed point tables flattened to a single array
*/
precomputeWindow(point, W) {
const { windows, windowSize } = calcWOpts(W, this.bits);
const points = [];
let p = point;
let base = p;
for (let window = 0; window < windows; window++) {
base = p;
points.push(base);
for (let i = 1; i < windowSize; i++) {
base = base.add(p);
points.push(base);
}
p = base.double();
}
return points;
}
/**
* Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
* More compact implementation:
* https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
* @returns real and fake (for const-time) points
*/
wNAF(W, precomputes, n) {
if (!this.Fn.isValid(n)) throw new Error("invalid scalar");
let p = this.ZERO;
let f = this.BASE;
const wo = calcWOpts(W, this.bits);
for (let window = 0; window < wo.windows; window++) {
const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
n = nextN;
if (isZero) f = f.add(negateCt(isNegF, precomputes[offsetF]));
else p = p.add(negateCt(isNeg, precomputes[offset]));
}
assert0(n);
return {
p,
f
};
}
/**
* Implements ec unsafe (non const-time) multiplication using precomputed tables and w-ary non-adjacent form.
* @param acc accumulator point to add result of multiplication
* @returns point
*/
wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
const wo = calcWOpts(W, this.bits);
for (let window = 0; window < wo.windows; window++) {
if (n === _0n$1) break;
const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
n = nextN;
if (isZero) continue;
else {
const item = precomputes[offset];
acc = acc.add(isNeg ? item.negate() : item);
}
}
assert0(n);
return acc;
}
getPrecomputes(W, point, transform) {
let comp = pointPrecomputes.get(point);
if (!comp) {
comp = this.precomputeWindow(point, W);
if (W !== 1) {
if (typeof transform === "function") comp = transform(comp);
pointPrecomputes.set(point, comp);
}
}
return comp;
}
cached(point, scalar, transform) {
const W = getW(point);
return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
}
unsafe(point, scalar, transform, prev) {
const W = getW(point);
if (W === 1) return this._unsafeLadder(point, scalar, prev);
return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
}
createCache(P, W) {
validateW(W, this.bits);
pointWindowSizes.set(P, W);
pointPrecomputes.delete(P);
}
hasCache(elm) {
return getW(elm) !== 1;
}
};
/**
* Endomorphism-specific multiplication for Koblitz curves.
* Cost: 128 dbl, 0-256 adds.
*/
function mulEndoUnsafe(Point, point, k1, k2) {
let acc = point;
let p1 = Point.ZERO;
let p2 = Point.ZERO;
while (k1 > _0n$1 || k2 > _0n$1) {
if (k1 & _1n$1) p1 = p1.add(acc);
if (k2 & _1n$1) p2 = p2.add(acc);
acc = acc.double();
k1 >>= _1n$1;
k2 >>= _1n$1;
}
return {
p1,
p2
};
}
/**
* Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).
* 30x faster vs naive addition on L=4096, 10x faster than precomputes.
* For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL.
* Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.
* @param c Curve Point constructor
* @param fieldN field over CURVE.N - important that it's not over CURVE.P
* @param points array of L curve points
* @param scalars array of L scalars (aka secret keys / bigints)
*/
function pippenger(c, fieldN, points, scalars) {
validateMSMPoints(points, c);
validateMSMScalars(scalars, fieldN);
const plength = points.length;
const slength = scalars.length;
if (plength !== slength) throw new Error("arrays of points and scalars must have equal length");
const zero = c.ZERO;
const wbits = bitLen(BigInt(plength));
let windowSize = 1;
if (wbits > 12) windowSize = wbits - 3;
else if (wbits > 4) windowSize = wbits - 2;
else if (wbits > 0) windowSize = 2;
const MASK = bitMask(windowSize);
const buckets = new Array(Number(MASK) + 1).fill(zero);
const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize;
let sum = zero;
for (let i = lastBits; i >= 0; i -= windowSize) {
buckets.fill(zero);
for (let j = 0; j < slength; j++) {
const scalar = scalars[j];
const wbits = Number(scalar >> BigInt(i) & MASK);
buckets[wbits] = buckets[wbits].add(points[j]);
}
let resI = zero;
for (let j = buckets.length - 1, sumI = zero; j > 0; j--) {
sumI = sumI.add(buckets[j]);
resI = resI.add(sumI);
}
sum = sum.add(resI);
if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double();
}
return sum;
}
function createField(order, field, isLE) {
if (field) {
if (field.ORDER !== order) throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
validateField(field);
return field;
} else return Field(order, { isLE });
}
/** Validates CURVE opts and creates fields */
function _createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
if (FpFnLE === void 0) FpFnLE = type === "edwards";
if (!CURVE || typeof CURVE !== "object") throw new Error(`expected valid ${type} CURVE object`);
for (const p of [
"p",
"n",
"h"
]) {
const val = CURVE[p];
if (!(typeof val === "bigint" && val > _0n$1)) throw new Error(`CURVE.${p} must be positive bigint`);
}
const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
const params = [
"Gx",
"Gy",
"a",
type === "weierstrass" ? "b" : "d"
];
for (const p of params) if (!Fp.isValid(CURVE[p])) throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
CURVE = Object.freeze(Object.assign({}, CURVE));
return {
CURVE,
Fp,
Fn
};
}
//#endregion
//#region node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/abstract/weierstrass.js
/**
* Short Weierstrass curve methods. The formula is: y² = x³ + ax + b.
*
* ### Design rationale for types
*
* * Interaction between classes from different curves should fail:
* `k256.Point.BASE.add(p256.Point.BASE)`
* * For this purpose we want to use `instanceof` operator, which is fast and works during runtime
* * Different calls of `curve()` would return different classes -
* `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,
* it won't affect others
*
* TypeScript can't infer types for classes created inside a function. Classes is one instance
* of nominative types in TypeScript and interfaces only check for shape, so it's hard to create
* unique type for every function call.
*
* We can use generic types via some param, like curve opts, but that would:
* 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)
* which is hard to debug.
* 2. Params can be generic and we can't enforce them to be constant value:
* if somebody creates curve from non-constant params,
* it would be allowed to interact with other curves with non-constant params
*
* @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den;
/**
* Splits scalar for GLV endomorphism.
*/
function _splitEndoScalar(k, basis, n) {
const [[a1, b1], [a2, b2]] = basis;
const c1 = divNearest(b2 * k, n);
const c2 = divNearest(-b1 * k, n);
let k1 = k - c1 * a1 - c2 * a2;
let k2 = -c1 * b1 - c2 * b2;
const k1neg = k1 < _0n;
const k2neg = k2 < _0n;
if (k1neg) k1 = -k1;
if (k2neg) k2 = -k2;
const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n;
if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) throw new Error("splitScalar (endomorphism): failed, k=" + k);
return {
k1neg,
k1,
k2neg,
k2
};
}
function validateSigFormat(format) {
if (![
"compact",
"recovered",
"der"
].includes(format)) throw new Error("Signature format must be \"compact\", \"recovered\", or \"der\"");
return format;
}
function validateSigOpts(opts, def) {
const optsn = {};
for (let optName of Object.keys(def)) optsn[optName] = opts[optName] === void 0 ? def[optName] : opts[optName];
_abool2(optsn.lowS, "lowS");
_abool2(optsn.prehash, "prehash");
if (optsn.format !== void 0) validateSigFormat(optsn.format);
return optsn;
}
var DERErr = class extends Error {
constructor(m = "") {
super(m);
}
};
/**
* ASN.1 DER encoding utilities. ASN is very complex & fragile. Format:
*
* [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S]
*
* Docs: https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/, https://luca.ntop.org/Teaching/Appunti/asn1.html
*/
const DER = {
Err: DERErr,
_tlv: {
encode: (tag, data) => {
const { Err: E } = DER;
if (tag < 0 || tag > 256) throw new E("tlv.encode: wrong tag");
if (data.length & 1) throw new E("tlv.encode: unpadded data");
const dataLen = data.length / 2;
const len = numberToHexUnpadded(dataLen);
if (len.length / 2 & 128) throw new E("tlv.encode: long form length too big");
const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : "";
return numberToHexUnpadded(tag) + lenLen + len + data;
},
decode(tag, data) {
const { Err: E } = DER;
let pos = 0;
if (tag < 0 || tag > 256) throw new E("tlv.encode: wrong tag");
if (data.length < 2 || data[pos++] !== tag) throw new E("tlv.decode: wrong tlv");
const first = data[pos++];
const isLong = !!(first & 128);
let length = 0;
if (!isLong) length = first;
else {
const lenLen = first & 127;
if (!lenLen) throw new E("tlv.decode(long): indefinite length not supported");
if (lenLen > 4) throw new E("tlv.decode(long): byte length is too big");
const lengthBytes = data.subarray(pos, pos + lenLen);
if (lengthBytes.length !== lenLen) throw new E("tlv.decode: length bytes not complete");
if (lengthBytes[0] === 0) throw new E("tlv.decode(long): zero leftmost byte");
for (const b of lengthBytes) length = length << 8 | b;
pos += lenLen;
if (length < 128) throw new E("tlv.decode(long): not minimal encoding");
}
const v = data.subarray(pos, pos + length);
if (v.length !== length) throw new E("tlv.decode: wrong value length");
return {
v,
l: data.subarray(pos + length)
};
}
},
_int: {
encode(num) {
const { Err: E } = DER;
if (num < _0n) throw new E("integer: negative integers are not allowed");
let hex = numberToHexUnpadded(num);
if (Number.parseInt(hex[0], 16) & 8) hex = "00" + hex;
if (hex.length & 1) throw new E("unexpected DER parsing assertion: unpadded hex");
return hex;
},
decode(data) {
const { Err: E } = DER;
if (data[0] & 128) throw new E("invalid signature integer: negative");
if (data[0] === 0 && !(data[1] & 128)) throw new E("invalid signature integer: unnecessary leading zero");
return bytesToNumberBE(data);
}
},
toSig(hex) {
const { Err: E, _int: int, _tlv: tlv } = DER;
const data = ensureBytes("signature", hex);
const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data);
if (seqLeftBytes.length) throw new E("invalid signature: left bytes after parsing");
const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes);
const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes);
if (sLeftBytes.length) throw new E("invalid signature: left bytes after parsing");
return {
r: int.decode(rBytes),
s: int.decode(sBytes)
};
},
hexFromSig(sig) {
const { _tlv: tlv, _int: int } = DER;
const seq = tlv.encode(2, int.encode(sig.r)) + tlv.encode(2, int.encode(sig.s));
return tlv.encode(48, seq);
}
};
const _0n = BigInt(0);
const _1n = BigInt(1);
const _2n = BigInt(2);
const _3n = BigInt(3);
const _4n = BigInt(4);
function _normFnElement(Fn, key) {
const { BYTES: expected } = Fn;
let num;
if (typeof key === "bigint") num = key;
else {
let bytes = ensureBytes("private key", key);
try {
num = Fn.fromBytes(bytes);
} catch (error) {
throw new Error(`invalid private key: expected ui8a of size ${expected}, got ${typeof key}`);
}
}
if (!Fn.isValidNot0(num)) throw new Error("invalid private key: out of range [1..N-1]");
return num;
}
/**
* Creates weierstrass Point constructor, based on specified curve options.
*
* @example
```js
const opts = {
p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'),
n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),
h: BigInt(1),
a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'),
b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'),
Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),
Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),
};
const p256_Point = weierstrass(opts);
```
*/
function weierstrassN(params, extraOpts = {}) {
const validated = _createCurveFields("weierstrass", params, extraOpts);
const { Fp, Fn } = validated;
let CURVE = validated.CURVE;
const { h: cofactor, n: CURVE_ORDER } = CURVE;
_validateObject(extraOpts, {}, {
allowInfinityPoint: "boolean",
clearCofactor: "function",
isTorsionFree: "function",
fromBytes: "function",
toBytes: "function",
endo: "object",
wrapPrivateKey: "boolean"
});
const { endo } = extraOpts;
if (endo) {
if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) throw new Error("invalid endo: expected \"beta\": bigint and \"basises\": array");
}
const lengths = getWLengths(Fp, Fn);
function assertCompressionIsSupported() {
if (!Fp.isOdd) throw new Error("compression is not supported: Field does not have .isOdd()");
}
function pointToBytes(_c, point, isCompressed) {
const { x, y } = point.toAffine();
const bx = Fp.toBytes(x);
_abool2(isCompressed, "isCompressed");
if (isCompressed) {
assertCompressionIsSupported();
return concatBytes(pprefix(!Fp.isOdd(y)), bx);
} else return concatBytes(Uint8Array.of(4), bx, Fp.toBytes(y));
}
function pointFromBytes(bytes) {
_abytes2(bytes, void 0, "Point");
const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths;
const length = bytes.length;
const head = bytes[0];
const tail = bytes.subarray(1);
if (length === comp && (head === 2 || head === 3)) {
const x = Fp.fromBytes(tail);
if (!Fp.isValid(x)) throw new Error("bad point: is not on curve, wrong x");
const y2 = weierstrassEquation(x);
let y;
try {
y = Fp.sqrt(y2);
} catch (sqrtError) {
const err = sqrtError instanceof Error ? ": " + sqrtError.message : "";
throw new Error("bad point: is not on curve, sqrt error" + err);
}
assertCompressionIsSupported();
const isYOdd = Fp.isOdd(y);
if ((head & 1) === 1 !== isYOdd) y = Fp.neg(y);
return {
x,
y
};
} else if (length === uncomp && head === 4) {
const L = Fp.BYTES;
const x = Fp.fromBytes(tail.subarray(0, L));
const y = Fp.fromBytes(tail.subarray(L, L * 2));
if (!isValidXY(x, y)) throw new Error("bad point: is not on curve");
return {
x,
y
};
} else throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`);
}
const encodePoint = extraOpts.toBytes || pointToBytes;
const decodePoint = extraOpts.fromBytes || pointFromBytes;
function weierstrassEquation(x) {
const x2 = Fp.sqr(x);
const x3 = Fp.mul(x2, x);
return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b);
}
/** Checks whether equation holds for given x, y: y² == x³ + ax + b */
function isValidXY(x, y) {
const left = Fp.sqr(y);
const right = weierstrassEquation(x);
return Fp.eql(left, right);
}
if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error("bad curve params: generator point");
const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n);
const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27));
if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error("bad curve params: a or b");
/** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */
function acoord(title, n, banZero = false) {
if (!Fp.isValid(n) || banZero && Fp.is0(n)) throw new Error(`bad point coordinate ${title}`);
return n;
}
function aprjpoint(other) {
if (!(other instanceof Point)) throw new Error("ProjectivePoint expected");
}
function splitEndoScalarN(k) {
if (!endo || !endo.basises) throw new Error("no endo");
return _splitEndoScalar(k, endo.basises, Fn.ORDER);
}
const toAffineMemo = memoized((p, iz) => {
const { X, Y, Z } = p;
if (Fp.eql(Z, Fp.ONE)) return {
x: X,
y: Y
};
const is0 = p.is0();
if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(Z);
const x = Fp.mul(X, iz);
const y = Fp.mul(Y, iz);
const zz = Fp.mul(Z, iz);
if (is0) return {
x: Fp.ZERO,
y: Fp.ZERO
};
if (!Fp.eql(zz, Fp.ONE)) throw new Error("invZ was invalid");
return {
x,
y
};
});
const assertValidMemo = memoized((p) => {
if (p.is0()) {
if (extraOpts.allowInfinityPoint && !Fp.is0(p.Y)) return;
throw new Error("bad point: ZERO");
}
const { x, y } = p.toAffine();
if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error("bad point: x or y not field elements");
if (!isValidXY(x, y)) throw new Error("bad point: equation left != right");
if (!p.isTorsionFree()) throw new Error("bad point: not in prime-order subgroup");
return true;
});
function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) {
k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);
k1p = negateCt(k1neg, k1p);
k2p = negateCt(k2neg, k2p);
return k1p.add(k2p);
}
/**
* Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z).
* Default Point works in 2d / affine coordinates: (x, y).
* We're doing calculations in projective, because its operations don't require costly inversion.
*/
class Point {
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
constructor(X, Y, Z) {
this.X = acoord("x", X);
this.Y = acoord("y", Y, true);
this.Z = acoord("z", Z);
Object.freeze(this);
}
static CURVE() {
return CURVE;
}
/** Does NOT validate if the point is valid. Use `.assertValidity()`. */
static fromAffine(p) {
const { x, y } = p || {};
if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error("invalid affine point");
if (p instanceof Point) throw new Error("projective point not allowed");
if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO;
return new Point(x, y, Fp.ONE);
}
static fromBytes(bytes) {
const P = Point.fromAffine(decodePoint(_abytes2(bytes, void 0, "point")));
P.assertValidity();
return P;
}
static fromHex(hex) {
return Point.fromBytes(ensureBytes("pointHex", hex));
}
get x() {
return this.toAffine().x;
}
get y() {
return this.toAffine().y;
}
/**
*
* @param windowSize
* @param isLazy true will defer table computation until the first multiplication
* @returns
*/
precompute(windowSize = 8, isLazy = true) {
wnaf.createCache(this, windowSize);
if (!isLazy) this.multiply(_3n);
return this;
}
/** A point on curve is valid if it conforms to equation. */
assertValidity() {
assertValidMemo(this);
}
hasEvenY() {
const { y } = this.toAffine();
if (!Fp.isOdd) throw new Error("Field doesn't support isOdd");
return !Fp.isOdd(y);
}
/** Compare one point to another. */
equals(other) {
aprjpoint(other);
const { X: X1, Y: Y1, Z: Z1 } = this;
const { X: X2, Y: Y2, Z: Z2 } = other;
const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));
const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));
return U1 && U2;
}
/** Flips point to one corresponding to (x, -y) in Affine coordinates. */
negate() {
return new Point(this.X, Fp.neg(this.Y), this.Z);
}
double() {
const { a, b } = CURVE;
const b3 = Fp.mul(b, _3n);
const { X: X1, Y: Y1, Z: Z1 } = this;
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
let t0 = Fp.mul(X1, X1);
let t1 = Fp.mul(Y1, Y1);
let t2 = Fp.mul(Z1, Z1);
let t3 = Fp.mul(X1, Y1);
t3 = Fp.add(t3, t3);
Z3 = Fp.mul(X1, Z1);
Z3 = Fp.add(Z3, Z3);
X3 = Fp.mul(a, Z3);
Y3 = Fp.mul(b3, t2);
Y3 = Fp.add(X3, Y3);
X3 = Fp.sub(t1, Y3);
Y3 = Fp.add(t1, Y3);
Y3 = Fp.mul(X3, Y3);
X3 = Fp.mul(t3, X3);
Z3 = Fp.mul(b3, Z3);
t2 = Fp.mul(a, t2);
t3 = Fp.sub(t0, t2);
t3 = Fp.mul(a, t3);
t3 = Fp.add(t3, Z3);
Z3 = Fp.add(t0, t0);
t0 = Fp.add(Z3, t0);
t0 = Fp.add(t0, t2);
t0 = Fp.mul(t0, t3);
Y3 = Fp.add(Y3, t0);
t2 = Fp.mul(Y1, Z1);
t2 = Fp.add(t2, t2);
t0 = Fp.mul(t2, t3);
X3 = Fp.sub(X3, t0);
Z3 = Fp.mul(t2, t1);
Z3 = Fp.add(Z3, Z3);
Z3 = Fp.add(Z3, Z3);
return new Point(X3, Y3, Z3);
}
add(other) {
aprjpoint(other);
const { X: X1, Y: Y1, Z: Z1 } = this;
const { X: X2, Y: Y2, Z: Z2 } = other;
let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO;
const a = CURVE.a;
const b3 = Fp.mul(CURVE.b, _3n);
let t0 = Fp.mul(X1, X2);
let t1 = Fp.mul(Y1, Y2);
let t2 = Fp.mul(Z1, Z2);
let t3 = Fp.add(X1, Y1);
let t4 = Fp.add(X2, Y2);
t3 = Fp.mul(t3, t4);
t4 = Fp.add(t0, t1);
t3 = Fp.sub(t3, t4);
t4 = Fp.add(X1, Z1);
let t5 = Fp.add(X2, Z2);
t4 = Fp.mul(t4, t5);
t5 = Fp.add(t0, t2);
t4 = Fp.sub(t4, t5);
t5 = Fp.add(Y1, Z1);
X3 = Fp.add(Y2, Z2);
t5 = Fp.mul(t5, X3);
X3 = Fp.add(t1, t2);
t5 = Fp.sub(t5, X3);
Z3 = Fp.mul(a, t4);
X3 = Fp.mul(b3, t2);
Z3 = Fp.add(X3, Z3);
X3 = Fp.sub(t1, Z3);
Z3 = Fp.add(t1, Z3);
Y3 = Fp.mul(X3, Z3);
t1 = Fp.add(t0, t0);
t1 = Fp.add(t1, t0);
t2 = Fp.mul(a, t2);
t4 = Fp.mul(b3, t4);
t1 = Fp.add(t1, t2);
t2 = Fp.sub(t0, t2);
t2 = Fp.mul(a, t2);
t4 = Fp.add(t4, t2);
t0 = Fp.mul(t1, t4);
Y3 = Fp.add(Y3, t0);
t0 = Fp.mul(t5, t4);
X3 = Fp.mul(t3, X3);
X3 = Fp.sub(X3, t0);
t0 = Fp.mul(t3, t1);
Z3 = Fp.mul(t5, Z3);
Z3 = Fp.add(Z3, t0);
return new Point(X3, Y3, Z3);
}
subtract(other) {
return this.add(other.negate());
}
is0() {
return this.equals(Point.ZERO);
}
/**
* Constant time multiplication.
* Uses wNAF method. Windowed method may be 10% faster,
* but takes 2x longer to generate and consumes 2x memory.
* Uses precomputes when available.
* Uses endomorphism for Koblitz curves.
* @param scalar by which the point would be multiplied
* @returns New point
*/
multiply(scalar) {
const { endo } = extraOpts;
if (!Fn.isValidNot0(scalar)) throw new Error("invalid scalar: out of range");
let point, fake;
const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));
/** See docs for {@link EndomorphismOpts} */
if (endo) {
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);
const { p: k1p, f: k1f } = mul(k1);
const { p: k2p, f: k2f } = mul(k2);
fake = k1f.add(k2f);
point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);
} else {
const { p, f } = mul(scalar);
point = p;
fake = f;
}
return normalizeZ(Point, [point, fake])[0];
}
/**
* Non-constant-time multiplication. Uses double-and-add algorithm.
* It's faster, but should only be used when you don't care about
* an exposed secret key e.g. sig verification, which works over *public* keys.
*/
multiplyUnsafe(sc) {
const { endo } = extraOpts;
const p = this;
if (!Fn.isValid(sc)) throw new Error("invalid scalar: out of range");
if (sc === _0n || p.is0()) return Point.ZERO;
if (sc === _1n) return p;
if (wnaf.hasCache(this)) return this.multiply(sc);
if (endo) {
const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);
const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2);
return finishEndo(endo.beta, p1, p2, k1neg, k2neg);
} else return wnaf.unsafe(p, sc);
}
multiplyAndAddUnsafe(Q, a, b) {
const sum = this.multiplyUnsafe(a).add(Q.multiplyUnsafe(b));
return sum.is0() ? void 0 : sum;
}
/**
* Converts Projective point to affine (x, y) coordinates.
* @param invertedZ Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch
*/
toAffine(invertedZ) {
return toAffineMemo(this, invertedZ);
}
/**
* Checks whether Point is free of torsion elements (is in prime subgroup).
* Always torsion-free for cofactor=1 curves.
*/
isTorsionFree() {
const { isTorsionFree } = extraOpts;
if (cofactor === _1n) return true;
if (isTorsionFree) return isTorsionFree(Point, this);
return wnaf.unsafe(this, CURVE_ORDER).is0();
}
clearCofactor() {
const { clearCofactor } = extraOpts;
if (cofactor === _1n) return this;
if (clearCofactor) return clearCofactor(Point, this);
return this.multiplyUnsafe(cofactor);
}
isSmallOrder() {
return this.multiplyUnsafe(cofactor).is0();
}
toBytes(isCompressed = true) {
_abool2(isCompressed, "isCompressed");
this.assertValidity();
return encodePoint(Point, this, isCompressed);
}
toHex(isCompressed = true) {
return bytesToHex(this.toBytes(isCompressed));
}
toString() {
return `<Point ${this.is0() ? "ZERO" : this.toHex()}>`;
}
get px() {
return this.X;
}
get py() {
return this.X;
}
get pz() {
return this.Z;
}
toRawBytes(isCompressed = true) {
return this.toBytes(isCompressed);
}
_setWindowSize(windowSize) {
this.precompute(windowSize);
}
static normalizeZ(points) {
return normalizeZ(Point, points);
}
static msm(points, scalars) {
return pippenger(Point, Fn, points, scalars);
}
static fromPrivateKey(privateKey) {
return Point.BASE.multiply(_normFnElement(Fn, privateKey));
}
}
Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);
Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);
Point.Fp = Fp;
Point.Fn = Fn;
const bits = Fn.BITS;
const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);
Point.BASE.precompute(8);
return Point;
}
function pprefix(hasEvenY) {
return Uint8Array.of(hasEvenY ? 2 : 3);
}
function getWLengths(Fp, Fn) {
return {
secretKey: Fn.BYTES,
publicKey: 1 + Fp.BYTES,
publicKeyUncompressed: 1 + 2 * Fp.BYTES,
publicKeyHasPrefix: true,
signature: 2 * Fn.BYTES
};
}
/**
* Sometimes users only need getPublicKey, getSharedSecret, and secret key handling.
* This helper ensures no signature functionality is present. Less code, smaller bundle size.
*/
function ecdh(Point, ecdhOpts = {}) {
const { Fn } = Point;
const randomBytes_ = ecdhOpts.randomBytes || randomBytes$2;
const lengths = Object.assign(getWLengths(Point.Fp, Fn), { seed: getMinHashLength(Fn.ORDER) });
function isValidSecretKey(secretKey) {
try {
return !!_normFnElement(Fn, secretKey);
} catch (error) {
return false;
}
}
function isValidPublicKey(publicKey, isCompressed) {
const { publicKey: comp, publicKeyUncompressed } = lengths;
try {
const l = publicKey.length;
if (isCompressed === true && l !== comp) return false;
if (isCompressed === false && l !== publicKeyUncompressed) return false;
return !!Point.fromBytes(publicKey);
} catch (error) {
return false;
}
}
/**
* Produces cryptographically secure secret key from random of size
* (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.
*/
function randomSecretKey(seed = randomBytes_(lengths.seed)) {
return mapHashToField(_abytes2(seed, lengths.seed, "seed"), Fn.ORDER);
}
/**
* Computes public key for a secret key. Checks for validity of the secret key.
* @param isCompressed whether to return compact (default), or full key
* @returns Public key, full when isCompressed=false; short when isCompressed=true
*/
function getPublicKey(secretKey, isCompressed = true) {
return Point.BASE.multiply(_normFnElement(Fn, secretKey)).toBytes(isCompressed);
}
function keygen(seed) {
const secretKey = randomSecretKey(seed);
return {
secretKey,
publicKey: getPublicKey(secretKey)
};
}
/**
* Quick and dirty check for item being public key. Does not validate hex, or being on-curve.
*/
function isProbPub(item) {
if (typeof item === "bigint") return false;
if (item instanceof Point) return true;
const { secretKey, publicKey, publicKeyUncompressed } = lengths;
if (Fn.allowedLengths || secretKey === publicKey) return void 0;
const l = ensureBytes("key", item).length;
return l === publicKey || l === publicKeyUncompressed;
}
/**
* ECDH (Elliptic Curve Diffie Hellman).
* Computes shared public key from secret key A and public key B.
* Checks: 1) secret key validity 2) shared key is on-curve.
* Does NOT hash the result.
* @param isCompressed whether to return compact (default), or full key
* @returns shared public key
*/
function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) {
if (isProbPub(secretKeyA) === true) throw new Error("first arg must be private key");
if (isProbPub(publicKeyB) === false) throw new Error("second arg must be public key");
const s = _normFnElement(Fn, secretKeyA);
return Point.fromHex(publicKeyB).multiply(s).toBytes(isCompressed);
}
return Object.freeze({
getPublicKey,
getSharedSecret,
keygen,
Point,
utils: {
isValidSecretKey,
isValidPublicKey,
randomSecretKey,
isValidPrivateKey: isValidSecretKey,
randomPrivateKey: randomSecretKey,
normPrivateKeyToScalar: (key) => _normFnElement(Fn, key),
precompute(windowSize = 8, point = Point.BASE) {
return point.precompute(windowSize, false);
}
},
lengths
});
}
/**
* Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function.
* We need `hash` for 2 features:
* 1. Message prehash-ing. NOT used if `sign` / `verify` are called with `prehash: false`
* 2. k generation in `sign`, using HMAC-drbg(hash)
*
* ECDSAOpts are only rarely needed.
*
* @example
* ```js
* const p256_Point = weierstrass(...);
* const p256_sha256 = ecdsa(p256_Point, sha256);
* const p256_sha224 = ecdsa(p256_Point, sha224);
* const p256_sha224_r = ecdsa(p256_Point, sha224, { randomBytes: (length) => { ... } });
* ```
*/
function ecdsa(Point, hash, ecdsaOpts = {}) {
ahash(hash);
_validateObject(ecdsaOpts, {}, {
hmac: "function",
lowS: "boolean",
randomBytes: "function",
bits2int: "function",
bits2int_modN: "function"
});
const randomBytes = ecdsaOpts.randomBytes || randomBytes$2;
const hmac = ecdsaOpts.hmac || ((key, ...msgs) => hmac$1(hash, key, concatBytes(...msgs)));
const { Fp, Fn } = Point;
const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;
const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);
const defaultSigOpts = {
prehash: false,
lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : false,
format: void 0,
extraEntropy: false
};
const defaultSigOpts_format = "compact";
function isBiggerThanHalfOrder(number) {
return number > CURVE_ORDER >> _1n;
}
function validateRS(title, num) {
if (!Fn.isValidNot0(num)) throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`);
return num;
}
function validateSigLength(bytes, format) {
validateSigFormat(format);
const size = lengths.signature;
return _abytes2(bytes, format === "compact" ? size : format === "recovered" ? size + 1 : void 0, `${format} signature`);
}
/**
* ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.
*/
class Signature {
constructor(r, s, recovery) {
this.r = validateRS("r", r);
this.s = validateRS("s", s);
if (recovery != null) this.recovery = recovery;
Object.freeze(this);
}
static fromBytes(bytes, format = defaultSigOpts_format) {
validateSigLength(bytes, format);
let recid;
if (format === "der") {
const { r, s } = DER.toSig(_abytes2(bytes));
return new Signature(r, s);
}
if (format === "recovered") {
recid = bytes[0];
format = "compact";
bytes = bytes.subarray(1);
}
const L = Fn.BYTES;
const r = bytes.subarray(0, L);
const s = bytes.subarray(L, L * 2);
return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid);
}
static fromHex(hex, format) {
return this.fromBytes(hexToBytes(hex), format);
}
addRecoveryBit(recovery) {
return new Signature(this.r, this.s, recovery);
}
recoverPublicKey(messageHash) {
const FIELD_ORDER = Fp.ORDER;
const { r, s, recovery: rec } = this;
if (rec == null || ![
0,
1,
2,
3
].includes(rec)) throw new Error("recovery id invalid");
if (CURVE_ORDER * _2n < FIELD_ORDER && rec > 1) throw new Error("recovery id is ambiguous for h>1 curve");
const radj = rec === 2 || rec === 3 ? r + CURVE_ORDER : r;
if (!Fp.isValid(radj)) throw new Error("recovery id 2 or 3 invalid");
const x = Fp.toBytes(radj);
const R = Point.fromBytes(concatBytes(pprefix((rec & 1) === 0), x));
const ir = Fn.inv(radj);
const h = bits2int_modN(ensureBytes("msgHash", messageHash));
const u1 = Fn.create(-h * ir);
const u2 = Fn.create(s * ir);
const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));
if (Q.is0()) throw new Error("point at infinify");
Q.assertValidity();
return Q;
}
hasHighS() {
return isBiggerThanHalfOrder(this.s);
}
toBytes(format = defaultSigOpts_format) {
validateSigFormat(format);
if (format === "der") return hexToBytes(DER.hexFromSig(this));
const r = Fn.toBytes(this.r);
const s = Fn.toBytes(this.s);
if (format === "recovered") {
if (this.recovery == null) throw new Error("recovery bit must be present");
return concatBytes(Uint8Array.of(this.recovery), r, s);
}
return concatBytes(r, s);
}
toHex(format) {
return bytesToHex(this.toBytes(format));
}
assertValidity() {}
static fromCompact(hex) {
return Signature.fromBytes(ensureBytes("sig", hex), "compact");
}
static fromDER(hex) {
return Signature.fromBytes(ensureBytes("sig", hex), "der");
}
normalizeS() {
return this.hasHighS() ? new Signature(this.r, Fn.neg(this.s), this.recovery) : this;
}
toDERRawBytes() {
return this.toBytes("der");
}
toDERHex() {
return bytesToHex(this.toBytes("der"));
}
toCompactRawBytes() {
return this.toBytes("compact");
}
toCompactHex() {
return bytesToHex(this.toBytes("compact"));
}
}
const bits2int = ecdsaOpts.bits2int || function bits2int_def(bytes) {
if (bytes.length > 8192) throw new Error("input is too large");
const num = bytesToNumberBE(bytes);
const delta = bytes.length * 8 - fnBits;
return delta > 0 ? num >> BigInt(delta) : num;
};
const bits2int_modN = ecdsaOpts.bits2int_modN || function bits2int_modN_def(bytes) {
return Fn.create(bits2int(bytes));
};
const ORDER_MASK = bitMask(fnBits);
/** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */
function int2octets(num) {
aInRange("num < 2^" + fnBits, num, _0n, ORDER_MASK);
return Fn.toBytes(num);
}
function validateMsgAndHash(message, prehash) {
_abytes2(message, void 0, "message");
return prehash ? _abytes2(hash(message), void 0, "prehashed message") : message;
}
/**
* Steps A, D of RFC6979 3.2.
* Creates RFC6979 seed; converts msg/privKey to numbers.
* Used only in sign, not in verify.
*
* Warning: we cannot assume here that message has same amount of bytes as curve order,
* this will be invalid at least for P521. Also it can be bigger for P224 + SHA256.
*/
function prepSig(message, privateKey, opts) {
if (["recovered", "canonical"].some((k) => k in opts)) throw new Error("sign() legacy options not supported");
const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts);
message = validateMsgAndHash(message, prehash);
const h1int = bits2int_modN(message);
const d = _normFnElement(Fn, privateKey);
const seedArgs = [int2octets(d), int2octets(h1int)];
if (extraEntropy != null && extraEntropy !== false) {
const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy;
seedArgs.push(ensureBytes("extraEntropy", e));
}
const seed = concatBytes(...seedArgs);
const m = h1int;
function k2sig(kBytes) {
const k = bits2int(kBytes);
if (!Fn.isValidNot0(k)) return;
const ik = Fn.inv(k);
const q = Point.BASE.multiply(k).toAffine();
const r = Fn.create(q.x);
if (r === _0n) return;
const s = Fn.create(ik * Fn.create(m + r * d));
if (s === _0n) return;
let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n);
let normS = s;
if (lowS && isBiggerThanHalfOrder(s)) {
normS = Fn.neg(s);
recovery ^= 1;
}
return new Signature(r, normS, recovery);
}
return {
seed,
k2sig
};
}
/**
* Signs message hash with a secret key.
*
* ```
* sign(m, d) where
* k = rfc6979_hmac_drbg(m, d)
* (x, y) = G × k
* r = x mod n
* s = (m + dr) / k mod n
* ```
*/
function sign(message, secretKey, opts = {}) {
message = ensureBytes("message", message);
const { seed, k2sig } = prepSig(message, secretKey, opts);
return createHmacDrbg(hash.outputLen, Fn.BYTES, hmac)(seed, k2sig);
}
function tryParsingSig(sg) {
let sig = void 0;
const isHex = typeof sg === "string" || isBytes(sg);
const isObj = !isHex && sg !== null && typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint";
if (!isHex && !isObj) throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");
if (isObj) sig = new Signature(sg.r, sg.s);
else if (isHex) {
try {
sig = Signature.fromBytes(ensureBytes("sig", sg), "der");
} catch (derError) {
if (!(derError instanceof DER.Err)) throw derError;
}
if (!sig) try {
sig = Signature.fromBytes(ensureBytes("sig", sg), "compact");
} catch (error) {
return false;
}
}
if (!sig) return false;
return sig;
}
/**
* Verifies a signature against message and public key.
* Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}.
* Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:
*
* ```
* verify(r, s, h, P) where
* u1 = hs^-1 mod n
* u2 = rs^-1 mod n
* R = u1⋅G + u2⋅P
* mod(R.x, n) == r
* ```
*/
function verify(signature, message, publicKey, opts = {}) {
const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);
publicKey = ensureBytes("publicKey", publicKey);
message = validateMsgAndHash(ensureBytes("message", message), prehash);
if ("strict" in opts) throw new Error("options.strict was renamed to lowS");
const sig = format === void 0 ? tryParsingSig(signature) : Signature.fromBytes(ensureBytes("sig", signature), format);
if (sig === false) return false;
try {
const P = Point.fromBytes(publicKey);
if (lowS && sig.hasHighS()) return false;
const { r, s } = sig;
const h = bits2int_modN(message);
const is = Fn.inv(s);
const u1 = Fn.create(h * is);
const u2 = Fn.create(r * is);
const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2));
if (R.is0()) return false;
return Fn.create(R.x) === r;
} catch (e) {
return false;
}
}
function recoverPublicKey(signature, message, opts = {}) {
const { prehash } = validateSigOpts(opts, defaultSigOpts);
message = validateMsgAndHash(message, prehash);
return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes();
}
return Object.freeze({
keygen,
getPublicKey,
getSharedSecret,
utils,
lengths,
Point,
sign,
verify,
recoverPublicKey,
Signature,
hash
});
}
function _weierstrass_legacy_opts_to_new(c) {
const CURVE = {
a: c.a,
b: c.b,
p: c.Fp.ORDER,
n: c.n,
h: c.h,
Gx: c.Gx,
Gy: c.Gy
};
const Fp = c.Fp;
let allowedLengths = c.allowedPrivateKeyLengths ? Array.from(new Set(c.allowedPrivateKeyLengths.map((l) => Math.ceil(l / 2)))) : void 0;
return {
CURVE,
curveOpts: {
Fp,
Fn: Field(CURVE.n, {
BITS: c.nBitLength,
allowedLengths,
modFromBytes: c.wrapPrivateKey
}),
allowInfinityPoint: c.allowInfinityPoint,
endo: c.endo,
isTorsionFree: c.isTorsionFree,
clearCofactor: c.clearCofactor,
fromBytes: c.fromBytes,
toBytes: c.toBytes
}
};
}
function _ecdsa_legacy_opts_to_new(c) {
const { CURVE, curveOpts } = _weierstrass_legacy_opts_to_new(c);
const ecdsaOpts = {
hmac: c.hmac,
randomBytes: c.randomBytes,
lowS: c.lowS,
bits2int: c.bits2int,
bits2int_modN: c.bits2int_modN
};
return {
CURVE,
curveOpts,
hash: c.hash,
ecdsaOpts
};
}
function _ecdsa_new_output_to_legacy(c, _ecdsa) {
const Point = _ecdsa.Point;
return Object.assign({}, _ecdsa, {
ProjectivePoint: Point,
CURVE: Object.assign({}, c, nLength(Point.Fn.ORDER, Point.Fn.BITS))
});
}
function weierstrass(c) {
const { CURVE, curveOpts, hash, ecdsaOpts } = _ecdsa_legacy_opts_to_new(c);
return _ecdsa_new_output_to_legacy(c, ecdsa(weierstrassN(CURVE, curveOpts), hash, ecdsaOpts));
}
//#endregion
//#region node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/_shortw_utils.js
/**
* Utilities for short weierstrass curves, combined with noble-hashes.
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
/** @deprecated use new `weierstrass()` and `ecdsa()` methods */
function createCurve(curveDef, defHash) {
const create = (hash) => weierstrass({
...curveDef,
hash
});
return {
...create(defHash),
create
};
}
//#endregion
//#region node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/nist.js
/**
* Internal module for NIST P256, P384, P521 curves.
* Do not use for now.
* @module
*/
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
const p256_CURVE = {
p: BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),
n: BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),
h: BigInt(1),
a: BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),
b: BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),
Gx: BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),
Gy: BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")
};
const p384_CURVE = {
p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),
n: BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),
h: BigInt(1),
a: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),
b: BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),
Gx: BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),
Gy: BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")
};
const p521_CURVE = {
p: BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
n: BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),
h: BigInt(1),
a: BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),
b: BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),
Gx: BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),
Gy: BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")
};
const Fp256 = Field(p256_CURVE.p);
const Fp384 = Field(p384_CURVE.p);
const Fp521 = Field(p521_CURVE.p);
/** NIST P256 (aka secp256r1, prime256v1) curve, ECDSA and ECDH methods. */
const p256$1 = createCurve({
...p256_CURVE,
Fp: Fp256,
lowS: false
}, sha256);
createCurve({
...p384_CURVE,
Fp: Fp384,
lowS: false
}, sha384);
createCurve({
...p521_CURVE,
Fp: Fp521,
lowS: false,
allowedPrivateKeyLengths: [
130,
131,
132
]
}, sha512);
//#endregion
//#region node_modules/.pnpm/@noble+curves@1.9.7/node_modules/@noble/curves/esm/p256.js
/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
/** @deprecated use `import { p256 } from '@noble/curves/nist.js';` */
const p256 = p256$1;
//#endregion
//#region node_modules/.pnpm/dns-packet@5.6.1/node_modules/dns-packet/types.js
var require_types = /* @__PURE__ */ __commonJSMin(((exports) => {
exports.toString = function(type) {
switch (type) {
case 1: return "A";
case 10: return "NULL";
case 28: return "AAAA";
case 18: return "AFSDB";
case 42: return "APL";
case 257: return "CAA";
case 60: return "CDNSKEY";
case 59: return "CDS";
case 37: return "CERT";
case 5: return "CNAME";
case 49: return "DHCID";
case 32769: return "DLV";
case 39: return "DNAME";
case 48: return "DNSKEY";
case 43: return "DS";
case 55: return "HIP";
case 13: return "HINFO";
case 45: return "IPSECKEY";
case 25: return "KEY";
case 36: return "KX";
case 29: return "LOC";
case 15: return "MX";
case 35: return "NAPTR";
case 2: return "NS";
case 47: return "NSEC";
case 50: return "NSEC3";
case 51: return "NSEC3PARAM";
case 12: return "PTR";
case 46: return "RRSIG";
case 17: return "RP";
case 24: return "SIG";
case 6: return "SOA";
case 99: return "SPF";
case 33: return "SRV";
case 44: return "SSHFP";
case 32768: return "TA";
case 249: return "TKEY";
case 52: return "TLSA";
case 250: return "TSIG";
case 16: return "TXT";
case 252: return "AXFR";
case 251: return "IXFR";
case 41: return "OPT";
case 255: return "ANY";
}
return "UNKNOWN_" + type;
};
exports.toType = function(name) {
switch (name.toUpperCase()) {
case "A": return 1;
case "NULL": return 10;
case "AAAA": return 28;
case "AFSDB": return 18;
case "APL": return 42;
case "CAA": return 257;
case "CDNSKEY": return 60;
case "CDS": return 59;
case "CERT": return 37;
case "CNAME": return 5;
case "DHCID": return 49;
case "DLV": return 32769;
case "DNAME": return 39;
case "DNSKEY": return 48;
case "DS": return 43;
case "HIP": return 55;
case "HINFO": return 13;
case "IPSECKEY": return 45;
case "KEY": return 25;
case "KX": return 36;
case "LOC": return 29;
case "MX": return 15;
case "NAPTR": return 35;
case "NS": return 2;
case "NSEC": return 47;
case "NSEC3": return 50;
case "NSEC3PARAM": return 51;
case "PTR": return 12;
case "RRSIG": return 46;
case "RP": return 17;
case "SIG": return 24;
case "SOA": return 6;
case "SPF": return 99;
case "SRV": return 33;
case "SSHFP": return 44;
case "TA": return 32768;
case "TKEY": return 249;
case "TLSA": return 52;
case "TSIG": return 250;
case "TXT": return 16;
case "AXFR": return 252;
case "IXFR": return 251;
case "OPT": return 41;
case "ANY": return 255;
case "*": return 255;
}
if (name.toUpperCase().startsWith("UNKNOWN_")) return parseInt(name.slice(8));
return 0;
};
}));
//#endregion
//#region node_modules/.pnpm/dns-packet@5.6.1/node_modules/dns-packet/rcodes.js
var require_rcodes = /* @__PURE__ */ __commonJSMin(((exports) => {
exports.toString = function(rcode) {
switch (rcode) {
case 0: return "NOERROR";
case 1: return "FORMERR";
case 2: return "SERVFAIL";
case 3: return "NXDOMAIN";
case 4: return "NOTIMP";
case 5: return "REFUSED";
case 6: return "YXDOMAIN";
case 7: return "YXRRSET";
case 8: return "NXRRSET";
case 9: return "NOTAUTH";
case 10: return "NOTZONE";
case 11: return "RCODE_11";
case 12: return "RCODE_12";
case 13: return "RCODE_13";
case 14: return "RCODE_14";
case 15: return "RCODE_15";
}
return "RCODE_" + rcode;
};
exports.toRcode = function(code) {
switch (code.toUpperCase()) {
case "NOERROR": return 0;
case "FORMERR": return 1;
case "SERVFAIL": return 2;
case "NXDOMAIN": return 3;
case "NOTIMP": return 4;
case "REFUSED": return 5;
case "YXDOMAIN": return 6;
case "YXRRSET": return 7;
case "NXRRSET": return 8;
case "NOTAUTH": return 9;
case "NOTZONE": return 10;
case "RCODE_11": return 11;
case "RCODE_12": return 12;
case "RCODE_13": return 13;
case "RCODE_14": return 14;
case "RCODE_15": return 15;
}
return 0;
};
}));
//#endregion
//#region node_modules/.pnpm/dns-packet@5.6.1/node_modules/dns-packet/opcodes.js
var require_opcodes = /* @__PURE__ */ __commonJSMin(((exports) => {
exports.toString = function(opcode) {
switch (opcode) {
case 0: return "QUERY";
case 1: return "IQUERY";
case 2: return "STATUS";
case 3: return "OPCODE_3";
case 4: return "NOTIFY";
case 5: return "UPDATE";
case 6: return "OPCODE_6";
case 7: return "OPCODE_7";
case 8: return "OPCODE_8";
case 9: return "OPCODE_9";
case 10: return "OPCODE_10";
case 11: return "OPCODE_11";
case 12: return "OPCODE_12";
case 13: return "OPCODE_13";
case 14: return "OPCODE_14";
case 15: return "OPCODE_15";
}
return "OPCODE_" + opcode;
};
exports.toOpcode = function(code) {
switch (code.toUpperCase()) {
case "QUERY": return 0;
case "IQUERY": return 1;
case "STATUS": return 2;
case "OPCODE_3": return 3;
case "NOTIFY": return 4;
case "UPDATE": return 5;
case "OPCODE_6": return 6;
case "OPCODE_7": return 7;
case "OPCODE_8": return 8;
case "OPCODE_9": return 9;
case "OPCODE_10": return 10;
case "OPCODE_11": return 11;
case "OPCODE_12": return 12;
case "OPCODE_13": return 13;
case "OPCODE_14": return 14;
case "OPCODE_15": return 15;
}
return 0;
};
}));
//#endregion
//#region node_modules/.pnpm/dns-packet@5.6.1/node_modules/dns-packet/classes.js
var require_classes = /* @__PURE__ */ __commonJSMin(((exports) => {
exports.toString = function(klass) {
switch (klass) {
case 1: return "IN";
case 2: return "CS";
case 3: return "CH";
case 4: return "HS";
case 255: return "ANY";
}
return "UNKNOWN_" + klass;
};
exports.toClass = function(name) {
switch (name.toUpperCase()) {
case "IN": return 1;
case "CS": return 2;
case "CH": return 3;
case "HS": return 4;
case "ANY": return 255;
}
return 0;
};
}));
//#endregion
//#region node_modules/.pnpm/dns-packet@5.6.1/node_modules/dns-packet/optioncodes.js
var require_optioncodes = /* @__PURE__ */ __commonJSMin(((exports) => {
exports.toString = function(type) {
switch (type) {
case 1: return "LLQ";
case 2: return "UL";
case 3: return "NSID";
case 5: return "DAU";
case 6: return "DHU";
case 7: return "N3U";
case 8: return "CLIENT_SUBNET";
case 9: return "EXPIRE";
case 10: return "COOKIE";
case 11: return "TCP_KEEPALIVE";
case 12: return "PADDING";
case 13: return "CHAIN";
case 14: return "KEY_TAG";
case 26946: return "DEVICEID";
}
if (type < 0) return null;
return `OPTION_${type}`;
};
exports.toCode = function(name) {
if (typeof name === "number") return name;
if (!name) return -1;
switch (name.toUpperCase()) {
case "OPTION_0": return 0;
case "LLQ": return 1;
case "UL": return 2;
case "NSID": return 3;
case "OPTION_4": return 4;
case "DAU": return 5;
case "DHU": return 6;
case "N3U": return 7;
case "CLIENT_SUBNET": return 8;
case "EXPIRE": return 9;
case "COOKIE": return 10;
case "TCP_KEEPALIVE": return 11;
case "PADDING": return 12;
case "CHAIN": return 13;
case "KEY_TAG": return 14;
case "DEVICEID": return 26946;
case "OPTION_65535": return 65535;
}
const m = name.match(/_(\d+)$/);
if (m) return parseInt(m[1], 10);
return -1;
};
}));
//#endregion
//#region node_modules/.pnpm/@leichtgewicht+ip-codec@2.0.5/node_modules/@leichtgewicht/ip-codec/index.cjs
var require_ip_codec = /* @__PURE__ */ __commonJSMin(((exports, module) => {
var ipCodec = (function(exports$1) {
"use strict";
Object.defineProperty(exports$1, "__esModule", { value: true });
exports$1.decode = decode;
exports$1.encode = encode;
exports$1.familyOf = familyOf;
exports$1.name = void 0;
exports$1.sizeOf = sizeOf;
exports$1.v6 = exports$1.v4 = void 0;
const v4Regex = /^(\d{1,3}\.){3,3}\d{1,3}$/;
const v4Size = 4;
const v6Regex = /^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i;
const v6Size = 16;
const v4 = {
name: "v4",
size: v4Size,
isFormat: (ip) => v4Regex.test(ip),
encode(ip, buff, offset) {
offset = ~~offset;
buff = buff || new Uint8Array(offset + v4Size);
const max = ip.length;
let n = 0;
for (let i = 0; i < max;) {
const c = ip.charCodeAt(i++);
if (c === 46) {
buff[offset++] = n;
n = 0;
} else n = n * 10 + (c - 48);
}
buff[offset] = n;
return buff;
},
decode(buff, offset) {
offset = ~~offset;
return `${buff[offset++]}.${buff[offset++]}.${buff[offset++]}.${buff[offset]}`;
}
};
exports$1.v4 = v4;
const v6 = {
name: "v6",
size: v6Size,
isFormat: (ip) => ip.length > 0 && v6Regex.test(ip),
encode(ip, buff, offset) {
offset = ~~offset;
let end = offset + v6Size;
let fill = -1;
let hexN = 0;
let decN = 0;
let prevColon = true;
let useDec = false;
buff = buff || new Uint8Array(offset + v6Size);
for (let i = 0; i < ip.length; i++) {
let c = ip.charCodeAt(i);
if (c === 58) {
if (prevColon) {
if (fill !== -1) {
if (offset < end) buff[offset] = 0;
if (offset < end - 1) buff[offset + 1] = 0;
offset += 2;
} else if (offset < end) fill = offset;
} else {
if (useDec === true) {
if (offset < end) buff[offset] = decN;
offset++;
} else {
if (offset < end) buff[offset] = hexN >> 8;
if (offset < end - 1) buff[offset + 1] = hexN & 255;
offset += 2;
}
hexN = 0;
decN = 0;
}
prevColon = true;
useDec = false;
} else if (c === 46) {
if (offset < end) buff[offset] = decN;
offset++;
decN = 0;
hexN = 0;
prevColon = false;
useDec = true;
} else {
prevColon = false;
if (c >= 97) c -= 87;
else if (c >= 65) c -= 55;
else {
c -= 48;
decN = decN * 10 + c;
}
hexN = (hexN << 4) + c;
}
}
if (prevColon === false) {
if (useDec === true) {
if (offset < end) buff[offset] = decN;
offset++;
} else {
if (offset < end) buff[offset] = hexN >> 8;
if (offset < end - 1) buff[offset + 1] = hexN & 255;
offset += 2;
}
} else if (fill === 0) {
if (offset < end) buff[offset] = 0;
if (offset < end - 1) buff[offset + 1] = 0;
offset += 2;
} else if (fill !== -1) {
offset += 2;
for (let i = Math.min(offset - 1, end - 1); i >= fill + 2; i--) buff[i] = buff[i - 2];
buff[fill] = 0;
buff[fill + 1] = 0;
fill = offset;
}
if (fill !== offset && fill !== -1) {
if (offset > end - 2) offset = end - 2;
while (end > fill) buff[--end] = offset < end && offset > fill ? buff[--offset] : 0;
} else while (offset < end) buff[offset++] = 0;
return buff;
},
decode(buff, offset) {
offset = ~~offset;
let result = "";
for (let i = 0; i < v6Size; i += 2) {
if (i !== 0) result += ":";
result += (buff[offset + i] << 8 | buff[offset + i + 1]).toString(16);
}
return result.replace(/(^|:)0(:0)*:0(:|$)/, "$1::$3").replace(/:{3,4}/, "::");
}
};
exports$1.v6 = v6;
exports$1.name = "ip";
function sizeOf(ip) {
if (v4.isFormat(ip)) return v4.size;
if (v6.isFormat(ip)) return v6.size;
throw Error(`Invalid ip address: ${ip}`);
}
function familyOf(string) {
return sizeOf(string) === v4.size ? 1 : 2;
}
function encode(ip, buff, offset) {
offset = ~~offset;
const size = sizeOf(ip);
if (typeof buff === "function") buff = buff(offset + size);
if (size === v4.size) return v4.encode(ip, buff, offset);
return v6.encode(ip, buff, offset);
}
function decode(buff, offset, length) {
offset = ~~offset;
length = length || buff.length - offset;
if (length === v4.size) return v4.decode(buff, offset, length);
if (length === v6.size) return v6.decode(buff, offset, length);
throw Error(`Invalid buffer size needs to be ${v4.size} for v4 or ${v6.size} for v6.`);
}
return "default" in exports$1 ? exports$1.default : exports$1;
})({});
if (typeof define === "function" && define.amd) define([], function() {
return ipCodec;
});
else if (typeof module === "object" && typeof exports === "object") module.exports = ipCodec;
}));
//#endregion
//#region node_modules/.pnpm/dns-packet@5.6.1/node_modules/dns-packet/index.js
var require_dns_packet = /* @__PURE__ */ __commonJSMin(((exports) => {
const Buffer$1 = __require("buffer").Buffer;
const types = require_types();
const rcodes = require_rcodes();
const opcodes = require_opcodes();
const classes = require_classes();
const optioncodes = require_optioncodes();
const ip = require_ip_codec();
const QUERY_FLAG = 0;
const RESPONSE_FLAG = 32768;
const FLUSH_MASK = 32768;
const NOT_FLUSH_MASK = -32769;
const QU_MASK = 32768;
const NOT_QU_MASK = -32769;
const name = exports.name = {};
name.encode = function(str, buf, offset, { mail = false } = {}) {
if (!buf) buf = Buffer$1.alloc(name.encodingLength(str));
if (!offset) offset = 0;
const oldOffset = offset;
const n = str.replace(/^\.|\.$/gm, "");
if (n.length) {
let list = [];
if (mail) {
let localPart = "";
n.split(".").forEach((label) => {
if (label.endsWith("\\")) localPart += (localPart.length ? "." : "") + label.slice(0, -1);
else if (list.length === 0 && localPart.length) list.push(localPart + "." + label);
else list.push(label);
});
} else list = n.split(".");
for (let i = 0; i < list.length; i++) {
const len = buf.write(list[i], offset + 1);
buf[offset] = len;
offset += len + 1;
}
}
buf[offset++] = 0;
name.encode.bytes = offset - oldOffset;
return buf;
};
name.encode.bytes = 0;
name.decode = function(buf, offset, { mail = false } = {}) {
if (!offset) offset = 0;
const list = [];
let oldOffset = offset;
let totalLength = 0;
let consumedBytes = 0;
let jumped = false;
while (true) {
if (offset >= buf.length) throw new Error("Cannot decode name (buffer overflow)");
const len = buf[offset++];
consumedBytes += jumped ? 0 : 1;
if (len === 0) break;
else if ((len & 192) === 0) {
if (offset + len > buf.length) throw new Error("Cannot decode name (buffer overflow)");
totalLength += len + 1;
if (totalLength > 254) throw new Error("Cannot decode name (name too long)");
let label = buf.toString("utf-8", offset, offset + len);
if (mail) label = label.replace(/\./g, "\\.");
list.push(label);
offset += len;
consumedBytes += jumped ? 0 : len;
} else if ((len & 192) === 192) {
if (offset + 1 > buf.length) throw new Error("Cannot decode name (buffer overflow)");
const jumpOffset = buf.readUInt16BE(offset - 1) - 49152;
if (jumpOffset >= oldOffset) throw new Error("Cannot decode name (bad pointer)");
offset = jumpOffset;
oldOffset = jumpOffset;
consumedBytes += jumped ? 0 : 1;
jumped = true;
} else throw new Error("Cannot decode name (bad label)");
}
name.decode.bytes = consumedBytes;
return list.length === 0 ? "." : list.join(".");
};
name.decode.bytes = 0;
name.encodingLength = function(n) {
if (n === "." || n === "..") return 1;
return Buffer$1.byteLength(n.replace(/^\.|\.$/gm, "")) + 2;
};
const string = {};
string.encode = function(s, buf, offset) {
if (!buf) buf = Buffer$1.alloc(string.encodingLength(s));
if (!offset) offset = 0;
const len = buf.write(s, offset + 1);
buf[offset] = len;
string.encode.bytes = len + 1;
return buf;
};
string.encode.bytes = 0;
string.decode = function(buf, offset) {
if (!offset) offset = 0;
const len = buf[offset];
const s = buf.toString("utf-8", offset + 1, offset + 1 + len);
string.decode.bytes = len + 1;
return s;
};
string.decode.bytes = 0;
string.encodingLength = function(s) {
return Buffer$1.byteLength(s) + 1;
};
const header = {};
header.encode = function(h, buf, offset) {
if (!buf) buf = header.encodingLength(h);
if (!offset) offset = 0;
const flags = (h.flags || 0) & 32767;
const type = h.type === "response" ? RESPONSE_FLAG : QUERY_FLAG;
buf.writeUInt16BE(h.id || 0, offset);
buf.writeUInt16BE(flags | type, offset + 2);
buf.writeUInt16BE(h.questions.length, offset + 4);
buf.writeUInt16BE(h.answers.length, offset + 6);
buf.writeUInt16BE(h.authorities.length, offset + 8);
buf.writeUInt16BE(h.additionals.length, offset + 10);
return buf;
};
header.encode.bytes = 12;
header.decode = function(buf, offset) {
if (!offset) offset = 0;
if (buf.length < 12) throw new Error("Header must be 12 bytes");
const flags = buf.readUInt16BE(offset + 2);
return {
id: buf.readUInt16BE(offset),
type: flags & RESPONSE_FLAG ? "response" : "query",
flags: flags & 32767,
flag_qr: (flags >> 15 & 1) === 1,
opcode: opcodes.toString(flags >> 11 & 15),
flag_aa: (flags >> 10 & 1) === 1,
flag_tc: (flags >> 9 & 1) === 1,
flag_rd: (flags >> 8 & 1) === 1,
flag_ra: (flags >> 7 & 1) === 1,
flag_z: (flags >> 6 & 1) === 1,
flag_ad: (flags >> 5 & 1) === 1,
flag_cd: (flags >> 4 & 1) === 1,
rcode: rcodes.toString(flags & 15),
questions: new Array(buf.readUInt16BE(offset + 4)),
answers: new Array(buf.readUInt16BE(offset + 6)),
authorities: new Array(buf.readUInt16BE(offset + 8)),
additionals: new Array(buf.readUInt16BE(offset + 10))
};
};
header.decode.bytes = 12;
header.encodingLength = function() {
return 12;
};
const runknown = exports.unknown = {};
runknown.encode = function(data, buf, offset) {
if (!buf) buf = Buffer$1.alloc(runknown.encodingLength(data));
if (!offset) offset = 0;
buf.writeUInt16BE(data.length, offset);
data.copy(buf, offset + 2);
runknown.encode.bytes = data.length + 2;
return buf;
};
runknown.encode.bytes = 0;
runknown.decode = function(buf, offset) {
if (!offset) offset = 0;
const len = buf.readUInt16BE(offset);
const data = buf.slice(offset + 2, offset + 2 + len);
runknown.decode.bytes = len + 2;
return data;
};
runknown.decode.bytes = 0;
runknown.encodingLength = function(data) {
return data.length + 2;
};
const rns = exports.ns = {};
rns.encode = function(data, buf, offset) {
if (!buf) buf = Buffer$1.alloc(rns.encodingLength(data));
if (!offset) offset = 0;
name.encode(data, buf, offset + 2);
buf.writeUInt16BE(name.encode.bytes, offset);
rns.encode.bytes = name.encode.bytes + 2;
return buf;
};
rns.encode.bytes = 0;
rns.decode = function(buf, offset) {
if (!offset) offset = 0;
const len = buf.readUInt16BE(offset);
const dd = name.decode(buf, offset + 2);
rns.decode.bytes = len + 2;
return dd;
};
rns.decode.bytes = 0;
rns.encodingLength = function(data) {
return name.encodingLength(data) + 2;
};
const rsoa = exports.soa = {};
rsoa.encode = function(data, buf, offset) {
if (!buf) buf = Buffer$1.alloc(rsoa.encodingLength(data));
if (!offset) offset = 0;
const oldOffset = offset;
offset += 2;
name.encode(data.mname, buf, offset);
offset += name.encode.bytes;
name.encode(data.rname, buf, offset, { mail: true });
offset += name.encode.bytes;
buf.writeUInt32BE(data.serial || 0, offset);
offset += 4;
buf.writeUInt32BE(data.refresh || 0, offset);
offset += 4;
buf.writeUInt32BE(data.retry || 0, offset);
offset += 4;
buf.writeUInt32BE(data.expire || 0, offset);
offset += 4;
buf.writeUInt32BE(data.minimum || 0, offset);
offset += 4;
buf.writeUInt16BE(offset - oldOffset - 2, oldOffset);
rsoa.encode.bytes = offset - oldOffset;
return buf;
};
rsoa.encode.bytes = 0;
rsoa.decode = function(buf, offset) {
if (!offset) offset = 0;
const oldOffset = offset;
const data = {};
offset += 2;
data.mname = name.decode(buf, offset);
offset += name.decode.bytes;
data.rname = name.decode(buf, offset, { mail: true });
offset += name.decode.bytes;
data.serial = buf.readUInt32BE(offset);
offset += 4;
data.refresh = buf.readUInt32BE(offset);
offset += 4;
data.retry = buf.readUInt32BE(offset);
offset += 4;
data.expire = buf.readUInt32BE(offset);
offset += 4;
data.minimum = buf.readUInt32BE(offset);
offset += 4;
rsoa.decode.bytes = offset - oldOffset;
return data;
};
rsoa.decode.bytes = 0;
rsoa.encodingLength = function(data) {
return 22 + name.encodingLength(data.mname) + name.encodingLength(data.rname);
};
const rtxt = exports.txt = {};
rtxt.encode = function(data, buf, offset) {
if (!Array.isArray(data)) data = [data];
for (let i = 0; i < data.length; i++) {
if (typeof data[i] === "string") data[i] = Buffer$1.from(data[i]);
if (!Buffer$1.isBuffer(data[i])) throw new Error("Must be a Buffer");
}
if (!buf) buf = Buffer$1.alloc(rtxt.encodingLength(data));
if (!offset) offset = 0;
const oldOffset = offset;
offset += 2;
data.forEach(function(d) {
buf[offset++] = d.length;
d.copy(buf, offset, 0, d.length);
offset += d.length;
});
buf.writeUInt16BE(offset - oldOffset - 2, oldOffset);
rtxt.encode.bytes = offset - oldOffset;
return buf;
};
rtxt.encode.bytes = 0;
rtxt.decode = function(buf, offset) {
if (!offset) offset = 0;
const oldOffset = offset;
let remaining = buf.readUInt16BE(offset);
offset += 2;
let data = [];
while (remaining > 0) {
const len = buf[offset++];
--remaining;
if (remaining < len) throw new Error("Buffer overflow");
data.push(buf.slice(offset, offset + len));
offset += len;
remaining -= len;
}
rtxt.decode.bytes = offset - oldOffset;
return data;
};
rtxt.decode.bytes = 0;
rtxt.encodingLength = function(data) {
if (!Array.isArray(data)) data = [data];
let length = 2;
data.forEach(function(buf) {
if (typeof buf === "string") length += Buffer$1.byteLength(buf) + 1;
else length += buf.length + 1;
});
return length;
};
const rnull = exports.null = {};
rnull.encode = function(data, buf, offset) {
if (!buf) buf = Buffer$1.alloc(rnull.encodingLength(data));
if (!offset) offset = 0;
if (typeof data === "string") data = Buffer$1.from(data);
if (!data) data = Buffer$1.alloc(0);
const oldOffset = offset;
offset += 2;
const len = data.length;
data.copy(buf, offset, 0, len);
offset += len;
buf.writeUInt16BE(offset - oldOffset - 2, oldOffset);
rnull.encode.bytes = offset - oldOffset;
return buf;
};
rnull.encode.bytes = 0;
rnull.decode = function(buf, offset) {
if (!offset) offset = 0;
const oldOffset = offset;
const len = buf.readUInt16BE(offset);
offset += 2;
const data = buf.slice(offset, offset + len);
offset += len;
rnull.decode.bytes = offset - oldOffset;
return data;
};
rnull.decode.bytes = 0;
rnull.encodingLength = function(data) {
if (!data) return 2;
return (Buffer$1.isBuffer(data) ? data.length : Buffer$1.byteLength(data)) + 2;
};
const rhinfo = exports.hinfo = {};
rhinfo.encode = function(data, buf, offset) {
if (!buf) buf = Buffer$1.alloc(rhinfo.encodingLength(data));
if (!offset) offset = 0;
const oldOffset = offset;
offset += 2;
string.encode(data.cpu, buf, offset);
offset += string.encode.bytes;
string.encode(data.os, buf, offset);
offset += string.encode.bytes;
buf.writeUInt16BE(offset - oldOffset - 2, oldOffset);
rhinfo.encode.bytes = offset - oldOffset;
return buf;
};
rhinfo.encode.bytes = 0;
rhinfo.decode = function(buf, offset) {
if (!offset) offset = 0;
const oldOffset = offset;
const data = {};
offset += 2;
data.cpu = string.decode(buf, offset);
offset += string.decode.bytes;
data.os = string.decode(buf, offset);
offset += string.decode.bytes;
rhinfo.decode.bytes = offset - oldOffset;
return data;
};
rhinfo.decode.bytes = 0;
rhinfo.encodingLength = function(data) {
return string.encodingLength(data.cpu) + string.encodingLength(data.os) + 2;
};
const rptr = exports.ptr = {};
const rcname = exports.cname = rptr;
const rdname = exports.dname = rptr;
rptr.encode = function(data, buf, offset) {
if (!buf) buf = Buffer$1.alloc(rptr.encodingLength(data));
if (!offset) offset = 0;
name.encode(data, buf, offset + 2);
buf.writeUInt16BE(name.encode.bytes, offset);
rptr.encode.bytes = name.encode.bytes + 2;
return buf;
};
rptr.encode.bytes = 0;
rptr.decode = function(buf, offset) {
if (!offset) offset = 0;
const data = name.decode(buf, offset + 2);
rptr.decode.bytes = name.decode.bytes + 2;
return data;
};
rptr.decode.bytes = 0;
rptr.encodingLength = function(data) {
return name.encodingLength(data) + 2;
};
const rsrv = exports.srv = {};
rsrv.encode = function(data, buf, offset) {
if (!buf) buf = Buffer$1.alloc(rsrv.encodingLength(data));
if (!offset) offset = 0;
buf.writeUInt16BE(data.priority || 0, offset + 2);
buf.writeUInt16BE(data.weight || 0, offset + 4);
buf.writeUInt16BE(data.port || 0, offset + 6);
name.encode(data.target, buf, offset + 8);
const len = name.encode.bytes + 6;
buf.writeUInt16BE(len, offset);
rsrv.encode.bytes = len + 2;
return buf;
};
rsrv.encode.bytes = 0;
rsrv.decode = function(buf, offset) {
if (!offset) offset = 0;
const len = buf.readUInt16BE(offset);
const data = {};
data.priority = buf.readUInt16BE(offset + 2);
data.weight = buf.readUInt16BE(offset + 4);
data.port = buf.readUInt16BE(offset + 6);
data.target = name.decode(buf, offset + 8);
rsrv.decode.bytes = len + 2;
return data;
};
rsrv.decode.bytes = 0;
rsrv.encodingLength = function(data) {
return 8 + name.encodingLength(data.target);
};
const rcaa = exports.caa = {};
rcaa.ISSUER_CRITICAL = 128;
rcaa.encode = function(data, buf, offset) {
const len = rcaa.encodingLength(data);
if (!buf) buf = Buffer$1.alloc(rcaa.encodingLength(data));
if (!offset) offset = 0;
if (data.issuerCritical) data.flags = rcaa.ISSUER_CRITICAL;
buf.writeUInt16BE(len - 2, offset);
offset += 2;
buf.writeUInt8(data.flags || 0, offset);
offset += 1;
string.encode(data.tag, buf, offset);
offset += string.encode.bytes;
buf.write(data.value, offset);
offset += Buffer$1.byteLength(data.value);
rcaa.encode.bytes = len;
return buf;
};
rcaa.encode.bytes = 0;
rcaa.decode = function(buf, offset) {
if (!offset) offset = 0;
const len = buf.readUInt16BE(offset);
offset += 2;
const oldOffset = offset;
const data = {};
data.flags = buf.readUInt8(offset);
offset += 1;
data.tag = string.decode(buf, offset);
offset += string.decode.bytes;
data.value = buf.toString("utf-8", offset, oldOffset + len);
data.issuerCritical = !!(data.flags & rcaa.ISSUER_CRITICAL);
rcaa.decode.bytes = len + 2;
return data;
};
rcaa.decode.bytes = 0;
rcaa.encodingLength = function(data) {
return string.encodingLength(data.tag) + string.encodingLength(data.value) + 2;
};
const rmx = exports.mx = {};
rmx.encode = function(data, buf, offset) {
if (!buf) buf = Buffer$1.alloc(rmx.encodingLength(data));
if (!offset) offset = 0;
const oldOffset = offset;
offset += 2;
buf.writeUInt16BE(data.preference || 0, offset);
offset += 2;
name.encode(data.exchange, buf, offset);
offset += name.encode.bytes;
buf.writeUInt16BE(offset - oldOffset - 2, oldOffset);
rmx.encode.bytes = offset - oldOffset;
return buf;
};
rmx.encode.bytes = 0;
rmx.decode = function(buf, offset) {
if (!offset) offset = 0;
const oldOffset = offset;
const data = {};
offset += 2;
data.preference = buf.readUInt16BE(offset);
offset += 2;
data.exchange = name.decode(buf, offset);
offset += name.decode.bytes;
rmx.decode.bytes = offset - oldOffset;
return data;
};
rmx.encodingLength = function(data) {
return 4 + name.encodingLength(data.exchange);
};
const ra = exports.a = {};
ra.encode = function(host, buf, offset) {
if (!buf) buf = Buffer$1.alloc(ra.encodingLength(host));
if (!offset) offset = 0;
buf.writeUInt16BE(4, offset);
offset += 2;
ip.v4.encode(host, buf, offset);
ra.encode.bytes = 6;
return buf;
};
ra.encode.bytes = 0;
ra.decode = function(buf, offset) {
if (!offset) offset = 0;
offset += 2;
const host = ip.v4.decode(buf, offset);
ra.decode.bytes = 6;
return host;
};
ra.decode.bytes = 0;
ra.encodingLength = function() {
return 6;
};
const raaaa = exports.aaaa = {};
raaaa.encode = function(host, buf, offset) {
if (!buf) buf = Buffer$1.alloc(raaaa.encodingLength(host));
if (!offset) offset = 0;
buf.writeUInt16BE(16, offset);
offset += 2;
ip.v6.encode(host, buf, offset);
raaaa.encode.bytes = 18;
return buf;
};
raaaa.encode.bytes = 0;
raaaa.decode = function(buf, offset) {
if (!offset) offset = 0;
offset += 2;
const host = ip.v6.decode(buf, offset);
raaaa.decode.bytes = 18;
return host;
};
raaaa.decode.bytes = 0;
raaaa.encodingLength = function() {
return 18;
};
const roption = exports.option = {};
roption.encode = function(option, buf, offset) {
if (!buf) buf = Buffer$1.alloc(roption.encodingLength(option));
if (!offset) offset = 0;
const oldOffset = offset;
const code = optioncodes.toCode(option.code);
buf.writeUInt16BE(code, offset);
offset += 2;
if (option.data) {
buf.writeUInt16BE(option.data.length, offset);
offset += 2;
option.data.copy(buf, offset);
offset += option.data.length;
} else switch (code) {
case 8:
const spl = option.sourcePrefixLength || 0;
const fam = option.family || ip.familyOf(option.ip);
const ipBuf = ip.encode(option.ip, Buffer$1.alloc);
const ipLen = Math.ceil(spl / 8);
buf.writeUInt16BE(ipLen + 4, offset);
offset += 2;
buf.writeUInt16BE(fam, offset);
offset += 2;
buf.writeUInt8(spl, offset++);
buf.writeUInt8(option.scopePrefixLength || 0, offset++);
ipBuf.copy(buf, offset, 0, ipLen);
offset += ipLen;
break;
case 11:
if (option.timeout) {
buf.writeUInt16BE(2, offset);
offset += 2;
buf.writeUInt16BE(option.timeout, offset);
offset += 2;
} else {
buf.writeUInt16BE(0, offset);
offset += 2;
}
break;
case 12:
const len = option.length || 0;
buf.writeUInt16BE(len, offset);
offset += 2;
buf.fill(0, offset, offset + len);
offset += len;
break;
case 14:
const tagsLen = option.tags.length * 2;
buf.writeUInt16BE(tagsLen, offset);
offset += 2;
for (const tag of option.tags) {
buf.writeUInt16BE(tag, offset);
offset += 2;
}
break;
default: throw new Error(`Unknown roption code: ${option.code}`);
}
roption.encode.bytes = offset - oldOffset;
return buf;
};
roption.encode.bytes = 0;
roption.decode = function(buf, offset) {
if (!offset) offset = 0;
const option = {};
option.code = buf.readUInt16BE(offset);
option.type = optioncodes.toString(option.code);
offset += 2;
const len = buf.readUInt16BE(offset);
offset += 2;
option.data = buf.slice(offset, offset + len);
switch (option.code) {
case 8:
option.family = buf.readUInt16BE(offset);
offset += 2;
option.sourcePrefixLength = buf.readUInt8(offset++);
option.scopePrefixLength = buf.readUInt8(offset++);
const padded = Buffer$1.alloc(option.family === 1 ? 4 : 16);
buf.copy(padded, 0, offset, offset + len - 4);
option.ip = ip.decode(padded);
break;
case 11:
if (len > 0) {
option.timeout = buf.readUInt16BE(offset);
offset += 2;
}
break;
case 14:
option.tags = [];
for (let i = 0; i < len; i += 2) {
option.tags.push(buf.readUInt16BE(offset));
offset += 2;
}
}
roption.decode.bytes = len + 4;
return option;
};
roption.decode.bytes = 0;
roption.encodingLength = function(option) {
if (option.data) return option.data.length + 4;
switch (optioncodes.toCode(option.code)) {
case 8:
const spl = option.sourcePrefixLength || 0;
return Math.ceil(spl / 8) + 8;
case 11: return typeof option.timeout === "number" ? 6 : 4;
case 12: return option.length + 4;
case 14: return 4 + option.tags.length * 2;
}
throw new Error(`Unknown roption code: ${option.code}`);
};
const ropt = exports.opt = {};
ropt.encode = function(options, buf, offset) {
if (!buf) buf = Buffer$1.alloc(ropt.encodingLength(options));
if (!offset) offset = 0;
const oldOffset = offset;
const rdlen = encodingLengthList(options, roption);
buf.writeUInt16BE(rdlen, offset);
offset = encodeList(options, roption, buf, offset + 2);
ropt.encode.bytes = offset - oldOffset;
return buf;
};
ropt.encode.bytes = 0;
ropt.decode = function(buf, offset) {
if (!offset) offset = 0;
const oldOffset = offset;
const options = [];
let rdlen = buf.readUInt16BE(offset);
offset += 2;
let o = 0;
while (rdlen > 0) {
options[o++] = roption.decode(buf, offset);
offset += roption.decode.bytes;
rdlen -= roption.decode.bytes;
}
ropt.decode.bytes = offset - oldOffset;
return options;
};
ropt.decode.bytes = 0;
ropt.encodingLength = function(options) {
return 2 + encodingLengthList(options || [], roption);
};
const rdnskey = exports.dnskey = {};
rdnskey.PROTOCOL_DNSSEC = 3;
rdnskey.ZONE_KEY = 128;
rdnskey.SECURE_ENTRYPOINT = 32768;
rdnskey.encode = function(key, buf, offset) {
if (!buf) buf = Buffer$1.alloc(rdnskey.encodingLength(key));
if (!offset) offset = 0;
const oldOffset = offset;
const keydata = key.key;
if (!Buffer$1.isBuffer(keydata)) throw new Error("Key must be a Buffer");
offset += 2;
buf.writeUInt16BE(key.flags, offset);
offset += 2;
buf.writeUInt8(rdnskey.PROTOCOL_DNSSEC, offset);
offset += 1;
buf.writeUInt8(key.algorithm, offset);
offset += 1;
keydata.copy(buf, offset, 0, keydata.length);
offset += keydata.length;
rdnskey.encode.bytes = offset - oldOffset;
buf.writeUInt16BE(rdnskey.encode.bytes - 2, oldOffset);
return buf;
};
rdnskey.encode.bytes = 0;
rdnskey.decode = function(buf, offset) {
if (!offset) offset = 0;
const oldOffset = offset;
var key = {};
var length = buf.readUInt16BE(offset);
offset += 2;
key.flags = buf.readUInt16BE(offset);
offset += 2;
if (buf.readUInt8(offset) !== rdnskey.PROTOCOL_DNSSEC) throw new Error("Protocol must be 3");
offset += 1;
key.algorithm = buf.readUInt8(offset);
offset += 1;
key.key = buf.slice(offset, oldOffset + length + 2);
offset += key.key.length;
rdnskey.decode.bytes = offset - oldOffset;
return key;
};
rdnskey.decode.bytes = 0;
rdnskey.encodingLength = function(key) {
return 6 + Buffer$1.byteLength(key.key);
};
const rrrsig = exports.rrsig = {};
rrrsig.encode = function(sig, buf, offset) {
if (!buf) buf = Buffer$1.alloc(rrrsig.encodingLength(sig));
if (!offset) offset = 0;
const oldOffset = offset;
const signature = sig.signature;
if (!Buffer$1.isBuffer(signature)) throw new Error("Signature must be a Buffer");
offset += 2;
buf.writeUInt16BE(types.toType(sig.typeCovered), offset);
offset += 2;
buf.writeUInt8(sig.algorithm, offset);
offset += 1;
buf.writeUInt8(sig.labels, offset);
offset += 1;
buf.writeUInt32BE(sig.originalTTL, offset);
offset += 4;
buf.writeUInt32BE(sig.expiration, offset);
offset += 4;
buf.writeUInt32BE(sig.inception, offset);
offset += 4;
buf.writeUInt16BE(sig.keyTag, offset);
offset += 2;
name.encode(sig.signersName, buf, offset);
offset += name.encode.bytes;
signature.copy(buf, offset, 0, signature.length);
offset += signature.length;
rrrsig.encode.bytes = offset - oldOffset;
buf.writeUInt16BE(rrrsig.encode.bytes - 2, oldOffset);
return buf;
};
rrrsig.encode.bytes = 0;
rrrsig.decode = function(buf, offset) {
if (!offset) offset = 0;
const oldOffset = offset;
var sig = {};
var length = buf.readUInt16BE(offset);
offset += 2;
sig.typeCovered = types.toString(buf.readUInt16BE(offset));
offset += 2;
sig.algorithm = buf.readUInt8(offset);
offset += 1;
sig.labels = buf.readUInt8(offset);
offset += 1;
sig.originalTTL = buf.readUInt32BE(offset);
offset += 4;
sig.expiration = buf.readUInt32BE(offset);
offset += 4;
sig.inception = buf.readUInt32BE(offset);
offset += 4;
sig.keyTag = buf.readUInt16BE(offset);
offset += 2;
sig.signersName = name.decode(buf, offset);
offset += name.decode.bytes;
sig.signature = buf.slice(offset, oldOffset + length + 2);
offset += sig.signature.length;
rrrsig.decode.bytes = offset - oldOffset;
return sig;
};
rrrsig.decode.bytes = 0;
rrrsig.encodingLength = function(sig) {
return 20 + name.encodingLength(sig.signersName) + Buffer$1.byteLength(sig.signature);
};
const rrp = exports.rp = {};
rrp.encode = function(data, buf, offset) {
if (!buf) buf = Buffer$1.alloc(rrp.encodingLength(data));
if (!offset) offset = 0;
const oldOffset = offset;
offset += 2;
name.encode(data.mbox || ".", buf, offset, { mail: true });
offset += name.encode.bytes;
name.encode(data.txt || ".", buf, offset);
offset += name.encode.bytes;
rrp.encode.bytes = offset - oldOffset;
buf.writeUInt16BE(rrp.encode.bytes - 2, oldOffset);
return buf;
};
rrp.encode.bytes = 0;
rrp.decode = function(buf, offset) {
if (!offset) offset = 0;
const oldOffset = offset;
const data = {};
offset += 2;
data.mbox = name.decode(buf, offset, { mail: true }) || ".";
offset += name.decode.bytes;
data.txt = name.decode(buf, offset) || ".";
offset += name.decode.bytes;
rrp.decode.bytes = offset - oldOffset;
return data;
};
rrp.decode.bytes = 0;
rrp.encodingLength = function(data) {
return 2 + name.encodingLength(data.mbox || ".") + name.encodingLength(data.txt || ".");
};
const typebitmap = {};
typebitmap.encode = function(typelist, buf, offset) {
if (!buf) buf = Buffer$1.alloc(typebitmap.encodingLength(typelist));
if (!offset) offset = 0;
const oldOffset = offset;
var typesByWindow = [];
for (var i = 0; i < typelist.length; i++) {
var typeid = types.toType(typelist[i]);
if (typesByWindow[typeid >> 8] === void 0) typesByWindow[typeid >> 8] = [];
typesByWindow[typeid >> 8][typeid >> 3 & 31] |= 1 << 7 - (typeid & 7);
}
for (i = 0; i < typesByWindow.length; i++) if (typesByWindow[i] !== void 0) {
var windowBuf = Buffer$1.from(typesByWindow[i]);
buf.writeUInt8(i, offset);
offset += 1;
buf.writeUInt8(windowBuf.length, offset);
offset += 1;
windowBuf.copy(buf, offset);
offset += windowBuf.length;
}
typebitmap.encode.bytes = offset - oldOffset;
return buf;
};
typebitmap.encode.bytes = 0;
typebitmap.decode = function(buf, offset, length) {
if (!offset) offset = 0;
const oldOffset = offset;
var typelist = [];
while (offset - oldOffset < length) {
var window = buf.readUInt8(offset);
offset += 1;
var windowLength = buf.readUInt8(offset);
offset += 1;
for (var i = 0; i < windowLength; i++) {
var b = buf.readUInt8(offset + i);
for (var j = 0; j < 8; j++) if (b & 1 << 7 - j) {
var typeid = types.toString(window << 8 | i << 3 | j);
typelist.push(typeid);
}
}
offset += windowLength;
}
typebitmap.decode.bytes = offset - oldOffset;
return typelist;
};
typebitmap.decode.bytes = 0;
typebitmap.encodingLength = function(typelist) {
var extents = [];
for (var i = 0; i < typelist.length; i++) {
var typeid = types.toType(typelist[i]);
extents[typeid >> 8] = Math.max(extents[typeid >> 8] || 0, typeid & 255);
}
var len = 0;
for (i = 0; i < extents.length; i++) if (extents[i] !== void 0) len += 2 + Math.ceil((extents[i] + 1) / 8);
return len;
};
const rnsec = exports.nsec = {};
rnsec.encode = function(record, buf, offset) {
if (!buf) buf = Buffer$1.alloc(rnsec.encodingLength(record));
if (!offset) offset = 0;
const oldOffset = offset;
offset += 2;
name.encode(record.nextDomain, buf, offset);
offset += name.encode.bytes;
typebitmap.encode(record.rrtypes, buf, offset);
offset += typebitmap.encode.bytes;
rnsec.encode.bytes = offset - oldOffset;
buf.writeUInt16BE(rnsec.encode.bytes - 2, oldOffset);
return buf;
};
rnsec.encode.bytes = 0;
rnsec.decode = function(buf, offset) {
if (!offset) offset = 0;
const oldOffset = offset;
var record = {};
var length = buf.readUInt16BE(offset);
offset += 2;
record.nextDomain = name.decode(buf, offset);
offset += name.decode.bytes;
record.rrtypes = typebitmap.decode(buf, offset, length - (offset - oldOffset));
offset += typebitmap.decode.bytes;
rnsec.decode.bytes = offset - oldOffset;
return record;
};
rnsec.decode.bytes = 0;
rnsec.encodingLength = function(record) {
return 2 + name.encodingLength(record.nextDomain) + typebitmap.encodingLength(record.rrtypes);
};
const rnsec3 = exports.nsec3 = {};
rnsec3.encode = function(record, buf, offset) {
if (!buf) buf = Buffer$1.alloc(rnsec3.encodingLength(record));
if (!offset) offset = 0;
const oldOffset = offset;
const salt = record.salt;
if (!Buffer$1.isBuffer(salt)) throw new Error("salt must be a Buffer");
const nextDomain = record.nextDomain;
if (!Buffer$1.isBuffer(nextDomain)) throw new Error("nextDomain must be a Buffer");
offset += 2;
buf.writeUInt8(record.algorithm, offset);
offset += 1;
buf.writeUInt8(record.flags, offset);
offset += 1;
buf.writeUInt16BE(record.iterations, offset);
offset += 2;
buf.writeUInt8(salt.length, offset);
offset += 1;
salt.copy(buf, offset, 0, salt.length);
offset += salt.length;
buf.writeUInt8(nextDomain.length, offset);
offset += 1;
nextDomain.copy(buf, offset, 0, nextDomain.length);
offset += nextDomain.length;
typebitmap.encode(record.rrtypes, buf, offset);
offset += typebitmap.encode.bytes;
rnsec3.encode.bytes = offset - oldOffset;
buf.writeUInt16BE(rnsec3.encode.bytes - 2, oldOffset);
return buf;
};
rnsec3.encode.bytes = 0;
rnsec3.decode = function(buf, offset) {
if (!offset) offset = 0;
const oldOffset = offset;
var record = {};
var length = buf.readUInt16BE(offset);
offset += 2;
record.algorithm = buf.readUInt8(offset);
offset += 1;
record.flags = buf.readUInt8(offset);
offset += 1;
record.iterations = buf.readUInt16BE(offset);
offset += 2;
const saltLength = buf.readUInt8(offset);
offset += 1;
record.salt = buf.slice(offset, offset + saltLength);
offset += saltLength;
const hashLength = buf.readUInt8(offset);
offset += 1;
record.nextDomain = buf.slice(offset, offset + hashLength);
offset += hashLength;
record.rrtypes = typebitmap.decode(buf, offset, length - (offset - oldOffset));
offset += typebitmap.decode.bytes;
rnsec3.decode.bytes = offset - oldOffset;
return record;
};
rnsec3.decode.bytes = 0;
rnsec3.encodingLength = function(record) {
return 8 + record.salt.length + record.nextDomain.length + typebitmap.encodingLength(record.rrtypes);
};
const rds = exports.ds = {};
rds.encode = function(digest, buf, offset) {
if (!buf) buf = Buffer$1.alloc(rds.encodingLength(digest));
if (!offset) offset = 0;
const oldOffset = offset;
const digestdata = digest.digest;
if (!Buffer$1.isBuffer(digestdata)) throw new Error("Digest must be a Buffer");
offset += 2;
buf.writeUInt16BE(digest.keyTag, offset);
offset += 2;
buf.writeUInt8(digest.algorithm, offset);
offset += 1;
buf.writeUInt8(digest.digestType, offset);
offset += 1;
digestdata.copy(buf, offset, 0, digestdata.length);
offset += digestdata.length;
rds.encode.bytes = offset - oldOffset;
buf.writeUInt16BE(rds.encode.bytes - 2, oldOffset);
return buf;
};
rds.encode.bytes = 0;
rds.decode = function(buf, offset) {
if (!offset) offset = 0;
const oldOffset = offset;
var digest = {};
var length = buf.readUInt16BE(offset);
offset += 2;
digest.keyTag = buf.readUInt16BE(offset);
offset += 2;
digest.algorithm = buf.readUInt8(offset);
offset += 1;
digest.digestType = buf.readUInt8(offset);
offset += 1;
digest.digest = buf.slice(offset, oldOffset + length + 2);
offset += digest.digest.length;
rds.decode.bytes = offset - oldOffset;
return digest;
};
rds.decode.bytes = 0;
rds.encodingLength = function(digest) {
return 6 + Buffer$1.byteLength(digest.digest);
};
const rsshfp = exports.sshfp = {};
rsshfp.getFingerprintLengthForHashType = function getFingerprintLengthForHashType(hashType) {
switch (hashType) {
case 1: return 20;
case 2: return 32;
}
};
rsshfp.encode = function encode(record, buf, offset) {
if (!buf) buf = Buffer$1.alloc(rsshfp.encodingLength(record));
if (!offset) offset = 0;
const oldOffset = offset;
offset += 2;
buf[offset] = record.algorithm;
offset += 1;
buf[offset] = record.hash;
offset += 1;
const fingerprintBuf = Buffer$1.from(record.fingerprint.toUpperCase(), "hex");
if (fingerprintBuf.length !== rsshfp.getFingerprintLengthForHashType(record.hash)) throw new Error("Invalid fingerprint length");
fingerprintBuf.copy(buf, offset);
offset += fingerprintBuf.byteLength;
rsshfp.encode.bytes = offset - oldOffset;
buf.writeUInt16BE(rsshfp.encode.bytes - 2, oldOffset);
return buf;
};
rsshfp.encode.bytes = 0;
rsshfp.decode = function decode(buf, offset) {
if (!offset) offset = 0;
const oldOffset = offset;
const record = {};
offset += 2;
record.algorithm = buf[offset];
offset += 1;
record.hash = buf[offset];
offset += 1;
const fingerprintLength = rsshfp.getFingerprintLengthForHashType(record.hash);
record.fingerprint = buf.slice(offset, offset + fingerprintLength).toString("hex").toUpperCase();
offset += fingerprintLength;
rsshfp.decode.bytes = offset - oldOffset;
return record;
};
rsshfp.decode.bytes = 0;
rsshfp.encodingLength = function(record) {
return 4 + Buffer$1.from(record.fingerprint, "hex").byteLength;
};
const rnaptr = exports.naptr = {};
rnaptr.encode = function(data, buf, offset) {
if (!buf) buf = Buffer$1.alloc(rnaptr.encodingLength(data));
if (!offset) offset = 0;
const oldOffset = offset;
offset += 2;
buf.writeUInt16BE(data.order || 0, offset);
offset += 2;
buf.writeUInt16BE(data.preference || 0, offset);
offset += 2;
string.encode(data.flags, buf, offset);
offset += string.encode.bytes;
string.encode(data.services, buf, offset);
offset += string.encode.bytes;
string.encode(data.regexp, buf, offset);
offset += string.encode.bytes;
name.encode(data.replacement, buf, offset);
offset += name.encode.bytes;
rnaptr.encode.bytes = offset - oldOffset;
buf.writeUInt16BE(rnaptr.encode.bytes - 2, oldOffset);
return buf;
};
rnaptr.encode.bytes = 0;
rnaptr.decode = function(buf, offset) {
if (!offset) offset = 0;
const oldOffset = offset;
const data = {};
offset += 2;
data.order = buf.readUInt16BE(offset);
offset += 2;
data.preference = buf.readUInt16BE(offset);
offset += 2;
data.flags = string.decode(buf, offset);
offset += string.decode.bytes;
data.services = string.decode(buf, offset);
offset += string.decode.bytes;
data.regexp = string.decode(buf, offset);
offset += string.decode.bytes;
data.replacement = name.decode(buf, offset);
offset += name.decode.bytes;
rnaptr.decode.bytes = offset - oldOffset;
return data;
};
rnaptr.decode.bytes = 0;
rnaptr.encodingLength = function(data) {
return string.encodingLength(data.flags) + string.encodingLength(data.services) + string.encodingLength(data.regexp) + name.encodingLength(data.replacement) + 6;
};
const rtlsa = exports.tlsa = {};
rtlsa.encode = function(cert, buf, offset) {
if (!buf) buf = Buffer$1.alloc(rtlsa.encodingLength(cert));
if (!offset) offset = 0;
const oldOffset = offset;
const certdata = cert.certificate;
if (!Buffer$1.isBuffer(certdata)) throw new Error("Certificate must be a Buffer");
offset += 2;
buf.writeUInt8(cert.usage, offset);
offset += 1;
buf.writeUInt8(cert.selector, offset);
offset += 1;
buf.writeUInt8(cert.matchingType, offset);
offset += 1;
certdata.copy(buf, offset, 0, certdata.length);
offset += certdata.length;
rtlsa.encode.bytes = offset - oldOffset;
buf.writeUInt16BE(rtlsa.encode.bytes - 2, oldOffset);
return buf;
};
rtlsa.encode.bytes = 0;
rtlsa.decode = function(buf, offset) {
if (!offset) offset = 0;
const oldOffset = offset;
const cert = {};
const length = buf.readUInt16BE(offset);
offset += 2;
cert.usage = buf.readUInt8(offset);
offset += 1;
cert.selector = buf.readUInt8(offset);
offset += 1;
cert.matchingType = buf.readUInt8(offset);
offset += 1;
cert.certificate = buf.slice(offset, oldOffset + length + 2);
offset += cert.certificate.length;
rtlsa.decode.bytes = offset - oldOffset;
return cert;
};
rtlsa.decode.bytes = 0;
rtlsa.encodingLength = function(cert) {
return 5 + Buffer$1.byteLength(cert.certificate);
};
const renc = exports.record = function(type) {
switch (type.toUpperCase()) {
case "A": return ra;
case "PTR": return rptr;
case "CNAME": return rcname;
case "DNAME": return rdname;
case "TXT": return rtxt;
case "NULL": return rnull;
case "AAAA": return raaaa;
case "SRV": return rsrv;
case "HINFO": return rhinfo;
case "CAA": return rcaa;
case "NS": return rns;
case "SOA": return rsoa;
case "MX": return rmx;
case "OPT": return ropt;
case "DNSKEY": return rdnskey;
case "RRSIG": return rrrsig;
case "RP": return rrp;
case "NSEC": return rnsec;
case "NSEC3": return rnsec3;
case "SSHFP": return rsshfp;
case "DS": return rds;
case "NAPTR": return rnaptr;
case "TLSA": return rtlsa;
}
return runknown;
};
const answer = exports.answer = {};
answer.encode = function(a, buf, offset) {
if (!buf) buf = Buffer$1.alloc(answer.encodingLength(a));
if (!offset) offset = 0;
const oldOffset = offset;
name.encode(a.name, buf, offset);
offset += name.encode.bytes;
buf.writeUInt16BE(types.toType(a.type), offset);
if (a.type.toUpperCase() === "OPT") {
if (a.name !== ".") throw new Error("OPT name must be root.");
buf.writeUInt16BE(a.udpPayloadSize || 4096, offset + 2);
buf.writeUInt8(a.extendedRcode || 0, offset + 4);
buf.writeUInt8(a.ednsVersion || 0, offset + 5);
buf.writeUInt16BE(a.flags || 0, offset + 6);
offset += 8;
ropt.encode(a.options || [], buf, offset);
offset += ropt.encode.bytes;
} else {
let klass = classes.toClass(a.class === void 0 ? "IN" : a.class);
if (a.flush) klass |= FLUSH_MASK;
buf.writeUInt16BE(klass, offset + 2);
buf.writeUInt32BE(a.ttl || 0, offset + 4);
offset += 8;
const enc = renc(a.type);
enc.encode(a.data, buf, offset);
offset += enc.encode.bytes;
}
answer.encode.bytes = offset - oldOffset;
return buf;
};
answer.encode.bytes = 0;
answer.decode = function(buf, offset) {
if (!offset) offset = 0;
const a = {};
const oldOffset = offset;
a.name = name.decode(buf, offset);
offset += name.decode.bytes;
a.type = types.toString(buf.readUInt16BE(offset));
if (a.type === "OPT") {
a.udpPayloadSize = buf.readUInt16BE(offset + 2);
a.extendedRcode = buf.readUInt8(offset + 4);
a.ednsVersion = buf.readUInt8(offset + 5);
a.flags = buf.readUInt16BE(offset + 6);
a.flag_do = (a.flags >> 15 & 1) === 1;
a.options = ropt.decode(buf, offset + 8);
offset += 8 + ropt.decode.bytes;
} else {
const klass = buf.readUInt16BE(offset + 2);
a.ttl = buf.readUInt32BE(offset + 4);
a.class = classes.toString(klass & NOT_FLUSH_MASK);
a.flush = !!(klass & FLUSH_MASK);
const enc = renc(a.type);
a.data = enc.decode(buf, offset + 8);
offset += 8 + enc.decode.bytes;
}
answer.decode.bytes = offset - oldOffset;
return a;
};
answer.decode.bytes = 0;
answer.encodingLength = function(a) {
const data = a.data !== null && a.data !== void 0 ? a.data : a.options;
return name.encodingLength(a.name) + 8 + renc(a.type).encodingLength(data);
};
const question = exports.question = {};
question.encode = function(q, buf, offset) {
if (!buf) buf = Buffer$1.alloc(question.encodingLength(q));
if (!offset) offset = 0;
const oldOffset = offset;
name.encode(q.name, buf, offset);
offset += name.encode.bytes;
buf.writeUInt16BE(types.toType(q.type), offset);
offset += 2;
buf.writeUInt16BE(classes.toClass(q.class === void 0 ? "IN" : q.class), offset);
offset += 2;
question.encode.bytes = offset - oldOffset;
return q;
};
question.encode.bytes = 0;
question.decode = function(buf, offset) {
if (!offset) offset = 0;
const oldOffset = offset;
const q = {};
q.name = name.decode(buf, offset);
offset += name.decode.bytes;
q.type = types.toString(buf.readUInt16BE(offset));
offset += 2;
q.class = classes.toString(buf.readUInt16BE(offset));
offset += 2;
if (!!(q.class & QU_MASK)) q.class &= NOT_QU_MASK;
question.decode.bytes = offset - oldOffset;
return q;
};
question.decode.bytes = 0;
question.encodingLength = function(q) {
return name.encodingLength(q.name) + 4;
};
exports.AUTHORITATIVE_ANSWER = 1024;
exports.TRUNCATED_RESPONSE = 512;
exports.RECURSION_DESIRED = 256;
exports.RECURSION_AVAILABLE = 128;
exports.AUTHENTIC_DATA = 32;
exports.CHECKING_DISABLED = 16;
exports.DNSSEC_OK = 32768;
exports.encode = function(result, buf, offset) {
const allocing = !buf;
if (allocing) buf = Buffer$1.alloc(exports.encodingLength(result));
if (!offset) offset = 0;
const oldOffset = offset;
if (!result.questions) result.questions = [];
if (!result.answers) result.answers = [];
if (!result.authorities) result.authorities = [];
if (!result.additionals) result.additionals = [];
header.encode(result, buf, offset);
offset += header.encode.bytes;
offset = encodeList(result.questions, question, buf, offset);
offset = encodeList(result.answers, answer, buf, offset);
offset = encodeList(result.authorities, answer, buf, offset);
offset = encodeList(result.additionals, answer, buf, offset);
exports.encode.bytes = offset - oldOffset;
if (allocing && exports.encode.bytes !== buf.length) return buf.slice(0, exports.encode.bytes);
return buf;
};
exports.encode.bytes = 0;
exports.decode = function(buf, offset) {
if (!offset) offset = 0;
const oldOffset = offset;
const result = header.decode(buf, offset);
offset += header.decode.bytes;
offset = decodeList(result.questions, question, buf, offset);
offset = decodeList(result.answers, answer, buf, offset);
offset = decodeList(result.authorities, answer, buf, offset);
offset = decodeList(result.additionals, answer, buf, offset);
exports.decode.bytes = offset - oldOffset;
return result;
};
exports.decode.bytes = 0;
exports.encodingLength = function(result) {
return header.encodingLength(result) + encodingLengthList(result.questions || [], question) + encodingLengthList(result.answers || [], answer) + encodingLengthList(result.authorities || [], answer) + encodingLengthList(result.additionals || [], answer);
};
exports.streamEncode = function(result) {
const buf = exports.encode(result);
const sbuf = Buffer$1.alloc(2);
sbuf.writeUInt16BE(buf.byteLength);
const combine = Buffer$1.concat([sbuf, buf]);
exports.streamEncode.bytes = combine.byteLength;
return combine;
};
exports.streamEncode.bytes = 0;
exports.streamDecode = function(sbuf) {
const len = sbuf.readUInt16BE(0);
if (sbuf.byteLength < len + 2) return null;
const result = exports.decode(sbuf.slice(2));
exports.streamDecode.bytes = exports.decode.bytes;
return result;
};
exports.streamDecode.bytes = 0;
function encodingLengthList(list, enc) {
let len = 0;
for (let i = 0; i < list.length; i++) len += enc.encodingLength(list[i]);
return len;
}
function encodeList(list, enc, buf, offset) {
for (let i = 0; i < list.length; i++) {
enc.encode(list[i], buf, offset);
offset += enc.encode.bytes;
}
return offset;
}
function decodeList(list, enc, buf, offset) {
for (let i = 0; i < list.length; i++) {
list[i] = enc.decode(buf, offset);
offset += enc.decode.bytes;
}
return offset;
}
}));
//#endregion
//#region node_modules/.pnpm/thunky@1.1.0/node_modules/thunky/index.js
var require_thunky = /* @__PURE__ */ __commonJSMin(((exports, module) => {
var nextTick = nextTickArgs;
process.nextTick(upgrade, 42);
module.exports = thunky;
function thunky(fn) {
var state = run;
return thunk;
function thunk(callback) {
state(callback || noop);
}
function run(callback) {
var stack = [callback];
state = wait;
fn(done);
function wait(callback) {
stack.push(callback);
}
function done(err) {
var args = arguments;
state = isError(err) ? run : finished;
while (stack.length) finished(stack.shift());
function finished(callback) {
nextTick(apply, callback, args);
}
}
}
}
function isError(err) {
return Object.prototype.toString.call(err) === "[object Error]";
}
function noop() {}
function apply(callback, args) {
callback.apply(null, args);
}
function upgrade(val) {
if (val === 42) nextTick = process.nextTick;
}
function nextTickArgs(fn, a, b) {
process.nextTick(function() {
fn(a, b);
});
}
}));
//#endregion
//#region node_modules/.pnpm/werift@0.24.4_supports-color@10.2.2/node_modules/werift/lib/index.mjs
var import_multicast_dns = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports, module) => {
var packet = require_dns_packet();
var dgram = __require("dgram");
var thunky = require_thunky();
var events = __require("events");
var os$2 = __require("os");
var noop = function() {};
module.exports = function(opts) {
if (!opts) opts = {};
var that = new events.EventEmitter();
var port = typeof opts.port === "number" ? opts.port : 5353;
var type = opts.type || "udp4";
var ip = opts.ip || opts.host || (type === "udp4" ? "224.0.0.251" : null);
var me = {
address: ip,
port
};
var memberships = {};
var destroyed = false;
var interval = null;
if (type === "udp6" && (!ip || !opts.interface)) throw new Error("For IPv6 multicast you must specify `ip` and `interface`");
var socket = opts.socket || dgram.createSocket({
type,
reuseAddr: opts.reuseAddr !== false,
toString: function() {
return type;
}
});
socket.on("error", function(err) {
if (err.code === "EACCES" || err.code === "EADDRINUSE") that.emit("error", err);
else that.emit("warning", err);
});
socket.on("message", function(message, rinfo) {
try {
message = packet.decode(message);
} catch (err) {
that.emit("warning", err);
return;
}
that.emit("packet", message, rinfo);
if (message.type === "query") that.emit("query", message, rinfo);
if (message.type === "response") that.emit("response", message, rinfo);
});
socket.on("listening", function() {
if (!port) port = me.port = socket.address().port;
if (opts.multicast !== false) {
that.update();
interval = setInterval(that.update, 5e3);
socket.setMulticastTTL(opts.ttl || 255);
socket.setMulticastLoopback(opts.loopback !== false);
}
});
var bind = thunky(function(cb) {
if (!port || opts.bind === false) return cb(null);
socket.once("error", cb);
socket.bind(port, opts.bind || opts.interface, function() {
socket.removeListener("error", cb);
cb(null);
});
});
bind(function(err) {
if (err) return that.emit("error", err);
that.emit("ready");
});
that.send = function(value, rinfo, cb) {
if (typeof rinfo === "function") return that.send(value, null, rinfo);
if (!cb) cb = noop;
if (!rinfo) rinfo = me;
else if (!rinfo.host && !rinfo.address) rinfo.address = me.address;
bind(onbind);
function onbind(err) {
if (destroyed) return cb();
if (err) return cb(err);
var message = packet.encode(value);
socket.send(message, 0, message.length, rinfo.port, rinfo.address || rinfo.host, cb);
}
};
that.response = that.respond = function(res, rinfo, cb) {
if (Array.isArray(res)) res = { answers: res };
res.type = "response";
res.flags = (res.flags || 0) | packet.AUTHORITATIVE_ANSWER;
that.send(res, rinfo, cb);
};
that.query = function(q, type, rinfo, cb) {
if (typeof type === "function") return that.query(q, null, null, type);
if (typeof type === "object" && type && type.port) return that.query(q, null, type, rinfo);
if (typeof rinfo === "function") return that.query(q, type, null, rinfo);
if (!cb) cb = noop;
if (typeof q === "string") q = [{
name: q,
type: type || "ANY"
}];
if (Array.isArray(q)) q = {
type: "query",
questions: q
};
q.type = "query";
that.send(q, rinfo, cb);
};
that.destroy = function(cb) {
if (!cb) cb = noop;
if (destroyed) return process.nextTick(cb);
destroyed = true;
clearInterval(interval);
for (var iface in memberships) try {
socket.dropMembership(ip, iface);
} catch (e) {}
memberships = {};
socket.close(cb);
};
that.update = function() {
var ifaces = opts.interface ? [].concat(opts.interface) : allInterfaces();
var updated = false;
for (var i = 0; i < ifaces.length; i++) {
var addr = ifaces[i];
if (memberships[addr]) continue;
try {
socket.addMembership(ip, addr);
memberships[addr] = true;
updated = true;
} catch (err) {
that.emit("warning", err);
}
}
if (updated) {
if (socket.setMulticastInterface) try {
socket.setMulticastInterface(opts.interface || defaultInterface());
} catch (err) {
that.emit("warning", err);
}
that.emit("networkInterface");
}
};
return that;
};
function defaultInterface() {
var networks = os$2.networkInterfaces();
var names = Object.keys(networks);
for (var i = 0; i < names.length; i++) {
var net = networks[names[i]];
for (var j = 0; j < net.length; j++) {
var iface = net[j];
if (isIPv4(iface.family) && !iface.internal) {
if (os$2.platform() === "darwin" && names[i] === "en0") return iface.address;
return "0.0.0.0";
}
}
}
return "127.0.0.1";
}
function allInterfaces() {
var networks = os$2.networkInterfaces();
var names = Object.keys(networks);
var res = [];
for (var i = 0; i < names.length; i++) {
var net = networks[names[i]];
for (var j = 0; j < net.length; j++) {
var iface = net[j];
if (isIPv4(iface.family)) {
res.push(iface.address);
break;
}
}
}
return res;
}
function isIPv4(family) {
return family === 4 || family === "IPv4";
}
})))(), 1);
function random16() {
return randomBytes$1(2).readUInt16BE(0);
}
function random32() {
return randomBytes$1(4).readUInt32BE(0);
}
function bufferXor(a, b) {
if (a.length !== b.length) throw new TypeError("[webrtc-stun] You can not XOR buffers which length are different");
const length = a.length;
const buffer2 = Buffer.allocUnsafe(length);
for (let i = 0; i < length; i++) buffer2[i] = a[i] ^ b[i];
return buffer2;
}
function bufferArrayXor(arr) {
const length = [...arr].sort((a, b) => a.length - b.length).reverse()[0].length;
const xored = Buffer.allocUnsafe(length);
for (let i = 0; i < length; i++) {
xored[i] = 0;
arr.forEach((buffer2) => {
xored[i] ^= buffer2[i] ?? 0;
});
}
return xored;
}
var BitWriter = class {
constructor(bitLength) {
this.bitLength = bitLength;
}
value = 0;
set(size, startIndex, value) {
value &= (1 << size) - 1;
this.value |= value << this.bitLength - size - startIndex;
return this;
}
get buffer() {
const length = Math.ceil(this.bitLength / 8);
const buf = Buffer.alloc(length);
buf.writeUIntBE(this.value, 0, length);
return buf;
}
};
var BitWriter2 = class {
/**
* 各valueがオクテットを跨いではならない
*/
constructor(bitLength) {
this.bitLength = bitLength;
if (bitLength > 32) throw new Error();
}
_value = 0n;
offset = 0n;
set(value, size = 1) {
let value_b = BigInt(value);
const size_b = BigInt(size);
value_b &= (1n << size_b) - 1n;
this._value |= value_b << BigInt(this.bitLength) - size_b - this.offset;
this.offset += size_b;
return this;
}
get value() {
return Number(this._value);
}
get buffer() {
const length = Math.ceil(this.bitLength / 8);
const buf = Buffer.alloc(length);
buf.writeUIntBE(this.value, 0, length);
return buf;
}
};
function getBit(bits, startIndex, length = 1) {
let bin = bits.toString(2).split("");
bin = [...Array(8 - bin.length).fill("0"), ...bin];
const s = bin.slice(startIndex, startIndex + length).join("");
return Number.parseInt(s, 2);
}
function paddingByte(bits) {
const dec = bits.toString(2).split("");
return [...[...Array(8 - dec.length)].map(() => "0"), ...dec].join("");
}
function paddingBits(bits, expectLength) {
const dec = bits.toString(2);
return [...[...Array(expectLength - dec.length)].map(() => "0"), ...dec].join("");
}
function bufferWriter(bytes, values) {
return createBufferWriter(bytes)(values);
}
function createBufferWriter(bytes, singleBuffer) {
const length = bytes.reduce((acc, cur) => acc + cur, 0);
const reuseBuffer = singleBuffer ? Buffer.alloc(length) : void 0;
return (values) => {
const buf = reuseBuffer || Buffer.alloc(length);
let offset = 0;
values.forEach((v, i) => {
const size = bytes[i];
if (size === 8) buf.writeBigUInt64BE(v, offset);
else buf.writeUIntBE(v, offset, size);
offset += size;
});
return buf;
};
}
function bufferWriterLE(bytes, values) {
const length = bytes.reduce((acc, cur) => acc + cur, 0);
const buf = Buffer.alloc(length);
let offset = 0;
values.forEach((v, i) => {
const size = bytes[i];
if (size === 8) buf.writeBigUInt64LE(v, offset);
else buf.writeUIntLE(v, offset, size);
offset += size;
});
return buf;
}
function bufferReader(buf, bytes) {
let offset = 0;
return bytes.map((v) => {
let read;
if (v === 8) read = buf.readBigUInt64BE(offset);
else read = buf.readUIntBE(offset, v);
offset += v;
return read;
});
}
var BufferChain = class {
buffer;
constructor(size) {
this.buffer = Buffer.alloc(size);
}
writeInt16BE(value, offset) {
this.buffer.writeInt16BE(value, offset);
return this;
}
writeUInt8(value, offset) {
this.buffer.writeUInt8(value, offset);
return this;
}
};
var dumpBuffer = (data) => "0x" + data.toString("hex").replace(/(.)(.)/g, "$1$2 ").split(" ").filter((s) => s != void 0 && s.length > 0).join(",0x");
function buffer2ArrayBuffer(buf) {
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
}
var BitStream = class {
constructor(uint8Array) {
this.uint8Array = uint8Array;
}
position = 0;
bitsPending = 0;
writeBits(bits, value) {
if (bits == 0) return this;
value &= 4294967295 >>> 32 - bits;
let bitsConsumed;
if (this.bitsPending > 0) {
if (this.bitsPending > bits) {
this.uint8Array[this.position - 1] |= value << this.bitsPending - bits;
bitsConsumed = bits;
this.bitsPending -= bits;
} else if (this.bitsPending == bits) {
this.uint8Array[this.position - 1] |= value;
bitsConsumed = bits;
this.bitsPending = 0;
} else {
this.uint8Array[this.position - 1] |= value >> bits - this.bitsPending;
bitsConsumed = this.bitsPending;
this.bitsPending = 0;
}
} else {
bitsConsumed = Math.min(8, bits);
this.bitsPending = 8 - bitsConsumed;
this.uint8Array[this.position++] = value >> bits - bitsConsumed << this.bitsPending;
}
bits -= bitsConsumed;
if (bits > 0) this.writeBits(bits, value);
return this;
}
readBits(bits) {
return this._readBits(bits);
}
_readBits(bits, bitBuffer) {
if (typeof bitBuffer == "undefined") bitBuffer = 0;
if (bits == 0) return bitBuffer;
let partial;
let bitsConsumed;
if (this.bitsPending > 0) {
const byte = this.uint8Array[this.position - 1] & 255 >> 8 - this.bitsPending;
bitsConsumed = Math.min(this.bitsPending, bits);
this.bitsPending -= bitsConsumed;
partial = byte >> this.bitsPending;
} else {
bitsConsumed = Math.min(8, bits);
this.bitsPending = 8 - bitsConsumed;
partial = this.uint8Array[this.position++] >> this.bitsPending;
}
bits -= bitsConsumed;
bitBuffer = bitBuffer << bitsConsumed | partial;
return bits > 0 ? this._readBits(bits, bitBuffer) : bitBuffer;
}
seekTo(bitPos) {
this.position = bitPos / 8 | 0;
this.bitsPending = bitPos % 8;
if (this.bitsPending > 0) {
this.bitsPending = 8 - this.bitsPending;
this.position++;
}
}
};
var POLY_CRC32 = 3988292384;
var POLY_CRC32C = 2197175160;
function isBufferLike(input) {
return typeof input !== "string";
}
function generateCRCTable(polynomial) {
const table = new Array(256);
let c = 0;
for (let n = 0; n < 256; ++n) {
c = n;
c = c & 1 ? polynomial ^ c >>> 1 : c >>> 1;
c = c & 1 ? polynomial ^ c >>> 1 : c >>> 1;
c = c & 1 ? polynomial ^ c >>> 1 : c >>> 1;
c = c & 1 ? polynomial ^ c >>> 1 : c >>> 1;
c = c & 1 ? polynomial ^ c >>> 1 : c >>> 1;
c = c & 1 ? polynomial ^ c >>> 1 : c >>> 1;
c = c & 1 ? polynomial ^ c >>> 1 : c >>> 1;
c = c & 1 ? polynomial ^ c >>> 1 : c >>> 1;
table[n] = c;
}
return new Int32Array(table);
}
function generateSliceBy16Tables(table0) {
const table = /* @__PURE__ */ new Int32Array(4096);
let c = 0;
let v = 0;
let n = 0;
for (n = 0; n < 256; ++n) table[n] = table0[n];
for (n = 0; n < 256; ++n) {
v = table0[n];
for (c = 256 + n; c < 4096; c += 256) v = table[c] = v >>> 8 ^ table0[v & 255];
}
const out = [];
for (n = 1; n < 16; ++n) out[n - 1] = table.subarray(n * 256, n * 256 + 256);
return out;
}
function crcGenericString(value, seed, table0) {
let crc = seed ^ -1;
let i = 0;
const len = value.length;
let c = 0;
let d = 0;
while (i < len) {
c = value.charCodeAt(i++);
if (c < 128) crc = crc >>> 8 ^ table0[(crc ^ c) & 255];
else if (c < 2048) {
crc = crc >>> 8 ^ table0[(crc ^ (192 | c >> 6 & 31)) & 255];
crc = crc >>> 8 ^ table0[(crc ^ (128 | c & 63)) & 255];
} else if (c >= 55296 && c < 57344) {
c = (c & 1023) + 64;
d = value.charCodeAt(i++) & 1023;
crc = crc >>> 8 ^ table0[(crc ^ (240 | c >> 8 & 7)) & 255];
crc = crc >>> 8 ^ table0[(crc ^ (128 | c >> 2 & 63)) & 255];
crc = crc >>> 8 ^ table0[(crc ^ (128 | d >> 6 & 15 | (c & 3) << 4)) & 255];
crc = crc >>> 8 ^ table0[(crc ^ (128 | d & 63)) & 255];
} else {
crc = crc >>> 8 ^ table0[(crc ^ (224 | c >> 12 & 15)) & 255];
crc = crc >>> 8 ^ table0[(crc ^ (128 | c >> 6 & 63)) & 255];
crc = crc >>> 8 ^ table0[(crc ^ (128 | c & 63)) & 255];
}
}
return ~crc >>> 0;
}
function crcBuffer(value, seed, table0, tables16) {
const [t1, t2, t3, t4, t5, t6, t7, t8, t9, ta, tb, tc, td, te, tf] = tables16;
let crc = seed ^ -1;
let i = 0;
let len = value.length - 15;
while (i < len) crc = tf[value[i++] ^ crc & 255] ^ te[value[i++] ^ crc >>> 8 & 255] ^ td[value[i++] ^ crc >>> 16 & 255] ^ tc[value[i++] ^ crc >>> 24] ^ tb[value[i++]] ^ ta[value[i++]] ^ t9[value[i++]] ^ t8[value[i++]] ^ t7[value[i++]] ^ t6[value[i++]] ^ t5[value[i++]] ^ t4[value[i++]] ^ t3[value[i++]] ^ t2[value[i++]] ^ t1[value[i++]] ^ table0[value[i++]];
for (len += 15; i < len;) crc = crc >>> 8 ^ table0[(crc ^ value[i++]) & 255];
return ~crc >>> 0;
}
var table32 = generateCRCTable(POLY_CRC32);
var tables32By16 = generateSliceBy16Tables(table32);
var table32c = generateCRCTable(POLY_CRC32C);
var tables32cBy16 = generateSliceBy16Tables(table32c);
function crc32(input, seed = 0) {
if (isBufferLike(input)) return crcBuffer(input, seed, table32, tables32By16);
return crcGenericString(input, seed, table32);
}
function crc32c(input, seed = 0) {
if (isBufferLike(input)) return crcBuffer(input, seed, table32c, tables32cBy16);
return crcGenericString(input, seed, table32c);
}
function uint8Add(a, b) {
return a + b & 255;
}
function uint16Add(a, b) {
return a + b & 65535;
}
function uint32Add(a, b) {
return Number(BigInt(a) + BigInt(b) & 4294967295n);
}
function uint24(v) {
return v & 16777215;
}
function uint16Gt(a, b) {
const halfMod = 32768;
return a < b && b - a > halfMod || a > b && a - b < halfMod;
}
function uint16Gte(a, b) {
return a === b || uint16Gt(a, b);
}
function uint32Gt(a, b) {
const halfMod = 2147483648;
return a < b && b - a > halfMod || a > b && a - b < halfMod;
}
function uint32Gte(a, b) {
return a === b || uint32Gt(a, b);
}
var int = (n) => Number.parseInt(n, 10);
var PromiseQueue = class {
queue = [];
running = false;
push = (promise) => new Promise((r, f) => {
this.queue.push({
promise,
done: r,
failed: f
});
if (!this.running) this.run();
});
async run() {
const task = this.queue.shift();
if (task) {
this.running = true;
try {
const res = await task.promise();
task.done(res);
} catch (error) {
task.failed(error);
}
this.run();
} else this.running = false;
}
cancel() {
this.queue = [];
}
};
var interfaceAddress = (type, interfaceAddresses) => interfaceAddresses ? interfaceAddresses[type] : void 0;
async function randomPort(protocol = "udp4", interfaceAddresses) {
const socket = createSocket(protocol);
setImmediate(() => socket.bind({
port: 0,
address: interfaceAddress(protocol, interfaceAddresses)
}));
await new Promise((r) => {
socket.once("error", r);
socket.once("listening", r);
});
const port = socket.address()?.port;
await new Promise((r) => socket.close(() => r()));
return port;
}
async function randomPorts(num, protocol = "udp4", interfaceAddresses) {
return Promise.all([...Array(num)].map(() => randomPort(protocol, interfaceAddresses)));
}
async function findPort(min, max, protocol = "udp4", interfaceAddresses) {
let port;
for (let i = min; i <= max; i++) {
const socket = createSocket(protocol);
setImmediate(() => socket.bind({
port: i,
address: interfaceAddress(protocol, interfaceAddresses)
}));
if (await new Promise((r) => {
socket.once("error", (e) => r(e));
socket.once("listening", () => r());
})) {
await new Promise((r) => socket.close(() => r()));
continue;
}
port = socket.address()?.port;
await new Promise((r) => socket.close(() => r()));
if (min <= port && port <= max) break;
}
if (!port) throw new Error("port not found");
return port;
}
function normalizeFamilyNodeV18(family) {
if (family === "IPv4") return 4;
if (family === "IPv6") return 6;
return family;
}
var WeriftError = class extends Error {
message;
payload;
path;
constructor(props) {
super(props.message);
}
toJSON() {
return {
message: this.message,
payload: JSON.parse(JSON.stringify(this.payload)),
path: this.path
};
}
};
var debug = import_src.default.debug;
var Event2 = class {
event = {
stack: [],
promiseStack: [],
eventId: 0
};
ended = false;
onended;
onerror = (e) => {};
execute = (...args) => {
if (this.ended) return;
for (const item of this.event.stack) item.execute(...args);
(async () => {
for (const item of this.event.promiseStack) await item.execute(...args);
})().catch((e) => {
this.onerror(e);
});
};
complete = () => {
if (this.ended) return;
for (const item of this.event.stack) if (item.complete) item.complete();
this.allUnsubscribe();
this.ended = true;
if (this.onended) {
this.onended();
this.onended = void 0;
}
};
error = (e) => {
if (this.ended) return;
for (const item of this.event.stack) if (item.error) item.error(e);
this.allUnsubscribe();
};
allUnsubscribe = () => {
if (this.ended) return;
this.event = {
stack: [],
promiseStack: [],
eventId: 0
};
};
subscribe = (execute, complete, error) => {
const id = this.event.eventId;
this.event.stack.push({
execute,
id,
complete,
error
});
this.event.eventId++;
const unSubscribe = () => {
this.event.stack = this.event.stack.filter((item) => item.id !== id && item);
};
const disposer = (disposer2) => {
disposer2.push(unSubscribe);
};
return {
unSubscribe,
disposer
};
};
pipe(e) {
this.subscribe((...args) => {
e.execute(...args);
});
}
queuingSubscribe = (execute, complete, error) => {
if (this.ended) throw new Error("event completed");
const id = this.event.eventId;
this.event.promiseStack.push({
execute,
id,
complete,
error
});
this.event.eventId++;
const unSubscribe = () => {
this.event.stack = this.event.stack.filter((item) => item.id !== id && item);
};
const disposer = (disposer2) => {
disposer2.push(unSubscribe);
};
return {
unSubscribe,
disposer
};
};
once = (execute, complete, error) => {
const off = this.subscribe((...args) => {
off.unSubscribe();
execute(...args);
}, complete, error);
};
watch = (cb, timeLimit) => new Promise((resolve, reject) => {
const timeout = timeLimit && setTimeout(() => {
reject("Event watch timeout");
}, timeLimit);
const { unSubscribe } = this.subscribe((...args) => {
if (cb(...args)) {
if (timeout) clearTimeout(timeout);
unSubscribe();
resolve(args);
}
});
});
asPromise = (timeLimit) => new Promise((resolve, reject) => {
const timeout = timeLimit && setTimeout(() => {
reject("Event asPromise timeout");
}, timeLimit);
this.once((...args) => {
if (timeout) clearTimeout(timeout);
resolve(args);
}, () => {
if (timeout) clearTimeout(timeout);
resolve([]);
}, (err5) => {
if (timeout) clearTimeout(timeout);
reject(err5);
});
});
get returnTrigger() {
const { execute, error, complete } = this;
return {
execute,
error,
complete
};
}
get returnListener() {
const { subscribe, once, asPromise } = this;
return {
subscribe,
once,
asPromise
};
}
get length() {
return this.event.stack.length;
}
};
var EventDisposer = class {
_disposer = [];
push(disposer) {
this._disposer.push(disposer);
}
dispose() {
this._disposer.forEach((d) => d());
this._disposer = [];
}
};
var log = debug("werift-ice:packages/ice/src/transport.ts");
var UdpTransport = class _UdpTransport {
constructor(socketType, options = {}) {
this.socketType = socketType;
this.options = options;
this.socket = createSocket(socketType);
this.socket.on("message", (data, info) => {
if (normalizeFamilyNodeV18(info.family) === 6) [info.address] = info.address.split("%");
this.rinfo = info;
try {
this.onData(data, [info.address, info.port]);
} catch (error) {
log("onData error", error);
}
});
}
type = "udp";
socket;
rinfo;
onData = () => {};
closed = false;
static async init(type, options = {}) {
const transport = new _UdpTransport(type, options);
await transport.init();
return transport;
}
async init() {
const address = interfaceAddress(this.socketType, this.options.interfaceAddresses);
if (this.options.port) this.socket.bind({
port: this.options.port,
address
});
else if (this.options.portRange) {
const port = await findPort(this.options.portRange[0], this.options.portRange[1], this.socketType, this.options.interfaceAddresses);
this.socket.bind({
port,
address
});
} else this.socket.bind({ address });
await new Promise((r) => this.socket.once("listening", r));
}
send = async (data, addr) => {
if (addr && !net$1.isIP(addr[0])) return new Promise((r, f) => {
this.socket.send(data, addr[1], addr[0], (error) => {
if (error) {
log("send error", addr, data);
f(error);
} else r();
});
});
else {
addr = addr ?? [this.rinfo?.address, this.rinfo?.port];
this.socket.send(data, addr[1], addr[0]);
}
};
get address() {
return this.socket.address();
}
get host() {
return this.socket.address().address;
}
get port() {
return this.socket.address().port;
}
close = () => new Promise((r) => {
this.closed = true;
this.socket.once("close", r);
try {
this.socket.close();
} catch (error) {
r();
}
});
};
var TcpTransport = class _TcpTransport {
type = "tcp";
stream;
constructor(addr) {
this.stream = new StreamTransport("tcp", () => connect({
port: addr[1],
host: addr[0]
}));
}
static async init(addr) {
const transport = new _TcpTransport(addr);
await transport.init();
return transport;
}
async init() {
await this.stream.waitForConnect();
}
get address() {
return this.stream.address;
}
get closed() {
return this.stream.closed;
}
get onData() {
return this.stream.onData;
}
set onData(handler) {
this.stream.onData = handler;
}
send = async (data, addr) => {
await this.stream.send(data, addr);
};
close = async () => {
await this.stream.close();
};
};
var TlsTransport = class _TlsTransport {
type = "tls";
stream;
constructor(addr, options = {}) {
this.stream = new StreamTransport("tls", () => tls$1.connect({
...options,
host: addr[0],
port: addr[1]
}));
}
static async init(addr, options = {}) {
const transport = new _TlsTransport(addr, options);
await transport.init();
return transport;
}
async init() {
await this.stream.waitForConnect();
}
get address() {
return this.stream.address;
}
get closed() {
return this.stream.closed;
}
get onData() {
return this.stream.onData;
}
set onData(handler) {
this.stream.onData = handler;
}
send = async (data, addr) => {
await this.stream.send(data, addr);
};
close = async () => {
await this.stream.close();
};
};
var StreamTransport = class {
constructor(type, createClient, connectEvent = type === "tls" ? "secureConnect" : "connect") {
this.createClient = createClient;
this.connectEvent = connectEvent;
this.type = type;
this.connect();
}
type;
connecting;
client;
onData = () => {};
closed = false;
connect() {
if (this.closed) return;
if (this.client) this.client.destroy();
const client = this.createClient();
this.client = client;
this.connecting = new Promise((r, f) => {
const onConnect = () => {
client.off("error", onConnectError);
r();
};
const onConnectError = (error) => {
client.off(this.connectEvent, onConnect);
f(error);
};
client.once(this.connectEvent, onConnect);
client.once("error", onConnectError);
});
client.on("data", (data) => {
const addr = [this.client.remoteAddress, this.client.remotePort];
this.onData(data, addr);
});
client.on("end", () => {
this.connect();
});
client.on("error", (error) => {
log(`${this.type} transport error`, error);
});
}
async waitForConnect() {
await this.connecting;
}
get address() {
return {};
}
send = async (data, addr) => {
await this.connecting;
await new Promise((resolve, reject) => {
this.client.write(data, (err5) => {
if (err5) {
reject(err5);
return;
}
resolve();
});
});
};
close = async () => {
this.closed = true;
this.client?.destroy();
};
};
var SignatureAlgorithm = {
rsa_1: 1,
ecdsa_3: 3
};
var HashAlgorithm = { sha256_4: 4 };
var CipherSuite = {
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195: 49195,
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199: 49199
};
var CipherSuiteList = Object.values(CipherSuite);
var NamedCurveAlgorithm = {
x25519_29: 29,
secp256r1_23: 23
};
var NamedCurveAlgorithmList = Object.values(NamedCurveAlgorithm);
var CurveType = { named_curve_3: 3 };
var SignatureScheme = {
rsa_pkcs1_sha256: 1025,
ecdsa_secp256r1_sha256: 1027
};
var certificateTypes = [1, 64];
var signatures = [{
hash: HashAlgorithm.sha256_4,
signature: SignatureAlgorithm.rsa_1
}, {
hash: HashAlgorithm.sha256_4,
signature: SignatureAlgorithm.ecdsa_3
}];
var p256Keypair = () => {
const priv = p256.utils.randomPrivateKey();
const pub = p256.getPublicKey(priv, false);
return {
privateKey: Buffer.from(priv),
publicKey: Buffer.from(pub)
};
};
var p256PreMasterSecret = ({ publicKey, privateKey }) => {
const res = p256.getSharedSecret(privateKey, publicKey);
return Buffer.from(res).subarray(1);
};
function prfPreMasterSecret(publicKey, privateKey, curve) {
switch (curve) {
case NamedCurveAlgorithm.secp256r1_23: return p256PreMasterSecret({
publicKey,
privateKey
});
case NamedCurveAlgorithm.x25519_29: return Buffer.from(import_nacl_fast.default.scalarMult(privateKey, publicKey));
default: throw new Error();
}
}
function hmac(algorithm, secret, data) {
const hash2 = createHmac$1(algorithm, secret);
hash2.update(data);
return hash2.digest();
}
function prfPHash(secret, seed, requestedLegth, algorithm = "sha256") {
const totalLength = requestedLegth;
const bufs = [];
let Ai = seed;
do {
Ai = hmac(algorithm, secret, Ai);
const output = hmac(algorithm, secret, Buffer.concat([Ai, seed]));
bufs.push(output);
requestedLegth -= output.length;
} while (requestedLegth > 0);
return Buffer.concat(bufs, totalLength);
}
function prfMasterSecret(preMasterSecret, clientRandom, serverRandom) {
return prfPHash(preMasterSecret, Buffer.concat([
Buffer.from("master secret"),
clientRandom,
serverRandom
]), 48);
}
function prfExtendedMasterSecret(preMasterSecret, handshakes) {
const sessionHash = hash$1("sha256", handshakes);
return prfPHash(preMasterSecret, Buffer.concat([Buffer.from("extended master secret"), sessionHash]), 48);
}
function exportKeyingMaterial(label, length, masterSecret, localRandom, remoteRandom, isClient) {
const clientRandom = isClient ? localRandom : remoteRandom;
const serverRandom = isClient ? remoteRandom : localRandom;
return prfPHash(masterSecret, Buffer.concat([
Buffer.from(label),
clientRandom,
serverRandom
]), length);
}
function hash$1(algorithm, data) {
return createHash$1(algorithm).update(data).digest();
}
function prfVerifyData(masterSecret, handshakes, label, size = 12) {
const bytes = hash$1("sha256", handshakes);
return prfPHash(masterSecret, Buffer.concat([Buffer.from(label), bytes]), size);
}
function prfVerifyDataClient(masterSecret, handshakes) {
return prfVerifyData(masterSecret, handshakes, "client finished");
}
function prfVerifyDataServer(masterSecret, handshakes) {
return prfVerifyData(masterSecret, handshakes, "server finished");
}
function prfEncryptionKeys(masterSecret, clientRandom, serverRandom, prfKeyLen, prfIvLen, prfNonceLen, algorithm = "sha256") {
const size = prfKeyLen * 2 + prfIvLen * 2;
const secret = masterSecret;
const seed = Buffer.concat([serverRandom, clientRandom]);
const keyBlock = prfPHash(secret, Buffer.concat([Buffer.from("key expansion"), seed]), size, algorithm);
const stream = (0, import_src$1.createDecode)(keyBlock);
const clientWriteKey = stream.readBuffer(prfKeyLen);
const serverWriteKey = stream.readBuffer(prfKeyLen);
const clientNonceImplicit = stream.readBuffer(prfIvLen);
const serverNonceImplicit = stream.readBuffer(prfIvLen);
const clientNonce = Buffer.alloc(prfNonceLen, 0);
const serverNonce = Buffer.alloc(prfNonceLen, 0);
clientNonceImplicit.copy(clientNonce, 0);
serverNonceImplicit.copy(serverNonce, 0);
return {
clientWriteKey,
serverWriteKey,
clientNonce,
serverNonce
};
}
var SessionType = {
CLIENT: 1,
SERVER: 2
};
var AbstractCipher = class {
id = 0;
name;
hashAlgorithm;
verifyDataLength = 12;
blockAlgorithm;
kx;
/**
* Init cipher.
* @abstract
*/
init(...args) {
throw new Error("not implemented");
}
/**
* Encrypts data.
* @abstract
*/
encrypt(...args) {
throw new Error("not implemented");
}
/**
* Decrypts data.
* @abstract
*/
decrypt(...args) {
throw new Error("not implemented");
}
/**
* @returns {string}
*/
toString() {
return this.name;
}
};
var crypto$2 = webcrypto;
import_x509_cjs.cryptoProvider.set(crypto$2);
var CipherContext = class {
constructor(sessionType, certPem, keyPem, signatureHashAlgorithm) {
this.sessionType = sessionType;
this.certPem = certPem;
this.keyPem = keyPem;
if (certPem && keyPem && signatureHashAlgorithm) this.parseX509(certPem, keyPem, signatureHashAlgorithm);
}
localRandom;
remoteRandom;
cipherSuite;
remoteCertificate;
remoteKeyPair;
localKeyPair;
masterSecret;
cipher;
namedCurve;
signatureHashAlgorithm;
localCert;
localPrivateKey;
/**
*
* @param signatureHash
* @param namedCurveAlgorithm necessary when use ecdsa
*/
static createSelfSignedCertificateWithKey = async (signatureHash, namedCurveAlgorithm) => {
const signatureAlgorithmName = (() => {
switch (signatureHash.signature) {
case SignatureAlgorithm.rsa_1: return "RSASSA-PKCS1-v1_5";
case SignatureAlgorithm.ecdsa_3: return "ECDSA";
}
})();
const hash2 = (() => {
switch (signatureHash.hash) {
case HashAlgorithm.sha256_4: return "SHA-256";
}
})();
const namedCurve = (() => {
switch (namedCurveAlgorithm) {
case NamedCurveAlgorithm.secp256r1_23: return "P-256";
case NamedCurveAlgorithm.x25519_29:
if (signatureAlgorithmName === "ECDSA") return "P-256";
return "X25519";
default:
if (signatureAlgorithmName === "ECDSA") return "P-256";
if (signatureAlgorithmName === "RSASSA-PKCS1-v1_5") return "X25519";
}
})();
const alg = (() => {
switch (signatureAlgorithmName) {
case "ECDSA": return {
name: signatureAlgorithmName,
hash: hash2,
namedCurve
};
case "RSASSA-PKCS1-v1_5": return {
name: signatureAlgorithmName,
hash: hash2,
publicExponent: new Uint8Array([
1,
0,
1
]),
modulusLength: 2048
};
}
})();
const keys = await crypto$2.subtle.generateKey(alg, true, ["sign", "verify"]);
return {
certPem: (await import_x509_cjs.X509CertificateGenerator.createSelfSigned({
serialNumber: randomBytes$1(8).toString("hex"),
name: "C=AU, ST=Some-State, O=Internet Widgits Pty Ltd",
notBefore: /* @__PURE__ */ new Date(),
notAfter: new Date(Date.now() + 31536e7),
signingAlgorithm: alg,
keys
})).toString("pem"),
keyPem: import_x509_cjs.PemConverter.encode(await crypto$2.subtle.exportKey("pkcs8", keys.privateKey), "private key"),
signatureHash
};
};
encryptPacket(pkt) {
const header = pkt.recordLayerHeader;
const version = header.protocolVersion.major << 8 | header.protocolVersion.minor;
const enc = this.cipher.encrypt(this.sessionType, pkt.fragment, {
type: header.contentType,
version,
epoch: header.epoch,
sequenceNumber: header.sequenceNumber
});
pkt.fragment = enc;
pkt.recordLayerHeader.contentLen = enc.length;
return pkt;
}
decryptPacket(pkt) {
const header = pkt.recordLayerHeader;
const version = header.protocolVersion.major << 8 | header.protocolVersion.minor;
return this.cipher.decrypt(this.sessionType, pkt.fragment, {
type: header.contentType,
version,
epoch: header.epoch,
sequenceNumber: header.sequenceNumber
});
}
verifyData(buf) {
if (this.sessionType === SessionType.CLIENT) return prfVerifyDataClient(this.masterSecret, buf);
else return prfVerifyDataServer(this.masterSecret, buf);
}
signatureData(data, hash2) {
const signature = createSign(hash2).update(data);
const key = this.localPrivateKey.toPEM().toString();
return signature.sign(key);
}
generateKeySignature(hashAlgorithm) {
const clientRandom = this.sessionType === SessionType.CLIENT ? this.localRandom : this.remoteRandom;
const serverRandom = this.sessionType === SessionType.SERVER ? this.localRandom : this.remoteRandom;
const sig = this.valueKeySignature(clientRandom.serialize(), serverRandom.serialize(), this.localKeyPair.publicKey, this.namedCurve);
return this.localPrivateKey.sign(sig, hashAlgorithm);
}
parseX509(certPem, keyPem, signatureHash) {
const cert = import_build.Certificate.fromPEM(Buffer.from(certPem));
const sec = import_build.PrivateKey.fromPEM(Buffer.from(keyPem));
this.localCert = cert.raw;
this.localPrivateKey = sec;
this.signatureHashAlgorithm = signatureHash;
}
valueKeySignature(clientRandom, serverRandom, publicKey, namedCurve) {
const serverParams = Buffer.from((0, import_src$1.encode)({
type: CurveType.named_curve_3,
curve: namedCurve,
len: publicKey.length
}, {
type: import_src$1.types.uint8,
curve: import_src$1.types.uint16be,
len: import_src$1.types.uint8
}).slice());
return Buffer.concat([
clientRandom,
serverRandom,
serverParams,
publicKey
]);
}
};
var SrtpContext = class {
srtpProfile;
static findMatchingSRTPProfile(remote, local) {
for (const v of local) if (remote.includes(v)) return v;
}
};
var dumpBuffer2 = (data) => "0x" + data.toString("hex").replace(/(.)(.)/g, "$1$2 ").split(" ").filter((s) => s != void 0 && s.length > 0).join(",0x");
var getObjectSummary = (obj) => Object.entries({ ...obj }).reduce((acc, [key, value]) => {
if (typeof value === "number" || typeof value === "string") acc[key] = value;
if (Buffer.isBuffer(value)) acc[key] = dumpBuffer2(value);
return acc;
}, {});
var FragmentedHandshake = class _FragmentedHandshake {
constructor(msg_type, length, message_seq, fragment_offset, fragment_length, fragment) {
this.msg_type = msg_type;
this.length = length;
this.message_seq = message_seq;
this.fragment_offset = fragment_offset;
this.fragment_length = fragment_length;
this.fragment = fragment;
}
static spec = {
msg_type: import_src$1.types.uint8,
length: import_src$1.types.uint24be,
message_seq: import_src$1.types.uint16be,
fragment_offset: import_src$1.types.uint24be,
fragment_length: import_src$1.types.uint24be,
fragment: import_src$1.types.buffer((context) => context.current.fragment_length)
};
get summary() {
return getObjectSummary(this);
}
static createEmpty() {
return new _FragmentedHandshake(void 0, void 0, void 0, void 0, void 0, void 0);
}
static deSerialize(buf) {
return new _FragmentedHandshake(...Object.values((0, import_src$1.decode)(buf, _FragmentedHandshake.spec)));
}
serialize() {
const res = (0, import_src$1.encode)(this, _FragmentedHandshake.spec).slice();
return Buffer.from(res);
}
chunk(maxFragmentLength) {
let start = 0;
const totalLength = this.fragment.length;
if (totalLength === 0) return [new _FragmentedHandshake(this.msg_type, totalLength, this.message_seq, start, 0, this.fragment)];
const fragments = [];
if (!maxFragmentLength) maxFragmentLength = 1240;
while (start < totalLength) {
const fragmentLength = Math.min(maxFragmentLength, totalLength - start);
const data = Buffer.from(this.fragment.slice(start, start + fragmentLength));
if (data.length <= 0) throw new Error(`Zero or less bytes processed while fragmenting handshake message.`);
fragments.push(new _FragmentedHandshake(this.msg_type, totalLength, this.message_seq, start, data.length, data));
start += data.length;
}
return fragments;
}
static assemble(messages) {
if (!messages?.length) throw new Error("cannot reassemble handshake from empty array");
messages = messages.sort((a, b) => a.fragment_offset - b.fragment_offset);
const combined = Buffer.alloc(messages[0].length);
for (const msg of messages) msg.fragment.copy(combined, msg.fragment_offset);
return new _FragmentedHandshake(messages[0].msg_type, messages[0].length, messages[0].message_seq, 0, combined.length, combined);
}
static findAllFragments(fragments, type) {
const reference = fragments.find((v) => v.msg_type === type);
if (!reference) return [];
if (!fragments?.length) return [];
return fragments.filter((f) => {
return f.msg_type === reference.msg_type && f.message_seq === reference.message_seq && f.length === reference.length;
});
}
};
var { uint16be, uint24be, buffer, array, uint8, string } = import_src$1.types;
var ExtensionList = array({
type: uint16be,
data: buffer(uint16be)
}, uint16be, "bytes");
var ASN11Cert = buffer(uint24be);
var ClientCertificateType = uint8;
var DistinguishedName = string(uint16be);
var SignatureHashAlgorithm = {
hash: uint8,
signature: uint8
};
var ProtocolVersion = {
major: uint8,
minor: uint8
};
var DtlsRandom = class _DtlsRandom {
constructor(gmt_unix_time = Math.floor(Date.now() / 1e3), random_bytes = randomBytes$1(28)) {
this.gmt_unix_time = gmt_unix_time;
this.random_bytes = random_bytes;
}
static spec = {
gmt_unix_time: import_src$1.types.uint32be,
random_bytes: import_src$1.types.buffer(28)
};
static deSerialize(buf) {
return new _DtlsRandom(...Object.values((0, import_src$1.decode)(buf, _DtlsRandom.spec)));
}
static from(spec) {
return new _DtlsRandom(...Object.values(spec));
}
serialize() {
const res = (0, import_src$1.encode)(this, _DtlsRandom.spec).slice();
return Buffer.from(res);
}
};
var ClientHello = class _ClientHello {
constructor(clientVersion, random, sessionId, cookie, cipherSuites2, compressionMethods, extensions) {
this.clientVersion = clientVersion;
this.random = random;
this.sessionId = sessionId;
this.cookie = cookie;
this.cipherSuites = cipherSuites2;
this.compressionMethods = compressionMethods;
this.extensions = extensions;
}
msgType = 1;
messageSeq = 0;
static spec = {
clientVersion: {
major: import_src$1.types.uint8,
minor: import_src$1.types.uint8
},
random: DtlsRandom.spec,
sessionId: import_src$1.types.buffer(import_src$1.types.uint8),
cookie: import_src$1.types.buffer(import_src$1.types.uint8),
cipherSuites: import_src$1.types.array(import_src$1.types.uint16be, import_src$1.types.uint16be, "bytes"),
compressionMethods: import_src$1.types.array(import_src$1.types.uint8, import_src$1.types.uint8, "bytes"),
extensions: ExtensionList
};
static createEmpty() {
return new _ClientHello(void 0, void 0, void 0, void 0, void 0, void 0, void 0);
}
static deSerialize(buf) {
return new _ClientHello(...Object.values((0, import_src$1.decode)(buf, _ClientHello.spec)));
}
serialize() {
const res = (0, import_src$1.encode)(this, _ClientHello.spec).slice();
return Buffer.from(res);
}
toFragment() {
const body = this.serialize();
return new FragmentedHandshake(this.msgType, body.length, this.messageSeq, 0, body.length, body);
}
};
var MACHeader = class _MACHeader {
constructor(epoch, sequenceNumber, contentType, protocolVersion, contentLen) {
this.epoch = epoch;
this.sequenceNumber = sequenceNumber;
this.contentType = contentType;
this.protocolVersion = protocolVersion;
this.contentLen = contentLen;
}
static spec = {
epoch: import_src$1.types.uint16be,
sequenceNumber: import_src$1.types.uint48be,
contentType: import_src$1.types.uint8,
protocolVersion: ProtocolVersion,
contentLen: import_src$1.types.uint16be
};
static createEmpty() {
return new _MACHeader(void 0, void 0, void 0, void 0, void 0);
}
static deSerialize(buf) {
return new _MACHeader(...Object.values((0, import_src$1.decode)(buf, _MACHeader.spec)));
}
serialize() {
const res = (0, import_src$1.encode)(this, _MACHeader.spec).slice();
return Buffer.from(res);
}
};
var DtlsPlaintext = class _DtlsPlaintext {
constructor(recordLayerHeader, fragment) {
this.recordLayerHeader = recordLayerHeader;
this.fragment = fragment;
}
get summary() {
return {
header: this.recordLayerHeader,
fragment: dumpBuffer2(this.fragment)
};
}
static createEmpty() {
return new _DtlsPlaintext(void 0, void 0);
}
static deSerialize(buf) {
if (buf.length < 13) throw new Error("Invalid DTLS record: buffer is too short");
const contentType = buf.readUInt8(0);
const majorVersion = buf.readUInt8(1);
const minorVersion = buf.readUInt8(2);
const epoch = buf.readUInt16BE(3);
const sequenceNumber = buf.slice(5, 11).readUIntBE(0, 6);
const contentLen = buf.readUInt16BE(11);
if (buf.length < 13 + contentLen) throw new Error("Invalid DTLS record: fragment length exceeds buffer");
const fragment = buf.slice(13, 13 + contentLen);
return new _DtlsPlaintext({
contentType,
protocolVersion: {
major: majorVersion,
minor: minorVersion
},
epoch,
sequenceNumber,
contentLen
}, fragment);
}
serialize() {
const fragmentLength = this.fragment.length;
const totalLength = 13 + fragmentLength;
const buffer2 = Buffer.alloc(totalLength);
buffer2.writeUInt8(this.recordLayerHeader.contentType, 0);
buffer2.writeUInt8(this.recordLayerHeader.protocolVersion.major, 1);
buffer2.writeUInt8(this.recordLayerHeader.protocolVersion.minor, 2);
buffer2.writeUInt16BE(this.recordLayerHeader.epoch, 3);
buffer2.writeUIntBE(this.recordLayerHeader.sequenceNumber, 5, 6);
buffer2.writeUInt16BE(fragmentLength, 11);
this.fragment.copy(buffer2, 13);
return buffer2;
}
computeMACHeader() {
return new MACHeader(this.recordLayerHeader.epoch, this.recordLayerHeader.sequenceNumber, this.recordLayerHeader.contentType, this.recordLayerHeader.protocolVersion, this.recordLayerHeader.contentLen).serialize();
}
};
var createFragments = (dtls) => (handshakes) => {
dtls.lastFlight = handshakes;
return handshakes.flatMap((handshake) => {
handshake.messageSeq = dtls.sequenceNumber++;
return handshake.toFragment().chunk();
});
};
var createPlaintext = (dtls) => (fragments, recordSequenceNumber) => {
return fragments.map((msg) => {
return new DtlsPlaintext({
contentType: msg.type,
protocolVersion: dtls.version,
epoch: dtls.epoch,
sequenceNumber: recordSequenceNumber,
contentLen: msg.fragment.length
}, msg.fragment);
});
};
var AlertDesc = /* @__PURE__ */ ((AlertDesc2) => {
AlertDesc2[AlertDesc2["CloseNotify"] = 0] = "CloseNotify";
AlertDesc2[AlertDesc2["UnexpectedMessage"] = 10] = "UnexpectedMessage";
AlertDesc2[AlertDesc2["BadRecordMac"] = 20] = "BadRecordMac";
AlertDesc2[AlertDesc2["DecryptionFailed"] = 21] = "DecryptionFailed";
AlertDesc2[AlertDesc2["RecordOverflow"] = 22] = "RecordOverflow";
AlertDesc2[AlertDesc2["DecompressionFailure"] = 30] = "DecompressionFailure";
AlertDesc2[AlertDesc2["HandshakeFailure"] = 40] = "HandshakeFailure";
AlertDesc2[AlertDesc2["NoCertificate"] = 41] = "NoCertificate";
AlertDesc2[AlertDesc2["BadCertificate"] = 42] = "BadCertificate";
AlertDesc2[AlertDesc2["UnsupportedCertificate"] = 43] = "UnsupportedCertificate";
AlertDesc2[AlertDesc2["CertificateRevoked"] = 44] = "CertificateRevoked";
AlertDesc2[AlertDesc2["CertificateExpired"] = 45] = "CertificateExpired";
AlertDesc2[AlertDesc2["CertificateUnknown"] = 46] = "CertificateUnknown";
AlertDesc2[AlertDesc2["IllegalParameter"] = 47] = "IllegalParameter";
AlertDesc2[AlertDesc2["UnknownCa"] = 48] = "UnknownCa";
AlertDesc2[AlertDesc2["AccessDenied"] = 49] = "AccessDenied";
AlertDesc2[AlertDesc2["DecodeError"] = 50] = "DecodeError";
AlertDesc2[AlertDesc2["DecryptError"] = 51] = "DecryptError";
AlertDesc2[AlertDesc2["ExportRestriction"] = 60] = "ExportRestriction";
AlertDesc2[AlertDesc2["ProtocolVersion"] = 70] = "ProtocolVersion";
AlertDesc2[AlertDesc2["InsufficientSecurity"] = 71] = "InsufficientSecurity";
AlertDesc2[AlertDesc2["InternalError"] = 80] = "InternalError";
AlertDesc2[AlertDesc2["UserCanceled"] = 90] = "UserCanceled";
AlertDesc2[AlertDesc2["NoRenegotiation"] = 100] = "NoRenegotiation";
AlertDesc2[AlertDesc2["UnsupportedExtension"] = 110] = "UnsupportedExtension";
return AlertDesc2;
})(AlertDesc || {});
var warn = debug("werift-dtls : packages/dtls/src/flight/flight.ts : warn");
var err = debug("werift-dtls : packages/dtls/src/flight/flight.ts : err");
var Flight = class _Flight {
constructor(transport, dtls, flight, nextFlight) {
this.transport = transport;
this.dtls = dtls;
this.flight = flight;
this.nextFlight = nextFlight;
}
state = "PREPARING";
static RetransmitCount = 10;
createPacket(handshakes) {
const fragments = createFragments(this.dtls)(handshakes);
this.dtls.bufferHandshakeCache(fragments, true, this.flight);
return createPlaintext(this.dtls)(fragments.map((fragment) => ({
type: 22,
fragment: fragment.serialize()
})), ++this.dtls.recordSequenceNumber);
}
async transmit(buffers) {
let retransmitCount = 0;
for (; retransmitCount <= _Flight.RetransmitCount; retransmitCount++) {
this.setState("SENDING");
this.send(buffers).catch((e) => {
err("fail to send", err);
});
this.setState("WAITING");
if (this.nextFlight === void 0) {
this.setState("FINISHED");
break;
}
await setTimeout$2(1e3 * ((retransmitCount + 1) / 2));
if (this.dtls.flight >= this.nextFlight) {
this.setState("FINISHED");
break;
} else warn(this.dtls.sessionId, "retransmit", retransmitCount, this.dtls.flight);
}
if (retransmitCount > _Flight.RetransmitCount) {
err(this.dtls.sessionId, "retransmit failed", retransmitCount);
throw new Error(`over retransmitCount : ${this.flight} ${this.nextFlight}`);
}
}
send = (buf) => Promise.all(buf.map((v) => this.transport.send(v)));
setState(state) {
this.state = state;
}
};
var Flight1 = class extends Flight {
constructor(udp, dtls, cipher) {
super(udp, dtls, 1, 3);
this.cipher = cipher;
}
async exec(extensions) {
if (this.dtls.flight === 1) throw new Error();
this.dtls.flight = 1;
const hello = new ClientHello({
major: 254,
minor: 253
}, new DtlsRandom(), Buffer.from([]), Buffer.from([]), CipherSuiteList, [0], extensions);
this.dtls.version = hello.clientVersion;
this.cipher.localRandom = DtlsRandom.from(hello.random);
const packets = this.createPacket([hello]);
const buf = Buffer.concat(packets.map((v) => v.serialize()));
await this.transmit([buf]);
}
};
var log2 = debug("werift-dtls : packages/dtls/src/flight/client/flight3.ts : log");
var Flight3 = class extends Flight {
constructor(udp, dtls) {
super(udp, dtls, 3, 5);
}
async exec(verifyReq) {
if (this.dtls.flight === 3) throw new Error();
this.dtls.flight = 3;
this.dtls.handshakeCache = [];
const [clientHello] = this.dtls.lastFlight;
log2("dtls version", clientHello.clientVersion);
clientHello.cookie = verifyReq.cookie;
this.dtls.cookie = verifyReq.cookie;
const packets = this.createPacket([clientHello]);
const buf = Buffer.concat(packets.map((v) => v.serialize()));
await this.transmit([buf]);
}
};
var signTypes = {
NULL: 0,
ECDHE: 1
};
var keyTypes = {
NULL: 0,
RSA: 1,
ECDSA: 2,
PSK: 3
};
var kxTypes = {
NULL: 0,
RSA: 1,
ECDHE_RSA: 2,
ECDHE_ECDSA: 3,
PSK: 4,
ECDHE_PSK: 5
};
var KeyExchange = class {
id = 0;
name;
signType;
keyType;
/**
* @returns {string}
*/
toString() {
return this.name;
}
};
function createRSAKeyExchange() {
const exchange = new KeyExchange();
exchange.id = kxTypes.RSA;
exchange.name = "RSA";
exchange.keyType = keyTypes.RSA;
return exchange;
}
function createECDHERSAKeyExchange() {
const exchange = new KeyExchange();
exchange.id = kxTypes.ECDHE_RSA;
exchange.name = "ECDHE_RSA";
exchange.signType = signTypes.ECDHE;
exchange.keyType = keyTypes.RSA;
return exchange;
}
function createECDHEECDSAKeyExchange() {
const exchange = new KeyExchange();
exchange.id = kxTypes.ECDHE_ECDSA;
exchange.name = "ECDHE_ECDSA";
exchange.signType = signTypes.ECDHE;
exchange.keyType = keyTypes.ECDSA;
return exchange;
}
function createPSKKeyExchange() {
const exchange = new KeyExchange();
exchange.id = kxTypes.PSK;
exchange.name = "PSK";
exchange.signType = signTypes.NULL;
exchange.keyType = keyTypes.PSK;
return exchange;
}
function createECDHEPSKKeyExchange() {
const exchange = new KeyExchange();
exchange.id = kxTypes.ECDHE_PSK;
exchange.name = "ECDHE_PSK";
exchange.signType = signTypes.ECDHE;
exchange.keyType = keyTypes.PSK;
return exchange;
}
var err2 = debug("werift-dtls : packages/dtls/src/cipher/suites/aead.ts : err");
var AEADCipher = class extends AbstractCipher {
keyLength = 0;
nonceLength = 0;
ivLength = 0;
authTagLength = 0;
nonceImplicitLength = 0;
nonceExplicitLength = 0;
clientWriteKey;
serverWriteKey;
clientNonce;
serverNonce;
constructor() {
super();
}
get summary() {
return getObjectSummary(this);
}
init(masterSecret, serverRandom, clientRandom) {
const keys = prfEncryptionKeys(masterSecret, clientRandom, serverRandom, this.keyLength, this.ivLength, this.nonceLength, this.hashAlgorithm);
this.clientWriteKey = keys.clientWriteKey;
this.serverWriteKey = keys.serverWriteKey;
this.clientNonce = keys.clientNonce;
this.serverNonce = keys.serverNonce;
}
/**
* Encrypt message.
*/
encrypt(type, data, header) {
const isClient = type === SessionType.CLIENT;
const iv = isClient ? this.clientNonce : this.serverNonce;
const writeKey = isClient ? this.clientWriteKey : this.serverWriteKey;
if (!iv || !writeKey) throw new Error();
iv.writeUInt16BE(header.epoch, this.nonceImplicitLength);
iv.writeUIntBE(header.sequenceNumber, this.nonceImplicitLength + 2, 6);
const explicitNonce = iv.slice(this.nonceImplicitLength);
const additionalBuffer = this.encodeAdditionalBuffer(header, data.length);
const cipher = createCipheriv$1(this.blockAlgorithm, writeKey, iv, { authTagLength: this.authTagLength });
cipher.setAAD(additionalBuffer, { plaintextLength: data.length });
const headPart = cipher.update(data);
const finalPart = cipher.final();
const authTag = cipher.getAuthTag();
return Buffer.concat([
explicitNonce,
headPart,
finalPart,
authTag
]);
}
encodeAdditionalBuffer(header, dataLength) {
const additionalBuffer = Buffer.alloc(13);
additionalBuffer.writeUInt16BE(header.epoch, 0);
additionalBuffer.writeUintBE(header.sequenceNumber, 2, 6);
additionalBuffer.writeUInt8(header.type, 8);
additionalBuffer.writeUInt16BE(header.version, 9);
additionalBuffer.writeUInt16BE(dataLength, 11);
return additionalBuffer;
}
/**
* Decrypt message.
*/
decrypt(type, data, header) {
const isClient = type === SessionType.CLIENT;
const iv = isClient ? this.serverNonce : this.clientNonce;
const writeKey = isClient ? this.serverWriteKey : this.clientWriteKey;
if (!iv || !writeKey) throw new Error();
data.subarray(0, this.nonceExplicitLength).copy(iv, this.nonceImplicitLength);
const encrypted = data.subarray(this.nonceExplicitLength, data.length - this.authTagLength);
const authTag = data.subarray(data.length - this.authTagLength);
const additionalBuffer = this.encodeAdditionalBuffer(header, encrypted.length);
const decipher = createDecipheriv$1(this.blockAlgorithm, writeKey, iv, { authTagLength: this.authTagLength });
decipher.setAuthTag(authTag);
decipher.setAAD(additionalBuffer, { plaintextLength: encrypted.length });
const headPart = decipher.update(encrypted);
try {
const finalPart = decipher.final();
return finalPart.length > 0 ? Buffer.concat([headPart, finalPart]) : headPart;
} catch (error) {
err2("decrypt failed", error, type, dumpBuffer2(data), header, this.summary);
throw error;
}
}
};
var cipherSuites = {
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: 49195,
TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: 49196,
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: 49199,
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: 49200,
TLS_RSA_WITH_AES_128_GCM_SHA256: 156,
TLS_RSA_WITH_AES_256_GCM_SHA384: 157,
TLS_PSK_WITH_AES_128_GCM_SHA256: 168,
TLS_PSK_WITH_AES_256_GCM_SHA384: 169,
TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256: 53249,
TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384: 53250,
TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256: 52396,
TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: 52393,
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: 52392,
TLS_PSK_WITH_CHACHA20_POLY1305_SHA256: 52395
};
var AEAD_AES_128_GCM = {
K_LEN: 16,
N_MIN: 12,
N_MAX: 12,
P_MAX: 2 ** 36 - 31,
A_MAX: 2 ** 53 - 1,
C_MAX: 2 ** 36 - 15
};
var AEAD_AES_256_GCM = {
K_LEN: 32,
N_MIN: 12,
N_MAX: 12,
P_MAX: 2 ** 36 - 31,
A_MAX: 2 ** 53 - 1,
C_MAX: 2 ** 36 - 15
};
var RSA_KEY_EXCHANGE = createRSAKeyExchange();
var ECDHE_RSA_KEY_EXCHANGE = createECDHERSAKeyExchange();
var ECDHE_ECDSA_KEY_EXCHANGE = createECDHEECDSAKeyExchange();
var PSK_KEY_EXCHANGE = createPSKKeyExchange();
var ECDHE_PSK_KEY_EXCHANGE = createECDHEPSKKeyExchange();
function createCipher(cipher) {
switch (cipher) {
case cipherSuites.TLS_RSA_WITH_AES_128_GCM_SHA256: return createAEADCipher(cipherSuites.TLS_RSA_WITH_AES_128_GCM_SHA256, "TLS_RSA_WITH_AES_128_GCM_SHA256", "aes-128-gcm", RSA_KEY_EXCHANGE, AEAD_AES_128_GCM);
case cipherSuites.TLS_RSA_WITH_AES_256_GCM_SHA384: return createAEADCipher(cipherSuites.TLS_RSA_WITH_AES_256_GCM_SHA384, "TLS_RSA_WITH_AES_256_GCM_SHA384", "aes-256-gcm", RSA_KEY_EXCHANGE, AEAD_AES_256_GCM, "sha384");
case cipherSuites.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: return createAEADCipher(cipherSuites.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "aes-128-gcm", ECDHE_RSA_KEY_EXCHANGE, AEAD_AES_128_GCM);
case cipherSuites.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: return createAEADCipher(cipherSuites.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "aes-256-gcm", ECDHE_RSA_KEY_EXCHANGE, AEAD_AES_256_GCM, "sha384");
case cipherSuites.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: return createAEADCipher(cipherSuites.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "aes-128-gcm", ECDHE_ECDSA_KEY_EXCHANGE, AEAD_AES_128_GCM);
case cipherSuites.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: return createAEADCipher(cipherSuites.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "aes-256-gcm", ECDHE_ECDSA_KEY_EXCHANGE, AEAD_AES_256_GCM, "sha384");
case cipherSuites.TLS_PSK_WITH_AES_128_GCM_SHA256: return createAEADCipher(cipherSuites.TLS_PSK_WITH_AES_128_GCM_SHA256, "TLS_PSK_WITH_AES_128_GCM_SHA256", "aes-128-gcm", PSK_KEY_EXCHANGE, AEAD_AES_128_GCM, "sha256");
case cipherSuites.TLS_PSK_WITH_AES_256_GCM_SHA384: return createAEADCipher(cipherSuites.TLS_PSK_WITH_AES_256_GCM_SHA384, "TLS_PSK_WITH_AES_256_GCM_SHA384", "aes-256-gcm", PSK_KEY_EXCHANGE, AEAD_AES_256_GCM, "sha384");
case cipherSuites.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256: return createAEADCipher(cipherSuites.TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256, "TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256", "aes-128-gcm", ECDHE_PSK_KEY_EXCHANGE, AEAD_AES_128_GCM, "sha256");
case cipherSuites.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384: return createAEADCipher(cipherSuites.TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384, "TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384", "aes-256-gcm", ECDHE_PSK_KEY_EXCHANGE, AEAD_AES_256_GCM, "sha384");
}
return null;
}
function createAEADCipher(id, name, block, kx, constants, hash2 = "sha256") {
const cipher = new AEADCipher();
cipher.id = id;
cipher.name = name;
cipher.blockAlgorithm = block;
cipher.kx = kx;
cipher.hashAlgorithm = hash2;
cipher.keyLength = constants.K_LEN;
cipher.nonceLength = constants.N_MAX;
cipher.nonceImplicitLength = 4;
cipher.nonceExplicitLength = 8;
cipher.ivLength = cipher.nonceImplicitLength;
cipher.authTagLength = 16;
return cipher;
}
function generateKeyPair(namedCurve) {
switch (namedCurve) {
case NamedCurveAlgorithm.secp256r1_23: {
const { privateKey, publicKey } = p256Keypair();
return {
curve: namedCurve,
privateKey,
publicKey
};
}
case NamedCurveAlgorithm.x25519_29: {
const keys = import_nacl_fast.default.box.keyPair();
return {
curve: namedCurve,
privateKey: Buffer.from(keys.secretKey.buffer),
publicKey: Buffer.from(keys.publicKey.buffer)
};
}
default: throw new Error();
}
}
var ExtendedMasterSecret = class {
static type = 23;
};
var RenegotiationIndication = class _RenegotiationIndication {
static type = 65281;
static spec = {
type: import_src$1.types.uint16be,
data: import_src$1.types.uint8
};
type = _RenegotiationIndication.type;
data = 0;
constructor(props = {}) {
Object.assign(this, props);
}
static createEmpty() {
return new _RenegotiationIndication();
}
static deSerialize(buf) {
return new _RenegotiationIndication((0, import_src$1.decode)(buf, _RenegotiationIndication.spec));
}
serialize() {
const res = (0, import_src$1.encode)(this, _RenegotiationIndication.spec).slice();
return Buffer.from(res);
}
get extension() {
return {
type: this.type,
data: this.serialize().slice(2)
};
}
};
var UseSRTP = class _UseSRTP {
static type = 14;
static spec = {
type: import_src$1.types.uint16be,
data: import_src$1.types.buffer(import_src$1.types.uint16be)
};
type = _UseSRTP.type;
data = Buffer.from([]);
profiles = [];
mki = Buffer.from([0]);
constructor(props = {}) {
Object.assign(this, props);
}
static create(profiles, mki) {
return new _UseSRTP({
profiles,
mki
});
}
static deSerialize(buf) {
const useSrtp = new _UseSRTP((0, import_src$1.decode)(buf, _UseSRTP.spec));
const profileLength = useSrtp.data.readUInt16BE();
const profiles = new Array(profileLength / 2);
for (let i = 0; i < profiles.length; i++) profiles[i] = useSrtp.data.readUInt16BE(i * 2 + 2);
useSrtp.profiles = profiles;
useSrtp.mki = useSrtp.data.slice(profileLength + 2);
return useSrtp;
}
serialize() {
const profileLength = Buffer.alloc(2);
profileLength.writeUInt16BE(this.profiles.length * 2);
const data = Buffer.concat([
profileLength,
...this.profiles.map((profile) => {
const buf = Buffer.alloc(2);
buf.writeUInt16BE(profile);
return buf;
}),
this.mki
]);
this.data = data;
const res = (0, import_src$1.encode)(this, _UseSRTP.spec).slice();
return Buffer.from(res);
}
static fromData(buf) {
const head = Buffer.alloc(4);
head.writeUInt16BE(_UseSRTP.type);
head.writeUInt16BE(buf.length, 2);
return _UseSRTP.deSerialize(Buffer.concat([head, buf]));
}
get extension() {
return {
type: this.type,
data: this.serialize().slice(4)
};
}
};
var Certificate2 = class _Certificate {
constructor(certificateList) {
this.certificateList = certificateList;
}
msgType = 11;
messageSeq;
static spec = { certificateList: import_src$1.types.array(ASN11Cert, import_src$1.types.uint24be, "bytes") };
static createEmpty() {
return new _Certificate(void 0);
}
static deSerialize(buf) {
return new _Certificate(...Object.values((0, import_src$1.decode)(buf, _Certificate.spec)));
}
serialize() {
const res = (0, import_src$1.encode)(this, _Certificate.spec).slice();
return Buffer.from(res);
}
toFragment() {
const body = this.serialize();
return new FragmentedHandshake(this.msgType, body.length, this.messageSeq, 0, body.length, body);
}
};
var ChangeCipherSpec = class _ChangeCipherSpec {
constructor(type = 1) {
this.type = type;
}
static spec = { type: import_src$1.types.uint8 };
static createEmpty() {
return new _ChangeCipherSpec();
}
static deSerialize(buf) {
return new _ChangeCipherSpec(...Object.values((0, import_src$1.decode)(buf, _ChangeCipherSpec.spec)));
}
serialize() {
const res = (0, import_src$1.encode)(this, _ChangeCipherSpec.spec).slice();
return Buffer.from(res);
}
};
var CertificateVerify = class _CertificateVerify {
constructor(algorithm, signature) {
this.algorithm = algorithm;
this.signature = signature;
}
msgType = 15;
messageSeq;
static spec = {
algorithm: import_src$1.types.uint16be,
signature: import_src$1.types.buffer(import_src$1.types.uint16be)
};
static createEmpty() {
return new _CertificateVerify(void 0, void 0);
}
static deSerialize(buf) {
const res = (0, import_src$1.decode)(buf, _CertificateVerify.spec);
return new _CertificateVerify(...Object.values(res));
}
serialize() {
const res = (0, import_src$1.encode)(this, _CertificateVerify.spec).slice();
return Buffer.from(res);
}
toFragment() {
const body = this.serialize();
return new FragmentedHandshake(this.msgType, body.length, this.messageSeq, 0, body.length, body);
}
};
var ClientKeyExchange = class _ClientKeyExchange {
constructor(publicKey) {
this.publicKey = publicKey;
}
msgType = 16;
messageSeq;
static spec = { publicKey: import_src$1.types.buffer(import_src$1.types.uint8) };
static createEmpty() {
return new _ClientKeyExchange(void 0);
}
static deSerialize(buf) {
const res = (0, import_src$1.decode)(buf, _ClientKeyExchange.spec);
return new _ClientKeyExchange(...Object.values(res));
}
serialize() {
const res = (0, import_src$1.encode)(this, _ClientKeyExchange.spec).slice();
return Buffer.from(res);
}
toFragment() {
const body = this.serialize();
return new FragmentedHandshake(this.msgType, body.length, this.messageSeq, 0, body.length, body);
}
};
var Finished = class _Finished {
constructor(verifyData) {
this.verifyData = verifyData;
}
msgType = 20;
messageSeq;
static createEmpty() {
return new _Finished(void 0);
}
static deSerialize(buf) {
return new _Finished(buf);
}
serialize() {
return this.verifyData;
}
toFragment() {
const body = this.serialize();
return new FragmentedHandshake(this.msgType, body.length, this.messageSeq, 0, body.length, body);
}
};
var ServerCertificateRequest = class _ServerCertificateRequest {
constructor(certificateTypes2, signatures2, authorities) {
this.certificateTypes = certificateTypes2;
this.signatures = signatures2;
this.authorities = authorities;
}
msgType = 13;
messageSeq;
static spec = {
certificateTypes: import_src$1.types.array(ClientCertificateType, import_src$1.types.uint8, "bytes"),
signatures: import_src$1.types.array(SignatureHashAlgorithm, import_src$1.types.uint16be, "bytes"),
authorities: import_src$1.types.array(DistinguishedName, import_src$1.types.uint16be, "bytes")
};
static createEmpty() {
return new _ServerCertificateRequest(void 0, void 0, void 0);
}
static deSerialize(buf) {
return new _ServerCertificateRequest(...Object.values((0, import_src$1.decode)(buf, _ServerCertificateRequest.spec)));
}
serialize() {
const res = (0, import_src$1.encode)(this, _ServerCertificateRequest.spec).slice();
return Buffer.from(res);
}
toFragment() {
const body = this.serialize();
return new FragmentedHandshake(this.msgType, body.length, this.messageSeq, 0, body.length, body);
}
};
var ServerHello = class _ServerHello {
constructor(serverVersion, random, sessionId, cipherSuite, compressionMethod, extensions) {
this.serverVersion = serverVersion;
this.random = random;
this.sessionId = sessionId;
this.cipherSuite = cipherSuite;
this.compressionMethod = compressionMethod;
this.extensions = extensions;
}
msgType = 2;
messageSeq;
static spec = {
serverVersion: ProtocolVersion,
random: DtlsRandom.spec,
sessionId: import_src$1.types.buffer(import_src$1.types.uint8),
cipherSuite: import_src$1.types.uint16be,
compressionMethod: import_src$1.types.uint8
};
static createEmpty() {
return new _ServerHello(void 0, void 0, void 0, void 0, void 0, void 0);
}
static deSerialize(buf) {
const res = (0, import_src$1.decode)(buf, _ServerHello.spec);
const cls = new _ServerHello(...Object.values(res));
if (cls.serialize().length < buf.length) return new _ServerHello(...Object.values((0, import_src$1.decode)(buf, {
..._ServerHello.spec,
extensions: ExtensionList
})));
return cls;
}
serialize() {
const res = this.extensions === void 0 ? (0, import_src$1.encode)(this, _ServerHello.spec).slice() : (0, import_src$1.encode)(this, {
..._ServerHello.spec,
extensions: ExtensionList
}).slice();
return Buffer.from(res);
}
toFragment() {
const body = this.serialize();
return new FragmentedHandshake(this.msgType, body.length, this.messageSeq, 0, body.length, body);
}
};
var ServerHelloDone = class _ServerHelloDone {
msgType = 14;
messageSeq;
static spec = {};
static createEmpty() {
return new _ServerHelloDone();
}
static deSerialize(buf) {
return new _ServerHelloDone(...Object.values((0, import_src$1.decode)(buf, _ServerHelloDone.spec)));
}
serialize() {
const res = (0, import_src$1.encode)(this, _ServerHelloDone.spec).slice();
return Buffer.from(res);
}
toFragment() {
const body = this.serialize();
return new FragmentedHandshake(this.msgType, body.length, this.messageSeq, 0, body.length, body);
}
};
function encodeBuffer(obj, spec) {
return Buffer.from((0, import_src$1.encode)(obj, spec).slice());
}
var ServerKeyExchange = class _ServerKeyExchange {
constructor(ellipticCurveType, namedCurve, publicKeyLength, publicKey, hashAlgorithm, signatureAlgorithm, signatureLength, signature) {
this.ellipticCurveType = ellipticCurveType;
this.namedCurve = namedCurve;
this.publicKeyLength = publicKeyLength;
this.publicKey = publicKey;
this.hashAlgorithm = hashAlgorithm;
this.signatureAlgorithm = signatureAlgorithm;
this.signatureLength = signatureLength;
this.signature = signature;
}
msgType = 12;
messageSeq;
static spec = {
ellipticCurveType: import_src$1.types.uint8,
namedCurve: import_src$1.types.uint16be,
publicKeyLength: import_src$1.types.uint8,
publicKey: import_src$1.types.buffer((ctx) => ctx.current.publicKeyLength),
hashAlgorithm: import_src$1.types.uint8,
signatureAlgorithm: import_src$1.types.uint8,
signatureLength: import_src$1.types.uint16be,
signature: import_src$1.types.buffer((ctx) => ctx.current.signatureLength)
};
static createEmpty() {
return new _ServerKeyExchange(void 0, void 0, void 0, void 0, void 0, void 0, void 0, void 0);
}
static deSerialize(buf) {
const res = (0, import_src$1.decode)(buf, _ServerKeyExchange.spec);
return new _ServerKeyExchange(...Object.values(res));
}
serialize() {
return encodeBuffer(this, _ServerKeyExchange.spec);
}
toFragment() {
const body = this.serialize();
return new FragmentedHandshake(this.msgType, body.length, this.messageSeq, 0, body.length, body);
}
};
var ProtectionProfileAes128CmHmacSha1_80 = 1;
var ProtectionProfileAeadAes128Gcm = 7;
var Profiles = [1, 7];
var keyLength = (profile) => {
switch (profile) {
case 1:
case 7: return 16;
}
};
var saltLength = (profile) => {
switch (profile) {
case 1: return 14;
case 7: return 12;
}
};
function leb128encode(value) {
if (!Number.isInteger(value) || value < 0 || !Number.isSafeInteger(value)) throw new Error("LEB128 encode requires a non-negative safe integer");
const bytes = [];
let remaining = value;
do {
let byte = remaining & 127;
remaining = Math.floor(remaining / 128);
if (remaining !== 0) byte |= 128;
bytes.push(byte);
} while (remaining !== 0);
return Buffer.from(bytes);
}
var log3 = debug("werift-rtp : packages/rtp/src/codec/av1.ts");
var AV1RtpPayload = class _AV1RtpPayload {
/**
* RtpStartsWithFragment
* MUST be set to 1 if the first OBU element is an OBU fragment that is a continuation of an OBU fragment from the previous packet, and MUST be set to 0 otherwise.
*/
zBit_RtpStartsWithFragment;
/**
* RtpEndsWithFragment
* MUST be set to 1 if the last OBU element is an OBU fragment that will continue in the next packet, and MUST be set to 0 otherwise.
*/
yBit_RtpEndsWithFragment;
/**
* RtpNumObus
* two bit field that describes the number of OBU elements in the packet. This field MUST be set equal to 0 or equal to the number of OBU elements contained in the packet. If set to 0, each OBU element MUST be preceded by a length field.
*/
w_RtpNumObus;
/**
* RtpStartsNewCodedVideoSequence
* MUST be set to 1 if the packet is the first packet of a coded video sequence, and MUST be set to 0 otherwise.
*/
nBit_RtpStartsNewCodedVideoSequence;
obu_or_fragment = [];
static deSerialize = (buf) => {
const p = new _AV1RtpPayload();
let offset = 0;
p.zBit_RtpStartsWithFragment = getBit(buf[offset], 0);
p.yBit_RtpEndsWithFragment = getBit(buf[offset], 1);
p.w_RtpNumObus = getBit(buf[offset], 2, 2);
p.nBit_RtpStartsNewCodedVideoSequence = getBit(buf[offset], 4);
offset++;
if (p.nBit_RtpStartsNewCodedVideoSequence && p.zBit_RtpStartsWithFragment) throw new Error();
[...Array(p.w_RtpNumObus - 1).keys()].forEach((i) => {
const [elementSize, bytes] = leb128decode(buf.subarray(offset));
const start = offset + bytes;
const end = start + elementSize;
let isFragment2 = false;
if (p.zBit_RtpStartsWithFragment && i === 0) isFragment2 = true;
p.obu_or_fragment.push({
data: buf.subarray(start, end),
isFragment: isFragment2
});
offset += bytes + elementSize;
});
let isFragment = false;
if (p.yBit_RtpEndsWithFragment || p.w_RtpNumObus === 1 && p.zBit_RtpStartsWithFragment) isFragment = true;
p.obu_or_fragment.push({
data: buf.subarray(offset),
isFragment
});
return p;
};
static isDetectedFinalPacketInSequence(header) {
return header.marker;
}
get isKeyframe() {
return this.nBit_RtpStartsNewCodedVideoSequence === 1;
}
static getFrame(payloads) {
const frames = [];
const objects = payloads.flatMap((p) => p.obu_or_fragment).reduce((acc, cur, i) => {
acc[i] = cur;
return acc;
}, {});
const length = Object.keys(objects).length;
for (const i of Object.keys(objects).map(Number)) {
const exist = objects[i];
if (!exist) continue;
const { data, isFragment } = exist;
if (isFragment) {
let fragments = [];
for (let head = i; head < length; head++) {
const target = objects[head];
if (target.isFragment) {
fragments.push(target.data);
delete objects[head];
} else break;
}
if (fragments.length <= 1) {
log3("fragment lost, maybe packet lost");
fragments = [];
}
frames.push(Buffer.concat(fragments));
} else frames.push(data);
}
const obus = frames.map((f) => AV1Obu.deSerialize(f));
const lastObu = obus.pop();
return Buffer.concat([...obus.map((o) => {
o.obu_has_size_field = 1;
return o.serialize();
}), lastObu.serialize()]);
}
};
var AV1Obu = class _AV1Obu {
obu_forbidden_bit;
obu_type;
obu_extension_flag;
obu_has_size_field;
obu_reserved_1bit;
payload;
static deSerialize(buf) {
const obu = new _AV1Obu();
let offset = 0;
obu.obu_forbidden_bit = getBit(buf[offset], 0);
obu.obu_type = OBU_TYPES[getBit(buf[offset], 1, 4)];
obu.obu_extension_flag = getBit(buf[offset], 5);
obu.obu_has_size_field = getBit(buf[offset], 6);
obu.obu_reserved_1bit = getBit(buf[offset], 7);
offset++;
obu.payload = buf.subarray(offset);
return obu;
}
serialize() {
const header = new BitWriter2(8).set(this.obu_forbidden_bit).set(OBU_TYPE_IDS[this.obu_type], 4).set(this.obu_extension_flag).set(this.obu_has_size_field).set(this.obu_reserved_1bit).buffer;
let obuSize = Buffer.alloc(0);
if (this.obu_has_size_field) obuSize = leb128encode(this.payload.length);
return Buffer.concat([
header,
obuSize,
this.payload
]);
}
};
function leb128decode(buf) {
let value = 0;
let leb128bytes = 0;
for (let i = 0; i < 8; i++) {
if (i >= buf.length) throw new Error("LEB128 decode incomplete");
const leb128byte = buf.readUInt8(i);
value += (leb128byte & 127) * 128 ** i;
leb128bytes++;
if (!(leb128byte & 128)) {
if (!Number.isSafeInteger(value)) throw new Error("LEB128 value exceeds safe integer");
return [value, leb128bytes];
}
}
throw new Error("LEB128 decode incomplete");
}
var OBU_TYPES = {
0: "Reserved",
1: "OBU_SEQUENCE_HEADER",
2: "OBU_TEMPORAL_DELIMITER",
3: "OBU_FRAME_HEADER",
4: "OBU_TILE_GROUP",
5: "OBU_METADATA",
6: "OBU_FRAME",
7: "OBU_REDUNDANT_FRAME_HEADER",
8: "OBU_TILE_LIST",
15: "OBU_PADDING"
};
var OBU_TYPE_IDS = Object.entries(OBU_TYPES).reduce((acc, [key, value]) => {
acc[value] = Number(key);
return acc;
}, {});
var H264RtpPayload = class _H264RtpPayload {
/**forbidden_zero_bit */
f;
/**nal_ref_idc */
nri;
/**nal_unit_types */
nalUnitType;
/**start of a fragmented NAL unit */
s;
/**end of a fragmented NAL unit */
e;
r;
nalUnitPayloadType;
payload;
fragment;
static deSerialize(buf, fragment) {
const h264 = new _H264RtpPayload();
let offset = 0;
const naluHeader = buf[offset];
h264.f = getBit(naluHeader, 0);
h264.nri = getBit(naluHeader, 1, 2);
h264.nalUnitType = getBit(naluHeader, 3, 5);
offset++;
h264.s = getBit(buf[offset], 0);
h264.e = getBit(buf[offset], 1);
h264.r = getBit(buf[offset], 2);
h264.nalUnitPayloadType = getBit(buf[offset], 3, 5);
offset++;
if (0 < h264.nalUnitType && h264.nalUnitType < NalUnitType.stap_a) h264.payload = this.packaging(buf);
else if (h264.nalUnitType === NalUnitType.stap_a) {
let offset2 = stap_aHeaderSize;
let result = Buffer.alloc(0);
while (offset2 < buf.length) {
const naluSize = buf.readUInt16BE(offset2);
offset2 += stap_aNALULengthSize;
result = Buffer.concat([result, this.packaging(buf.subarray(offset2, offset2 + naluSize))]);
offset2 += naluSize;
}
h264.payload = result;
} else if (h264.nalUnitType === NalUnitType.fu_a) {
if (!fragment) fragment = Buffer.alloc(0);
const fu = buf.subarray(offset);
h264.fragment = Buffer.concat([fragment, fu]);
if (h264.e) {
const bitStream = new BitStream(Buffer.alloc(1)).writeBits(1, 0).writeBits(2, h264.nri).writeBits(5, h264.nalUnitPayloadType);
const nalu = Buffer.concat([bitStream.uint8Array, h264.fragment]);
h264.fragment = void 0;
h264.payload = this.packaging(nalu);
}
}
return h264;
}
static packaging(buf) {
return Buffer.concat([annex_bNALUStartCode, buf]);
}
static isDetectedFinalPacketInSequence(header) {
return header.marker;
}
get isKeyframe() {
return this.nalUnitType === NalUnitType.idrSlice || this.nalUnitPayloadType === NalUnitType.idrSlice;
}
get isPartitionHead() {
if (this.nalUnitType === NalUnitType.fu_a || this.nalUnitType === NalUnitType.fu_b) return this.s !== 0;
return true;
}
};
var NalUnitType = {
idrSlice: 5,
stap_a: 24,
stap_b: 25,
mtap16: 26,
mtap24: 27,
fu_a: 28,
fu_b: 29
};
var annex_bNALUStartCode = Buffer.from([
0,
0,
0,
1
]);
var stap_aHeaderSize = 1;
var stap_aNALULengthSize = 2;
var OpusRtpPayload = class _OpusRtpPayload {
payload;
static deSerialize(buf) {
const opus = new _OpusRtpPayload();
opus.payload = buf;
return opus;
}
static isDetectedFinalPacketInSequence(header) {
return true;
}
get isKeyframe() {
return true;
}
static createCodecPrivate(samplingFrequency = 48e3) {
return Buffer.concat([
Buffer.from("OpusHead"),
bufferWriter([1, 1], [1, 2]),
bufferWriterLE([
2,
4,
2,
1
], [
312,
samplingFrequency,
0,
0
])
]);
}
};
var Vp8RtpPayload = class _Vp8RtpPayload {
xBit;
nBit;
sBit;
pid;
iBit;
lBit;
tBit;
kBit;
mBit;
pictureId;
payload;
size0 = 0;
hBit;
ver;
pBit;
size1 = 0;
size2 = 0;
static deSerialize(buf) {
const p = new _Vp8RtpPayload();
let offset = 0;
p.xBit = getBit(buf[offset], 0);
p.nBit = getBit(buf[offset], 2);
p.sBit = getBit(buf[offset], 3);
p.pid = getBit(buf[offset], 5, 3);
offset++;
if (p.xBit) {
p.iBit = getBit(buf[offset], 0);
p.lBit = getBit(buf[offset], 1);
p.tBit = getBit(buf[offset], 2);
p.kBit = getBit(buf[offset], 3);
offset++;
}
if (p.iBit) {
p.mBit = getBit(buf[offset], 0);
if (p.mBit) {
const _7 = paddingByte(getBit(buf[offset], 1, 7));
const _8 = paddingByte(buf[offset + 1]);
p.pictureId = Number.parseInt(_7 + _8, 2);
offset += 2;
} else {
p.pictureId = getBit(buf[offset], 1, 7);
offset++;
}
}
if (p.lBit) offset++;
if (p.lBit || p.kBit) {
if (p.tBit) {}
if (p.kBit) {}
offset++;
}
p.payload = buf.subarray(offset);
if (p.payloadHeaderExist) {
p.size0 = getBit(buf[offset], 0, 3);
p.hBit = getBit(buf[offset], 3);
p.ver = getBit(buf[offset], 4, 3);
p.pBit = getBit(buf[offset], 7);
offset++;
p.size1 = buf[offset];
offset++;
p.size2 = buf[offset];
}
return p;
}
static isDetectedFinalPacketInSequence(header) {
return header.marker;
}
get isKeyframe() {
return this.pBit === 0;
}
get isPartitionHead() {
return this.sBit === 1;
}
get payloadHeaderExist() {
return this.sBit === 1 && this.pid === 0;
}
get size() {
if (this.payloadHeaderExist) return this.size0 + 8 * this.size1 + 2048 * this.size2;
return 0;
}
};
var Vp9RtpPayload = class _Vp9RtpPayload {
/**Picture ID (PID) present */
iBit;
/**Inter-picture predicted frame */
pBit;
/**Layer indices present */
lBit;
/**Flexible mode */
fBit;
/**Start of a frame */
bBit;
/**End of a frame */
eBit;
/**Scalability structure */
vBit;
zBit;
m;
pictureId;
tid;
u;
sid;
/**inter_layer_predicted */
d;
tl0PicIdx;
pDiff = [];
n_s;
y;
g;
width = [];
height = [];
n_g = 0;
pgT = [];
pgU = [];
pgP_Diff = [];
payload;
static deSerialize(buf) {
const { p, offset } = this.parseRtpPayload(buf);
p.payload = buf.subarray(offset);
return p;
}
static parseRtpPayload(buf) {
const p = new _Vp9RtpPayload();
let offset = 0;
p.iBit = getBit(buf[offset], 0);
p.pBit = getBit(buf[offset], 1);
p.lBit = getBit(buf[offset], 2);
p.fBit = getBit(buf[offset], 3);
p.bBit = getBit(buf[offset], 4);
p.eBit = getBit(buf[offset], 5);
p.vBit = getBit(buf[offset], 6);
p.zBit = getBit(buf[offset], 7);
offset++;
if (p.iBit) {
p.m = getBit(buf[offset], 0);
if (p.m) {
const _7 = paddingByte(getBit(buf[offset], 1, 7));
const _8 = paddingByte(buf[offset + 1]);
p.pictureId = Number.parseInt(_7 + _8, 2);
offset += 2;
} else {
p.pictureId = getBit(buf[offset], 1, 7);
offset++;
}
}
if (p.lBit) {
p.tid = getBit(buf[offset], 0, 3);
p.u = getBit(buf[offset], 3);
p.sid = getBit(buf[offset], 4, 3);
p.d = getBit(buf[offset], 7);
offset++;
if (p.fBit === 0) {
p.tl0PicIdx = buf[offset];
offset++;
}
}
if (p.fBit && p.pBit) for (;;) {
p.pDiff = [...p.pDiff, getBit(buf[offset], 0, 7)];
const n = getBit(buf[offset], 7);
offset++;
if (n === 0) break;
}
if (p.vBit) {
p.n_s = getBit(buf[offset], 0, 3);
p.y = getBit(buf[offset], 3);
p.g = getBit(buf[offset], 4);
offset++;
if (p.y) [...Array(p.n_s + 1)].forEach(() => {
p.width.push(buf.readUInt16BE(offset));
offset += 2;
p.height.push(buf.readUInt16BE(offset));
offset += 2;
});
if (p.g) {
p.n_g = buf[offset];
offset++;
}
if (p.n_g > 0) [...Array(p.n_g).keys()].forEach((i) => {
p.pgT.push(getBit(buf[offset], 0, 3));
p.pgU.push(getBit(buf[offset], 3));
const r = getBit(buf[offset], 4, 2);
offset++;
p.pgP_Diff[i] = [];
if (r > 0) [...Array(r)].forEach(() => {
p.pgP_Diff[i].push(buf[offset]);
offset++;
});
});
}
return {
offset,
p
};
}
static isDetectedFinalPacketInSequence(header) {
return header.marker;
}
get isKeyframe() {
return !!(!this.pBit && this.bBit && (!this.sid || !this.lBit));
}
get isPartitionHead() {
return this.bBit && (!this.lBit || !this.d);
}
};
var DePacketizerBase = class {
payload;
fragment;
static deSerialize(buf, fragment) {
return {};
}
static isDetectedFinalPacketInSequence(header) {
return true;
}
get isKeyframe() {
return true;
}
};
function dePacketizeRtpPackets(codec, packets, frameFragmentBuffer) {
const basicCodecParser = (Depacketizer) => {
const partitions = [];
for (const p of packets) {
const codec2 = Depacketizer.deSerialize(p.payload, frameFragmentBuffer);
if (codec2.fragment) {
frameFragmentBuffer ??= Buffer.alloc(0);
frameFragmentBuffer = codec2.fragment;
} else if (codec2.payload) frameFragmentBuffer = void 0;
partitions.push(codec2);
}
return {
isKeyframe: !!partitions.find((f) => f.isKeyframe),
data: Buffer.concat(partitions.map((f) => f.payload).filter((p) => p)),
sequence: packets.at(-1)?.header.sequenceNumber ?? 0,
timestamp: packets.at(-1)?.header.timestamp ?? 0,
frameFragmentBuffer
};
};
switch (codec.toUpperCase()) {
case "AV1": {
const chunks = packets.map((p) => AV1RtpPayload.deSerialize(p.payload));
return {
isKeyframe: !!chunks.find((f) => f.isKeyframe),
data: AV1RtpPayload.getFrame(chunks),
sequence: packets.at(-1)?.header.sequenceNumber ?? 0,
timestamp: packets.at(-1)?.header.timestamp ?? 0
};
}
case "MPEG4/ISO/AVC": return basicCodecParser(H264RtpPayload);
case "VP8": return basicCodecParser(Vp8RtpPayload);
case "VP9": return basicCodecParser(Vp9RtpPayload);
case "OPUS": return basicCodecParser(OpusRtpPayload);
default: throw new Error();
}
}
var depacketizerCodecs = [
"MPEG4/ISO/AVC",
"VP8",
"VP9",
"OPUS",
"AV1"
];
function enumerate(arr) {
return arr.map((v, i) => [i, v]);
}
function growBufferSize(buf, size) {
const glow = Buffer.alloc(size);
buf.copy(glow);
return glow;
}
function Int(v) {
return Number.parseInt(v.toString(), 10);
}
var timer = {
setTimeout: (...args) => {
const id = setTimeout(...args);
return () => clearTimeout(id);
},
setInterval: (...args) => {
const id = setInterval(() => {
args[0]();
}, ...args.slice(1));
return () => clearInterval(id);
}
};
function isMedia(buf) {
const firstByte = buf[0];
return firstByte > 127 && firstByte < 192;
}
var RTCP_HEADER_SIZE = 4;
var RtcpHeader = class _RtcpHeader {
version = 2;
padding = false;
count = 0;
type = 0;
/**このパケットの長さは、ヘッダーと任意のパディングを含む32ビットワードから 1を引いたものである */
length = 0;
constructor(props = {}) {
Object.assign(this, props);
}
static serialize(type, count, payload, length) {
const buf = new _RtcpHeader({
type,
count,
version: 2,
length
}).serialize();
return Buffer.concat([buf, payload]);
}
serialize() {
const v_p_rc = new BitWriter(8);
v_p_rc.set(2, 0, this.version);
if (this.padding) v_p_rc.set(1, 2, 1);
v_p_rc.set(5, 3, this.count);
return bufferWriter([
1,
1,
2
], [
v_p_rc.value,
this.type,
this.length
]);
}
static deSerialize(buf) {
const [v_p_rc, type, length] = bufferReader(buf, [
1,
1,
2
]);
const version = getBit(v_p_rc, 0, 2);
const padding = getBit(v_p_rc, 2, 1) > 0;
const count = getBit(v_p_rc, 3, 5);
return new _RtcpHeader({
version,
padding,
count,
type,
length
});
}
};
var FullIntraRequest = class _FullIntraRequest {
static count = 4;
count = _FullIntraRequest.count;
senderSsrc;
mediaSsrc;
fir = [];
constructor(props = {}) {
Object.assign(this, props);
}
get length() {
return Math.floor(this.serialize().length / 4 - 1);
}
static deSerialize(data) {
const [senderSsrc, mediaSsrc] = bufferReader(data, [4, 4]);
const fir = [];
for (let i = 8; i < data.length; i += 8) fir.push({
ssrc: data.readUInt32BE(i),
sequenceNumber: data[i + 4]
});
return new _FullIntraRequest({
senderSsrc,
mediaSsrc,
fir
});
}
serialize() {
const ssrcs = bufferWriter([4, 4], [this.senderSsrc, this.mediaSsrc]);
const fir = Buffer.alloc(this.fir.length * 8);
this.fir.forEach(({ ssrc, sequenceNumber }, i) => {
fir.writeUInt32BE(ssrc, i * 8);
fir[i * 8 + 4] = sequenceNumber;
});
return Buffer.concat([ssrcs, fir]);
}
};
var PictureLossIndication = class _PictureLossIndication {
static count = 1;
count = _PictureLossIndication.count;
length = 2;
senderSsrc;
mediaSsrc;
constructor(props = {}) {
Object.assign(this, props);
}
static deSerialize(data) {
const [senderSsrc, mediaSsrc] = bufferReader(data, [4, 4]);
return new _PictureLossIndication({
senderSsrc,
mediaSsrc
});
}
serialize() {
return bufferWriter([4, 4], [this.senderSsrc, this.mediaSsrc]);
}
};
var ReceiverEstimatedMaxBitrate = class _ReceiverEstimatedMaxBitrate {
static count = 15;
length;
count = _ReceiverEstimatedMaxBitrate.count;
senderSsrc;
mediaSsrc;
uniqueID = "REMB";
ssrcNum = 0;
brExp;
brMantissa;
bitrate;
ssrcFeedbacks = [];
constructor(props = {}) {
Object.assign(this, props);
}
static deSerialize(data) {
const [senderSsrc, mediaSsrc, uniqueID, ssrcNum, e_m] = bufferReader(data, [
4,
4,
4,
1,
1
]);
const brExp = getBit(e_m, 0, 6);
const brMantissa = (getBit(e_m, 6, 2) << 16) + (data[14] << 8) + data[15];
const bitrate = brExp > 46 ? 18446744073709551615n : BigInt(brMantissa) << BigInt(brExp);
const ssrcFeedbacks = [];
for (let i = 16; i < data.length; i += 4) {
const feedback = data.slice(i).readUIntBE(0, 4);
ssrcFeedbacks.push(feedback);
}
return new _ReceiverEstimatedMaxBitrate({
senderSsrc,
mediaSsrc,
uniqueID: bufferWriter([4], [uniqueID]).toString(),
ssrcNum,
brExp,
brMantissa,
ssrcFeedbacks,
bitrate
});
}
serialize() {
const constant = Buffer.concat([
bufferWriter([4, 4], [this.senderSsrc, this.mediaSsrc]),
Buffer.from(this.uniqueID),
bufferWriter([1], [this.ssrcNum])
]);
const writer = new BitWriter(24);
writer.set(6, 0, this.brExp).set(18, 6, this.brMantissa);
const feedbacks = Buffer.concat(this.ssrcFeedbacks.map((feedback) => bufferWriter([4], [feedback])));
const buf = Buffer.concat([
constant,
bufferWriter([3], [writer.value]),
feedbacks
]);
this.length = buf.length / 4;
return buf;
}
};
var log4 = debug("werift-rtp: /rtcp/psfb/index");
var RtcpPayloadSpecificFeedback = class _RtcpPayloadSpecificFeedback {
static type = 206;
type = _RtcpPayloadSpecificFeedback.type;
feedback;
constructor(props = {}) {
Object.assign(this, props);
}
serialize() {
const payload = this.feedback.serialize();
return RtcpHeader.serialize(this.type, this.feedback.count, payload, this.feedback.length);
}
static deSerialize(data, header) {
let feedback;
switch (header.count) {
case FullIntraRequest.count:
feedback = FullIntraRequest.deSerialize(data);
break;
case PictureLossIndication.count:
feedback = PictureLossIndication.deSerialize(data);
break;
case ReceiverEstimatedMaxBitrate.count:
feedback = ReceiverEstimatedMaxBitrate.deSerialize(data);
break;
default: log4("unknown psfb packet", header.count);
}
return new _RtcpPayloadSpecificFeedback({ feedback });
}
};
var RtcpRrPacket = class _RtcpRrPacket {
ssrc = 0;
reports = [];
static type = 201;
type = _RtcpRrPacket.type;
constructor(props = {}) {
Object.assign(this, props);
}
serialize() {
let payload = bufferWriter([4], [this.ssrc]);
payload = Buffer.concat([payload, ...this.reports.map((report) => report.serialize())]);
return RtcpHeader.serialize(_RtcpRrPacket.type, this.reports.length, payload, Math.floor(payload.length / 4));
}
static deSerialize(data, count) {
const [ssrc] = bufferReader(data, [4]);
let pos = 4;
const reports = [];
for (let _ = 0; _ < count; _++) {
reports.push(RtcpReceiverInfo.deSerialize(data.slice(pos, pos + 24)));
pos += 24;
}
return new _RtcpRrPacket({
ssrc,
reports
});
}
};
var RtcpReceiverInfo = class _RtcpReceiverInfo {
ssrc;
fractionLost;
packetsLost;
highestSequence;
jitter;
/**last SR */
lsr;
/**delay since last SR */
dlsr;
constructor(props = {}) {
Object.assign(this, props);
}
toJSON() {
return {
ssrc: this.ssrc,
fractionLost: this.fractionLost,
packetsLost: this.packetsLost,
highestSequence: this.highestSequence,
jitter: this.jitter,
lsr: this.lsr,
dlsr: this.dlsr
};
}
serialize() {
return bufferWriter([
4,
1,
3,
4,
4,
4,
4
], [
this.ssrc,
this.fractionLost,
this.packetsLost,
this.highestSequence,
this.jitter,
this.lsr,
this.dlsr
]);
}
static deSerialize(data) {
const [ssrc, fractionLost, packetsLost, highestSequence, jitter, lsr, dlsr] = bufferReader(data, [
4,
1,
3,
4,
4,
4,
4
]);
return new _RtcpReceiverInfo({
ssrc,
fractionLost,
packetsLost,
highestSequence,
jitter,
lsr,
dlsr
});
}
};
var RtcpTransportLayerFeedbackType = 205;
var GenericNack = class _GenericNack {
static count = 1;
count = _GenericNack.count;
header;
senderSsrc;
mediaSourceSsrc;
lost = [];
toJSON() {
return {
lost: this.lost,
senderSsrc: this.senderSsrc,
mediaSourceSsrc: this.mediaSourceSsrc
};
}
constructor(props = {}) {
Object.assign(this, props);
if (!this.header) this.header = new RtcpHeader({
type: RtcpTransportLayerFeedbackType,
count: this.count,
version: 2
});
}
static deSerialize(data, header) {
const [senderSsrc, mediaSourceSsrc] = bufferReader(data, [4, 4]);
const lost = [];
for (let pos = 8; pos < data.length; pos += 4) {
const [pid, blp] = bufferReader(data.subarray(pos), [2, 2]);
lost.push(pid);
for (let diff = 0; diff < 16; diff++) if (blp >> diff & 1) lost.push(pid + diff + 1);
}
return new _GenericNack({
header,
senderSsrc,
mediaSourceSsrc,
lost
});
}
serialize() {
const ssrcPair = bufferWriter([4, 4], [this.senderSsrc, this.mediaSourceSsrc]);
const fci = [];
if (this.lost.length > 0) {
let headPid = this.lost[0], blp = 0;
this.lost.slice(1).forEach((pid) => {
const diff = pid - headPid - 1;
if (diff >= 0 && diff < 16) blp |= 1 << diff;
else {
fci.push(bufferWriter([2, 2], [headPid, blp]));
headPid = pid;
blp = 0;
}
});
fci.push(bufferWriter([2, 2], [headPid, blp]));
}
const buf = Buffer.concat([ssrcPair, Buffer.concat(fci)]);
this.header.length = buf.length / 4;
return Buffer.concat([this.header.serialize(), buf]);
}
};
var log5 = debug("werift/rtp/rtcp/rtpfb/twcc");
var TransportWideCC = class _TransportWideCC {
static count = 15;
count = _TransportWideCC.count;
length = 2;
senderSsrc;
mediaSourceSsrc;
baseSequenceNumber;
packetStatusCount;
/** 24bit multiples of 64ms */
referenceTime;
fbPktCount;
packetChunks = [];
recvDeltas = [];
header;
constructor(props = {}) {
Object.assign(this, props);
if (!this.header) this.header = new RtcpHeader({
type: 205,
count: this.count,
version: 2
});
}
static deSerialize(data, header) {
const [senderSsrc, mediaSsrc, baseSequenceNumber, packetStatusCount, referenceTime, fbPktCount] = bufferReader(data, [
4,
4,
2,
2,
3,
1
]);
const packetChunks = [];
const recvDeltas = [];
let packetStatusPos = 16;
for (let processedPacketNum = 0; processedPacketNum < packetStatusCount;) {
const type = getBit(data.slice(packetStatusPos, packetStatusPos + 1)[0], 0, 1);
let iPacketStatus;
switch (type) {
case 0:
{
const packetStatus = RunLengthChunk.deSerialize(data.slice(packetStatusPos, packetStatusPos + 2));
iPacketStatus = packetStatus;
const packetNumberToProcess = Math.min(packetStatusCount - processedPacketNum, packetStatus.runLength);
if (packetStatus.packetStatus === 1 || packetStatus.packetStatus === 2) for (let _ = 0; _ < packetNumberToProcess; _++) recvDeltas.push(new RecvDelta({ type: packetStatus.packetStatus }));
processedPacketNum += packetNumberToProcess;
}
break;
case 1: {
const packetStatus = StatusVectorChunk.deSerialize(data.slice(packetStatusPos, packetStatusPos + 2));
iPacketStatus = packetStatus;
if (packetStatus.symbolSize === 0) packetStatus.symbolList.forEach((v) => {
if (v === 1) recvDeltas.push(new RecvDelta({ type: 1 }));
});
if (packetStatus.symbolSize === 1) packetStatus.symbolList.forEach((v) => {
if (v === 1 || v === 2) recvDeltas.push(new RecvDelta({ type: v }));
});
processedPacketNum += packetStatus.symbolList.length;
}
}
if (!iPacketStatus) throw new Error();
packetStatusPos += 2;
packetChunks.push(iPacketStatus);
}
let recvDeltaPos = packetStatusPos;
recvDeltas.forEach((delta) => {
if (delta.type === 1) {
delta.deSerialize(data.slice(recvDeltaPos, recvDeltaPos + 1));
recvDeltaPos++;
}
if (delta.type === 2) {
delta.deSerialize(data.slice(recvDeltaPos, recvDeltaPos + 2));
recvDeltaPos += 2;
}
});
return new _TransportWideCC({
senderSsrc,
mediaSourceSsrc: mediaSsrc,
baseSequenceNumber,
packetStatusCount,
referenceTime,
fbPktCount,
recvDeltas,
packetChunks,
header
});
}
serialize() {
const constBuf = bufferWriter([
4,
4,
2,
2,
3,
1
], [
this.senderSsrc,
this.mediaSourceSsrc,
this.baseSequenceNumber,
this.packetStatusCount,
this.referenceTime,
this.fbPktCount
]);
const chunks = Buffer.concat(this.packetChunks.map((chunk) => chunk.serialize()));
const deltas = Buffer.concat(this.recvDeltas.map((delta) => {
try {
return delta.serialize();
} catch (error) {
log5(error?.message);
return;
}
}).filter((v) => v));
const buf = Buffer.concat([
constBuf,
chunks,
deltas
]);
if (this.header.padding && buf.length % 4 !== 0) {
const rest = 4 - buf.length % 4;
const padding = Buffer.alloc(rest);
padding[padding.length - 1] = padding.length;
this.header.length = Math.floor((buf.length + padding.length) / 4);
return Buffer.concat([
this.header.serialize(),
buf,
padding
]);
}
this.header.length = Math.floor(buf.length / 4);
return Buffer.concat([this.header.serialize(), buf]);
}
get packetResults() {
const currentSequenceNumber = this.baseSequenceNumber - 1;
const results = this.packetChunks.filter((v) => v instanceof RunLengthChunk).flatMap((chunk) => chunk.results(currentSequenceNumber));
let deltaIdx = 0;
let currentReceivedAtMs = BigInt(this.referenceTime) * 64n;
for (const result of results) {
const recvDelta = this.recvDeltas[deltaIdx];
if (!result.received || !recvDelta) continue;
currentReceivedAtMs += BigInt(recvDelta.delta) / 1000n;
result.delta = recvDelta.delta;
result.receivedAtMs = Number(currentReceivedAtMs);
deltaIdx++;
}
return results;
}
};
var RunLengthChunk = class _RunLengthChunk {
type;
packetStatus;
/** 13bit */
runLength;
constructor(props = {}) {
Object.assign(this, props);
this.type = 0;
}
static deSerialize(data) {
const packetStatus = getBit(data[0], 1, 2);
const runLength = (getBit(data[0], 3, 5) << 8) + data[1];
return new _RunLengthChunk({
type: 0,
packetStatus,
runLength
});
}
serialize() {
return new BitWriter2(16).set(0).set(this.packetStatus, 2).set(this.runLength, 13).buffer;
}
results(currentSequenceNumber) {
const received = this.packetStatus === 1 || this.packetStatus === 2;
const results = [];
for (let i = 0; i <= this.runLength; ++i) results.push(new PacketResult({
sequenceNumber: ++currentSequenceNumber,
received
}));
return results;
}
};
var StatusVectorChunk = class _StatusVectorChunk {
type;
symbolSize;
symbolList = [];
constructor(props = {}) {
Object.assign(this, props);
}
static deSerialize(data) {
const type = 1;
let symbolSize = getBit(data[0], 1, 1);
const symbolList = [];
function range(n, cb) {
for (let i = 0; i < n; i++) cb(i);
}
switch (symbolSize) {
case 0:
range(6, (i) => symbolList.push(getBit(data[0], 2 + i, 1)));
range(8, (i) => symbolList.push(getBit(data[1], i, 1)));
break;
case 1:
range(3, (i) => symbolList.push(getBit(data[0], 2 + i * 2, 2)));
range(4, (i) => symbolList.push(getBit(data[1], i * 2, 2)));
break;
default: symbolSize = (getBit(data[0], 2, 6) << 8) + data[1];
}
return new _StatusVectorChunk({
type,
symbolSize,
symbolList
});
}
serialize() {
const buf = Buffer.alloc(2);
const writer = new BitWriter2(16).set(1).set(this.symbolSize);
const bits = this.symbolSize === 0 ? 1 : 2;
this.symbolList.forEach((v) => {
writer.set(v, bits);
});
buf.writeUInt16BE(writer.value);
return buf;
}
};
var RecvDelta = class _RecvDelta {
/**optional (If undefined, it will be set automatically.)*/
type;
/**micro sec */
delta;
constructor(props = {}) {
Object.assign(this, props);
}
static deSerialize(data) {
let type;
let delta;
if (data.length === 1) {
type = 1;
delta = 250 * data[0];
} else if (data.length === 2) {
type = 2;
delta = 250 * data.readInt16BE();
}
if (type === void 0 || delta === void 0) throw new Error();
return new _RecvDelta({
type,
delta
});
}
deSerialize(data) {
const res = _RecvDelta.deSerialize(data);
this.delta = res.delta;
}
parsed = false;
parseDelta() {
this.delta = Math.floor(this.delta / 250);
if (this.delta < 0 || this.delta > 255) {
if (this.delta > 32767) this.delta = 32767;
if (this.delta < -32768) this.delta = -32768;
if (!this.type) this.type = 2;
} else if (!this.type) this.type = 1;
this.parsed = true;
}
serialize() {
if (!this.parsed) this.parseDelta();
if (this.type === 1) {
const buf = Buffer.alloc(1);
buf.writeUInt8(this.delta);
return buf;
} else if (this.type === 2) {
const buf = Buffer.alloc(2);
buf.writeInt16BE(this.delta);
return buf;
}
throw new Error("errDeltaExceedLimit " + this.delta + " " + this.type);
}
};
var PacketChunk = /* @__PURE__ */ ((PacketChunk2) => {
PacketChunk2[PacketChunk2["TypeTCCRunLengthChunk"] = 0] = "TypeTCCRunLengthChunk";
PacketChunk2[PacketChunk2["TypeTCCStatusVectorChunk"] = 1] = "TypeTCCStatusVectorChunk";
PacketChunk2[PacketChunk2["packetStatusChunkLength"] = 2] = "packetStatusChunkLength";
return PacketChunk2;
})(PacketChunk || {});
var PacketStatus = /* @__PURE__ */ ((PacketStatus2) => {
PacketStatus2[PacketStatus2["TypeTCCPacketNotReceived"] = 0] = "TypeTCCPacketNotReceived";
PacketStatus2[PacketStatus2["TypeTCCPacketReceivedSmallDelta"] = 1] = "TypeTCCPacketReceivedSmallDelta";
PacketStatus2[PacketStatus2["TypeTCCPacketReceivedLargeDelta"] = 2] = "TypeTCCPacketReceivedLargeDelta";
PacketStatus2[PacketStatus2["TypeTCCPacketReceivedWithoutDelta"] = 3] = "TypeTCCPacketReceivedWithoutDelta";
return PacketStatus2;
})(PacketStatus || {});
var PacketResult = class {
sequenceNumber = 0;
delta = 0;
received = false;
receivedAtMs = 0;
constructor(props) {
Object.assign(this, props);
}
};
var log6 = debug("werift-rtp:packages/rtp/rtcp/rtpfb/index");
var RtcpTransportLayerFeedback = class _RtcpTransportLayerFeedback {
static type = RtcpTransportLayerFeedbackType;
type = _RtcpTransportLayerFeedback.type;
feedback;
header;
constructor(props = {}) {
Object.assign(this, props);
}
serialize() {
return this.feedback.serialize();
}
static deSerialize(data, header) {
let feedback;
switch (header.count) {
case GenericNack.count:
feedback = GenericNack.deSerialize(data, header);
break;
case TransportWideCC.count:
feedback = TransportWideCC.deSerialize(data, header);
break;
default: log6("unknown rtpfb packet", header.count);
}
return new _RtcpTransportLayerFeedback({
feedback,
header
});
}
};
var RtcpSourceDescriptionPacket = class _RtcpSourceDescriptionPacket {
static type = 202;
type = _RtcpSourceDescriptionPacket.type;
chunks = [];
constructor(props) {
Object.assign(this, props);
}
get length() {
let length = 0;
this.chunks.forEach((chunk) => length += chunk.length);
return length;
}
serialize() {
let payload = Buffer.concat(this.chunks.map((chunk) => chunk.serialize()));
while (payload.length % 4) payload = Buffer.concat([payload, Buffer.from([0])]);
return RtcpHeader.serialize(this.type, this.chunks.length, payload, payload.length / 4);
}
static deSerialize(payload, header) {
const chunks = [];
for (let i = 0; i < payload.length;) {
const chunk = SourceDescriptionChunk.deSerialize(payload.slice(i));
chunks.push(chunk);
i += chunk.length;
}
return new _RtcpSourceDescriptionPacket({ chunks });
}
};
var SourceDescriptionChunk = class _SourceDescriptionChunk {
source;
items = [];
constructor(props = {}) {
Object.assign(this, props);
}
get length() {
let length = 4;
this.items.forEach((item) => length += item.length);
length += 1;
length += getPadding(length);
return length;
}
serialize() {
const data = Buffer.concat([bufferWriter([4], [this.source]), Buffer.concat(this.items.map((item) => item.serialize()))]);
return Buffer.concat([data, Buffer.alloc(getPadding(data.length))]);
}
static deSerialize(data) {
const source = data.readUInt32BE();
const items = [];
for (let i = 4; i < data.length;) {
if (data[i] === 0) break;
const item = SourceDescriptionItem.deSerialize(data.slice(i));
items.push(item);
i += item.length;
}
return new _SourceDescriptionChunk({
source,
items
});
}
};
var SourceDescriptionItem = class _SourceDescriptionItem {
type;
text;
constructor(props) {
Object.assign(this, props);
}
get length() {
return 2 + Buffer.from(this.text).length;
}
serialize() {
const text = Buffer.from(this.text);
return Buffer.concat([bufferWriter([1, 1], [this.type, text.length]), text]);
}
static deSerialize(data) {
const type = data[0];
const octetCount = data[1];
const text = data.slice(2, 2 + octetCount).toString();
return new _SourceDescriptionItem({
type,
text
});
}
};
function getPadding(len) {
if (len % 4 == 0) return 0;
return 4 - len % 4;
}
var RtcpSrPacket = class _RtcpSrPacket {
ssrc = 0;
senderInfo;
reports = [];
static type = 200;
type = _RtcpSrPacket.type;
constructor(props) {
Object.assign(this, props);
}
toJSON() {
return {
ssrc: this.ssrc,
senderInfo: this.senderInfo.toJSON(),
reports: this.reports.map((r) => r.toJSON())
};
}
serialize() {
let payload = Buffer.alloc(4);
payload.writeUInt32BE(this.ssrc);
payload = Buffer.concat([payload, this.senderInfo.serialize()]);
payload = Buffer.concat([payload, ...this.reports.map((report) => report.serialize())]);
return RtcpHeader.serialize(_RtcpSrPacket.type, this.reports.length, payload, Math.floor(payload.length / 4));
}
static deSerialize(payload, count) {
const ssrc = payload.readUInt32BE();
const senderInfo = RtcpSenderInfo.deSerialize(payload.subarray(4, 24));
let pos = 24;
const reports = [];
for (let _ = 0; _ < count; _++) {
reports.push(RtcpReceiverInfo.deSerialize(payload.subarray(pos, pos + 24)));
pos += 24;
}
return new _RtcpSrPacket({
ssrc,
senderInfo,
reports
});
}
};
var RtcpSenderInfo = class _RtcpSenderInfo {
ntpTimestamp;
rtpTimestamp;
packetCount;
octetCount;
constructor(props = {}) {
Object.assign(this, props);
}
toJSON() {
return {
ntpTimestamp: ntpTime2Sec(this.ntpTimestamp),
rtpTimestamp: this.rtpTimestamp
};
}
serialize() {
return bufferWriter([
8,
4,
4,
4
], [
this.ntpTimestamp,
this.rtpTimestamp,
this.packetCount,
this.octetCount
]);
}
static deSerialize(data) {
const [ntpTimestamp, rtpTimestamp, packetCount, octetCount] = bufferReader(data, [
8,
4,
4,
4
]);
return new _RtcpSenderInfo({
ntpTimestamp,
rtpTimestamp,
packetCount,
octetCount
});
}
};
var ntpTime2Sec = (ntp) => {
const [ntpSec, ntpMsec] = bufferReader(bufferWriter([8], [ntp]), [4, 4]);
return Number(`${ntpSec}.${ntpMsec}`);
};
var log7 = debug("werift-rtp:packages/rtp/src/rtcp/rtcp.ts");
var RtcpPacketConverter = class {
static deSerialize(data) {
let pos = 0;
const packets = [];
while (pos < data.length) {
const header = RtcpHeader.deSerialize(data.subarray(pos, pos + 4));
pos += 4;
let payload = data.subarray(pos);
pos += header.length * 4;
if (header.padding) payload = payload.subarray(0, payload.length - payload.subarray(-1)[0]);
try {
switch (header.type) {
case RtcpSrPacket.type:
packets.push(RtcpSrPacket.deSerialize(payload, header.count));
break;
case RtcpRrPacket.type:
packets.push(RtcpRrPacket.deSerialize(payload, header.count));
break;
case RtcpSourceDescriptionPacket.type:
packets.push(RtcpSourceDescriptionPacket.deSerialize(payload, header));
break;
case RtcpTransportLayerFeedback.type:
packets.push(RtcpTransportLayerFeedback.deSerialize(payload, header));
break;
case RtcpPayloadSpecificFeedback.type: packets.push(RtcpPayloadSpecificFeedback.deSerialize(payload, header));
}
} catch (error) {
log7("deSerialize RTCP", error);
}
}
return packets;
}
};
function isRtcp(buf) {
return buf.length >= 2 && buf[1] >= 192 && buf[1] <= 208;
}
var RTP_EXTENSION_URI = {
sdesMid: "urn:ietf:params:rtp-hdrext:sdes:mid",
sdesRTPStreamID: "urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",
repairedRtpStreamId: "urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",
transportWideCC: "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",
absSendTime: "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",
dependencyDescriptor: "https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension",
audioLevelIndication: "urn:ietf:params:rtp-hdrext:ssrc-audio-level",
videoOrientation: "urn:3gpp:video-orientation"
};
function rtpHeaderExtensionsParser(extensions, extIdUriMap) {
return extensions.map((extension) => {
const uri = extIdUriMap[extension.id];
if (!uri) return {
uri: "unknown",
value: extension.payload
};
switch (uri) {
case RTP_EXTENSION_URI.sdesMid:
case RTP_EXTENSION_URI.sdesRTPStreamID:
case RTP_EXTENSION_URI.repairedRtpStreamId: return {
uri,
value: deserializeString(extension.payload)
};
case RTP_EXTENSION_URI.transportWideCC: return {
uri,
value: deserializeUint16BE(extension.payload)
};
case RTP_EXTENSION_URI.absSendTime: return {
uri,
value: deserializeAbsSendTime(extension.payload)
};
case RTP_EXTENSION_URI.audioLevelIndication: return {
uri,
value: deserializeAudioLevelIndication(extension.payload)
};
case RTP_EXTENSION_URI.videoOrientation: return {
uri,
value: deserializeVideoOrientation(extension.payload)
};
default: return {
uri,
value: extension.payload
};
}
}).reduce((acc, cur) => {
if (cur) acc[cur.uri] = cur.value;
return acc;
}, {});
}
function serializeSdesMid(id) {
return Buffer.from(id);
}
function serializeSdesRTPStreamID(id) {
return Buffer.from(id);
}
function serializeRepairedRtpStreamId(id) {
return Buffer.from(id);
}
function serializeTransportWideCC(transportSequenceNumber) {
return bufferWriter([2], [transportSequenceNumber]);
}
function serializeAbsSendTime(ntpTime2) {
const buf = Buffer.alloc(3);
const time = ntpTime2 >> 14n & 16777215n;
buf.writeUIntBE(Number(time), 0, 3);
return buf;
}
function serializeAudioLevelIndication(level) {
const stream = new BitStream(Buffer.alloc(1));
stream.writeBits(1, 1);
stream.writeBits(7, level);
return stream.uint8Array;
}
function deserializeString(buf) {
return buf.toString();
}
function deserializeUint16BE(buf) {
return buf.readUInt16BE();
}
function deserializeAbsSendTime(buf) {
return bufferReader(buf, [3])[0];
}
function deserializeAudioLevelIndication(buf) {
const stream = new BitStream(buf);
return {
v: stream.readBits(1) === 1,
level: stream.readBits(7)
};
}
function deserializeVideoOrientation(payload) {
const stream = new BitStream(payload);
stream.readBits(4);
return {
c: stream.readBits(1),
f: stream.readBits(1),
r1: stream.readBits(1),
r0: stream.readBits(1)
};
}
var log8 = debug("packages/rtp/src/rtp/red/packet.ts");
var Red = class _Red {
header;
blocks = [];
static deSerialize(bufferOrArrayBuffer) {
const buf = bufferOrArrayBuffer instanceof ArrayBuffer ? Buffer.from(bufferOrArrayBuffer) : bufferOrArrayBuffer;
const red = new _Red();
let offset = 0;
[red.header, offset] = RedHeader.deSerialize(buf);
red.header.fields.forEach(({ blockLength, timestampOffset: timestampOffset2, blockPT }) => {
if (blockLength && timestampOffset2) {
const block = buf.subarray(offset, offset + blockLength);
red.blocks.push({
block,
blockPT,
timestampOffset: timestampOffset2
});
offset += blockLength;
} else {
const block = buf.subarray(offset);
red.blocks.push({
block,
blockPT
});
}
});
return red;
}
serialize() {
this.header = new RedHeader();
for (const { timestampOffset: timestampOffset2, blockPT, block } of this.blocks) if (timestampOffset2) this.header.fields.push({
fBit: 1,
blockPT,
blockLength: block.length,
timestampOffset: timestampOffset2
});
else this.header.fields.push({
fBit: 0,
blockPT
});
let buf = this.header.serialize();
for (const { block } of this.blocks) buf = Buffer.concat([buf, block]);
return buf;
}
};
var RedHeader = class _RedHeader {
fields = [];
static deSerialize(buf) {
let offset = 0;
const header = new _RedHeader();
for (;;) {
const field = {};
header.fields.push(field);
const bitStream = new BitStream(buf.subarray(offset));
field.fBit = bitStream.readBits(1);
field.blockPT = bitStream.readBits(7);
offset++;
if (field.fBit === 0) break;
field.timestampOffset = bitStream.readBits(14);
field.blockLength = bitStream.readBits(10);
offset += 3;
}
return [header, offset];
}
serialize() {
let buf = Buffer.alloc(0);
for (const field of this.fields) try {
if (field.timestampOffset && field.blockLength) {
const bitStream = new BitStream(Buffer.alloc(4)).writeBits(1, field.fBit).writeBits(7, field.blockPT).writeBits(14, field.timestampOffset).writeBits(10, field.blockLength);
buf = Buffer.concat([buf, bitStream.uint8Array]);
} else {
const bitStream = new BitStream(Buffer.alloc(1)).writeBits(1, 0).writeBits(7, field.blockPT);
buf = Buffer.concat([buf, bitStream.uint8Array]);
}
} catch (error) {
log8(error?.message);
}
return buf;
}
};
var RedEncoder = class {
constructor(distance = 1) {
this.distance = distance;
}
cache = [];
cacheSize = 10;
push(payload) {
this.cache.push(payload);
if (this.cache.length > this.cacheSize) this.cache.shift();
}
build() {
const red = new Red();
const redundantPayloads = this.cache.slice(-(this.distance + 1));
const presentPayload = redundantPayloads.pop();
if (!presentPayload) return red;
redundantPayloads.forEach((redundant) => {
const timestampOffset2 = uint32Add(presentPayload.timestamp, -redundant.timestamp);
if (timestampOffset2 > Max14Uint) return;
red.blocks.push({
block: redundant.block,
blockPT: redundant.blockPT,
timestampOffset: timestampOffset2
});
});
red.blocks.push({
block: presentPayload.block,
blockPT: presentPayload.blockPT
});
return red;
}
};
var Max14Uint = 16383;
var RedHandler = class {
size = 150;
sequenceNumbers = [];
push(red, base) {
const packets = [];
red.blocks.forEach(({ blockPT, timestampOffset: timestampOffset2, block }, i) => {
const sequenceNumber = uint16Add(base.header.sequenceNumber, -(red.blocks.length - (i + 1)));
if (timestampOffset2) packets.push(new RtpPacket(new RtpHeader({
timestamp: uint32Add(base.header.timestamp, -timestampOffset2),
payloadType: blockPT,
ssrc: base.header.ssrc,
sequenceNumber,
marker: true
}), block));
else packets.push(new RtpPacket(new RtpHeader({
timestamp: base.header.timestamp,
payloadType: blockPT,
ssrc: base.header.ssrc,
sequenceNumber,
marker: true
}), block));
});
return packets.filter((p) => {
if (this.sequenceNumbers.includes(p.header.sequenceNumber)) return false;
else {
if (this.sequenceNumbers.length > this.size) this.sequenceNumbers.shift();
this.sequenceNumbers.push(p.header.sequenceNumber);
return true;
}
});
}
};
var ExtensionProfiles = {
OneByte: 48862,
TwoByte: 4096
};
var seqNumOffset = 2;
var timestampOffset = 4;
var ssrcOffset = 8;
var csrcOffset = 12;
var csrcSize = 4;
var RtpHeader = class _RtpHeader {
version = 2;
padding = false;
paddingSize = 0;
extension = false;
marker = false;
payloadOffset = 0;
payloadType = 0;
/**16bit, 初期値はランダムである必要があります*/
sequenceNumber = 0;
/**32bit microsec (milli/1000), 初期値はランダムである必要があります*/
timestamp = 0;
ssrc = 0;
csrcLength = 0;
csrc = [];
extensionProfile = ExtensionProfiles.OneByte;
/**deserialize only */
extensionLength;
extensions = [];
constructor(props = {}) {
Object.assign(this, props);
}
static deSerialize(rawPacket) {
const h = new _RtpHeader();
let currOffset = 0;
const v_p_x_cc = rawPacket[currOffset++];
h.version = getBit(v_p_x_cc, 0, 2);
h.padding = getBit(v_p_x_cc, 2) > 0;
h.extension = getBit(v_p_x_cc, 3) > 0;
h.csrcLength = getBit(v_p_x_cc, 4, 4);
h.csrc = [...Array(h.csrcLength)].map(() => {
const csrc = rawPacket.readUInt32BE(currOffset);
currOffset += 4;
return csrc;
});
currOffset += csrcOffset - 1;
const m_pt = rawPacket[1];
h.marker = getBit(m_pt, 0) > 0;
h.payloadType = getBit(m_pt, 1, 7);
h.sequenceNumber = rawPacket.readUInt16BE(seqNumOffset);
h.timestamp = rawPacket.readUInt32BE(timestampOffset);
h.ssrc = rawPacket.readUInt32BE(ssrcOffset);
for (let i = 0; i < h.csrc.length; i++) {
const offset = csrcOffset + i * csrcSize;
h.csrc[i] = rawPacket.subarray(offset).readUInt32BE();
}
if (h.extension) {
h.extensionProfile = rawPacket.subarray(currOffset).readUInt16BE();
currOffset += 2;
const extensionLength = rawPacket.subarray(currOffset).readUInt16BE() * 4;
h.extensionLength = extensionLength;
currOffset += 2;
switch (h.extensionProfile) {
case ExtensionProfiles.OneByte:
{
const end = currOffset + extensionLength;
while (currOffset < end) {
if (rawPacket[currOffset] === 0) {
currOffset++;
continue;
}
const extId = rawPacket[currOffset] >> 4;
const len = (rawPacket[currOffset] & (rawPacket[currOffset] ^ 240)) + 1;
currOffset++;
if (extId === 15) break;
const extension = {
id: extId,
payload: rawPacket.subarray(currOffset, currOffset + len)
};
h.extensions = [...h.extensions, extension];
currOffset += len;
}
}
break;
case ExtensionProfiles.TwoByte:
{
const end = currOffset + extensionLength;
while (currOffset < end) {
if (rawPacket[currOffset] === 0) {
currOffset++;
continue;
}
const extId = rawPacket[currOffset];
currOffset++;
const len = rawPacket[currOffset];
currOffset++;
const extension = {
id: extId,
payload: rawPacket.subarray(currOffset, currOffset + len)
};
h.extensions = [...h.extensions, extension];
currOffset += len;
}
}
break;
default: {
const extension = {
id: 0,
payload: rawPacket.subarray(currOffset, currOffset + extensionLength)
};
h.extensions = [...h.extensions, extension];
currOffset += h.extensions[0].payload.length;
}
}
}
h.payloadOffset = currOffset;
if (h.padding) h.paddingSize = rawPacket[rawPacket.length - 1];
return h;
}
get serializeSize() {
const { csrc, extensionProfile, extensions } = this;
let size = 12 + csrc.length * csrcSize;
if (extensions.length > 0 || this.extension === true) {
let extSize = 4;
switch (extensionProfile) {
case ExtensionProfiles.OneByte:
for (const extension of extensions) extSize += 1 + extension.payload.length;
break;
case ExtensionProfiles.TwoByte:
for (const extension of extensions) extSize += 2 + extension.payload.length;
break;
default: extSize += extensions[0].payload.length;
}
size += Math.floor((extSize + 3) / 4) * 4;
}
return size;
}
serialize(size) {
const buf = Buffer.alloc(size);
let offset = 0;
const v_p_x_cc = new BitWriter(8);
v_p_x_cc.set(2, 0, this.version);
if (this.padding) v_p_x_cc.set(1, 2, 1);
if (this.extensions.length > 0) this.extension = true;
if (this.extension) v_p_x_cc.set(1, 3, 1);
v_p_x_cc.set(4, 4, this.csrc.length);
buf.writeUInt8(v_p_x_cc.value, offset++);
const m_pt = new BitWriter(8);
if (this.marker) m_pt.set(1, 0, 1);
m_pt.set(7, 1, this.payloadType);
buf.writeUInt8(m_pt.value, offset++);
buf.writeUInt16BE(this.sequenceNumber, seqNumOffset);
offset += 2;
buf.writeUInt32BE(this.timestamp, timestampOffset);
offset += 4;
buf.writeUInt32BE(this.ssrc, ssrcOffset);
offset += 4;
for (const csrc of this.csrc) {
buf.writeUInt32BE(csrc, offset);
offset += 4;
}
if (this.extension) {
const extHeaderPos = offset;
buf.writeUInt16BE(this.extensionProfile, offset);
offset += 4;
const startExtensionsPos = offset;
switch (this.extensionProfile) {
case ExtensionProfiles.OneByte:
for (const extension of this.extensions) {
buf.writeUInt8(extension.id << 4 | extension.payload.length - 1, offset++);
extension.payload.copy(buf, offset);
offset += extension.payload.length;
}
break;
case ExtensionProfiles.TwoByte:
for (const extension of this.extensions) {
buf.writeUInt8(extension.id, offset++);
buf.writeUInt8(extension.payload.length, offset++);
extension.payload.copy(buf, offset);
offset += extension.payload.length;
}
break;
default: {
const extLen = this.extensions[0].payload.length;
if (extLen % 4 != 0) throw new Error();
this.extensions[0].payload.copy(buf, offset);
offset += extLen;
}
}
const extSize = offset - startExtensionsPos;
const roundedExtSize = Math.trunc((extSize + 3) / 4) * 4;
buf.writeUInt16BE(Math.trunc(roundedExtSize / 4), extHeaderPos + 2);
for (let i = 0; i < roundedExtSize - extSize; i++) {
buf.writeUInt8(0, offset);
offset++;
}
}
this.payloadOffset = offset;
return buf;
}
};
var RtpPacket = class _RtpPacket {
constructor(header, payload) {
this.header = header;
this.payload = payload;
}
get serializeSize() {
return this.header.serializeSize + this.payload.length;
}
clone() {
return new _RtpPacket(new RtpHeader({ ...this.header }), this.payload);
}
serialize() {
let buf = this.header.serialize(this.header.serializeSize + this.payload.length);
const { payloadOffset } = this.header;
this.payload.copy(buf, payloadOffset);
if (this.header.padding) {
const padding = Buffer.alloc(this.header.paddingSize);
padding.writeUInt8(this.header.paddingSize, this.header.paddingSize - 1);
buf = Buffer.concat([buf, padding]);
}
return buf;
}
static deSerialize(buf) {
const header = RtpHeader.deSerialize(buf);
return new _RtpPacket(header, buf.subarray(header.payloadOffset, buf.length - header.paddingSize));
}
clear() {
this.payload = null;
}
};
function unwrapRtx(rtx, payloadType, ssrc) {
return new RtpPacket(new RtpHeader({
payloadType,
marker: rtx.header.marker,
sequenceNumber: rtx.payload.readUInt16BE(0),
timestamp: rtx.header.timestamp,
ssrc
}), rtx.payload.subarray(2));
}
function wrapRtx(packet, payloadType, sequenceNumber, ssrc) {
const originalSequence = Buffer.allocUnsafe(2);
originalSequence.writeUInt16BE(packet.header.sequenceNumber, 0);
return new RtpPacket(new RtpHeader({
payloadType,
marker: packet.header.marker,
sequenceNumber,
timestamp: packet.header.timestamp,
ssrc,
csrc: packet.header.csrc,
extensions: packet.header.extensions
}), Buffer.concat([originalSequence, packet.payload]));
}
var CipherAesBase = class {
constructor(srtpSessionKey, srtpSessionSalt, srtcpSessionKey, srtcpSessionSalt) {
this.srtpSessionKey = srtpSessionKey;
this.srtpSessionSalt = srtpSessionSalt;
this.srtcpSessionKey = srtcpSessionKey;
this.srtcpSessionSalt = srtcpSessionSalt;
}
encryptRtp(header, payload, rolloverCounter) {
return Buffer.from([]);
}
decryptRtp(cipherText, rolloverCounter, header) {
return [];
}
encryptRTCP(rawRtcp, srtcpIndex) {
return Buffer.from([]);
}
decryptRTCP(encrypted) {
return [];
}
};
var SrtpAuthenticationError = class extends Error {
constructor(message) {
super(message);
this.name = "SrtpAuthenticationError";
}
};
var minRtpHeaderSize = 12;
var minRtcpPacketSize = 8;
function parseSrtpRtpHeader(packet, authTagLength, message = "Failed to authenticate SRTP packet") {
const authTagOffset = packet.length - authTagLength;
assertAuthenticatedPacketLength(packet.length >= minRtpHeaderSize + authTagLength, message);
const header = wrapAuthenticationError(() => RtpHeader.deSerialize(packet.subarray(0, authTagOffset)), message);
header.paddingSize = 0;
assertAuthenticatedPacketLength(header.payloadOffset >= minRtpHeaderSize && header.payloadOffset <= authTagOffset, message);
return header;
}
function parseSrtcpHeader(packet, authTagLength, srtcpIndexSize3, message = "Failed to authenticate SRTCP packet") {
assertAuthenticatedPacketLength(packet.length >= minRtcpPacketSize + authTagLength + srtcpIndexSize3, message);
return wrapAuthenticationError(() => RtcpHeader.deSerialize(packet.subarray(0, 4)), message);
}
function assertAuthenticatedPacketLength(condition, message) {
if (!condition) throw new SrtpAuthenticationError(message);
}
function wrapAuthenticationError(parse, message) {
try {
return parse();
} catch {
throw new SrtpAuthenticationError(message);
}
}
function finalizeSrtpRtpHeader(header, packet, message = "Failed to authenticate SRTP packet") {
if (!header.padding) {
header.paddingSize = 0;
return header;
}
assertAuthenticatedPacketLength(packet.length > header.payloadOffset, message);
const paddingSize = packet[packet.length - 1];
assertAuthenticatedPacketLength(paddingSize > 0 && paddingSize <= packet.length - header.payloadOffset, message);
header.paddingSize = paddingSize;
return header;
}
var CipherAesCtr = class extends CipherAesBase {
constructor(srtpSessionKey, srtpSessionSalt, srtcpSessionKey, srtcpSessionSalt, srtpSessionAuthTag, srtcpSessionAuthTag) {
super(srtpSessionKey, srtpSessionSalt, srtcpSessionKey, srtcpSessionSalt);
this.srtpSessionAuthTag = srtpSessionAuthTag;
this.srtcpSessionAuthTag = srtcpSessionAuthTag;
}
authTagLength = 10;
encryptRtp(header, payload, rolloverCounter) {
const headerBuffer = header.serialize(header.serializeSize);
const counter = this.generateCounter(header.sequenceNumber, rolloverCounter, header.ssrc, this.srtpSessionSalt);
const enc = createCipheriv$1("aes-128-ctr", this.srtpSessionKey, counter).update(payload);
const authTag = this.generateSrtpAuthTag(rolloverCounter, headerBuffer, enc);
return Buffer.concat([
headerBuffer,
enc,
authTag
]);
}
decryptRtp(cipherText, rolloverCounter, header = parseSrtpRtpHeader(cipherText, this.authTagLength)) {
const authTagOffset = cipherText.length - this.authTagLength;
const encryptedPacket = cipherText.subarray(0, authTagOffset);
assertAuthTag(cipherText.subarray(authTagOffset), this.generateSrtpAuthTag(rolloverCounter, encryptedPacket.subarray(0, header.payloadOffset), encryptedPacket.subarray(header.payloadOffset)), "Failed to authenticate SRTP packet");
const counter = this.generateCounter(header.sequenceNumber, rolloverCounter, header.ssrc, this.srtpSessionSalt);
const cipher = createDecipheriv$1("aes-128-ctr", this.srtpSessionKey, counter);
const payload = encryptedPacket.subarray(header.payloadOffset);
const buf = cipher.update(payload);
const dst = Buffer.concat([encryptedPacket.subarray(0, header.payloadOffset), buf]);
return [dst, finalizeSrtpRtpHeader(header, dst, "Failed to authenticate SRTP packet")];
}
encryptRTCP(rtcpPacket, srtcpIndex) {
let out = Buffer.from(rtcpPacket);
const ssrc = out.readUInt32BE(4);
const counter = this.generateCounter(srtcpIndex & 65535, srtcpIndex >> 16, ssrc, this.srtcpSessionSalt);
createCipheriv$1("aes-128-ctr", this.srtcpSessionKey, counter).update(out.slice(8)).copy(out, 8);
out = Buffer.concat([out, Buffer.alloc(4)]);
out.writeUInt32BE(srtcpIndex, out.length - 4);
out[out.length - 4] |= 128;
const authTag = this.generateSrtcpAuthTag(out);
out = Buffer.concat([out, authTag]);
return out;
}
decryptRTCP(encrypted) {
const header = parseSrtcpHeader(encrypted, this.authTagLength, srtcpIndexSize);
const tailOffset = encrypted.length - (this.authTagLength + srtcpIndexSize);
const authenticatedPortion = encrypted.subarray(0, encrypted.length - this.authTagLength);
assertAuthTag(encrypted.subarray(encrypted.length - this.authTagLength), this.generateSrtcpAuthTag(authenticatedPortion), "Failed to authenticate SRTCP packet");
const out = Buffer.from(encrypted).slice(0, tailOffset);
if (encrypted[tailOffset] >>> 7 === 0) return [out, header];
let srtcpIndex = encrypted.readUInt32BE(tailOffset);
srtcpIndex &= 2147483647;
const ssrc = encrypted.readUInt32BE(4);
const counter = this.generateCounter(srtcpIndex & 65535, srtcpIndex >> 16, ssrc, this.srtcpSessionSalt);
createDecipheriv$1("aes-128-ctr", this.srtcpSessionKey, counter).update(out.subarray(8)).copy(out, 8);
return [out, header];
}
generateSrtcpAuthTag(buf) {
return createHmac$1("sha1", this.srtcpSessionAuthTag).update(buf).digest().slice(0, 10);
}
generateCounter(sequenceNumber, rolloverCounter, ssrc, sessionSalt) {
const counter = Buffer.alloc(16);
counter.writeUInt32BE(ssrc, 4);
counter.writeUInt32BE(rolloverCounter, 8);
counter.writeUInt32BE(Number(BigInt(sequenceNumber) << 16n), 12);
for (let i = 0; i < sessionSalt.length; i++) counter[i] ^= sessionSalt[i];
return counter;
}
generateSrtpAuthTag(roc, ...buffers) {
const srtpSessionAuth = createHmac$1("sha1", this.srtpSessionAuthTag);
const rocRaw = Buffer.alloc(4);
rocRaw.writeUInt32BE(roc);
for (const buf of buffers) srtpSessionAuth.update(buf);
return srtpSessionAuth.update(rocRaw).digest().subarray(0, 10);
}
};
var srtcpIndexSize = 4;
function assertAuthTag(actual, expected, message) {
if (actual.length !== expected.length || !timingSafeEqual$1(actual, expected)) throw new SrtpAuthenticationError(message);
}
var CipherAesGcm = class extends CipherAesBase {
aeadAuthTagLen = 16;
rtpIvWriter = createBufferWriter([
2,
4,
4,
2
], true);
rtcpIvWriter = createBufferWriter([
2,
4,
2,
4
], true);
aadWriter = createBufferWriter([4], true);
constructor(srtpSessionKey, srtpSessionSalt, srtcpSessionKey, srtcpSessionSalt) {
super(srtpSessionKey, srtpSessionSalt, srtcpSessionKey, srtcpSessionSalt);
}
encryptRtp(header, payload, rolloverCounter) {
const hdr = header.serialize(header.serializeSize);
const iv = this.rtpInitializationVector(header, rolloverCounter);
const cipher = createCipheriv$1("aes-128-gcm", this.srtpSessionKey, iv);
cipher.setAAD(hdr);
const enc = cipher.update(payload);
cipher.final();
const authTag = cipher.getAuthTag();
return Buffer.concat([
hdr,
enc,
authTag
]);
}
decryptRtp(cipherText, rolloverCounter, header = parseSrtpRtpHeader(cipherText, this.aeadAuthTagLen)) {
const headerBuffer = cipherText.subarray(0, header.payloadOffset);
const authTagOffset = cipherText.length - this.aeadAuthTagLen;
const authTag = cipherText.subarray(authTagOffset);
let dst = Buffer.from([]);
dst = growBufferSize(dst, cipherText.length - this.aeadAuthTagLen);
headerBuffer.copy(dst);
const iv = this.rtpInitializationVector(header, rolloverCounter);
const enc = cipherText.slice(header.payloadOffset, authTagOffset);
const decipher = createDecipheriv$1("aes-128-gcm", this.srtpSessionKey, iv);
decipher.setAAD(headerBuffer);
decipher.setAuthTag(authTag);
const dec = decipher.update(enc);
finalizeAuthenticatedDecryption(decipher, "SRTP");
dec.copy(dst, header.payloadOffset);
return [dst, finalizeSrtpRtpHeader(header, dst, "Failed to authenticate SRTP packet")];
}
encryptRTCP(rtcpPacket, srtcpIndex) {
const ssrc = rtcpPacket.readUInt32BE(4);
const addPos = rtcpPacket.length + this.aeadAuthTagLen;
let dst = Buffer.from([]);
dst = growBufferSize(dst, addPos + srtcpIndexSize2);
rtcpPacket.slice(0, 8).copy(dst);
const iv = this.rtcpInitializationVector(ssrc, srtcpIndex);
const aad = this.rtcpAdditionalAuthenticatedData(rtcpPacket, srtcpIndex);
const cipher = createCipheriv$1("aes-128-gcm", this.srtcpSessionKey, iv);
cipher.setAAD(aad);
const enc = cipher.update(rtcpPacket.slice(8));
cipher.final();
enc.copy(dst, 8);
cipher.getAuthTag().copy(dst, 8 + enc.length);
aad.slice(8, 12).copy(dst, addPos);
return dst;
}
decryptRTCP(encrypted) {
const header = parseSrtcpHeader(encrypted, this.aeadAuthTagLen, srtcpIndexSize2);
const srtcpIndexOffset = encrypted.length - srtcpIndexSize2;
const authTagOffset = srtcpIndexOffset - this.aeadAuthTagLen;
const ssrc = encrypted.readUInt32BE(4);
const encodedSrtcpIndex = encrypted.readUInt32BE(srtcpIndexOffset);
const isEncrypted = encodedSrtcpIndex >>> 31 === 1;
const srtcpIndex = encodedSrtcpIndex & ~(rtcpEncryptionFlag << 24);
const iv = this.rtcpInitializationVector(ssrc, srtcpIndex);
const aad = isEncrypted ? Buffer.concat([encrypted.subarray(0, 8), encrypted.subarray(srtcpIndexOffset)]) : Buffer.concat([encrypted.subarray(0, authTagOffset), encrypted.subarray(srtcpIndexOffset)]);
const cipherText = isEncrypted ? encrypted.slice(8, authTagOffset) : Buffer.alloc(0);
const dst = isEncrypted ? Buffer.alloc(authTagOffset) : Buffer.from(encrypted.subarray(0, authTagOffset));
if (isEncrypted) encrypted.slice(0, 8).copy(dst);
const decipher = createDecipheriv$1("aes-128-gcm", this.srtcpSessionKey, iv);
decipher.setAAD(aad);
decipher.setAuthTag(encrypted.subarray(authTagOffset, srtcpIndexOffset));
const dec = decipher.update(cipherText);
finalizeAuthenticatedDecryption(decipher, "SRTCP");
if (isEncrypted) dec.copy(dst, 8);
return [dst, header];
}
rtpInitializationVector(header, rolloverCounter) {
const iv = this.rtpIvWriter([
0,
header.ssrc,
rolloverCounter,
header.sequenceNumber
]);
for (let i = 0; i < iv.length; i++) iv[i] ^= this.srtpSessionSalt[i];
return iv;
}
rtcpInitializationVector(ssrc, srtcpIndex) {
const iv = this.rtcpIvWriter([
0,
ssrc,
0,
srtcpIndex
]);
for (let i = 0; i < iv.length; i++) iv[i] ^= this.srtcpSessionSalt[i];
return iv;
}
rtcpAdditionalAuthenticatedData(rtcpPacket, srtcpIndex) {
const aad = Buffer.concat([rtcpPacket.subarray(0, 8), this.aadWriter([srtcpIndex])]);
aad[8] |= rtcpEncryptionFlag;
return aad;
}
};
var srtcpIndexSize2 = 4;
var rtcpEncryptionFlag = 128;
function finalizeAuthenticatedDecryption(decipher, packetType) {
try {
decipher.final();
} catch {
throw new SrtpAuthenticationError(`Failed to authenticate ${packetType} packet`);
}
}
function aes128EcbEncrypt(key, plaintext) {
const cipher = createCipheriv$1("aes-128-ecb", key, null);
cipher.setAutoPadding(false);
return Buffer.concat([cipher.update(plaintext), cipher.final()]);
}
var Context = class {
constructor(masterKey, masterSalt, profile) {
this.masterKey = masterKey;
this.masterSalt = masterSalt;
this.profile = profile;
{
const diff = 14 - masterSalt.length;
if (diff > 0) this.masterSalt = Buffer.concat([masterSalt, Buffer.alloc(diff)]);
}
this.srtpSessionKey = this.generateSessionKey(0);
this.srtpSessionSalt = this.generateSessionSalt(2);
this.srtpSessionAuthTag = this.generateSessionAuthTag(1);
this.srtpSessionAuth = createHmac$1("sha1", this.srtpSessionAuthTag);
this.srtcpSessionKey = this.generateSessionKey(3);
this.srtcpSessionSalt = this.generateSessionSalt(5);
this.srtcpSessionAuthTag = this.generateSessionAuthTag(4);
this.srtcpSessionAuth = createHmac$1("sha1", this.srtcpSessionAuthTag);
switch (profile) {
case 1:
this.cipher = new CipherAesCtr(this.srtpSessionKey, this.srtpSessionSalt, this.srtcpSessionKey, this.srtcpSessionSalt, this.srtpSessionAuthTag, this.srtcpSessionAuthTag);
break;
case 7: this.cipher = new CipherAesGcm(this.srtpSessionKey, this.srtpSessionSalt, this.srtcpSessionKey, this.srtcpSessionSalt);
}
}
srtpSSRCStates = {};
srtpSessionKey;
srtpSessionSalt;
srtpSessionAuthTag;
srtpSessionAuth;
srtcpSSRCStates = {};
srtcpSessionKey;
srtcpSessionSalt;
srtcpSessionAuthTag;
srtcpSessionAuth;
cipher;
generateSessionKey(label) {
let sessionKey = Buffer.from(this.masterSalt);
const labelAndIndexOverKdr = Buffer.from([
label,
0,
0,
0,
0,
0,
0
]);
for (let i = labelAndIndexOverKdr.length - 1, j = sessionKey.length - 1; i >= 0; i--, j--) sessionKey[j] = sessionKey[j] ^ labelAndIndexOverKdr[i];
sessionKey = Buffer.concat([sessionKey, Buffer.from([0, 0])]);
return aes128EcbEncrypt(this.masterKey, sessionKey);
}
generateSessionSalt(label) {
let sessionSalt = Buffer.from(this.masterSalt);
const labelAndIndexOverKdr = Buffer.from([
label,
0,
0,
0,
0,
0,
0
]);
for (let i = labelAndIndexOverKdr.length - 1, j = sessionSalt.length - 1; i >= 0; i--, j--) sessionSalt[j] = sessionSalt[j] ^ labelAndIndexOverKdr[i];
sessionSalt = Buffer.concat([sessionSalt, Buffer.from([0, 0])]);
sessionSalt = aes128EcbEncrypt(this.masterKey, sessionSalt);
return sessionSalt.subarray(0, 14);
}
generateSessionAuthTag(label) {
const sessionAuthTag = Buffer.from(this.masterSalt);
const labelAndIndexOverKdr = Buffer.from([
label,
0,
0,
0,
0,
0,
0
]);
for (let i = labelAndIndexOverKdr.length - 1, j = sessionAuthTag.length - 1; i >= 0; i--, j--) sessionAuthTag[j] = sessionAuthTag[j] ^ labelAndIndexOverKdr[i];
let firstRun = Buffer.concat([sessionAuthTag, Buffer.from([0, 0])]);
let secondRun = Buffer.concat([sessionAuthTag, Buffer.from([0, 1])]);
firstRun = aes128EcbEncrypt(this.masterKey, firstRun);
secondRun = aes128EcbEncrypt(this.masterKey, secondRun);
return Buffer.concat([firstRun, secondRun.subarray(0, 4)]);
}
getSrtpSsrcState(ssrc) {
let s = this.srtpSSRCStates[ssrc];
if (s) return s;
s = {
ssrc,
rolloverCounter: 0,
lastSequenceNumber: 0
};
this.srtpSSRCStates[ssrc] = s;
return s;
}
getSrtcpSsrcState(ssrc) {
let s = this.srtcpSSRCStates[ssrc];
if (s) return s;
s = {
srtcpIndex: 0,
ssrc
};
this.srtcpSSRCStates[ssrc] = s;
return s;
}
updateRolloverCount(sequenceNumber, s) {
if (!s.rolloverHasProcessed) s.rolloverHasProcessed = true;
else if (sequenceNumber === 0) {
if (s.lastSequenceNumber > MaxROCDisorder) s.rolloverCounter++;
} else if (s.lastSequenceNumber < MaxROCDisorder && sequenceNumber > MaxSequenceNumber - MaxROCDisorder) {
if (s.rolloverCounter > 0) s.rolloverCounter--;
} else if (sequenceNumber < MaxROCDisorder && s.lastSequenceNumber > MaxSequenceNumber - MaxROCDisorder) s.rolloverCounter++;
s.lastSequenceNumber = sequenceNumber;
}
generateSrtpAuthTag(buf, roc) {
this.srtpSessionAuth = createHmac$1("sha1", this.srtpSessionAuthTag);
const rocRaw = Buffer.alloc(4);
rocRaw.writeUInt32BE(roc);
return this.srtpSessionAuth.update(buf).update(rocRaw).digest().slice(0, 10);
}
index(ssrc) {
const s = this.srtcpSSRCStates[ssrc];
if (!s) return 0;
return s.srtcpIndex;
}
setIndex(ssrc, index) {
const s = this.getSrtcpSsrcState(ssrc);
s.srtcpIndex = index % 2147483647;
}
};
var MaxROCDisorder = 100;
var MaxSequenceNumber = 65535;
var SrtcpContext = class extends Context {
constructor(masterKey, masterSalt, profile) {
super(masterKey, masterSalt, profile);
}
encryptRTCP(rawRtcp) {
const ssrc = rawRtcp.readUInt32BE(4);
const s = this.getSrtcpSsrcState(ssrc);
s.srtcpIndex++;
if (s.srtcpIndex >> maxSRTCPIndex) s.srtcpIndex = 0;
return this.cipher.encryptRTCP(rawRtcp, s.srtcpIndex);
}
decryptRTCP(encrypted) {
return this.cipher.decryptRTCP(encrypted);
}
};
var maxSRTCPIndex = 2147483647;
var Session = class {
constructor(ContextCls) {
this.ContextCls = ContextCls;
}
localContext;
remoteContext;
onData;
start(localMasterKey, localMasterSalt, remoteMasterKey, remoteMasterSalt, profile) {
this.localContext = new this.ContextCls(localMasterKey, localMasterSalt, profile);
this.remoteContext = new this.ContextCls(remoteMasterKey, remoteMasterSalt, profile);
}
};
var SrtcpSession = class extends Session {
constructor(config) {
super(SrtcpContext);
this.config = config;
this.start(config.keys.localMasterKey, config.keys.localMasterSalt, config.keys.remoteMasterKey, config.keys.remoteMasterSalt, config.profile);
}
decrypt = (buf) => {
const [decrypted] = this.remoteContext.decryptRTCP(buf);
return decrypted;
};
encrypt(rawRtcp) {
return this.localContext.encryptRTCP(rawRtcp);
}
};
var SrtpContext2 = class extends Context {
constructor(masterKey, masterSalt, profile) {
super(masterKey, masterSalt, profile);
}
encryptRtp(payload, header) {
const s = this.getSrtpSsrcState(header.ssrc);
this.updateRolloverCount(header.sequenceNumber, s);
return this.cipher.encryptRtp(header, payload, s.rolloverCounter);
}
decryptRtp(cipherText) {
const header = parseSrtpRtpHeader(cipherText, this.rtpAuthTagLength);
const existingState = this.srtpSSRCStates[header.ssrc];
const nextState = existingState ? { ...existingState } : {
ssrc: header.ssrc,
rolloverCounter: 0,
lastSequenceNumber: 0
};
this.updateRolloverCount(header.sequenceNumber, nextState);
const dec = this.cipher.decryptRtp(cipherText, nextState.rolloverCounter, header);
if (existingState) Object.assign(existingState, nextState);
else this.srtpSSRCStates[header.ssrc] = nextState;
return dec;
}
get rtpAuthTagLength() {
return this.profile === 7 ? 16 : 10;
}
};
var SrtpSession = class extends Session {
constructor(config) {
super(SrtpContext2);
this.config = config;
this.start(config.keys.localMasterKey, config.keys.localMasterSalt, config.keys.remoteMasterKey, config.keys.remoteMasterSalt, config.profile);
}
decrypt = (buf) => {
const [decrypted] = this.remoteContext.decryptRtp(buf);
return decrypted;
};
encrypt(payload, header) {
return this.localContext.encryptRtp(payload, header);
}
};
var RtpBuilder = class {
constructor(props) {
this.props = props;
}
sequenceNumber = random16();
timestamp = random32();
create(payload) {
this.sequenceNumber = uint16Add(this.sequenceNumber, 1);
const elapsed = this.props.between * this.props.clockRate / 1e3;
this.timestamp = uint32Add(this.timestamp, elapsed);
return new RtpPacket(new RtpHeader({
sequenceNumber: this.sequenceNumber,
timestamp: Number(this.timestamp),
payloadType: 96,
extension: true,
marker: false,
padding: false
}), payload);
}
};
var log9 = debug("werift-dtls : packages/dtls/src/flight/client/flight5.ts : log");
var Flight5 = class extends Flight {
constructor(udp, dtls, cipher, srtp) {
super(udp, dtls, 5, 7);
this.cipher = cipher;
this.srtp = srtp;
}
handleHandshake(handshake) {
this.dtls.bufferHandshakeCache([handshake], false, 4);
const message = (() => {
switch (handshake.msg_type) {
case 2: return ServerHello.deSerialize(handshake.fragment);
case 11: return Certificate2.deSerialize(handshake.fragment);
case 12: return ServerKeyExchange.deSerialize(handshake.fragment);
case 13: return ServerCertificateRequest.deSerialize(handshake.fragment);
case 14: return ServerHelloDone.deSerialize(handshake.fragment);
}
})();
if (message) handlers[message.msgType]({
dtls: this.dtls,
cipher: this.cipher,
srtp: this.srtp
})(message);
}
async exec() {
if (this.dtls.flight === 5) {
log9(this.dtls.sessionId, "flight5 twice");
this.send(this.dtls.lastMessage);
return;
}
this.dtls.flight = 5;
const needCertificate = this.dtls.requestedCertificateTypes.length > 0;
log9(this.dtls.sessionId, "send flight5", needCertificate);
const messages = [
needCertificate && this.sendCertificate(),
this.sendClientKeyExchange(),
needCertificate && this.sendCertificateVerify(),
this.sendChangeCipherSpec(),
this.sendFinished()
].filter((v) => v);
this.dtls.lastMessage = messages;
await this.transmit(messages);
}
sendCertificate() {
const certificate = new Certificate2([Buffer.from(this.cipher.localCert)]);
const packets = this.createPacket([certificate]);
return Buffer.concat(packets.map((v) => v.serialize()));
}
sendClientKeyExchange() {
if (!this.cipher.localKeyPair) throw new Error();
const clientKeyExchange = new ClientKeyExchange(this.cipher.localKeyPair.publicKey);
const packets = this.createPacket([clientKeyExchange]);
const buf = Buffer.concat(packets.map((v) => v.serialize()));
const localKeyPair = this.cipher.localKeyPair;
const remoteKeyPair = this.cipher.remoteKeyPair;
if (!remoteKeyPair.publicKey) throw new Error("not exist");
const preMasterSecret = prfPreMasterSecret(remoteKeyPair.publicKey, localKeyPair.privateKey, localKeyPair.curve);
log9(this.dtls.sessionId, "extendedMasterSecret", this.dtls.options.extendedMasterSecret, this.dtls.remoteExtendedMasterSecret);
const handshakes = Buffer.concat(this.dtls.sortedHandshakeCache.map((v) => v.serialize()));
this.cipher.masterSecret = this.dtls.options.extendedMasterSecret && this.dtls.remoteExtendedMasterSecret ? prfExtendedMasterSecret(preMasterSecret, handshakes) : prfMasterSecret(preMasterSecret, this.cipher.localRandom.serialize(), this.cipher.remoteRandom.serialize());
this.cipher.cipher = createCipher(this.cipher.cipherSuite);
this.cipher.cipher.init(this.cipher.masterSecret, this.cipher.remoteRandom.serialize(), this.cipher.localRandom.serialize());
log9(this.dtls.sessionId, "cipher", this.cipher.cipher.summary);
return buf;
}
sendCertificateVerify() {
const cache = Buffer.concat(this.dtls.sortedHandshakeCache.map((v) => v.serialize()));
const signed = this.cipher.signatureData(cache, "sha256");
const signatureScheme = (() => {
switch (this.cipher.signatureHashAlgorithm?.signature) {
case SignatureAlgorithm.ecdsa_3: return SignatureScheme.ecdsa_secp256r1_sha256;
case SignatureAlgorithm.rsa_1: return SignatureScheme.rsa_pkcs1_sha256;
}
})();
if (!signatureScheme) throw new Error();
log9(this.dtls.sessionId, "signatureScheme", this.cipher.signatureHashAlgorithm?.signature, signatureScheme);
const certificateVerify = new CertificateVerify(signatureScheme, signed);
const packets = this.createPacket([certificateVerify]);
return Buffer.concat(packets.map((v) => v.serialize()));
}
sendChangeCipherSpec() {
const changeCipherSpec = ChangeCipherSpec.createEmpty().serialize();
const packets = createPlaintext(this.dtls)([{
type: 20,
fragment: changeCipherSpec
}], ++this.dtls.recordSequenceNumber);
return Buffer.concat(packets.map((v) => v.serialize()));
}
sendFinished() {
const cache = Buffer.concat(this.dtls.sortedHandshakeCache.map((v) => v.serialize()));
const finish = new Finished(this.cipher.verifyData(cache));
this.dtls.epoch = 1;
const [packet] = this.createPacket([finish]);
this.dtls.recordSequenceNumber = 0;
const buf = this.cipher.encryptPacket(packet).serialize();
log9(this.dtls.sessionId, "finished", this.cipher.cipher.summary);
return buf;
}
};
var handlers = {};
handlers[2] = ({ cipher, srtp, dtls }) => (message) => {
log9(dtls.sessionId, "serverHello", message.cipherSuite);
cipher.remoteRandom = DtlsRandom.from(message.random);
cipher.cipherSuite = message.cipherSuite;
log9(dtls.sessionId, "selected cipherSuite", cipher.cipherSuite);
if (message.extensions) message.extensions.forEach((extension) => {
switch (extension.type) {
case UseSRTP.type:
{
const useSrtp = UseSRTP.fromData(extension.data);
const profile = SrtpContext.findMatchingSRTPProfile(useSrtp.profiles, dtls.options.srtpProfiles || []);
log9(dtls.sessionId, "selected srtp profile", profile);
if (profile == void 0) return;
srtp.srtpProfile = profile;
}
break;
case ExtendedMasterSecret.type:
dtls.remoteExtendedMasterSecret = true;
break;
case RenegotiationIndication.type: log9(dtls.sessionId, "RenegotiationIndication");
}
});
};
handlers[11] = ({ cipher, dtls }) => (message) => {
log9(dtls.sessionId, "handshake certificate", message);
cipher.remoteCertificate = message.certificateList[0];
};
handlers[12] = ({ cipher, dtls }) => (message) => {
if (!cipher.localRandom || !cipher.remoteRandom) throw new Error();
log9(dtls.sessionId, "ServerKeyExchange", message);
log9(dtls.sessionId, "selected curve", message.namedCurve);
cipher.remoteKeyPair = {
curve: message.namedCurve,
publicKey: message.publicKey
};
cipher.localKeyPair = generateKeyPair(message.namedCurve);
};
handlers[13] = ({ dtls }) => (message) => {
log9(dtls.sessionId, "certificate_request", message);
dtls.requestedCertificateTypes = message.certificateTypes;
dtls.requestedSignatureAlgorithms = message.signatures;
};
handlers[14] = ({ dtls }) => (msg) => {
log9(dtls.sessionId, "server_hello_done", msg);
};
var ServerHelloVerifyRequest = class _ServerHelloVerifyRequest {
constructor(serverVersion, cookie) {
this.serverVersion = serverVersion;
this.cookie = cookie;
}
msgType = 3;
messageSeq;
static spec = {
serverVersion: ProtocolVersion,
cookie: import_src$1.types.buffer(import_src$1.types.uint8)
};
static createEmpty() {
return new _ServerHelloVerifyRequest(void 0, void 0);
}
static deSerialize(buf) {
return new _ServerHelloVerifyRequest(...Object.values((0, import_src$1.decode)(buf, _ServerHelloVerifyRequest.spec)));
}
serialize() {
const res = (0, import_src$1.encode)(this, _ServerHelloVerifyRequest.spec).slice();
return Buffer.from(res);
}
get version() {
return {
major: 255 - this.serverVersion.major,
minor: 255 - this.serverVersion.minor
};
}
toFragment() {
const body = this.serialize();
return new FragmentedHandshake(this.msgType, body.length, this.messageSeq, 0, body.length, body);
}
};
var log10 = debug("werift-dtls : packages/dtls/src/context/dtls.ts : log");
var DtlsContext = class {
constructor(options, sessionType) {
this.options = options;
this.sessionType = sessionType;
}
version = {
major: 254,
minor: 253
};
lastFlight = [];
lastMessage = [];
recordSequenceNumber = 0;
sequenceNumber = 0;
epoch = 0;
flight = 0;
handshakeCache = {};
cookie;
requestedCertificateTypes = [];
requestedSignatureAlgorithms = [];
remoteExtendedMasterSecret = false;
get sessionId() {
return this.cookie ? this.cookie.toString("hex").slice(0, 10) : "";
}
get sortedHandshakeCache() {
return Object.entries(this.handshakeCache).sort(([a], [b]) => Number(a) - Number(b)).flatMap(([, { data }]) => data.sort((a, b) => a.message_seq - b.message_seq));
}
checkHandshakesExist = (handshakes) => !handshakes.find((type) => this.sortedHandshakeCache.find((h) => h.msg_type === type) == void 0);
bufferHandshakeCache(handshakes, isLocal, flight) {
if (!this.handshakeCache[flight]) this.handshakeCache[flight] = {
data: [],
isLocal,
flight
};
const filtered = handshakes.filter((h) => {
const exist = this.handshakeCache[flight].data.find((t) => t.msg_type === h.msg_type);
if (exist) {
log10(this.sessionId, "exist", exist.summary, isLocal, flight);
return false;
}
return true;
});
this.handshakeCache[flight].data = [...this.handshakeCache[flight].data, ...filtered];
}
};
var TransportContext = class {
constructor(socket) {
this.socket = socket;
}
send = (buf, addr) => {
return this.socket.send(buf, addr);
};
};
var EllipticCurves = class _EllipticCurves {
static type = 10;
static spec = {
type: import_src$1.types.uint16be,
data: import_src$1.types.array(import_src$1.types.uint16be, import_src$1.types.uint16be, "bytes")
};
type = _EllipticCurves.type;
data = [];
constructor(props = {}) {
Object.assign(this, props);
}
static createEmpty() {
return new _EllipticCurves();
}
static fromData(buf) {
return new _EllipticCurves({
type: _EllipticCurves.type,
data: (0, import_src$1.decode)(buf, _EllipticCurves.spec.data)
});
}
static deSerialize(buf) {
return new _EllipticCurves((0, import_src$1.decode)(buf, _EllipticCurves.spec));
}
serialize() {
return Buffer.from((0, import_src$1.encode)(this, _EllipticCurves.spec).slice());
}
get extension() {
return {
type: this.type,
data: this.serialize().slice(2)
};
}
};
var Signature = class _Signature {
static type = 13;
static spec = {
type: import_src$1.types.uint16be,
data: import_src$1.types.array({
hash: import_src$1.types.uint8,
signature: import_src$1.types.uint8
}, import_src$1.types.uint16be, "bytes")
};
type = _Signature.type;
data = [];
constructor(props = {}) {
Object.assign(this, props);
}
static createEmpty() {
return new _Signature();
}
static deSerialize(buf) {
return new _Signature((0, import_src$1.decode)(buf, _Signature.spec));
}
serialize() {
const res = (0, import_src$1.encode)(this, _Signature.spec).slice();
return Buffer.from(res);
}
static fromData(buf) {
const type = Buffer.alloc(2);
type.writeUInt16BE(_Signature.type);
return _Signature.deSerialize(Buffer.concat([type, buf]));
}
get extension() {
return {
type: this.type,
data: this.serialize().slice(2)
};
}
};
var Alert = class _Alert {
constructor(level, description) {
this.level = level;
this.description = description;
}
static spec = {
level: import_src$1.types.uint8,
description: import_src$1.types.uint8
};
static deSerialize(buf) {
return new _Alert(...Object.values((0, import_src$1.decode)(buf, _Alert.spec)));
}
serialize() {
const res = (0, import_src$1.encode)(this, _Alert.spec).slice();
return Buffer.from(res);
}
};
var log11 = debug("werift-dtls : packages/dtls/record/receive.ts : log");
var err3 = debug("werift-dtls : packages/dtls/record/receive.ts : err");
var parsePacket = (data) => {
let start = 0;
const packets = [];
while (data.length > start) {
const fragmentLength = data.readUInt16BE(start + 11);
if (data.length < start + (12 + fragmentLength)) break;
const packet = DtlsPlaintext.deSerialize(data.subarray(start));
packets.push(packet);
start += 13 + fragmentLength;
}
return packets;
};
var parsePlainText = (dtls, cipher) => (plain) => {
switch (plain.recordLayerHeader.contentType) {
case 20:
log11(dtls.sessionId, "change cipher spec");
return [{
type: 20,
data: void 0
}];
case 22: {
let raw = plain.fragment;
try {
if (plain.recordLayerHeader.epoch > 0) {
log11(dtls.sessionId, "decrypt handshake");
raw = cipher.decryptPacket(plain);
}
} catch (error) {
err3(dtls.sessionId, "decrypt failed", error);
throw error;
}
try {
let start = 0;
const handshakes = [];
while (raw.length > start) {
const handshake = FragmentedHandshake.deSerialize(raw.subarray(start));
handshakes.push({
type: 22,
data: handshake
});
start += handshake.fragment_length + 12;
}
return handshakes;
} catch (error) {
err3(dtls.sessionId, "decSerialize failed", error, raw);
throw error;
}
}
case 23: return [{
type: 23,
data: cipher.decryptPacket(plain)
}];
case 21: {
let alert = Alert.deSerialize(plain.fragment);
if (AlertDesc[alert.description] == void 0) {
const dec = cipher.decryptPacket(plain);
alert = Alert.deSerialize(dec);
}
err3(dtls.sessionId, "ContentType.alert", alert, AlertDesc[alert.description], "flight", dtls.flight, "lastFlight", dtls.lastFlight);
if (alert.level > 1) throw new Error("alert fatal error");
return [{
type: 21,
data: void 0
}];
}
default: return [{
type: 21,
data: void 0
}];
}
};
var log12 = debug("werift-dtls : packages/dtls/src/socket.ts : log");
var err4 = debug("werift-dtls : packages/dtls/src/socket.ts : err");
var DtlsSocket = class {
constructor(options, sessionType) {
this.options = options;
this.sessionType = sessionType;
this.dtls = new DtlsContext(this.options, this.sessionType);
this.cipher = new CipherContext(this.sessionType, this.options.cert, this.options.key, this.options.signatureHash);
this.transport = new TransportContext(this.options.transport);
this.setupExtensions();
this.transport.socket.onData = this.udpOnMessage;
}
onConnect = new Event2();
onData = new Event2();
onError = new Event2();
onClose = new Event2();
transport;
cipher;
dtls;
srtp = new SrtpContext();
connected = false;
extensions = [];
onHandleHandshakes;
bufferFragmentedHandshakes = [];
renegotiation() {
log12("renegotiation", this.sessionType);
this.connected = false;
this.cipher = new CipherContext(this.sessionType, this.options.cert, this.options.key, this.options.signatureHash);
this.dtls = new DtlsContext(this.options, this.sessionType);
this.srtp = new SrtpContext();
this.extensions = [];
this.bufferFragmentedHandshakes = [];
}
udpOnMessage = (data) => {
const packets = parsePacket(data);
for (const packet of packets) try {
const messages = parsePlainText(this.dtls, this.cipher)(packet);
for (const message of messages) switch (message.type) {
case 22:
{
const handshake = message.data;
const handshakes = this.handleFragmentHandshake([handshake]);
const assembled = Object.values(handshakes.reduce((acc, cur) => {
if (!acc[cur.msg_type]) acc[cur.msg_type] = [];
acc[cur.msg_type].push(cur);
return acc;
}, {})).map((v) => FragmentedHandshake.assemble(v)).sort((a, b) => a.msg_type - b.msg_type);
this.onHandleHandshakes(assembled).catch((error) => {
err4(this.dtls.sessionId, "onHandleHandshakes error", error);
this.onError.execute(error);
});
}
break;
case 23:
this.onData.execute(message.data);
break;
case 21: this.onClose.execute();
}
} catch (error) {
err4(this.dtls.sessionId, "catch udpOnMessage error", error);
}
};
setupExtensions() {
log12(this.dtls.sessionId, "support srtpProfiles", this.options.srtpProfiles);
if (this.options.srtpProfiles && this.options.srtpProfiles.length > 0) {
const useSrtp = UseSRTP.create(this.options.srtpProfiles, Buffer.from([0]));
this.extensions.push(useSrtp.extension);
}
{
const curve = EllipticCurves.createEmpty();
curve.data = NamedCurveAlgorithmList;
this.extensions.push(curve.extension);
}
{
const signature = Signature.createEmpty();
signature.data = signatures;
this.extensions.push(signature.extension);
}
if (this.options.extendedMasterSecret) this.extensions.push({
type: ExtendedMasterSecret.type,
data: Buffer.alloc(0)
});
{
const renegotiationIndication = RenegotiationIndication.createEmpty();
this.extensions.push(renegotiationIndication.extension);
}
}
waitForReady = (condition) => new Promise(async (r, f) => {
for (let i = 0; i < 10; i++) if (condition()) {
r();
break;
} else await setTimeout$2(100 * i);
f("waitForReady timeout");
});
handleFragmentHandshake(messages) {
let handshakes = messages.filter((v) => {
if (v.fragment_length !== v.length) {
this.bufferFragmentedHandshakes.push(v);
return false;
}
return true;
});
if (this.bufferFragmentedHandshakes.length > 1) {
const [last] = this.bufferFragmentedHandshakes.slice(-1);
if (last.fragment_offset + last.fragment_length === last.length) {
handshakes = [...this.bufferFragmentedHandshakes, ...handshakes];
this.bufferFragmentedHandshakes = [];
}
}
return handshakes;
}
/**send application data */
send = async (buf, addr) => {
const pkt = createPlaintext(this.dtls)([{
type: 23,
fragment: buf
}], ++this.dtls.recordSequenceNumber)[0];
await this.transport.send(this.cipher.encryptPacket(pkt).serialize(), addr);
};
close() {
this.transport.socket.close();
}
extractSessionKeys(keyLength2, saltLength2) {
const keyingMaterial = this.exportKeyingMaterial("EXTRACTOR-dtls_srtp", keyLength2 * 2 + saltLength2 * 2);
const { clientKey, serverKey, clientSalt, serverSalt } = (0, import_src$1.decode)(keyingMaterial, {
clientKey: import_src$1.types.buffer(keyLength2),
serverKey: import_src$1.types.buffer(keyLength2),
clientSalt: import_src$1.types.buffer(saltLength2),
serverSalt: import_src$1.types.buffer(saltLength2)
});
if (this.sessionType === SessionType.CLIENT) return {
localKey: clientKey,
localSalt: clientSalt,
remoteKey: serverKey,
remoteSalt: serverSalt
};
else return {
localKey: serverKey,
localSalt: serverSalt,
remoteKey: clientKey,
remoteSalt: clientSalt
};
}
exportKeyingMaterial(label, length) {
return exportKeyingMaterial(label, length, this.cipher.masterSecret, this.cipher.localRandom.serialize(), this.cipher.remoteRandom.serialize(), this.sessionType === SessionType.CLIENT);
}
get remoteCertificate() {
return this.cipher.remoteCertificate;
}
};
var log13 = debug("werift-dtls : packages/dtls/src/client.ts : log");
var DtlsClient = class extends DtlsSocket {
constructor(options) {
super(options, SessionType.CLIENT);
this.onHandleHandshakes = this.handleHandshakes;
log13(this.dtls.sessionId, "start client");
}
async connect() {
await new Flight1(this.transport, this.dtls, this.cipher).exec(this.extensions);
}
flight5;
handleHandshakes = async (assembled) => {
log13(this.dtls.sessionId, "handleHandshakes", assembled.map((a) => a.msg_type));
for (const handshake of assembled) switch (handshake.msg_type) {
case 3:
{
const verifyReq = ServerHelloVerifyRequest.deSerialize(handshake.fragment);
await new Flight3(this.transport, this.dtls).exec(verifyReq);
}
break;
case 2:
if (this.connected) return;
this.flight5 = new Flight5(this.transport, this.dtls, this.cipher, this.srtp);
this.flight5.handleHandshake(handshake);
break;
case 11:
case 12:
case 13:
await this.waitForReady(() => !!this.flight5);
this.flight5?.handleHandshake(handshake);
break;
case 14:
{
await this.waitForReady(() => !!this.flight5);
this.flight5?.handleHandshake(handshake);
const targets = [
11,
12,
this.options.certificateRequest && 13
].filter((n) => typeof n === "number");
await this.waitForReady(() => this.dtls.checkHandshakesExist(targets));
await this.flight5?.exec();
}
break;
case 20:
this.dtls.flight = 7;
this.connected = true;
this.onConnect.execute();
log13(this.dtls.sessionId, "dtls connected");
}
};
};
var log14 = debug("werift-dtls : packages/dtls/flight/server/flight2.ts : log");
var flight2 = (udp, dtls, cipher, srtp) => (clientHello) => {
log14("dtls version", clientHello.clientVersion);
dtls.flight = 2;
dtls.recordSequenceNumber = 0;
dtls.sequenceNumber = 0;
clientHello.extensions.forEach((extension) => {
switch (extension.type) {
case EllipticCurves.type:
{
const curves = EllipticCurves.fromData(extension.data).data;
log14(dtls.sessionId, "curves", curves);
cipher.namedCurve = curves.filter((curve2) => NamedCurveAlgorithmList.includes(curve2))[0];
log14(dtls.sessionId, "curve selected", cipher.namedCurve);
}
break;
case Signature.type:
{
if (!cipher.signatureHashAlgorithm) throw new Error("need to set certificate");
const signatureHash = Signature.fromData(extension.data).data;
log14(dtls.sessionId, "hash,signature", signatureHash);
const signature = signatureHash.find((v) => v.signature === cipher.signatureHashAlgorithm?.signature)?.signature;
const hash2 = signatureHash.find((v) => v.hash === cipher.signatureHashAlgorithm?.hash)?.hash;
if (signature == void 0 || hash2 == void 0) throw new Error("invalid signatureHash");
}
break;
case UseSRTP.type:
{
if (!dtls.options?.srtpProfiles) return;
if (dtls.options.srtpProfiles.length === 0) return;
const useSrtp = UseSRTP.fromData(extension.data);
log14(dtls.sessionId, "srtp profiles", useSrtp.profiles);
const profile = SrtpContext.findMatchingSRTPProfile(useSrtp.profiles, dtls.options?.srtpProfiles);
if (!profile) throw new Error();
srtp.srtpProfile = profile;
log14(dtls.sessionId, "srtp profile selected", srtp.srtpProfile);
}
break;
case ExtendedMasterSecret.type:
dtls.remoteExtendedMasterSecret = true;
break;
case RenegotiationIndication.type:
log14(dtls.sessionId, "RenegotiationIndication", extension.data);
break;
case 43: log14("dtls supported version", [...extension.data.subarray(1)].map((v) => v.toString(10)));
}
});
cipher.localRandom = new DtlsRandom();
cipher.remoteRandom = DtlsRandom.from(clientHello.random);
const suites = clientHello.cipherSuites;
log14(dtls.sessionId, "cipher suites", suites);
const suite = (() => {
switch (cipher.signatureHashAlgorithm?.signature) {
case SignatureAlgorithm.ecdsa_3: return CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256_49195;
case SignatureAlgorithm.rsa_1: return CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256_49199;
}
})();
if (suite === void 0 || !suites.includes(suite)) throw new Error("dtls cipher suite negotiation failed");
cipher.cipherSuite = suite;
log14(dtls.sessionId, "selected cipherSuite", cipher.cipherSuite);
cipher.localKeyPair = generateKeyPair(cipher.namedCurve);
dtls.cookie ||= randomBytes$1(20);
const helloVerifyReq = new ServerHelloVerifyRequest({
major: 254,
minor: 253
}, dtls.cookie);
const fragments = createFragments(dtls)([helloVerifyReq]);
const chunk = createPlaintext(dtls)(fragments.map((fragment) => ({
type: 22,
fragment: fragment.serialize()
})), ++dtls.recordSequenceNumber).map((v) => v.serialize());
for (const buf of chunk) udp.send(buf);
};
var log15 = debug("werift-dtls : packages/dtls/flight/server/flight4.ts : log");
var Flight4 = class extends Flight {
constructor(udp, dtls, cipher, srtp) {
super(udp, dtls, 4, 6);
this.cipher = cipher;
this.srtp = srtp;
}
async exec(clientHello, certificateRequest = false) {
if (this.dtls.flight === 4) {
log15(this.dtls.sessionId, "flight4 twice");
this.send(this.dtls.lastMessage);
return;
}
this.dtls.flight = 4;
this.dtls.sequenceNumber = 1;
this.dtls.bufferHandshakeCache([clientHello], false, 4);
const messages = [
this.sendServerHello(),
this.sendCertificate(),
this.sendServerKeyExchange(),
certificateRequest && this.sendCertificateRequest(),
this.sendServerHelloDone()
].filter((v) => v);
this.dtls.lastMessage = messages;
await this.transmit(messages);
}
sendServerHello() {
const extensions = [];
if (this.srtp.srtpProfile) extensions.push(UseSRTP.create([this.srtp.srtpProfile], Buffer.from([0])).extension);
if (this.dtls.options.extendedMasterSecret) extensions.push({
type: ExtendedMasterSecret.type,
data: Buffer.alloc(0)
});
const renegotiationIndication = RenegotiationIndication.createEmpty();
extensions.push(renegotiationIndication.extension);
const serverHello = new ServerHello(this.dtls.version, this.cipher.localRandom, Buffer.from([0]), this.cipher.cipherSuite, 0, extensions);
const packets = this.createPacket([serverHello]);
return Buffer.concat(packets.map((v) => v.serialize()));
}
sendCertificate() {
const certificate = new Certificate2([Buffer.from(this.cipher.localCert)]);
const packets = this.createPacket([certificate]);
return Buffer.concat(packets.map((v) => v.serialize()));
}
sendServerKeyExchange() {
const signature = this.cipher.generateKeySignature("sha256");
if (!this.cipher.signatureHashAlgorithm) throw new Error("not exist");
const keyExchange = new ServerKeyExchange(CurveType.named_curve_3, this.cipher.namedCurve, this.cipher.localKeyPair.publicKey.length, this.cipher.localKeyPair.publicKey, this.cipher.signatureHashAlgorithm.hash, this.cipher.signatureHashAlgorithm.signature, signature.length, signature);
const packets = this.createPacket([keyExchange]);
return Buffer.concat(packets.map((v) => v.serialize()));
}
sendCertificateRequest() {
const handshake = new ServerCertificateRequest(certificateTypes, signatures, []);
log15(this.dtls.sessionId, "sendCertificateRequest", handshake);
const packets = this.createPacket([handshake]);
return Buffer.concat(packets.map((v) => v.serialize()));
}
sendServerHelloDone() {
const handshake = new ServerHelloDone();
const packets = this.createPacket([handshake]);
return Buffer.concat(packets.map((v) => v.serialize()));
}
};
var log16 = debug("werift-dtls : packages/dtls/flight/server/flight6.ts");
var Flight6 = class extends Flight {
constructor(udp, dtls, cipher) {
super(udp, dtls, 6);
this.cipher = cipher;
}
handleHandshake(handshake) {
this.dtls.bufferHandshakeCache([handshake], false, 5);
const message = (() => {
switch (handshake.msg_type) {
case 11: return Certificate2.deSerialize(handshake.fragment);
case 15: return CertificateVerify.deSerialize(handshake.fragment);
case 16: return ClientKeyExchange.deSerialize(handshake.fragment);
case 20: return Finished.deSerialize(handshake.fragment);
}
})();
if (message) {
const handler = handlers2[message.msgType];
if (!handler) return;
handler({
dtls: this.dtls,
cipher: this.cipher
})(message);
}
}
async exec() {
if (this.dtls.flight === 6) {
log16(this.dtls.sessionId, "flight6 twice");
this.send(this.dtls.lastMessage);
return;
}
this.dtls.flight = 6;
const messages = [this.sendChangeCipherSpec(), this.sendFinished()];
this.dtls.lastMessage = messages;
await this.transmit(messages);
}
sendChangeCipherSpec() {
const changeCipherSpec = ChangeCipherSpec.createEmpty().serialize();
const packets = createPlaintext(this.dtls)([{
type: 20,
fragment: changeCipherSpec
}], ++this.dtls.recordSequenceNumber);
return Buffer.concat(packets.map((v) => v.serialize()));
}
sendFinished() {
const cache = Buffer.concat(this.dtls.sortedHandshakeCache.map((v) => v.serialize()));
const finish = new Finished(this.cipher.verifyData(cache));
this.dtls.epoch = 1;
const [packet] = this.createPacket([finish]);
this.dtls.recordSequenceNumber = 0;
return this.cipher.encryptPacket(packet).serialize();
}
};
var handlers2 = {};
handlers2[16] = ({ cipher, dtls }) => (message) => {
cipher.remoteKeyPair = {
curve: cipher.namedCurve,
publicKey: message.publicKey
};
if (!cipher.remoteKeyPair.publicKey || !cipher.localKeyPair || !cipher.remoteRandom || !cipher.localRandom) throw new Error("not exist");
const preMasterSecret = prfPreMasterSecret(cipher.remoteKeyPair.publicKey, cipher.localKeyPair.privateKey, cipher.localKeyPair.curve);
log16(dtls.sessionId, "extendedMasterSecret", dtls.options.extendedMasterSecret, dtls.remoteExtendedMasterSecret);
const handshakes = Buffer.concat(dtls.sortedHandshakeCache.map((v) => v.serialize()));
cipher.masterSecret = dtls.options.extendedMasterSecret && dtls.remoteExtendedMasterSecret ? prfExtendedMasterSecret(preMasterSecret, handshakes) : prfMasterSecret(preMasterSecret, cipher.remoteRandom.serialize(), cipher.localRandom.serialize());
cipher.cipher = createCipher(cipher.cipherSuite);
cipher.cipher.init(cipher.masterSecret, cipher.localRandom.serialize(), cipher.remoteRandom.serialize());
log16(dtls.sessionId, "setup cipher", cipher.cipher.summary);
};
handlers2[11] = ({ cipher, dtls }) => (message) => {
log16(dtls.sessionId, "handshake certificate", message);
cipher.remoteCertificate = message.certificateList[0];
};
handlers2[15] = ({ cipher, dtls }) => (message) => {
if (!cipher.remoteCertificate) throw new Error("client certificate missing before certificate verify");
log16(dtls.sessionId, "certificate_verify", message.algorithm);
};
handlers2[20] = ({ dtls }) => (message) => {
log16(dtls.sessionId, "finished", message);
};
var log17 = debug("werift-dtls : packages/dtls/src/server.ts : log");
var DtlsServer = class extends DtlsSocket {
constructor(options) {
super(options, SessionType.SERVER);
this.onHandleHandshakes = this.handleHandshakes;
log17(this.dtls.sessionId, "start server");
}
flight6;
handleHandshakes = async (assembled) => {
log17(this.dtls.sessionId, "handleHandshakes", assembled.map((a) => a.msg_type));
for (const handshake of assembled) switch (handshake.msg_type) {
case 1:
{
if (this.connected) this.renegotiation();
const clientHello = ClientHello.deSerialize(handshake.fragment);
if (clientHello.cookie.length === 0) {
log17(this.dtls.sessionId, "send flight2");
flight2(this.transport, this.dtls, this.cipher, this.srtp)(clientHello);
} else if (this.dtls.cookie && clientHello.cookie.equals(this.dtls.cookie)) {
log17(this.dtls.sessionId, "send flight4");
await new Flight4(this.transport, this.dtls, this.cipher, this.srtp).exec(handshake, this.options.certificateRequest);
} else log17("wrong state", {
dtlsCookie: this.dtls.cookie?.toString("hex").slice(10),
helloCookie: clientHello.cookie.toString("hex").slice(10)
});
}
break;
case 11:
case 15:
case 16:
if (this.connected) return;
this.flight6 = new Flight6(this.transport, this.dtls, this.cipher);
this.flight6.handleHandshake(handshake);
break;
case 20: {
await this.waitForReady(() => !!this.flight6);
this.flight6?.handleHandshake(handshake);
const requiredHandshakes = [
16,
this.options.certificateRequest && 11,
this.options.certificateRequest && 15
].filter((type) => typeof type === "number");
await this.waitForReady(() => this.dtls.checkHandshakesExist(requiredHandshakes));
await this.flight6?.exec();
this.connected = true;
this.onConnect.execute();
log17(this.dtls.sessionId, "dtls connected");
}
}
};
};
var COOKIE = 554869826;
var FINGERPRINT_LENGTH = 8;
var FINGERPRINT_XOR = 1398035790;
var HEADER_LENGTH = 20;
var INTEGRITY_LENGTH = 24;
var IPV4_PROTOCOL = 1;
var IPV6_PROTOCOL = 2;
var RETRY_MAX = 6;
var RETRY_RTO = 50;
var AttributeKeys = [
"FINGERPRINT",
"MESSAGE-INTEGRITY",
"MESSAGE-INTEGRITY-SHA256",
"CHANGE-REQUEST",
"PRIORITY",
"USERNAME",
"USERHASH",
"ICE-CONTROLLING",
"SOURCE-ADDRESS",
"USE-CANDIDATE",
"ICE-CONTROLLED",
"ERROR-CODE",
"UNKNOWN-ATTRIBUTES",
"XOR-MAPPED-ADDRESS",
"CHANGED-ADDRESS",
"LIFETIME",
"REQUESTED-TRANSPORT",
"NONCE",
"REALM",
"REQUESTED-ADDRESS-FAMILY",
"EVEN-PORT",
"PASSWORD-ALGORITHM",
"PASSWORD-ALGORITHMS",
"XOR-RELAYED-ADDRESS",
"RESERVATION-TOKEN",
"CHANNEL-NUMBER",
"XOR-PEER-ADDRESS",
"DATA",
"SOFTWARE",
"MAPPED-ADDRESS",
"ALTERNATE-DOMAIN",
"ALTERNATE-SERVER",
"RESPONSE-ORIGIN",
"OTHER-ADDRESS"
];
var classes = /* @__PURE__ */ ((classes2) => {
classes2[classes2["REQUEST"] = 0] = "REQUEST";
classes2[classes2["INDICATION"] = 16] = "INDICATION";
classes2[classes2["RESPONSE"] = 256] = "RESPONSE";
classes2[classes2["ERROR"] = 272] = "ERROR";
return classes2;
})(classes || {});
var methods = /* @__PURE__ */ ((methods2) => {
methods2[methods2["BINDING"] = 1] = "BINDING";
methods2[methods2["SHARED_SECRET"] = 2] = "SHARED_SECRET";
methods2[methods2["ALLOCATE"] = 3] = "ALLOCATE";
methods2[methods2["REFRESH"] = 4] = "REFRESH";
methods2[methods2["SEND"] = 6] = "SEND";
methods2[methods2["DATA"] = 7] = "DATA";
methods2[methods2["CREATE_PERMISSION"] = 8] = "CREATE_PERMISSION";
methods2[methods2["CHANNEL_BIND"] = 9] = "CHANNEL_BIND";
return methods2;
})(methods || {});
function isComprehensionRequiredAttribute(type) {
return type >= 0 && type <= 32767;
}
function isStunMessage(data) {
if (data.length < 20) return false;
if ((data[0] & 192) !== 0) return false;
if (data.readUInt32BE(4) !== 554869826) return false;
const length = data.readUInt16BE(2);
if (length % 4 !== 0) return false;
return data.length === 20 + length;
}
function encodeTcpFrame(data) {
const header = Buffer.alloc(2);
header.writeUInt16BE(data.length, 0);
return Buffer.concat([header, data]);
}
function splitTcpFrames(buffer2) {
const frames = [];
let offset = 0;
while (buffer2.length - offset >= 2) {
const length = buffer2.readUInt16BE(offset);
if (buffer2.length - offset < length + 2) break;
frames.push(buffer2.subarray(offset + 2, offset + 2 + length));
offset += 2 + length;
}
return {
frames,
rest: buffer2.subarray(offset)
};
}
function ipAddressToBuffer(address) {
if (isIPv4(address)) {
const buf = Buffer.allocUnsafe(4);
const parts = address.split(".");
for (let i = 0; i < 4; i++) buf[i] = Number(parts[i]) & 255;
return buf;
}
if (!isIPv6(address)) throw new Error(`Invalid ip address: ${address}`);
const sections = address.split(":", 8);
for (let i = 0; i < sections.length; i++) {
let v4Buffer;
if (isIPv4(sections[i])) {
v4Buffer = ipAddressToBuffer(sections[i]);
sections[i] = v4Buffer.subarray(0, 2).toString("hex");
}
if (v4Buffer && ++i < 8) sections.splice(i, 0, v4Buffer.subarray(2, 4).toString("hex"));
}
if (sections[0] === "") while (sections.length < 8) sections.unshift("0");
else if (sections[sections.length - 1] === "") while (sections.length < 8) sections.push("0");
else if (sections.length < 8) {
let emptyIndex = 0;
for (; emptyIndex < sections.length && sections[emptyIndex] !== ""; emptyIndex++);
const zeros = [];
for (let n = 9 - sections.length; n > 0; n--) zeros.push("0");
sections.splice(emptyIndex, 1, ...zeros);
}
const result = Buffer.allocUnsafe(16);
let offset = 0;
for (const section of sections) {
const word = Number.parseInt(section, 16) || 0;
result[offset++] = word >> 8 & 255;
result[offset++] = word & 255;
}
return result;
}
function bufferToIpAddress(buf) {
if (buf.length === 4) return `${buf[0]}.${buf[1]}.${buf[2]}.${buf[3]}`;
if (buf.length !== 16) throw new Error(`Invalid ip address buffer length: ${buf.length}`);
const hextets = [];
for (let i = 0; i < 16; i += 2) hextets.push(buf.readUInt16BE(i).toString(16));
let result = hextets.join(":");
result = result.replace(/(^|:)0(:0)*:0(:|$)/, "$1::$3");
result = result.replace(/:{3,4}/, "::");
return result;
}
function isIpV4Address(address) {
return isIPv4(address);
}
function packAddress(value) {
const [address] = value;
const protocol = isIpV4Address(address) ? 1 : 2;
const buffer2 = Buffer.alloc(4);
buffer2.writeUInt8(0, 0);
buffer2.writeUInt8(protocol, 1);
buffer2.writeUInt16BE(value[1], 2);
return Buffer.concat([buffer2, ipAddressToBuffer(address)]);
}
function unpackErrorCode(data) {
if (data.length < 4) throw new Error("STUN error code is less than 4 bytes");
const codeHigh = data.readUInt8(2);
const codeLow = data.readUInt8(3);
const reason = data.slice(4).toString("utf8");
return [codeHigh * 100 + codeLow, reason];
}
function unpackAddress(data) {
if (data.length < 4) throw new Error("STUN address length is less than 4 bytes");
const protocol = data.readUInt8(1);
const port = data.readUInt16BE(2);
const address = data.slice(4);
switch (protocol) {
case 1:
if (address.length !== 4) throw new Error("STUN address has invalid length for IPv4");
return [bufferToIpAddress(address), port];
case 2:
if (address.length !== 16) throw new Error("STUN address has invalid length for IPv6");
return [bufferToIpAddress(address), port];
default: throw new Error("STUN address has unknown protocol");
}
}
var cookieBuffer = Buffer.alloc(6);
cookieBuffer.writeUInt16BE(COOKIE >> 16, 0);
cookieBuffer.writeUInt32BE(COOKIE, 2);
function xorAddress(data, transactionId) {
const xPad = [...cookieBuffer, ...transactionId];
let xData = data.slice(0, 2);
for (let i = 2; i < data.length; i++) {
const num = data[i] ^ xPad[i - 2];
const buf = Buffer.alloc(1);
buf.writeUIntBE(num, 0, 1);
xData = Buffer.concat([xData, buf]);
}
return xData;
}
function unpackXorAddress(data, transactionId) {
return unpackAddress(xorAddress(data, transactionId));
}
function packErrorCode(value) {
const buffer2 = Buffer.alloc(4);
buffer2.writeUInt16BE(0, 0);
buffer2.writeUInt8(Math.floor(value[0] / 100), 2);
buffer2.writeUInt8(value[0] % 100, 3);
const encoded = Buffer.from(value[1], "utf8");
return Buffer.concat([buffer2, encoded]);
}
function packUnknownAttributes(value) {
const buffer2 = Buffer.alloc(value.length * 2);
value.forEach((attributeType, index) => {
buffer2.writeUInt16BE(attributeType, index * 2);
});
return buffer2;
}
function unpackUnknownAttributes(data) {
if (data.length % 2 !== 0) throw new Error("UNKNOWN-ATTRIBUTES must have an even length");
const attributes = [];
for (let offset = 0; offset < data.length; offset += 2) attributes.push(data.readUInt16BE(offset));
return attributes;
}
function packXorAddress(value, transactionId) {
return xorAddress(packAddress(value), transactionId);
}
var packUnsigned = (value) => {
const buffer2 = Buffer.alloc(4);
buffer2.writeUInt32BE(value, 0);
return buffer2;
};
var unpackUnsigned = (data) => data.readUInt32BE(0);
var packUnsignedShort = (value) => {
const buffer2 = Buffer.alloc(4);
buffer2.writeUInt16BE(value, 0);
return buffer2;
};
var unpackUnsignedShort = (data) => data.readUInt16BE(0);
var packUnsigned64 = (value) => {
const buffer2 = Buffer.allocUnsafe(8);
buffer2.writeBigUInt64BE(value, 0);
return buffer2;
};
var unpackUnsigned64 = (data) => data.readBigUInt64BE(0);
var packString = (value) => Buffer.from(value, "utf8");
var unpackString = (data) => data.toString("utf8");
var packSoftware = (value) => {
if ([...value].length >= 128) throw new Error("SOFTWARE must be shorter than 128 characters");
return packString(value);
};
var packBytes = (value) => value;
var unpackBytes = (data) => data;
var packNone = () => Buffer.alloc(0);
var unpackNone = () => null;
var ATTRIBUTES = [
[
1,
"MAPPED-ADDRESS",
packAddress,
unpackAddress
],
[
3,
"CHANGE-REQUEST",
packUnsigned,
unpackUnsigned
],
[
4,
"SOURCE-ADDRESS",
packAddress,
unpackAddress
],
[
5,
"CHANGED-ADDRESS",
packAddress,
unpackAddress
],
[
6,
"USERNAME",
packString,
unpackString
],
[
8,
"MESSAGE-INTEGRITY",
packBytes,
unpackBytes
],
[
9,
"ERROR-CODE",
packErrorCode,
unpackErrorCode
],
[
10,
"UNKNOWN-ATTRIBUTES",
packUnknownAttributes,
unpackUnknownAttributes
],
[
12,
"CHANNEL-NUMBER",
packUnsignedShort,
unpackUnsignedShort
],
[
13,
"LIFETIME",
packUnsigned,
unpackUnsigned
],
[
18,
"XOR-PEER-ADDRESS",
packXorAddress,
unpackXorAddress
],
[
19,
"DATA",
packBytes,
unpackBytes
],
[
20,
"REALM",
packString,
unpackString
],
[
21,
"NONCE",
packBytes,
unpackBytes
],
[
22,
"XOR-RELAYED-ADDRESS",
packXorAddress,
unpackXorAddress
],
[
23,
"REQUESTED-ADDRESS-FAMILY",
packUnsigned,
unpackUnsigned
],
[
24,
"EVEN-PORT",
packBytes,
unpackBytes
],
[
25,
"REQUESTED-TRANSPORT",
packUnsigned,
unpackUnsigned
],
[
28,
"MESSAGE-INTEGRITY-SHA256",
packBytes,
unpackBytes
],
[
29,
"PASSWORD-ALGORITHM",
packBytes,
unpackBytes
],
[
30,
"USERHASH",
packBytes,
unpackBytes
],
[
32,
"XOR-MAPPED-ADDRESS",
packXorAddress,
unpackXorAddress
],
[
34,
"RESERVATION-TOKEN",
packBytes,
unpackBytes
],
[
36,
"PRIORITY",
packUnsigned,
unpackUnsigned
],
[
37,
"USE-CANDIDATE",
packNone,
unpackNone
],
[
32770,
"PASSWORD-ALGORITHMS",
packBytes,
unpackBytes
],
[
32771,
"ALTERNATE-DOMAIN",
packString,
unpackString
],
[
32802,
"SOFTWARE",
packSoftware,
unpackString
],
[
32803,
"ALTERNATE-SERVER",
packAddress,
unpackAddress
],
[
32808,
"FINGERPRINT",
packUnsigned,
unpackUnsigned
],
[
32809,
"ICE-CONTROLLED",
packUnsigned64,
unpackUnsigned64
],
[
32810,
"ICE-CONTROLLING",
packUnsigned64,
unpackUnsigned64
],
[
32811,
"RESPONSE-ORIGIN",
packAddress,
unpackAddress
],
[
32812,
"OTHER-ADDRESS",
packAddress,
unpackAddress
]
];
var AttributeRepository = class {
constructor(attributes = []) {
this.attributes = attributes;
}
getAttributes() {
return this.attributes;
}
setAttribute(key, value) {
const existing = this.attributes.find((attribute) => attribute[0] === key);
if (existing) existing[1] = value;
else this.attributes.push([key, value]);
return this;
}
getAttributeValue(key) {
return this.attributes.find((candidate) => candidate[0] === key)?.[1];
}
get attributesKeys() {
return this.attributes.map((attribute) => attribute[0]);
}
clear() {
this.attributes = [];
}
};
var ATTRIBUTES_BY_TYPE = ATTRIBUTES.reduce((acc, cur) => {
acc[cur[0]] = cur;
return acc;
}, {});
var ATTRIBUTES_BY_NAME = ATTRIBUTES.reduce((acc, cur) => {
acc[cur[1]] = cur;
return acc;
}, {});
function parseMessage(data, integrityKey) {
if (!isStunMessage(data)) return;
const messageType = data.readUInt16BE(0);
const transactionId = Buffer.from(data.slice(8, 20));
const attributeRepository = new AttributeRepository();
const rawAttributes = [];
let messageIntegrityVerified = false;
for (let pos = 20; pos < data.length;) {
if (pos + 4 > data.length) return;
const attrType = data.readUInt16BE(pos);
const attrLen = data.readUInt16BE(pos + 2);
const valueStart = pos + 4;
const valueEnd = valueStart + attrLen;
if (valueEnd > data.length) return;
const payload = data.slice(valueStart, valueEnd);
const padLen = paddingLength(attrLen);
if (valueEnd + padLen > data.length) return;
const attribute = ATTRIBUTES_BY_TYPE[attrType];
if (attribute) {
const [, attrName, , attrUnpack] = attribute;
let value;
try {
value = attrUnpack.name === unpackXorAddress.name ? attrUnpack(payload, transactionId) : attrUnpack(payload);
} catch {
return;
}
attributeRepository.setAttribute(attrName, value);
if (attrName === "FINGERPRINT") {
const fingerprint2 = messageFingerprint(data.slice(0, pos));
if (attributeRepository.getAttributeValue("FINGERPRINT") !== fingerprint2) return;
} else if (attrName === "MESSAGE-INTEGRITY" && integrityKey) {
const integrity = messageIntegrity(data.slice(0, pos), integrityKey);
const expected = attributeRepository.getAttributeValue("MESSAGE-INTEGRITY");
if (!integrity.equals(expected)) return;
messageIntegrityVerified = true;
}
} else rawAttributes.push({
type: attrType,
length: attrLen,
value: Buffer.from(payload)
});
pos = valueEnd + padLen;
}
if (integrityKey && !messageIntegrityVerified) return;
return new Message(messageType & 16111, messageType & 272, transactionId, attributeRepository.getAttributes(), rawAttributes);
}
var Message = class extends AttributeRepository {
constructor(messageMethod, messageClass, transactionId = randomBytes$1(12), attributes = [], rawAttributes = []) {
super(attributes);
this.messageMethod = messageMethod;
this.messageClass = messageClass;
this.transactionId = transactionId;
this.rawAttributes = rawAttributes;
}
toJSON() {
return this.json;
}
get json() {
return {
messageMethod: this.messageMethod,
messageClass: this.messageClass,
attributes: this.attributes,
rawAttributes: this.rawAttributes.map((attribute) => ({
type: attribute.type,
length: attribute.value.length
}))
};
}
get transactionIdHex() {
return this.transactionId.toString("hex");
}
appendRawAttribute(type, value) {
this.rawAttributes.push({
type,
value: Buffer.from(value)
});
return this;
}
get unknownAttributeTypes() {
return this.rawAttributes.map((attribute) => attribute.type);
}
get bytes() {
const body = Buffer.concat(this.serializedAttributes.map((attribute) => serializeAttribute(attribute.type, attribute.value)));
const header = Buffer.alloc(8);
header.writeUInt16BE(this.messageMethod | this.messageClass, 0);
header.writeUInt16BE(body.length, 2);
header.writeUInt32BE(COOKIE, 4);
return Buffer.concat([
header,
this.transactionId,
body
]);
}
addMessageIntegrity(key) {
this.setAttribute("MESSAGE-INTEGRITY", this.messageIntegrity(key));
return this;
}
messageIntegrity(key) {
const checkData = setBodyLength(this.bytes, this.bytes.length - 20 + 24);
return Buffer.from(createHmac$1("sha1", key).update(checkData).digest("hex"), "hex");
}
addFingerprint() {
this.setAttribute("FINGERPRINT", messageFingerprint(this.bytes));
return this;
}
get serializedAttributes() {
const attributes = [];
for (const attrName of this.attributesKeys) {
const attrValue = this.getAttributeValue(attrName);
const [attrType, , attrPack] = ATTRIBUTES_BY_NAME[attrName];
const value = attrPack.name === packXorAddress.name ? attrPack(attrValue, this.transactionId) : attrPack(attrValue);
attributes.push({
type: attrType,
value
});
}
attributes.push(...this.rawAttributes.map((attribute) => ({
type: attribute.type,
value: Buffer.from(attribute.value)
})));
return attributes;
}
};
function serializeAttribute(type, value) {
const attrLen = value.length;
const padLen = paddingLength(attrLen);
const header = Buffer.alloc(4);
header.writeUInt16BE(type, 0);
header.writeUInt16BE(attrLen, 2);
return Buffer.concat([
header,
value,
Buffer.alloc(padLen)
]);
}
var setBodyLength = (data, length) => {
const output = Buffer.alloc(data.length);
data.copy(output, 0, 0, 2);
output.writeUInt16BE(length, 2);
data.copy(output, 4, 4);
return output;
};
function messageFingerprint(data) {
return (crc32(setBodyLength(data, data.length - 20 + 8)) ^ FINGERPRINT_XOR) >>> 0;
}
function messageIntegrity(data, key) {
const checkData = setBodyLength(data, data.length - 20 + 24);
return Buffer.from(createHmac$1("sha1", key).update(checkData).digest("hex"), "hex");
}
function paddingLength(length) {
const rest = length % 4;
return rest === 0 ? 0 : 4 - rest;
}
var TransactionError = class extends Error {
response;
addr;
};
var TransactionFailed = class extends TransactionError {
constructor(response, addr) {
super();
this.response = response;
this.addr = addr;
}
get str() {
let out = "STUN transaction failed";
const attribute = this.response.getAttributeValue("ERROR-CODE");
if (attribute) {
const [code, msg] = attribute;
out += ` (${code} - ${msg})`;
}
return out;
}
};
var TransactionTimeout = class extends TransactionError {
get str() {
return "STUN transaction timed out";
}
};
var log18 = debug("werift-ice:packages/ice/src/stun/transaction.ts");
async function resolveRequestAddress(addr, family = 0) {
if (isIP(addr[0])) return addr;
return [(await promises.lookup(addr[0], { family })).address, addr[1]];
}
function normalizeTransactionOptions(retransmissionsOrOptions, onRequestSent) {
if (retransmissionsOrOptions !== null && typeof retransmissionsOrOptions === "object") return retransmissionsOrOptions;
return {
retransmissions: typeof retransmissionsOrOptions === "number" ? retransmissionsOrOptions : void 0,
onRequestSent
};
}
function addressEquals(a, b) {
return a[0] === b[0] && a[1] === b[1];
}
var Transaction = class {
constructor(request, addr, protocol, retransmissionsOrOptions, onRequestSent) {
this.request = request;
this.addr = addr;
this.protocol = protocol;
const options = normalizeTransactionOptions(retransmissionsOrOptions, onRequestSent);
this.triesMax = 1 + (options.retransmissions ?? 6);
this.timeoutDelay = options.responseTimeout ?? 50;
this.onRequestSent = options.onRequestSent;
this.signal = options.signal;
this.expectedAddr = addr;
this.integrityKey = options.integrityKey;
}
timeoutDelay;
ended = false;
tries = 0;
triesMax;
onResponse = new Event2();
onRequestSent;
signal;
/** Remote address this transaction was sent to; responses must match. */
expectedAddr;
/**
* When set, protocol layers re-parse the wire response with this key so
* MESSAGE-INTEGRITY failures are rejected before responseReceived.
*/
integrityKey;
waitTimer;
waitResolve;
onAbort;
/**
* Accept a matching authenticated non-error response from the expected
* remote address. Wrong address, missing MESSAGE-INTEGRITY (when required),
* or non-success class is rejected without completing the transaction
* (wrong address / unauthenticated responses are ignored so we keep waiting).
*/
responseReceived = (message, addr) => {
if (this.ended || this.onResponse.length === 0) return;
if (!addressEquals(this.expectedAddr, addr)) {
log18("ignore STUN response from unexpected address", addr, "expected", this.expectedAddr);
return;
}
if (this.integrityKey) {
if (!(message.attributesKeys.includes("MESSAGE-INTEGRITY") || message.attributesKeys.includes("MESSAGE-INTEGRITY-SHA256"))) {
log18("ignore unauthenticated STUN response (MESSAGE-INTEGRITY required)");
return;
}
}
if (message.messageClass === 256) {
this.onResponse.execute(message, addr);
this.onResponse.complete();
} else this.onResponse.error(new TransactionFailed(message, addr));
};
run = async () => {
try {
if (this.signal?.aborted) throw new TransactionTimeout();
this.attachAbortListener();
this.retry().catch((e) => {
log18("retry failed", e);
});
return await this.onResponse.asPromise();
} catch (error) {
throw error;
} finally {
this.cancel();
}
};
attachAbortListener() {
if (!this.signal) return;
this.onAbort = () => {
this.failWithTimeout();
};
this.signal.addEventListener("abort", this.onAbort, { once: true });
}
failWithTimeout() {
if (this.ended) return;
this.ended = true;
this.clearWait();
if (this.onResponse.length > 0) this.onResponse.error(new TransactionTimeout());
}
clearWait() {
if (this.waitTimer !== void 0) {
clearTimeout(this.waitTimer);
this.waitTimer = void 0;
}
const resolve = this.waitResolve;
this.waitResolve = void 0;
resolve?.();
}
wait(ms) {
return new Promise((resolve) => {
if (this.ended || this.signal?.aborted) {
resolve();
return;
}
this.waitResolve = resolve;
this.waitTimer = setTimeout(() => {
this.waitTimer = void 0;
this.waitResolve = void 0;
resolve();
}, ms);
});
}
retry = async () => {
while (this.tries < this.triesMax && !this.ended) {
this.onRequestSent?.(this.tries);
this.protocol.sendStun(this.request, this.addr).catch((e) => {
log18("send stun failed", e);
});
await this.wait(this.timeoutDelay);
if (this.ended) break;
this.timeoutDelay *= 2;
this.tries++;
}
if (this.tries >= this.triesMax && !this.ended) {
log18(`retry failed times:${this.tries} maxLimit:${this.triesMax}`);
this.failWithTimeout();
}
};
cancel() {
this.ended = true;
this.clearWait();
if (this.signal && this.onAbort) {
this.signal.removeEventListener("abort", this.onAbort);
this.onAbort = void 0;
}
}
};
function buildTransactionOptions(integrityKey, retransmissionsOrOptions, onRequestSent) {
const options = normalizeTransactionOptions(retransmissionsOrOptions, onRequestSent);
if (integrityKey && !options.integrityKey) options.integrityKey = integrityKey;
return options;
}
var log19 = debug("werift-ice:packages/ice/src/stun/tcpProtocol.ts");
function socketKey(addr) {
return `${addr[0]}:${addr[1]}`;
}
function addressFromSocket(socket) {
if (!socket.remoteAddress || !socket.remotePort) return;
return [socket.remoteAddress, socket.remotePort];
}
async function waitForListening(server, host, port) {
return await new Promise((resolve, reject) => {
const onError = (error) => {
server.off("listening", onListening);
reject(error);
};
const onListening = () => {
server.off("error", onError);
resolve();
};
server.once("error", onError);
server.once("listening", onListening);
server.listen({
host,
port: port ?? 0,
exclusive: true
});
});
}
var BaseTcpProtocol = class _BaseTcpProtocol {
static type = "tcp";
type = _BaseTcpProtocol.type;
transactions = {};
localCandidate;
sentMessage;
localIp;
onRequestReceived = new Event2();
onDataReceived = new Event2();
sockets = /* @__PURE__ */ new Map();
rememberSocket(entry) {
const remoteAddr = entry.remoteAddr;
if (!remoteAddr) return;
this.sockets.set(socketKey(remoteAddr), entry);
}
forgetSocket(remoteAddr) {
if (!remoteAddr) return;
this.sockets.delete(socketKey(remoteAddr));
}
registerSocket(socket, remoteAddr) {
const entry = {
socket,
buffer: Buffer.alloc(0),
remoteAddr
};
if (remoteAddr) this.rememberSocket(entry);
socket.on("data", (data) => {
entry.buffer = Buffer.concat([entry.buffer, data]);
const { frames, rest } = splitTcpFrames(entry.buffer);
entry.buffer = rest;
const socketAddr = entry.remoteAddr ?? addressFromSocket(socket);
if (!entry.remoteAddr && socketAddr) {
entry.remoteAddr = socketAddr;
this.rememberSocket(entry);
}
if (!socketAddr) return;
for (const frame of frames) {
if (frame.length === 0) continue;
this.handleFrame(frame, socketAddr);
}
});
socket.on("close", () => {
this.forgetSocket(entry.remoteAddr);
});
socket.on("error", (error) => {
log19("tcp socket error", error);
});
return entry;
}
handleFrame(data, addr) {
try {
const message = parseMessage(data);
if (!message) {
this.onDataReceived.execute(data);
return;
}
if ((message.messageClass === 256 || message.messageClass === 272) && this.transactions[message.transactionIdHex]) {
const transaction = this.transactions[message.transactionIdHex];
const verified = transaction.integrityKey ? parseMessage(data, transaction.integrityKey) : message;
if (!verified) {
log19("STUN response failed MESSAGE-INTEGRITY check");
return;
}
transaction.responseReceived(verified, addr);
} else if (message.messageClass === 0) this.onRequestReceived.execute(message, addr, data);
} catch (error) {
log19("tcp frame parse error", error);
}
}
async sendFrame(data, addr) {
const entry = await this.getSocket(addr);
await new Promise((resolve, reject) => {
entry.socket.write(encodeTcpFrame(data), (error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}
async sendStun(message, addr) {
await this.sendFrame(message.bytes, addr);
}
async sendData(data, addr) {
await this.sendFrame(data, addr);
}
async request(request, addr, integrityKey, retransmissionsOrOptions, onRequestSent) {
if (this.transactions[request.transactionIdHex]) throw new Error("already requested");
if (integrityKey) {
request.addMessageIntegrity(integrityKey);
request.addFingerprint();
}
const resolvedAddr = await resolveRequestAddress(addr);
const options = buildTransactionOptions(integrityKey, retransmissionsOrOptions, onRequestSent);
const transaction = new Transaction(request, resolvedAddr, this, options);
this.transactions[request.transactionIdHex] = transaction;
try {
return await transaction.run();
} finally {
delete this.transactions[request.transactionIdHex];
}
}
async pruneForSelection(remoteAddr) {
for (const [key, entry] of this.sockets.entries()) {
if (remoteAddr && key === socketKey(remoteAddr)) continue;
entry.socket.destroy();
this.sockets.delete(key);
}
}
get activeSocketCount() {
return this.sockets.size;
}
get address() {
return {};
}
async close() {
Object.values(this.transactions).forEach((transaction) => {
transaction.cancel();
});
await this.pruneForSelection();
this.onRequestReceived.complete();
this.onDataReceived.complete();
}
};
var TcpActiveProtocol = class extends BaseTcpProtocol {
pendingSockets = /* @__PURE__ */ new Map();
async connectionMade(localIp) {
this.localIp = localIp;
}
async getSocket(addr) {
const key = socketKey(addr);
const existing = this.sockets.get(key);
if (existing) return existing;
const pending = this.pendingSockets.get(key);
if (pending) return await pending;
const connecting = new Promise((resolve, reject) => {
const socket = connect({
host: addr[0],
port: addr[1],
localAddress: this.localIp
});
const entry = this.registerSocket(socket, addr);
const onError = (error) => {
socket.off("connect", onConnect);
reject(error);
};
const onConnect = () => {
socket.off("error", onError);
resolve(entry);
};
socket.once("error", onError);
socket.once("connect", onConnect);
});
this.pendingSockets.set(key, connecting);
try {
return await connecting;
} finally {
this.pendingSockets.delete(key);
}
}
};
var TcpPassiveProtocol = class extends BaseTcpProtocol {
server = createServer((socket) => {
this.registerSocket(socket, addressFromSocket(socket));
});
async connectionMade(localIp, portRange) {
this.localIp = localIp;
if (portRange) {
let lastError;
for (let port = portRange[0]; port <= portRange[1]; port++) try {
await waitForListening(this.server, localIp, port);
return;
} catch (error) {
lastError = error;
}
throw lastError ?? /* @__PURE__ */ new Error("tcp port not found");
}
await waitForListening(this.server, localIp);
}
async getSocket(addr) {
const entry = this.sockets.get(socketKey(addr));
if (!entry) throw new Error("tcp passive connection not established");
return entry;
}
get listeningPort() {
const address = this.server.address();
if (!address || typeof address === "string") throw new Error("tcp passive protocol is not listening");
return address.port;
}
async close() {
await super.close();
await new Promise((resolve) => {
this.server.close(() => resolve());
});
}
};
var log20 = debug("werift-ice : packages/ice/src/stun/protocol.ts");
var StunProtocol = class _StunProtocol {
static type = "stun";
type = _StunProtocol.type;
transport;
transactions = {};
get transactionsKeys() {
return Object.keys(this.transactions);
}
localCandidate;
sentMessage;
localIp;
onRequestReceived = new Event2();
onDataReceived = new Event2();
constructor() {}
connectionMade = async (useIpv4, portRange, interfaceAddresses) => {
if (useIpv4) this.transport = await UdpTransport.init("udp4", {
portRange,
interfaceAddresses
});
else this.transport = await UdpTransport.init("udp6", {
portRange,
interfaceAddresses
});
this.transport.onData = (data, addr) => {
this.datagramReceived(data, addr);
};
};
datagramReceived(data, addr) {
try {
const message = parseMessage(data);
if (!message) {
if (this.localCandidate) this.onDataReceived.execute(data);
return;
}
if ((message.messageClass === 256 || message.messageClass === 272) && this.transactionsKeys.includes(message.transactionIdHex)) {
const transaction = this.transactions[message.transactionIdHex];
const verified = transaction.integrityKey ? parseMessage(data, transaction.integrityKey) : message;
if (!verified) {
log20("STUN response failed MESSAGE-INTEGRITY check");
return;
}
transaction.responseReceived(verified, addr);
} else if (message.messageClass === 0) this.onRequestReceived.execute(message, addr, data);
} catch (error) {
log20("datagramReceived error", error);
}
}
getExtraInfo() {
const { address: host, port } = this.transport.address;
return [host, port];
}
async sendStun(message, addr) {
if (this.transport.closed) return;
const data = message.bytes;
await this.transport.send(data, addr).catch(() => {
log20("sendStun failed", addr, message);
});
}
async sendData(data, addr) {
if (this.transport.closed) return;
await this.transport.send(data, addr);
}
async request(request, addr, integrityKey, retransmissionsOrOptions, onRequestSent) {
if (this.transactionsKeys.includes(request.transactionIdHex)) throw new Error("already request ed");
if (integrityKey) {
request.addMessageIntegrity(integrityKey);
request.addFingerprint();
}
const resolvedAddr = await resolveRequestAddress(addr, this.transport.socketType === "udp6" ? 6 : 4);
const options = buildTransactionOptions(integrityKey, retransmissionsOrOptions, onRequestSent);
const transaction = new Transaction(request, resolvedAddr, this, options);
this.transactions[request.transactionIdHex] = transaction;
try {
return await transaction.run();
} catch (e) {
throw e;
} finally {
delete this.transactions[request.transactionIdHex];
}
}
async close() {
Object.values(this.transactions).forEach((transaction) => {
transaction.cancel();
});
await this.transport.close();
this.onRequestReceived.complete();
this.onDataReceived.complete();
}
};
function makeTurnIntegrityKey(username, realm, password) {
return createHash$1("md5").update(Buffer.from([
username,
realm,
password
].join(":"))).digest();
}
function randomString(length) {
return randomBytes$1(length).toString("hex").substring(0, length);
}
function randomTransactionId() {
return randomBytes$1(12);
}
var PQueue = class {
queue = [];
wait = new Event2();
put(v) {
this.queue.push(v);
if (this.queue.length === 1) this.wait.execute(v);
}
get() {
const v = this.queue.shift();
if (!v) return new Promise((r) => {
this.wait.subscribe((v2) => {
this.queue.shift();
r(v2);
});
});
return v;
}
};
var cancelable = (ex) => {
let resolve;
let reject;
const p = new Promise((r, f) => {
resolve = r;
reject = f;
});
p.then(() => {
onCancel.execute(void 0);
onCancel.complete();
}).catch((e) => {
onCancel.execute(e ?? /* @__PURE__ */ new Error());
onCancel.complete();
});
const onCancel = new Event2();
ex(resolve, reject, onCancel).catch(() => {});
return {
awaitable: p,
resolve,
reject
};
};
function isChannelData(data) {
return data.length >= 4 && (data[0] & 192) === 64;
}
function encodeChannelData(channelNumber, data) {
const header = Buffer.alloc(4);
header.writeUInt16BE(channelNumber, 0);
header.writeUInt16BE(data.length, 2);
return Buffer.concat([header, data]);
}
function decodeChannelData(data) {
if (!isChannelData(data) || data.length < 4) return;
const channelNumber = data.readUInt16BE(0);
const length = data.readUInt16BE(2);
if (data.length < 4 + length) return;
return {
channelNumber,
data: data.subarray(4, 4 + length)
};
}
function padTurnFrame(data) {
const padding = paddingLength(data.length);
return padding > 0 ? Buffer.concat([data, Buffer.alloc(padding)]) : data;
}
function splitTurnTcpFrames(buffer2) {
const frames = [];
let offset = 0;
let malformed = false;
while (buffer2.length - offset >= 4) {
let frameLength;
if (isChannelData(buffer2.subarray(offset))) {
const payloadLength = buffer2.readUInt16BE(offset + 2);
frameLength = 4 + payloadLength + paddingLength(payloadLength);
} else if ((buffer2[offset] & 192) === 0) {
if (buffer2.length - offset < 20) break;
const stunBodyLength = buffer2.readUInt16BE(offset + 2);
frameLength = 20 + stunBodyLength + paddingLength(stunBodyLength);
} else {
malformed = true;
break;
}
if (buffer2.length - offset < frameLength) break;
frames.push(buffer2.subarray(offset, offset + frameLength));
offset += frameLength;
}
return {
frames,
malformed,
rest: buffer2.subarray(offset)
};
}
var log21 = debug("werift-ice:packages/ice/src/turn/protocol.ts");
var DEFAULT_CHANNEL_REFRESH_TIME = 500;
var DEFAULT_ALLOCATION_LIFETIME = 600;
var UDP_TRANSPORT = 285212672;
function isStreamTransport(transport) {
return transport.type === "tcp" || transport.type === "tls";
}
function permissionKey(addr) {
return addr[0];
}
function channelKey(addr) {
return JSON.stringify(addr);
}
var StunOverTurnProtocol = class _StunOverTurnProtocol {
constructor(turn) {
this.turn = turn;
turn.onData.subscribe((data, addr) => {
this.handleStunMessage(data, addr);
}).disposer(this.disposer);
}
static type = "turn";
type = _StunOverTurnProtocol.type;
localCandidate;
disposer = new EventDisposer();
onRequestReceived = new Event2();
onDataReceived = new Event2();
handleStunMessage = (data, addr) => {
try {
const message = parseMessage(data);
if (!message) {
this.onDataReceived.execute(data);
return;
}
if (message.messageClass === 256 || message.messageClass === 272) {
const transaction = this.turn.transactions[message.transactionIdHex];
if (transaction) {
const verified = transaction.integrityKey ? parseMessage(data, transaction.integrityKey) : message;
if (!verified) {
log21("STUN over TURN response failed MESSAGE-INTEGRITY check");
return;
}
transaction.responseReceived(verified, addr);
}
} else if (message.messageClass === 0) this.onRequestReceived.execute(message, addr, data);
} catch (error) {
log21("datagramReceived error", error);
}
};
async request(request, addr, integrityKey, retransmissionsOrOptions, onRequestSent) {
if (this.turn.transactions[request.transactionIdHex]) throw new Error("exist");
if (integrityKey) {
request.addMessageIntegrity(integrityKey);
request.addFingerprint();
}
const resolvedAddr = await resolveRequestAddress(addr);
const options = buildTransactionOptions(integrityKey, retransmissionsOrOptions, onRequestSent);
const transaction = new Transaction(request, resolvedAddr, this, options);
this.turn.transactions[request.transactionIdHex] = transaction;
try {
return await transaction.run();
} catch (e) {
throw e;
} finally {
delete this.turn.transactions[request.transactionIdHex];
}
}
async connectionMade() {}
async sendData(data, addr) {
await this.turn.sendData(data, addr);
}
async sendStun(message, addr) {
await this.turn.sendData(message.bytes, addr);
}
async close() {
this.disposer.dispose();
return this.turn.close();
}
};
var TurnProtocol = class _TurnProtocol {
constructor(server, username, password, lifetime, transport, options = {}) {
this.server = server;
this.username = username;
this.password = password;
this.lifetime = lifetime;
this.transport = transport;
this.options = options;
this.channelRefreshTime = this.options.channelRefreshTime ?? DEFAULT_CHANNEL_REFRESH_TIME;
}
static type = "turn";
type = _TurnProtocol.type;
onData = new Event2();
onRequestReceived = new Event2();
onDataReceived = new Event2();
integrityKey;
nonce;
realm;
relayedAddress;
mappedAddress;
localCandidate;
transactions = {};
refreshHandle;
channelNumber = 16384;
channelByAddr = {};
addrByChannel = {};
/**sec */
channelRefreshTime;
/**
* Serializes ChannelBind requests so allocation-wide auth state
* (nonce/realm/integrityKey) is not updated concurrently. Rejections
* must not poison this tail — see channelBindQueue assignment sites.
*/
channelBindQueue = Promise.resolve();
/** In-flight ChannelBind per peer transport address (dedupe concurrent). */
channelBindingByAddr = /* @__PURE__ */ new Map();
tcpBuffer = Buffer.alloc(0);
/** Permission cache keyed by peer IP only (RFC 8656). */
permissionByAddr = {};
/**
* Serializes CreatePermission requests (auth state race avoidance).
* Rejections must not poison this tail.
*/
permissionQueue = Promise.resolve();
/** In-flight CreatePermission per peer IP (dedupe concurrent). */
creatingPermissionByAddr = /* @__PURE__ */ new Map();
async connectionMade() {
this.transport.onData = (data, addr) => {
this.dataReceived(data, addr);
};
const request = new Message(3, 0);
request.setAttribute("LIFETIME", this.lifetime).setAttribute("REQUESTED-TRANSPORT", UDP_TRANSPORT);
const [response] = await this.requestWithRetry(request, this.server).catch((e) => {
log21("connect error", e);
throw e;
});
this.relayedAddress = response.getAttributeValue("XOR-RELAYED-ADDRESS");
this.mappedAddress = response.getAttributeValue("XOR-MAPPED-ADDRESS");
const exp = response.getAttributeValue("LIFETIME");
log21("connect", this.relayedAddress, this.mappedAddress, { exp });
this.refresh(exp);
}
handleChannelData(data) {
const decoded = decodeChannelData(data);
const addr = decoded && this.addrByChannel[decoded.channelNumber];
if (addr && decoded) this.onData.execute(decoded.data, addr);
}
handleSTUNMessage(data, addr) {
try {
const message = parseMessage(data);
if (!message) throw new Error("not stun message");
if (message.messageClass === 256 || message.messageClass === 272) {
const transaction = this.transactions[message.transactionIdHex];
if (transaction) {
const verified = transaction.integrityKey ? parseMessage(data, transaction.integrityKey) : message;
if (!verified) {
log21("TURN STUN response failed MESSAGE-INTEGRITY check");
return;
}
transaction.responseReceived(verified, addr);
}
} else if (message.messageClass === 0) this.onData.execute(data, addr);
if (message.getAttributeValue("DATA")) {
const buf = message.getAttributeValue("DATA");
const peerAddress = message.getAttributeValue("XOR-PEER-ADDRESS") ?? addr;
this.onData.execute(buf, peerAddress);
}
} catch (error) {
log21("parse error", data.toString());
}
}
dataReceived(data, addr) {
const datagramReceived = (data2, addr2) => {
if (data2.length >= 4 && isChannelData(data2)) this.handleChannelData(data2);
else this.handleSTUNMessage(data2, addr2);
};
if (isStreamTransport(this.transport)) {
this.tcpBuffer = Buffer.concat([this.tcpBuffer, data]);
const { frames, rest } = splitTurnTcpFrames(this.tcpBuffer);
this.tcpBuffer = rest;
for (const frame of frames) datagramReceived(frame, addr);
} else datagramReceived(data, addr);
}
async send(data, addr) {
if (this.transport.closed) return;
await this.transport.send(isStreamTransport(this.transport) ? padTurnFrame(data) : data, addr);
}
async createPermission(peerAddress) {
const request = new Message(8, 0);
request.setAttribute("XOR-PEER-ADDRESS", peerAddress).setAttribute("USERNAME", this.username).setAttribute("REALM", this.realm).setAttribute("NONCE", this.nonce);
await this.requestWithRetry(request, this.server);
}
refresh = (exp) => {
this.refreshHandle = cancelable(async (_, __, onCancel) => {
let run = true;
onCancel.once(() => {
run = false;
});
while (run) {
const delay = 5 / 6 * exp * 1e3;
log21("refresh delay", delay, { exp });
await setTimeout$2(delay);
const request = new Message(4, 0);
request.setAttribute("LIFETIME", exp);
try {
const [message] = await this.requestWithRetry(request, this.server);
exp = message.getAttributeValue("LIFETIME");
log21("refresh", { exp });
} catch (error) {
log21("refresh error", error);
}
}
});
};
async request(request, addr, _integrityKey, retransmissionsOrOptions, onRequestSent) {
if (this.transactions[request.transactionIdHex]) throw new Error("exist");
if (this.integrityKey) request.setAttribute("USERNAME", this.username).setAttribute("REALM", this.realm).setAttribute("NONCE", this.nonce).addMessageIntegrity(this.integrityKey).addFingerprint();
const resolvedAddr = await resolveRequestAddress(addr);
const options = buildTransactionOptions(this.integrityKey, retransmissionsOrOptions, onRequestSent);
const transaction = new Transaction(request, resolvedAddr, this, options);
this.transactions[request.transactionIdHex] = transaction;
try {
return await transaction.run();
} catch (e) {
throw e;
} finally {
delete this.transactions[request.transactionIdHex];
}
}
async requestWithRetry(request, addr) {
let message, address;
try {
[message, address] = await this.request(request, addr);
} catch (error) {
if (error instanceof TransactionFailed == false) {
log21("requestWithRetry error", error);
throw error;
}
this.server = error.addr;
const [errorCode] = error.response.getAttributeValue("ERROR-CODE");
const nonce = error.response.getAttributeValue("NONCE");
const realm = error.response.getAttributeValue("REALM");
if ((errorCode === 401 && realm || errorCode === 438 && this.realm) && nonce) {
log21("retry with nonce", errorCode);
this.nonce = nonce;
if (errorCode === 401) this.realm = realm;
this.integrityKey = makeIntegrityKey(this.username, this.realm, this.password);
request.transactionId = randomTransactionId();
[message, address] = await this.request(request, this.server);
} else throw error;
}
return [message, address];
}
async sendData(data, addr) {
let channel;
try {
channel = await this.getChannel(addr);
} catch (e) {
log21("channelBind error; falling back to Send Indication", e);
}
if (!channel) {
await this.getPermission(addr);
const indicate = new Message(6, 16).setAttribute("DATA", data).setAttribute("XOR-PEER-ADDRESS", addr);
await this.sendStun(indicate, this.server);
return;
}
await this.send(encodeChannelData(channel.number, data), this.server);
}
/**
* Ensure a CreatePermission exists for the peer IP.
* Peer failures are isolated: a rejection for peer A does not poison peer B.
*/
async getPermission(addr) {
const key = permissionKey(addr);
if (this.permissionByAddr[key]) return;
const existing = this.creatingPermissionByAddr.get(key);
if (existing) return existing;
const operation = this.permissionQueue.then(async () => {
if (this.permissionByAddr[key]) return;
await this.createPermission(addr);
this.permissionByAddr[key] = true;
});
this.permissionQueue = operation.then(() => void 0, () => void 0);
this.creatingPermissionByAddr.set(key, operation);
try {
await operation;
} catch (error) {
log21("createPermission error", error);
throw error;
} finally {
if (this.creatingPermissionByAddr.get(key) === operation) this.creatingPermissionByAddr.delete(key);
}
}
/**
* Ensure a ChannelBind exists for the peer transport address.
* Peer failures are isolated; concurrent same-peer calls share one Promise.
*/
async getChannel(addr) {
const key = channelKey(addr);
const existing = this.channelBindingByAddr.get(key);
if (existing) return existing;
const cached = this.channelByAddr[key];
const now = int(Date.now() / 1e3);
if (cached && cached.refreshAt > now) return cached;
const operation = this.channelBindQueue.then(() => this.ensureChannel(addr));
this.channelBindQueue = operation.then(() => void 0, () => void 0);
this.channelBindingByAddr.set(key, operation);
try {
return await operation;
} catch (error) {
log21("channelBind error", error);
throw error;
} finally {
if (this.channelBindingByAddr.get(key) === operation) this.channelBindingByAddr.delete(key);
}
}
/**
* Create or refresh a channel for addr. Provisional mapping is installed
* before the request so early ChannelData can be decoded; only a failed
* *initial* bind rolls the mapping back. Failed channel numbers are never
* reused.
*/
async ensureChannel(addr) {
const key = channelKey(addr);
const now = int(Date.now() / 1e3);
let channel = this.channelByAddr[key];
if (channel && channel.refreshAt > now) return channel;
const isNew = !channel;
if (!channel) {
channel = {
number: this.channelNumber++,
address: addr,
refreshAt: 0
};
this.channelByAddr[key] = channel;
this.addrByChannel[channel.number] = addr;
}
try {
await this.channelBind(channel.number, addr);
channel.refreshAt = int(Date.now() / 1e3) + this.channelRefreshTime;
log21(isNew ? "channelBind" : "channelBind refresh", channel);
return channel;
} catch (error) {
if (isNew) {
delete this.channelByAddr[key];
delete this.addrByChannel[channel.number];
}
throw error;
}
}
async channelBind(channelNumber, addr) {
const request = new Message(9, 0);
request.setAttribute("CHANNEL-NUMBER", channelNumber).setAttribute("XOR-PEER-ADDRESS", addr);
const [response] = await this.requestWithRetry(request, this.server);
if (response.messageMethod !== 9) throw new Error("should be CHANNEL_BIND");
}
async sendStun(message, addr) {
await this.send(message.bytes, addr);
}
async close() {
this.refreshHandle?.resolve?.();
await this.transport.close();
}
};
async function createTurnClient({ address, username, password }, { lifetime, portRange, interfaceAddresses, ssl, tlsOptions, transport: transportType } = {}) {
lifetime ??= DEFAULT_ALLOCATION_LIFETIME;
transportType ??= ssl ? "tls" : "udp";
const transport = transportType === "udp" ? await UdpTransport.init("udp4", {
portRange,
interfaceAddresses
}) : transportType === "tcp" ? await TcpTransport.init(address) : await TlsTransport.init(address, tlsOptions);
const turn = new TurnProtocol(address, username, password, lifetime, transport);
await turn.connectionMade();
return turn;
}
async function createStunOverTurnClient({ address, username, password }, { lifetime, portRange, interfaceAddresses, ssl, tlsOptions, transport: transportType } = {}) {
return new StunOverTurnProtocol(await createTurnClient({
address,
username,
password
}, {
lifetime,
portRange,
interfaceAddresses,
ssl,
tlsOptions,
transport: transportType
}));
}
function makeIntegrityKey(username, realm, password) {
return makeTurnIntegrityKey(username, realm, password);
}
var Candidate = class _Candidate {
constructor(foundation, component, transport, priority, host, port, type, relatedAddress, relatedPort, tcptype, generation, ufrag) {
this.foundation = foundation;
this.component = component;
this.transport = transport;
this.priority = priority;
this.host = host;
this.port = port;
this.type = type;
this.relatedAddress = relatedAddress;
this.relatedPort = relatedPort;
this.tcptype = tcptype;
this.generation = generation;
this.ufrag = ufrag;
}
id = randomUUID$1().toString();
refreshId() {
this.id = randomUUID$1().toString();
}
static fromSdp(sdp) {
const bits = sdp.split(" ");
if (bits.length < 8) throw new Error("SDP does not have enough properties");
const kwargs = {
foundation: bits[0],
component: Number(bits[1]),
transport: bits[2],
priority: Number(bits[3]),
host: bits[4],
port: Number(bits[5]),
type: bits[7]
};
for (let i = 8, il = bits.length - 1; i < il; i += 2) if (bits[i] === "raddr") kwargs["related_address"] = bits[i + 1];
else if (bits[i] === "rport") kwargs["related_port"] = Number(bits[i + 1]);
else if (bits[i] === "tcptype") kwargs["tcptype"] = bits[i + 1];
else if (bits[i] === "generation") kwargs["generation"] = Number(bits[i + 1]);
else if (bits[i] === "ufrag") kwargs["ufrag"] = bits[i + 1];
const { foundation, component, transport, priority, host, port, type } = kwargs;
return new _Candidate(foundation, component, transport, priority, host, port, type, kwargs["related_address"], kwargs["related_port"], kwargs["tcptype"], kwargs["generation"], kwargs["ufrag"]);
}
canPairWith(other) {
const a = isIPv4$1(this.host);
const b = isIPv4$1(other.host);
return this.component === other.component && this.transport.toLowerCase() === other.transport.toLowerCase() && canPairTcpCandidates(this, other) && a === b;
}
toSdp() {
let sdp = `${this.foundation} ${this.component} ${this.transport} ${this.priority} ${this.host} ${this.port} typ ${this.type}`;
if (this.relatedAddress) sdp += ` raddr ${this.relatedAddress}`;
if (this.relatedPort != void 0) sdp += ` rport ${this.relatedPort}`;
if (this.tcptype) sdp += ` tcptype ${this.tcptype}`;
if (this.generation != void 0) sdp += ` generation ${this.generation}`;
if (this.ufrag != void 0) sdp += ` ufrag ${this.ufrag}`;
return sdp;
}
};
var UDP_TYPE_PREFERENCE = {
host: 126,
prflx: 110,
srflx: 100,
relay: 0
};
var TCP_TYPE_PREFERENCE = {
host: 105,
prflx: 90,
srflx: 80,
relay: 0
};
var ACTIVE_PASSIVE_DIRECTION_PREFERENCE = {
active: 6,
passive: 4,
so: 2
};
var REFLEXIVE_DIRECTION_PREFERENCE = {
active: 4,
passive: 2,
so: 6
};
function normalizeTransport(transport) {
return transport?.toLowerCase() ?? "udp";
}
function normalizeTcpType(tcptype) {
switch (tcptype) {
case "active":
case "passive":
case "so": return tcptype;
default: return;
}
}
function canPairTcpCandidates(local, remote) {
if (normalizeTransport(local.transport) !== "tcp") return true;
const localType = normalizeTcpType(local.tcptype);
const remoteType = normalizeTcpType(remote.tcptype);
if (!localType || !remoteType) return false;
return localType === "active" && remoteType === "passive" || localType === "passive" && remoteType === "active" || localType === "so" && remoteType === "so";
}
function candidateLocalPreference({ candidateType, transport = "udp", tcptype, otherPreference = 8191 }) {
if (normalizeTransport(transport) !== "tcp") return otherPreference;
const tcpType = normalizeTcpType(tcptype) ?? "active";
return 8192 * (candidateType === "srflx" || candidateType === "prflx" ? REFLEXIVE_DIRECTION_PREFERENCE[tcpType] : ACTIVE_PASSIVE_DIRECTION_PREFERENCE[tcpType]) + otherPreference;
}
function candidateTypePreference(candidateType, transport = "udp") {
return (normalizeTransport(transport) === "tcp" ? TCP_TYPE_PREFERENCE : UDP_TYPE_PREFERENCE)[candidateType] ?? 0;
}
function candidateFoundation(candidateType, candidateTransport, baseAddress) {
const key = `${candidateType}|${candidateTransport}|${baseAddress}`;
return createHash$1("md5").update(key, "ascii").digest("hex").slice(7);
}
function candidatePriority(candidateType, options = 65535) {
const transport = typeof options === "number" ? "udp" : normalizeTransport(options.transport);
const localPref = typeof options === "number" ? options : options.localPreference ?? candidateLocalPreference({
candidateType,
transport,
tcptype: options.tcptype,
otherPreference: options.otherPreference
});
return (1 << 24) * candidateTypePreference(candidateType, transport) + 256 * localPref + 255;
}
function remoteTcpTypeForIncoming(localTcpType) {
switch (localTcpType) {
case "passive": return "active";
case "active": return "passive";
default: return "so";
}
}
var MdnsLookup = class {
cache = /* @__PURE__ */ new Map();
mdnsInstance = (0, import_multicast_dns.default)();
constructor() {
this.mdnsInstance.setMaxListeners(50);
}
lookup(host) {
return new Promise((r, f) => {
const cleanup = () => {
this.mdnsInstance.removeListener("response", l);
clearTimeout(timeout);
};
const timeout = setTimeout(() => {
cleanup();
f(/* @__PURE__ */ new Error("No mDNS response"));
}, 1e4);
const l = (response) => {
const a = response.answers?.[0];
if (a?.type !== "A") return;
if (a.name !== host) return;
cleanup();
r(a.data);
};
this.mdnsInstance.on("response", l);
this.mdnsInstance.query(host, "A");
});
}
close() {
this.mdnsInstance.destroy();
}
};
var log22 = debug("werift-ice : packages/ice/src/ice.ts : log");
var CandidatePair = class {
constructor(protocol, remoteCandidate, iceControlling) {
this.protocol = protocol;
this.remoteCandidate = remoteCandidate;
this.iceControlling = iceControlling;
}
id = randomUUID$1().toString();
handle;
nominated = false;
remoteNominated = false;
_state = 0;
get state() {
return this._state;
}
packetsSent = 0;
packetsReceived = 0;
bytesSent = 0;
bytesReceived = 0;
rtt;
totalRoundTripTime = 0;
roundTripTimeMeasurements = 0;
requestsReceived = 0;
requestsSent = 0;
responsesReceived = 0;
responsesSent = 0;
retransmissionsReceived = 0;
retransmissionsSent = 0;
consentRequestsSent = 0;
requestTransactionIds = /* @__PURE__ */ new Set();
toJSON() {
return this.json;
}
get json() {
return {
protocol: this.protocol.type,
localCandidate: this.localCandidate.toSdp(),
remoteCandidate: this.remoteCandidate.toSdp()
};
}
updateState(state) {
this._state = state;
}
get localCandidate() {
if (!this.protocol.localCandidate) throw new Error("localCandidate not exist");
return this.protocol.localCandidate;
}
get remoteAddr() {
return [this.remoteCandidate.host, this.remoteCandidate.port];
}
get component() {
return this.localCandidate.component;
}
get priority() {
return candidatePairPriority(this.localCandidate, this.remoteCandidate, this.iceControlling);
}
get foundation() {
return this.localCandidate.foundation;
}
noteIncomingRequest(transactionId) {
if (!this.requestTransactionIds.has(transactionId)) {
this.requestTransactionIds.add(transactionId);
return false;
}
this.retransmissionsReceived++;
return true;
}
};
var ICE_COMPLETED = 1;
var ICE_FAILED = 2;
var CONSENT_INTERVAL = 5;
var CONSENT_FAILURES = 6;
var CONSENT_TIMEOUT = 30;
var CONSENT_RESPONSE_TIMEOUT = 1e3;
var CONSENT_RESPONSE_TIMEOUT_MIN = 500;
function consentResponseTimeoutMs(rttSeconds) {
if (rttSeconds === void 0 || !Number.isFinite(rttSeconds) || rttSeconds <= 0) return CONSENT_RESPONSE_TIMEOUT;
return Math.max(500, Math.round(rttSeconds * 1e3 * 2 + 200));
}
var CandidatePairState = /* @__PURE__ */ ((CandidatePairState2) => {
CandidatePairState2[CandidatePairState2["FROZEN"] = 0] = "FROZEN";
CandidatePairState2[CandidatePairState2["WAITING"] = 1] = "WAITING";
CandidatePairState2[CandidatePairState2["IN_PROGRESS"] = 2] = "IN_PROGRESS";
CandidatePairState2[CandidatePairState2["SUCCEEDED"] = 3] = "SUCCEEDED";
CandidatePairState2[CandidatePairState2["FAILED"] = 4] = "FAILED";
return CandidatePairState2;
})(CandidatePairState || {});
var defaultOptions = {
iceLite: false,
useTcp: false,
useIpv4: true,
useIpv6: true
};
function validateRemoteCandidate(candidate) {
if (![
"host",
"relay",
"srflx"
].includes(candidate.type)) throw new Error(`Unexpected candidate type "${candidate.type}"`);
return candidate;
}
function sortCandidatePairs(pairs, iceControlling) {
return pairs.sort((a, b) => candidatePairPriority(a.localCandidate, a.remoteCandidate, iceControlling) - candidatePairPriority(b.localCandidate, b.remoteCandidate, iceControlling)).reverse();
}
function candidatePairPriority(local, remote, iceControlling) {
const G = iceControlling && local.priority || remote.priority;
const D = iceControlling && remote.priority || local.priority;
return 1 * Math.min(G, D) + 2 * Math.max(G, D) + (G > D ? 1 : 0);
}
async function serverReflexiveCandidate(protocol, stunServer) {
const request = new Message(1, 0);
try {
const [response] = await protocol.request(request, stunServer);
const localCandidate = protocol.localCandidate;
if (!localCandidate) throw new Error("not exist");
return new Candidate(candidateFoundation("srflx", localCandidate.transport, localCandidate.host), localCandidate.component, localCandidate.transport, candidatePriority("srflx", {
transport: localCandidate.transport,
tcptype: localCandidate.tcptype
}), response.getAttributeValue("XOR-MAPPED-ADDRESS")[0], response.getAttributeValue("XOR-MAPPED-ADDRESS")[1], "srflx", localCandidate.host, localCandidate.port, localCandidate.tcptype);
} catch (error) {
log22("error serverReflexiveCandidate", error);
}
}
function validateAddress(addr) {
if (addr && Number.isNaN(addr[1])) return [addr[0], 443];
return addr;
}
function selectAddressesFromInterfaces(interfaces, family, options = {}, isLinkLocal) {
const costlyNetworks = [
"ipsec",
"tun",
"utun",
"tap"
];
const banNetworks = ["vmnet", "veth"];
const { useLinkLocalAddress } = options;
const all = Object.keys(interfaces).map((nic) => {
for (const word of [...costlyNetworks, ...banNetworks]) if (nic.startsWith(word)) return {
nic,
addresses: []
};
return {
nic,
addresses: (interfaces[nic] ?? []).filter((details) => normalizeFamilyNodeV18(details.family) === family && !details.internal && (useLinkLocalAddress ? true : !isLinkLocal(details))).map((address) => address.address)
};
}).filter((address) => !!address);
all.sort((a, b) => a.nic.localeCompare(b.nic));
return Object.values(all).flatMap((entry) => entry.addresses);
}
var logger = debug("werift-ice : packages/ice/src/utils.ts");
async function getGlobalIp(stunServer, interfaceAddresses) {
const protocol = new StunProtocol();
await protocol.connectionMade(true, void 0, interfaceAddresses);
const request = new Message(1, 0);
const [response] = await protocol.request(request, stunServer ?? ["stun.l.google.com", 19302]);
await protocol.close();
return response.getAttributeValue("XOR-MAPPED-ADDRESS")[0];
}
function isLinkLocalAddress(info) {
return normalizeFamilyNodeV18(info.family) === 4 && info.address?.startsWith("169.254.") || normalizeFamilyNodeV18(info.family) === 6 && info.address?.startsWith("fe80::");
}
function nodeIpAddress(family, { useLinkLocalAddress } = {}) {
const interfaces = os$1.networkInterfaces();
logger(interfaces);
return selectAddressesFromInterfaces(interfaces, family, { useLinkLocalAddress }, isLinkLocalAddress);
}
function getHostAddresses(useIpv4, useIpv6, options = {}) {
const address = [];
if (useIpv4) address.push(...nodeIpAddress(4, options));
if (useIpv6) address.push(...nodeIpAddress(6, options));
return address;
}
var url2Address = (url) => {
if (!url) return;
const [address, port] = url.split(":");
return [address, Number.parseInt(port)];
};
var log23 = debug("werift-ice : packages/ice/src/ice.ts : log");
var Connection = class {
constructor(_iceControlling, options) {
this._iceControlling = _iceControlling;
this.options = {
...defaultOptions,
...options
};
if (this.iceLite) this._iceControlling = false;
const { stunServer, turnServer } = this.options;
this.stunServer = validateAddress(stunServer) ?? ["stun.l.google.com", 19302];
this.turnServer = validateAddress(turnServer);
this.restart();
log23("new Connection", this.options);
}
localUsername = randomString(4);
localPassword = randomString(22);
remoteIsLite = false;
remotePassword = "";
remoteUsername = "";
checkList = [];
localCandidates = [];
stunServer;
turnServer;
options;
remoteCandidatesEnd = false;
localCandidatesEnd = false;
generation = -1;
userHistory = {};
tieBreaker = randomBytes$1(8).readBigUInt64BE(0);
state = "new";
lookup;
_remoteCandidates = [];
nominated;
nominating = false;
checkListDone = false;
checkListState = new PQueue();
earlyChecks = [];
earlyChecksDone = false;
localCandidatesStart = false;
protocols = [];
queryConsentHandle;
/** RFC 7675 consent-to-send: application data may use the selected pair. */
consentFresh = false;
/** Invalidates in-flight consent callbacks on restart / close / replace / expire. */
consentSessionId = 0;
consentExpiryTimer;
consentRequestAbort;
onData = new Event2();
stateChanged = new Event2();
onIceCandidate = new Event2();
get iceControlling() {
return this._iceControlling;
}
set iceControlling(value) {
if (this.iceLite) value = false;
if (this.nominated) return;
this.applyIceControlling(value);
}
get iceLite() {
return this.options.iceLite;
}
async restart() {
this.generation++;
this.localUsername = randomString(4);
this.localPassword = randomString(22);
if (this.options.localPasswordPrefix) this.localPassword = this.options.localPasswordPrefix + this.localPassword.slice(this.options.localPasswordPrefix.length);
this.userHistory[this.localUsername] = this.localPassword;
this.remoteUsername = "";
this.remotePassword = "";
this.localCandidates = [];
this._remoteCandidates = [];
this.remoteCandidatesEnd = false;
this.localCandidatesEnd = false;
this.state = "new";
this.lookup?.close?.();
this.lookup = void 0;
this.nominated = void 0;
this.nominating = false;
this.checkList = [];
this.checkListDone = false;
this.checkListState = new PQueue();
this.earlyChecks = [];
this.earlyChecksDone = false;
this.localCandidatesStart = false;
for (const protocol of this.protocols) if (protocol.localCandidate) {
protocol.localCandidate.refreshId();
protocol.localCandidate.generation = this.generation;
protocol.localCandidate.ufrag = this.localUsername;
}
this.stopConsentLifecycle();
}
resetNominatedPair() {
log23("resetNominatedPair");
this.nominated = void 0;
this.nominating = false;
this.stopConsentLifecycle();
}
setRemoteParams({ iceLite, usernameFragment, password }) {
log23("setRemoteParams", {
iceLite,
usernameFragment,
password
});
this.remoteIsLite = iceLite;
this.remoteUsername = usernameFragment;
this.remotePassword = password;
}
async gatherCandidates() {
if (!this.localCandidatesStart) {
this.localCandidatesStart = true;
for (const protocol of this.protocols) if (protocol.localCandidate) {
protocol.localCandidate.generation = this.generation;
protocol.localCandidate.ufrag = this.localUsername;
this.appendLocalCandidate(protocol.localCandidate);
}
let address = getHostAddresses(this.options.useIpv4, this.options.useIpv6, { useLinkLocalAddress: this.options.useLinkLocalAddress });
const { interfaceAddresses } = this.options;
if (interfaceAddresses) {
const filteredAddresses = address.filter((check) => Object.values(interfaceAddresses).includes(check));
if (filteredAddresses.length) address = filteredAddresses;
}
if (this.options.additionalHostAddresses) address = Array.from(/* @__PURE__ */ new Set([...this.options.additionalHostAddresses, ...address]));
const candidatePromises = this.getCandidatePromises(address, 5);
await Promise.allSettled(candidatePromises);
this.localCandidatesEnd = true;
}
this.setState("completed");
}
appendLocalCandidate(candidate) {
this.localCandidates.push(candidate);
this.onIceCandidate.execute(candidate);
}
ensureProtocol(protocol) {
protocol.onRequestReceived.subscribe((msg, addr, data) => {
if (msg.messageMethod !== 1) {
this.respondError(msg, addr, protocol, [400, "Bad Request"]);
return;
}
const { remoteUsername: localUsername } = decodeTxUsername(msg.getAttributeValue("USERNAME"));
const localPassword = this.userHistory[localUsername] ?? this.localPassword;
const { iceControlling } = this;
if (iceControlling && msg.attributesKeys.includes("ICE-CONTROLLING")) {
if (this.tieBreaker >= msg.getAttributeValue("ICE-CONTROLLING")) {
this.respondError(msg, addr, protocol, [487, "Role Conflict"]);
return;
} else this.switchRole(false);
} else if (!iceControlling && msg.attributesKeys.includes("ICE-CONTROLLED")) {
if (this.iceLite || this.tieBreaker < msg.getAttributeValue("ICE-CONTROLLED")) {
this.respondError(msg, addr, protocol, [487, "Role Conflict"]);
return;
} else {
this.switchRole(true);
return;
}
}
if (this.options.filterStunResponse && !this.options.filterStunResponse(msg, addr, protocol)) return;
const response = new Message(1, 256, msg.transactionId);
response.setAttribute("XOR-MAPPED-ADDRESS", addr).addMessageIntegrity(Buffer.from(localPassword, "utf8")).addFingerprint();
protocol.sendStun(response, addr).catch((e) => {
log23("sendStun error", e);
});
if (this.checkList.length === 0 && !this.earlyChecksDone) this.earlyChecks.push([
msg,
addr,
protocol
]);
else this.checkIncoming(msg, addr, protocol);
});
protocol.onDataReceived.subscribe((data) => {
try {
const activePair = this.nominated;
if (activePair && activePair.protocol === protocol) {
activePair.packetsReceived++;
activePair.bytesReceived += data.length;
}
this.onData.execute(data);
} catch (error) {
log23("dataReceived", error);
}
});
}
getCandidatePromises(addresses, timeout = 5) {
const candidatePromises = [];
const { stunServer, turnServer } = this;
const { turnUsername, turnPassword } = this.options;
const gatherIceLite = this.iceLite;
const gatherRelayOnly = !gatherIceLite && this.options.forceTurn && turnServer && turnUsername && turnPassword;
addresses = addresses.filter((address) => {
if (this.protocols.find((protocol) => protocol.localIp === address)) return false;
return true;
});
const localStunPromises = gatherRelayOnly ? [] : addresses.map(async (address) => {
const protocol = new StunProtocol();
this.ensureProtocol(protocol);
try {
await protocol.connectionMade(isIPv4$1(address), this.options.portRange, this.options.interfaceAddresses);
protocol.localIp = address;
this.protocols.push(protocol);
log23("protocol", protocol.localIp);
const candidateAddress = [address, protocol.getExtraInfo()[1]];
protocol.localCandidate = new Candidate(candidateFoundation("host", "udp", candidateAddress[0]), 1, "udp", candidatePriority("host", { transport: "udp" }), candidateAddress[0], candidateAddress[1], "host", void 0, void 0, void 0, this.generation, this.localUsername);
this.pairLocalProtocol(protocol);
this.appendLocalCandidate(protocol.localCandidate);
return protocol;
} catch (error) {
log23("error protocol STUN", error);
}
});
if (!gatherRelayOnly) candidatePromises.push(...localStunPromises.map((localPromise) => localPromise.then((protocol) => protocol?.localCandidate)));
if (!gatherRelayOnly && this.options.useTcp) {
const tcpCandidatePromises = addresses.map(async (address) => {
const passiveProtocol = new TcpPassiveProtocol();
this.ensureProtocol(passiveProtocol);
await passiveProtocol.connectionMade(address, this.options.portRange);
passiveProtocol.localIp = address;
passiveProtocol.localCandidate = new Candidate(candidateFoundation("host", "tcp", address), 1, "tcp", candidatePriority("host", {
transport: "tcp",
tcptype: "passive"
}), address, passiveProtocol.listeningPort, "host", void 0, void 0, "passive", this.generation, this.localUsername);
this.protocols.push(passiveProtocol);
this.appendLocalCandidate(passiveProtocol.localCandidate);
if (!gatherIceLite) {
const activeProtocol = new TcpActiveProtocol();
this.ensureProtocol(activeProtocol);
await activeProtocol.connectionMade(address);
activeProtocol.localIp = address;
activeProtocol.localCandidate = new Candidate(candidateFoundation("host", "tcp", address), 1, "tcp", candidatePriority("host", {
transport: "tcp",
tcptype: "active"
}), address, 9, "host", void 0, void 0, "active", this.generation, this.localUsername);
this.protocols.push(activeProtocol);
this.pairLocalProtocol(activeProtocol);
this.appendLocalCandidate(activeProtocol.localCandidate);
}
});
candidatePromises.push(...tcpCandidatePromises);
}
if (!gatherIceLite && !gatherRelayOnly && stunServer) {
const stunCandidatePromises = localStunPromises.map(async (protocolPromise) => {
const protocol = await protocolPromise;
if (!protocol) return;
return new Promise(async (r, f) => {
const timer2 = setTimeout(f, timeout * 1e3);
if (protocol.localCandidate?.host && isIPv4$1(protocol.localCandidate?.host)) {
const candidate = await serverReflexiveCandidate(protocol, stunServer).catch((error) => {
log23("error", error);
});
if (candidate) this.appendLocalCandidate(candidate);
clearTimeout(timer2);
r(candidate);
} else {
clearTimeout(timer2);
r();
}
}).catch((error) => {
log23("query STUN server", error);
});
});
candidatePromises.push(...stunCandidatePromises);
}
if (!gatherIceLite && turnServer && turnUsername && turnPassword) {
const turnCandidatePromise = (async () => {
const turnTransport = this.options.turnTransport ?? "udp";
const protocol = await createStunOverTurnClient({
address: turnServer,
username: turnUsername,
password: turnPassword
}, {
portRange: this.options.portRange,
interfaceAddresses: this.options.interfaceAddresses,
transport: turnTransport,
tlsOptions: this.options.turnTlsOptions
}).catch(async (e) => {
if (turnTransport === "udp") return await createStunOverTurnClient({
address: turnServer,
username: turnUsername,
password: turnPassword
}, {
portRange: this.options.portRange,
interfaceAddresses: this.options.interfaceAddresses,
transport: "tcp"
});
else throw e;
});
this.ensureProtocol(protocol);
this.protocols.push(protocol);
const candidateAddress = protocol.turn.relayedAddress;
const relatedAddress = protocol.turn.mappedAddress;
log23("turn candidateAddress", candidateAddress);
protocol.localCandidate = new Candidate(candidateFoundation("relay", "udp", candidateAddress[0]), 1, "udp", candidatePriority("relay"), candidateAddress[0], candidateAddress[1], "relay", relatedAddress[0], relatedAddress[1], void 0, this.generation, this.localUsername);
this.appendLocalCandidate(protocol.localCandidate);
return protocol.localCandidate;
})().catch((error) => {
log23("query TURN server", error);
});
candidatePromises.push(turnCandidatePromise);
}
return candidatePromises;
}
async connect() {
log23("start connect ice");
if (!this.localCandidatesEnd) {
if (!this.localCandidatesStart) throw new Error("Local candidates gathering was not performed");
}
if (!this.remoteUsername || !this.remotePassword) throw new Error("Remote username or password is missing");
for (const c of this.remoteCandidates) this.pairRemoteCandidate(c);
this.sortCheckList();
if (!this.iceLite) this.unfreezeInitial();
log23("earlyChecks", this.localPassword, this.earlyChecks.length);
for (const earlyCheck of this.earlyChecks) this.checkIncoming(...earlyCheck);
this.earlyChecks = [];
this.earlyChecksDone = true;
if (this.iceLite) {
if (!this.nominated) {
let res2 = 2;
while (!this.checkListDone && this.state !== "closed") {
res2 = await this.checkListState.get();
log23("checkListState", res2);
if (res2 === 1) break;
}
if (res2 !== 1 && !this.nominated) throw new Error("ICE negotiation failed");
}
this.setState("connected");
return;
}
for (;;) {
if (this.state === "closed") break;
if (!this.schedulingChecks()) break;
await timers.setTimeout(20);
}
let res = 2;
while (this.checkList.length > 0 && res === 2) {
res = await this.checkListState.get();
log23("checkListState", res);
}
for (const check of this.checkList) check.handle?.resolve?.();
if (res !== 1) throw new Error("ICE negotiation failed");
this.queryConsent();
this.setState("connected");
}
unfreezeInitial() {
const [firstPair] = this.checkList;
if (!firstPair) return;
if (firstPair.state === 0) firstPair.updateState(1);
const seenFoundations = new Set(firstPair.localCandidate.foundation);
for (const pair of this.checkList) if (pair.component === firstPair.component && !seenFoundations.has(pair.localCandidate.foundation) && pair.state === 0) {
pair.updateState(1);
seenFoundations.add(pair.localCandidate.foundation);
}
}
schedulingChecks() {
{
const pair = this.checkList.filter((pair2) => {
if (this.options.forceTurn && pair2.protocol.type === StunProtocol.type) return false;
return true;
}).find((pair2) => pair2.state === 1);
if (pair) {
pair.handle = this.checkStart(pair);
return true;
}
}
{
const pair = this.checkList.find((pair2) => pair2.state === 0);
if (pair) {
pair.handle = this.checkStart(pair);
return true;
}
}
if (!this.remoteCandidatesEnd) return !this.checkListDone;
return false;
}
/**
* Stop consent request cadence, expiry timer, and outstanding transactions.
* Does not change ICE state by itself.
*/
stopConsentLifecycle() {
this.consentSessionId++;
this.consentFresh = false;
if (this.consentExpiryTimer !== void 0) {
clearTimeout(this.consentExpiryTimer);
this.consentExpiryTimer = void 0;
}
this.consentRequestAbort?.abort();
this.consentRequestAbort = void 0;
const handle = this.queryConsentHandle;
this.queryConsentHandle = void 0;
handle?.resolve?.();
}
/**
* ICE-lite interop only (not required by RFC 7675): mirror libwebrtc
* semi-aggressive nomination — attach USE-CANDIDATE when we are controlling,
* the remote is ICE-lite, and the target is the current selected pair.
*/
shouldNominateConsentRequest(pair) {
return this.iceControlling && this.remoteIsLite && this.nominated?.id === pair.id;
}
canSendApplicationData() {
if (!this.nominated) return false;
if (this.state === "closed" || this.state === "failed") return false;
if (this.iceLite) return true;
return this.consentFresh;
}
abortableDelay(ms, signal) {
return new Promise((resolve, reject) => {
if (signal.aborted) {
reject(new DOMException("The operation was aborted", "AbortError"));
return;
}
const timer2 = setTimeout(() => {
signal.removeEventListener("abort", onAbort);
resolve();
}, ms);
const onAbort = () => {
clearTimeout(timer2);
reject(new DOMException("The operation was aborted", "AbortError"));
};
signal.addEventListener("abort", onAbort, { once: true });
});
}
queryConsent = () => {
if (this.iceLite) return;
this.stopConsentLifecycle();
const sessionId = this.consentSessionId;
this.consentFresh = true;
const handle = cancelable(async (_, __, onCancel) => {
let canceled = false;
const cancelEvent = new AbortController();
const clearConsentExpiry = () => {
if (this.consentExpiryTimer === void 0) return;
clearTimeout(this.consentExpiryTimer);
this.consentExpiryTimer = void 0;
};
const refreshConsentExpiry = () => {
if (canceled || sessionId !== this.consentSessionId) return;
clearConsentExpiry();
this.consentExpiryTimer = setTimeout(() => {
this.consentExpiryTimer = void 0;
if (canceled || sessionId !== this.consentSessionId) return;
if (this.state === "closed" || this.state === "failed") return;
log23("Consent to send expired");
this.consentFresh = false;
this.consentSessionId++;
this.consentRequestAbort?.abort();
this.consentRequestAbort = void 0;
if (this.queryConsentHandle === handle) this.queryConsentHandle = void 0;
canceled = true;
cancelEvent.abort();
this.setState("failed");
}, 3e4);
};
onCancel.once(() => {
canceled = true;
if (sessionId === this.consentSessionId) {
clearConsentExpiry();
this.consentRequestAbort?.abort();
this.consentRequestAbort = void 0;
}
cancelEvent.abort();
if (this.queryConsentHandle === handle) this.queryConsentHandle = void 0;
});
refreshConsentExpiry();
const randomizedConsentInterval = () => 5 * (.8 + .4 * Math.random()) * 1e3;
let nextConsentAt = Date.now() + randomizedConsentInterval();
const isTerminalState = () => this.state === "closed" || this.state === "failed";
try {
while (!isTerminalState() && !canceled && sessionId === this.consentSessionId) {
await this.abortableDelay(Math.max(0, nextConsentAt - Date.now()), cancelEvent.signal);
if (canceled || isTerminalState() || sessionId !== this.consentSessionId) break;
nextConsentAt = Date.now() + randomizedConsentInterval();
const nominated = this.nominated;
if (!nominated) break;
const pairId = nominated.id;
const generation = this.generation;
const remotePassword = this.remotePassword;
const { localUsername, remoteUsername, iceControlling } = this;
const request = this.buildRequest({
nominate: this.shouldNominateConsentRequest(nominated),
localUsername,
remoteUsername,
iceControlling,
localCandidate: nominated.localCandidate
});
this.consentRequestAbort?.abort();
const requestAbort = new AbortController();
this.consentRequestAbort = requestAbort;
nominated.consentRequestsSent++;
nominated.requestsSent++;
const responseTimeout = consentResponseTimeoutMs(nominated.rtt);
const requestStartedAt = performance.now();
nominated.protocol.request(request, nominated.remoteAddr, Buffer.from(remotePassword, "utf8"), {
retransmissions: 0,
responseTimeout,
signal: requestAbort.signal,
onRequestSent: (attempt) => {
if (attempt > 0) nominated.retransmissionsSent++;
}
}).then(() => {
if (sessionId !== this.consentSessionId || canceled) return;
const state = this.state;
if (state === "closed" || state === "failed") return;
if (this.nominated?.id !== pairId) return;
if (this.generation !== generation) return;
if (this.remotePassword !== remotePassword) return;
const rtt = (performance.now() - requestStartedAt) / 1e3;
nominated.rtt = rtt;
nominated.totalRoundTripTime += rtt;
nominated.roundTripTimeMeasurements++;
nominated.responsesReceived++;
this.consentFresh = true;
refreshConsentExpiry();
if (state === "disconnected") this.setState("connected");
}).catch((error) => {
if (sessionId === this.consentSessionId && this.nominated?.id === pairId) log23("no stun response", error);
});
}
} catch (error) {} finally {
if (sessionId === this.consentSessionId) clearConsentExpiry();
}
});
this.queryConsentHandle = handle;
};
async close() {
this.setState("closed");
this.stopConsentLifecycle();
if (this.checkList && !this.checkListDone) this.checkListState.put(new Promise((r) => {
r(2);
}));
this.nominated = void 0;
for (const protocol of this.protocols) if (protocol.close) await protocol.close();
this.protocols = [];
this.localCandidates = [];
this.lookup?.close?.();
this.lookup = void 0;
}
setState(state) {
this.state = state;
this.stateChanged.execute(state);
}
async addRemoteCandidate(remoteCandidate) {
if (!remoteCandidate) {
this.remoteCandidatesEnd = true;
return;
}
if (remoteCandidate.host.includes(".local")) try {
if (!this.lookup) this.lookup = new MdnsLookup();
remoteCandidate.host = await this.lookup.lookup(remoteCandidate.host);
} catch (error) {
return;
}
try {
validateRemoteCandidate(remoteCandidate);
} catch (error) {
return;
}
log23("addRemoteCandidate", remoteCandidate);
this._remoteCandidates.push(remoteCandidate);
this.pairRemoteCandidate(remoteCandidate);
this.sortCheckList();
}
send = async (data) => {
if (!this.canSendApplicationData()) return;
const activePair = this.nominated;
await activePair.protocol.sendData(data, activePair.remoteAddr);
activePair.packetsSent++;
activePair.bytesSent += data.length;
};
getDefaultCandidate() {
const [candidate] = this.localCandidates.sort((a, b) => a.priority - b.priority);
return candidate;
}
set remoteCandidates(value) {
if (this.remoteCandidatesEnd) throw new Error("Cannot set remote candidates after end-of-candidates.");
this._remoteCandidates = [];
for (const remoteCandidate of value) {
try {
validateRemoteCandidate(remoteCandidate);
} catch (error) {
continue;
}
this._remoteCandidates.push(remoteCandidate);
}
this.remoteCandidatesEnd = true;
}
get remoteCandidates() {
return this._remoteCandidates;
}
get candidatePairs() {
return this.checkList;
}
sortCheckList() {
sortCandidatePairs(this.checkList, this.iceControlling);
}
findPair(protocol, remoteCandidate) {
return this.checkList.find((pair2) => pair2.protocol === protocol && pair2.remoteCandidate === remoteCandidate);
}
applyIceControlling(iceControlling) {
this._iceControlling = iceControlling;
for (const pair of this.checkList) pair.iceControlling = iceControlling;
}
switchRole(iceControlling) {
log23("switch role", iceControlling);
if (this.iceLite) iceControlling = false;
this.applyIceControlling(iceControlling);
this.sortCheckList();
}
checkComplete(pair) {
pair.handle = void 0;
if (pair.state === 3) {
if (pair.nominated && (pair.remoteCandidate.generation != void 0 ? pair.remoteCandidate.generation === this.generation : true) && this.nominated == void 0) {
log23("nominated", pair.toJSON());
this.nominated = pair;
this.nominating = false;
this.pruneTcpConnections(pair);
if (!this.iceLite && (this.state === "connected" || this.state === "completed")) this.queryConsent();
for (const p of this.checkList) if (p.component === pair.component && [1, 0].includes(p.state)) p.updateState(4);
}
if (this.nominated) {
if (!this.checkListDone) {
log23("ICE completed");
this.checkListState.put(new Promise((r) => r(1)));
this.checkListDone = true;
}
return;
}
log23("not completed", pair.toJSON());
for (const p of this.checkList) if (p.localCandidate.foundation === pair.localCandidate.foundation && p.state === 0) p.updateState(1);
}
{
const list = [3, 4];
if (this.checkList.find(({ state }) => !list.includes(state))) return;
}
if (!this.iceControlling) {
const target = 3;
if (this.checkList.find(({ state }) => state === target)) return;
}
if (!this.checkListDone) {
log23("ICE failed");
this.checkListState.put(new Promise((r) => {
r(2);
}));
}
}
checkStart = (pair) => cancelable(async (r) => {
log23("check start", pair.toJSON());
pair.updateState(2);
const result = {};
const { remotePassword, remoteUsername, generation } = this;
const localUsername = pair.localCandidate.ufrag ?? this.localUsername;
const nominate = this.iceControlling && !this.remoteIsLite;
const request = this.buildRequest({
nominate,
localUsername,
remoteUsername,
iceControlling: this.iceControlling,
localCandidate: pair.localCandidate
});
const startTime = performance.now();
try {
pair.requestsSent++;
const [response, addr] = await pair.protocol.request(request, pair.remoteAddr, Buffer.from(remotePassword, "utf8"), pair.localCandidate.transport.toLowerCase() === "tcp" ? 0 : 4, (attempt) => {
if (attempt > 0) pair.retransmissionsSent++;
});
pair.responsesReceived++;
const rtt = (performance.now() - startTime) / 1e3;
pair.rtt = rtt;
pair.totalRoundTripTime += rtt;
pair.roundTripTimeMeasurements++;
log23("response received", request.toJSON(), response.toJSON(), addr, {
localUsername,
remoteUsername,
remotePassword,
generation,
rtt
});
result.response = response;
result.addr = addr;
} catch (error) {
const exc = error;
log23("failure case", request.toJSON(), exc.response ? JSON.stringify(exc.response.toJSON(), null, 2) : error, {
localUsername,
remoteUsername,
remotePassword,
generation
}, pair.remoteAddr);
if (exc.response?.getAttributeValue("ERROR-CODE")[0] === 487) {
if (request.attributesKeys.includes("ICE-CONTROLLED")) this.switchRole(true);
else if (request.attributesKeys.includes("ICE-CONTROLLING")) this.switchRole(false);
await this.checkStart(pair).awaitable;
r();
return;
}
if (exc.response?.getAttributeValue("ERROR-CODE")[0] === 401) {
log23("retry 401", pair.toJSON());
await this.checkStart(pair).awaitable;
r();
return;
} else {
log23("checkStart CandidatePairState.FAILED", pair.toJSON());
pair.updateState(4);
this.checkComplete(pair);
r();
return;
}
}
if (result.addr[0] !== pair.remoteAddr[0] || result.addr[1] !== pair.remoteAddr[1]) {
pair.updateState(4);
this.checkComplete(pair);
r();
return;
}
if (nominate || pair.remoteNominated) pair.nominated = true;
else if (this.iceControlling && !this.nominating) {
this.nominating = true;
const request2 = this.buildRequest({
nominate: true,
localUsername,
remoteUsername,
iceControlling: this.iceControlling,
localCandidate: pair.localCandidate
});
try {
pair.requestsSent++;
await pair.protocol.request(request2, pair.remoteAddr, Buffer.from(this.remotePassword, "utf8"), pair.localCandidate.transport.toLowerCase() === "tcp" ? 0 : 4, (attempt) => {
if (attempt > 0) pair.retransmissionsSent++;
});
pair.responsesReceived++;
} catch (error) {
pair.updateState(4);
this.checkComplete(pair);
return;
}
pair.nominated = true;
}
pair.updateState(3);
this.checkComplete(pair);
r();
});
addPair(pair) {
this.checkList.push(pair);
this.sortCheckList();
}
checkIncoming(message, addr, protocol) {
const { remoteUsername: localUsername } = decodeTxUsername(message.getAttributeValue("USERNAME"));
let remoteCandidate;
const [host, port] = addr;
for (const c of this.remoteCandidates) if (c.host === host && c.port === port) {
remoteCandidate = c;
break;
}
if (!remoteCandidate) {
remoteCandidate = new Candidate(randomString(10), 1, protocol.localCandidate?.transport ?? "udp", message.getAttributeValue("PRIORITY"), host, port, "prflx", void 0, void 0, protocol.localCandidate?.transport === "tcp" ? remoteTcpTypeForIncoming(protocol.localCandidate.tcptype) : void 0, void 0, void 0);
this._remoteCandidates.push(remoteCandidate);
}
let pair = this.findPair(protocol, remoteCandidate);
if (!pair) {
pair = new CandidatePair(protocol, remoteCandidate, this.iceControlling);
pair.updateState(1);
this.addPair(pair);
}
pair.noteIncomingRequest(message.transactionIdHex);
pair.requestsReceived++;
pair.responsesSent++;
pair.localCandidate.ufrag = localUsername;
log23("Triggered Checks", message.toJSON(), pair.toJSON(), {
localUsername: this.localUsername,
remoteUsername: this.remoteUsername,
localPassword: this.localPassword,
remotePassword: this.remotePassword,
generation: this.generation
});
if (this.iceLite) {
if (message.attributesKeys.includes("USE-CANDIDATE") && !this.iceControlling) {
pair.remoteNominated = true;
pair.nominated = true;
pair.updateState(3);
this.checkComplete(pair);
}
return;
}
if ([1, 4].includes(pair.state)) pair.handle = this.checkStart(pair);
if (message.attributesKeys.includes("USE-CANDIDATE") && !this.iceControlling) {
pair.remoteNominated = true;
if (pair.state === 3) {
pair.nominated = true;
this.checkComplete(pair);
}
}
}
tryPair(protocol, remoteCandidate) {
if (protocol.localCandidate?.canPairWith(remoteCandidate) && !(protocol.localCandidate.transport.toLowerCase() === "tcp" && protocol.localCandidate.tcptype === "passive" && remoteCandidate.type !== "prflx") && !this.findPair(protocol, remoteCandidate)) {
const pair = new CandidatePair(protocol, remoteCandidate, this.iceControlling);
if (this.options.filterCandidatePair && !this.options.filterCandidatePair(pair)) return;
pair.updateState(1);
this.addPair(pair);
}
}
pairLocalProtocol(protocol) {
for (const remoteCandidate of this.remoteCandidates) this.tryPair(protocol, remoteCandidate);
}
pairRemoteCandidate = (remoteCandidate) => {
for (const protocol of this.protocols) this.tryPair(protocol, remoteCandidate);
};
buildRequest({ nominate, remoteUsername, localUsername, iceControlling, localCandidate }) {
const txUsername = encodeTxUsername({
remoteUsername,
localUsername
});
const request = new Message(1, 0);
request.setAttribute("USERNAME", txUsername).setAttribute("PRIORITY", candidatePriority("prflx", {
transport: localCandidate?.transport,
tcptype: localCandidate?.tcptype
}));
if (iceControlling) {
request.setAttribute("ICE-CONTROLLING", this.tieBreaker);
if (nominate) request.setAttribute("USE-CANDIDATE", null);
} else request.setAttribute("ICE-CONTROLLED", this.tieBreaker);
return request;
}
pruneTcpConnections(selectedPair) {
for (const protocol of this.protocols) {
if (protocol.localCandidate?.transport.toLowerCase() !== "tcp") continue;
if ("pruneForSelection" in protocol && typeof protocol.pruneForSelection === "function") protocol.pruneForSelection(protocol === selectedPair.protocol ? selectedPair.remoteAddr : void 0);
}
}
respondError(request, addr, protocol, errorCode) {
const response = new Message(request.messageMethod, 272, request.transactionId);
response.setAttribute("ERROR-CODE", errorCode).addMessageIntegrity(Buffer.from(this.localPassword, "utf8")).addFingerprint();
protocol.sendStun(response, addr).catch((e) => {
log23("sendStun error", e);
});
}
};
var encodeTxUsername = ({ remoteUsername, localUsername }) => {
return `${remoteUsername}:${localUsername}`;
};
var decodeTxUsername = (txUsername) => {
const [remoteUsername, localUsername] = txUsername.split(":");
return {
remoteUsername,
localUsername
};
};
function enumerate2(arr) {
return arr.map((v, i) => [i, v]);
}
function divide(from, split) {
const arr = from.split(split);
return [arr[0], arr.slice(1).join(split)];
}
var EventTarget = class extends EventEmitter {
emit(type, ...args) {
if (typeof type !== "string") return super.emit(type, ...args);
if (args.length === 0) return super.emit(type, new Event(type));
const [event, ...rest] = args;
if (event && typeof event === "object" && !("type" in event)) try {
Object.defineProperty(event, "type", {
configurable: true,
enumerable: true,
value: type
});
} catch {
return super.emit(type, {
type,
...event
}, ...rest);
}
return super.emit(type, event, ...rest);
}
addEventListener = (type, listener, options) => {
if (typeof options === "object" && options?.once) {
this.once(type, listener);
return;
}
this.addListener(type, listener);
};
removeEventListener = (type, listener) => {
this.removeListener(type, listener);
};
dispatchEvent = (event) => this.emit(event.type, event);
};
var log24 = debug("werift:packages/webrtc/src/dataChannel.ts");
function getDataChannelMessageSize(data) {
return Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data);
}
var RTCDataChannel = class extends EventTarget {
constructor(sctp, parameters, sendOpen = true) {
super();
this.sctp = sctp;
this.parameters = parameters;
this.sendOpen = sendOpen;
this.id = this.parameters.id;
if (parameters.negotiated) {
if (this.id == void 0 || this.id < 0 || this.id > 65534) throw new Error("ID must be in range 0-65534 if data channel is negotiated out-of-band");
this.sctp.dataChannelAddNegotiated(this);
} else if (sendOpen) {
this.sendOpen = false;
this.sctp.dataChannelOpen(this);
}
}
statsId = randomUUID$1().toString();
stateChange = new Event2();
stateChanged = new Event2();
onMessage = new Event2();
error = new Event2();
bufferedAmountLow = new Event2();
onopen;
onclose;
onclosing;
onmessage;
onerror;
isCreatedByRemote = false;
id;
readyState = "connecting";
bufferedAmount = 0;
_bufferedAmountLowThreshold = 0;
messagesSent = 0;
bytesSent = 0;
messagesReceived = 0;
bytesReceived = 0;
get ordered() {
return this.parameters.ordered;
}
get maxRetransmits() {
return this.parameters.maxRetransmits ?? null;
}
get maxPacketLifeTime() {
return this.parameters.maxPacketLifeTime ?? null;
}
get label() {
return this.parameters.label;
}
get protocol() {
return this.parameters.protocol;
}
get negotiated() {
return this.parameters.negotiated;
}
get bufferedAmountLowThreshold() {
return this._bufferedAmountLowThreshold;
}
set bufferedAmountLowThreshold(value) {
if (value < 0 || value > 4294967295) throw new Error("bufferedAmountLowThreshold must be in range 0 - 4294967295");
this._bufferedAmountLowThreshold = value;
}
setId(id) {
this.id = id;
}
setReadyState(state) {
if (state !== this.readyState) {
this.readyState = state;
this.stateChange.execute(state);
this.stateChanged.execute(state);
switch (state) {
case "open":
if (this.onopen) this.onopen();
this.emit("open");
break;
case "closed":
if (this.onclose) this.onclose();
this.emit("close");
break;
case "closing": if (this.onclosing) this.onclosing();
}
log24("change state", state);
}
}
addBufferedAmount(amount) {
const crossesThreshold = this.bufferedAmount > this.bufferedAmountLowThreshold && this.bufferedAmount + amount <= this.bufferedAmountLowThreshold;
this.bufferedAmount += amount;
if (crossesThreshold) {
this.bufferedAmountLow.execute();
this.emit("bufferedamountlow");
}
}
send(data) {
const size = this.sctp.datachannelSend(this, data);
this.messagesSent++;
this.bytesSent += size;
}
close() {
this.sctp.dataChannelClose(this);
}
};
var RTCDataChannelParameters = class {
label = "";
maxPacketLifeTime;
maxRetransmits;
ordered = true;
protocol = "";
negotiated = false;
id;
constructor(props = {}) {
Object.assign(this, props);
}
};
var useFIR = () => ({
type: "ccm",
parameter: "fir"
});
var useNACK = () => ({ type: "nack" });
var usePLI = () => ({
type: "nack",
parameter: "pli"
});
var useREMB = () => ({ type: "goog-remb" });
var useTWCC = () => ({ type: "transport-cc" });
var RTCRtpCodecParameters = class {
/**
* When specifying a codec with a fixed payloadType such as PCMU,
* it is necessary to set the correct PayloadType in RTCRtpCodecParameters in advance.
*/
payloadType;
mimeType;
clockRate;
channels;
rtcpFeedback = [];
parameters;
direction = "all";
constructor(props) {
Object.assign(this, props);
}
get name() {
return this.mimeType.split("/")[1];
}
get contentType() {
return this.mimeType.split("/")[0];
}
get str() {
let s = `${this.name}/${this.clockRate}`;
if (this.channels === 2) s += "/2";
return s;
}
};
var RTCRtpHeaderExtensionParameters = class {
id;
uri;
constructor(props) {
Object.assign(this, props);
}
};
var RTCRtcpParameters = class {
cname;
mux = false;
ssrc;
constructor(props = {}) {
Object.assign(this, props);
}
};
var RTCRtcpFeedback = class {
type;
parameter;
constructor(props = {}) {
Object.assign(this, props);
}
};
var RTCRtpRtxParameters = class {
ssrc;
constructor(props = {}) {
Object.assign(this, props);
}
};
var RTCRtpCodingParameters = class {
ssrc;
payloadType;
rtx;
constructor(props) {
Object.assign(this, props);
}
};
var RTCRtpSimulcastParameters = class {
rid;
direction;
constructor(props) {
Object.assign(this, props);
}
};
var useH264 = (props = {}) => new RTCRtpCodecParameters({
mimeType: "video/h264",
clockRate: 9e4,
rtcpFeedback: [
useNACK(),
usePLI(),
useREMB()
],
parameters: "profile-level-id=42e01f;packetization-mode=1;level-asymmetry-allowed=1",
...props
});
var useVP8 = (props = {}) => new RTCRtpCodecParameters({
mimeType: "video/VP8",
clockRate: 9e4,
rtcpFeedback: [
useNACK(),
usePLI(),
useREMB()
],
...props
});
var useVP9 = (props = {}) => new RTCRtpCodecParameters({
mimeType: "video/VP9",
clockRate: 9e4,
rtcpFeedback: [
useNACK(),
usePLI(),
useREMB()
],
...props
});
var useAV1X = (props = {}) => new RTCRtpCodecParameters({
mimeType: "video/AV1X",
clockRate: 9e4,
rtcpFeedback: [
useNACK(),
usePLI(),
useREMB()
],
...props
});
var useOPUS = (props = {}) => new RTCRtpCodecParameters({
mimeType: "audio/OPUS",
clockRate: 48e3,
channels: 2,
...props
});
var usePCMU = (props = {}) => new RTCRtpCodecParameters({
mimeType: "audio/PCMU",
clockRate: 8e3,
channels: 1,
payloadType: 0,
...props
});
var supportedCodecs = [
useAV1X(),
useVP9(),
useVP8(),
useH264(),
useOPUS(),
usePCMU()
].map((codec) => codec.mimeType);
var supportedVideoCodecs = supportedCodecs.filter((codec) => codec.toLowerCase().startsWith("video/"));
var supportedAudioCodecs = supportedCodecs.filter((codec) => codec.toLowerCase().startsWith("audio/"));
function useSdesMid() {
return new RTCRtpHeaderExtensionParameters({ uri: RTP_EXTENSION_URI.sdesMid });
}
function useSdesRTPStreamId() {
return new RTCRtpHeaderExtensionParameters({ uri: RTP_EXTENSION_URI.sdesRTPStreamID });
}
function useRepairedRtpStreamId() {
return new RTCRtpHeaderExtensionParameters({ uri: RTP_EXTENSION_URI.repairedRtpStreamId });
}
function useTransportWideCC() {
return new RTCRtpHeaderExtensionParameters({ uri: RTP_EXTENSION_URI.transportWideCC });
}
function useAbsSendTime() {
return new RTCRtpHeaderExtensionParameters({ uri: RTP_EXTENSION_URI.absSendTime });
}
function useDependencyDescriptor() {
return new RTCRtpHeaderExtensionParameters({ uri: RTP_EXTENSION_URI.dependencyDescriptor });
}
function useAudioLevelIndication() {
return new RTCRtpHeaderExtensionParameters({ uri: RTP_EXTENSION_URI.audioLevelIndication });
}
function useVideoOrientation() {
return new RTCRtpHeaderExtensionParameters({ uri: RTP_EXTENSION_URI.videoOrientation });
}
var DATA_CHANNEL_ACK = 2;
var DATA_CHANNEL_OPEN = 3;
var DATA_CHANNEL_RELIABLE = 0;
var WEBRTC_DCEP = 50;
var WEBRTC_STRING = 51;
var WEBRTC_BINARY = 53;
var WEBRTC_STRING_EMPTY = 56;
var WEBRTC_BINARY_EMPTY = 57;
var DISCARD_HOST = "0.0.0.0";
var DISCARD_PORT = 9;
var DTLS_ROLE_SETUP = {
auto: "actpass",
client: "active",
server: "passive"
};
var DTLS_SETUP_ROLE = Object.keys(DTLS_ROLE_SETUP).reduce((acc, cur) => {
const key = DTLS_ROLE_SETUP[cur];
acc[key] = cur;
return acc;
}, {});
var FMTP_INT_PARAMETERS = [
"apt",
"max-fr",
"max-fs",
"maxplaybackrate",
"minptime",
"stereo",
"useinbandfec"
];
var SSRC_INFO_ATTRS = [
"cname",
"msid",
"mslabel",
"label"
];
var SRTP_PROFILE = {
SRTP_AES128_CM_HMAC_SHA1_80: 1,
SRTP_AEAD_AES_128_GCM: 7
};
var SenderDirections = ["sendonly", "sendrecv"];
var ReceiverDirection = ["sendrecv", "recvonly"];
var RTCStatsReport = class extends Map {
constructor(stats) {
super();
if (stats) for (const stat of stats) this.set(stat.id, stat);
}
};
function generateStatsId(type, ...parts) {
return `${type}_${parts.filter((p) => p !== void 0).join("_")}`;
}
function generateCodecStatsId(transportId, payloadType, scopeId) {
return generateStatsId("codec", transportId, payloadType, scopeId);
}
function getStatsTimestamp() {
return performance.timeOrigin + performance.now();
}
function getReferencedStatsIds(stat) {
const references = [];
for (const [key, value] of Object.entries(stat)) {
if (key === "id") continue;
if (key.endsWith("Id")) {
if (typeof value === "string") references.push(value);
continue;
}
if (key.endsWith("Ids") && Array.isArray(value)) {
for (const entry of value) if (typeof entry === "string") references.push(entry);
}
}
return references;
}
function buildStatsReport(stats, rootIds) {
const index = /* @__PURE__ */ new Map();
for (const stat of stats) index.set(stat.id, stat);
if (!rootIds) return new RTCStatsReport([...index.values()]);
const includedIds = /* @__PURE__ */ new Set();
const queue = [...new Set(Array.from(rootIds))];
while (queue.length > 0) {
const id = queue.shift();
if (!id || includedIds.has(id)) continue;
const stat = index.get(id);
if (!stat) continue;
includedIds.add(id);
queue.push(...getReferencedStatsIds(stat));
}
return new RTCStatsReport([...includedIds].map((id) => index.get(id)).filter((stat) => !!stat));
}
var RTCRtpTransceiver = class {
constructor(kind, dtlsTransport, receiver, sender, _direction) {
this.kind = kind;
this.receiver = receiver;
this.sender = sender;
this._direction = _direction;
if (dtlsTransport) this.setDtlsTransport(dtlsTransport);
}
id = randomUUID$1().toString();
onTrack = new Event2();
mid = null;
mLineIndex;
/**should not be reused because it has been used for sending before. */
usedForSender = false;
_currentDirection;
offerDirection;
_codecs = [];
set codecs(codecs) {
this._codecs = codecs;
}
get codecs() {
return this._codecs;
}
headerExtensions = [];
options = {};
stopping = false;
stopped = false;
get dtlsTransport() {
return this.receiver.dtlsTransport;
}
/**RFC 8829 4.2.4. setDirectionに渡された最後の値を示します */
get direction() {
return this._direction;
}
set direction(direction) {
this.setDirection(direction);
}
setDirection(direction) {
this._direction = direction;
if (this._currentDirection && this._currentDirection !== "stopped" && SenderDirections.includes(this._currentDirection)) this.usedForSender = true;
}
/**RFC 8829 4.2.5. last negotiated direction */
get currentDirection() {
return this._currentDirection ?? null;
}
setCurrentDirection(direction) {
this._currentDirection = direction;
}
setDtlsTransport(dtls) {
this.receiver.setDtlsTransport(dtls);
this.sender.setDtlsTransport(dtls);
}
get msid() {
return this.msids[0];
}
get msids() {
return this.sender.streamIds.map((streamId) => `${streamId} ${this.sender.trackId}`);
}
addTrack(track) {
if (this.receiver.addTrack(track)) this.onTrack.execute(track, this);
}
stop() {
if (this.stopping) return;
this.stopping = true;
}
forceStop() {
if (this.stopped) return;
this.stopping = true;
this.stopped = true;
this.setCurrentDirection("stopped");
this.receiver.stop();
this.sender.stop();
}
getPayloadType(mimeType) {
return this.codecs.find((codec) => codec.mimeType.toLowerCase().includes(mimeType.toLowerCase()))?.payloadType;
}
getCodecStats() {
const timestamp = getStatsTimestamp();
return this.collectCodecStats(timestamp);
}
collectCodecStats(timestamp) {
const stats = [];
if (!this.dtlsTransport) return stats;
const transportId = generateStatsId("transport", this.dtlsTransport.id);
for (const codec of this.codecs) {
const codecStats = {
type: "codec",
id: generateCodecStatsId(transportId, codec.payloadType, this.id),
timestamp,
payloadType: codec.payloadType,
transportId,
mimeType: codec.mimeType,
clockRate: codec.clockRate,
channels: codec.channels,
sdpFmtpLine: codec.parameters
};
stats.push(codecStats);
}
return stats;
}
};
var Inactive = "inactive";
var Sendonly = "sendonly";
var Recvonly = "recvonly";
var Sendrecv = "sendrecv";
var Directions = [
Inactive,
Sendonly,
Recvonly,
Sendrecv
];
var MediaStreamTrack = class extends EventTarget {
uuid = randomUUID$1().toString();
/**MediaStream ID*/
streamId;
remote = false;
label;
kind;
id;
/**mediaSsrc */
ssrc;
rid;
header;
codec;
/**todo impl */
enabled = true;
onReceiveRtp = new Event2();
onReceiveRtcp = new Event2();
onSourceChanged = new Event2();
stopped = false;
muted = true;
constructor(props) {
super();
Object.assign(this, props);
this.onReceiveRtp.subscribe((rtp) => {
this.muted = false;
this.header = rtp.header;
});
this.label = `${this.remote ? "remote" : "local"} ${this.kind}`;
}
stop = () => {
this.stopped = true;
this.muted = true;
this.onReceiveRtp.complete();
this.emit("ended");
};
writeRtp = (rtp) => {
if (this.remote) throw new Error("this is remoteTrack");
if (this.stopped) return;
const packet = Buffer.isBuffer(rtp) ? RtpPacket.deSerialize(rtp) : rtp;
packet.header.payloadType = this.codec?.payloadType ?? packet.header.payloadType;
this.onReceiveRtp.execute(packet);
};
};
var MediaStream = class {
id;
tracks = [];
constructor(props = {}) {
if (Array.isArray(props)) this.tracks = props;
else Object.assign(this, props);
this.id ??= randomUUID$1().toString();
}
addTrack(track) {
track.streamId = this.id;
this.tracks.push(track);
}
removeTrack(track) {
this.tracks = this.tracks.filter((currentTrack) => currentTrack !== track);
if (track.streamId === this.id) track.streamId = void 0;
}
getTracks() {
return this.tracks;
}
getAudioTracks() {
return this.tracks.filter((track) => track.kind === "audio");
}
getVideoTracks() {
return this.tracks.filter((track) => track.kind === "video");
}
};
var log25 = debug("werift:packages/webrtc/src/utils.ts");
function fingerprint(file, hashName) {
const upper = (s) => s.toUpperCase();
const colon = (s) => s.match(/(.{2})/g).join(":");
return colon(upper(createHash$1(hashName).update(file).digest("hex")));
}
var fingerprintHashAlgorithms = {
sha1: "sha1",
"sha-1": "sha1",
sha224: "sha224",
"sha-224": "sha224",
sha256: "sha256",
"sha-256": "sha256",
sha384: "sha384",
"sha-384": "sha384",
sha512: "sha512",
"sha-512": "sha512"
};
function normalizeFingerprintAlgorithm(algorithm) {
return fingerprintHashAlgorithms[algorithm.trim().toLowerCase()];
}
function normalizeFingerprintValue(value) {
return value.replace(/[^0-9a-f]/gi, "").toLowerCase();
}
function isDtls(buf) {
const firstByte = buf[0];
return firstByte > 19 && firstByte < 64;
}
function reverseSimulcastDirection(dir) {
if (dir === "recv") return "send";
return "recv";
}
var andDirection = (a, b) => Directions[Directions.indexOf(a) & Directions.indexOf(b)];
function reverseDirection(dir) {
if (dir === "sendonly") return "recvonly";
if (dir === "recvonly") return "sendonly";
return dir;
}
var milliTime = Date.now;
var startupTimestampInMicroseconds = BigInt(Date.now()) * 1000n - process.hrtime.bigint() / 1000n;
var microTime = () => {
return startupTimestampInMicroseconds + process.hrtime.bigint() / 1000n;
};
var timestampSeconds = () => Date.now() / 1e3;
var ntpTime = () => {
const [sec, msec] = ((performance$1.timeOrigin + performance$1.now() - Date.UTC(1900, 0, 1)) / 1e3).toString().split(".").map(Number);
return bufferWriter([4, 4], [sec, msec]).readBigUInt64BE();
};
var ntpTimeToEpochMs = (ntp) => {
const [seconds, milliseconds] = bufferReader(bufferWriter([8], [ntp]), [4, 4]);
return seconds * 1e3 + milliseconds + Date.UTC(1900, 0, 1);
};
var compactNtp = (ntp) => {
const [, sec, msec] = bufferReader(bufferWriter([8], [ntp]), [
2,
2,
2,
2
]);
return bufferWriter([2, 2], [sec, msec]).readUInt32BE();
};
function parseIceServers(iceServers) {
const options = {};
for (const iceServer of iceServers) {
const urls = Array.isArray(iceServer.urls) ? iceServer.urls : [iceServer.urls];
for (const url of urls) {
const parsed = parseIceServerUrl(url);
if (!parsed) continue;
if (!options.stunServer && parsed.kind === "stun") options.stunServer = parsed.address;
if (!options.turnServer && parsed.kind === "turn") {
options.turnServer = parsed.address;
options.turnTransport = parsed.transport;
options.turnUsername = iceServer.username;
options.turnPassword = iceServer.credential;
}
}
}
log25("iceOptions", options);
return options;
}
function resolveTurnTransport({ configuredTurnTransport, forceTurnTCP, parsedTurnTransport }) {
if (parsedTurnTransport) return parsedTurnTransport;
if (configuredTurnTransport) return configuredTurnTransport;
if (forceTurnTCP) return "tcp";
}
function parseIceServerUrl(url) {
const matched = /^(stun|stuns|turn|turns):(.+)$/i.exec(url.trim());
if (!matched) return;
const [, rawScheme, rawRest] = matched;
const scheme = rawScheme.toLowerCase();
const [authority] = rawRest.split("?", 1);
const [, query = ""] = rawRest.split("?");
const address = parseAddress(authority, defaultPort(scheme));
if (!address) return;
if (scheme === "stun" || scheme === "stuns") return {
kind: "stun",
address
};
const transport = resolveParsedTurnTransport({
scheme,
transportParam: new URLSearchParams(query).get("transport")
});
if (transport === "invalid") return;
return {
kind: "turn",
address,
transport
};
}
function resolveParsedTurnTransport({ scheme, transportParam }) {
if (transportParam == null) return scheme === "turns" ? "tls" : void 0;
if (transportParam === "udp") return scheme === "turns" ? "invalid" : "udp";
if (transportParam === "tcp") return scheme === "turns" ? "tls" : "tcp";
return "invalid";
}
function defaultPort(scheme) {
if (scheme === "stuns" || scheme === "turns") return 5349;
return 3478;
}
function parseAddress(value, fallbackPort) {
const authority = value.startsWith("//") ? value.slice(2) : value;
if (!authority) return;
if (authority.startsWith("[")) {
const closingBracket = authority.indexOf("]");
if (closingBracket === -1) return;
return [authority.slice(1, closingBracket), parsePort(authority.slice(closingBracket + 1), fallbackPort)];
}
const firstColon = authority.indexOf(":");
const lastColon = authority.lastIndexOf(":");
if (firstColon !== -1 && firstColon === lastColon) return [authority.slice(0, firstColon), parsePort(authority.slice(firstColon + 1), fallbackPort)];
return [authority, fallbackPort];
}
function parsePort(value, fallbackPort) {
const portString = value.startsWith(":") ? value.slice(1) : value;
const port = Number.parseInt(portString, 10);
return Number.isFinite(port) ? port : fallbackPort;
}
var createSelfSignedCertificate = CipherContext.createSelfSignedCertificateWithKey;
var MediaStreamTrackFactory = class {
static async rtpSource({ port, kind, cb }) {
port ??= await randomPort();
const track = new MediaStreamTrack({ kind });
const udp = createSocket("udp4");
udp.bind(port);
const onMessage = (msg) => {
if (cb) msg = cb(msg);
track.writeRtp(msg);
};
udp.addListener("message", onMessage);
const dispose = () => {
udp.removeListener("message", onMessage);
try {
udp.close();
} catch (error) {}
};
return [
track,
port,
dispose
];
}
};
var deepMerge = (dst, src) => {
if (!dst || typeof dst !== "object") {
if (src !== null && typeof src === "object") return src;
else return dst;
}
if (!src || typeof src !== "object") {
if (src == void 0) return dst;
return src;
}
for (const key in src) if (Object.prototype.hasOwnProperty.call(src, key)) {
const sourceValue = src[key];
if (sourceValue != void 0) dst[key] = sourceValue;
}
return dst;
};
var log26 = debug("werift:packages/webrtc/src/media/receiver/nack.ts");
var LOST_SIZE = 150;
var NackHandler = class {
constructor(receiver) {
this.receiver = receiver;
}
newEstSeqNum = 0;
_lost = {};
nackLoop;
onPacketLost = new Event2();
mediaSourceSsrc;
retryCount = 10;
closed = false;
get lostSeqNumbers() {
return Object.keys(this._lost).map(Number).sort();
}
getLost(seq) {
return this._lost[seq];
}
setLost(seq, count) {
this._lost[seq] = count;
if (this.nackLoop || this.closed) return;
this.nackLoop = setInterval(async () => {
try {
await this.sendNack();
if (!Object.keys(this._lost).length) {
clearInterval(this.nackLoop);
this.nackLoop = void 0;
}
} catch (error) {
log26("failed to send nack", error);
}
}, 5);
}
removeLost(sequenceNumber) {
delete this._lost[sequenceNumber];
}
addPacket(packet) {
const { sequenceNumber, ssrc } = packet.header;
this.mediaSourceSsrc = ssrc;
if (this.newEstSeqNum === 0) {
this.newEstSeqNum = sequenceNumber;
return;
}
if (this.getLost(sequenceNumber)) {
this.removeLost(sequenceNumber);
return;
}
if (sequenceNumber === uint16Add(this.newEstSeqNum, 1)) this.newEstSeqNum = sequenceNumber;
else if (sequenceNumber > uint16Add(this.newEstSeqNum, 1)) {
for (let i = uint16Add(this.newEstSeqNum, 1); i < sequenceNumber; i = uint16Add(i, 1)) this.setLost(i, 1);
this.newEstSeqNum = sequenceNumber;
this.pruneLost();
}
}
pruneLost() {
if (this.lostSeqNumbers.length > LOST_SIZE) this._lost = Object.entries(this._lost).slice(-LOST_SIZE).reduce((acc, [key, v]) => {
acc[key] = v;
return acc;
}, {});
}
close() {
this.closed = true;
clearInterval(this.nackLoop);
this._lost = {};
}
updateRetryCount() {
this.lostSeqNumbers.forEach((seq) => {
if (this._lost[seq]++ > this.retryCount) {
this.removeLost(seq);
return seq;
}
});
}
sendNack = () => new Promise((r, f) => {
if (this.lostSeqNumbers.length > 0 && this.mediaSourceSsrc) {
const nack = new GenericNack({
senderSsrc: this.receiver.rtcpSsrc,
mediaSourceSsrc: this.mediaSourceSsrc,
lost: this.lostSeqNumbers
});
const rtcp = new RtcpTransportLayerFeedback({ feedback: nack });
this.receiver.dtlsTransport.sendRtcp([rtcp]).then(r).catch(f);
this.updateRetryCount();
this.onPacketLost.execute(nack);
}
});
};
var log27 = debug("werift:packages/webrtc/media/receiver/receiverTwcc");
var ReceiverTWCC = class {
constructor(dtlsTransport, rtcpSsrc, mediaSourceSsrc) {
this.dtlsTransport = dtlsTransport;
this.rtcpSsrc = rtcpSsrc;
this.mediaSourceSsrc = mediaSourceSsrc;
this.runTWCC();
}
extensionInfo = {};
twccRunning = false;
/** uint8 */
fbPktCount = 0;
lastTimestamp;
handleTWCC(transportSequenceNumber) {
this.extensionInfo[transportSequenceNumber] = {
tsn: transportSequenceNumber,
timestamp: microTime()
};
if (Object.keys(this.extensionInfo).length > 10) this.sendTWCC();
}
async runTWCC() {
while (this.twccRunning) {
this.sendTWCC();
await setTimeout$2(100);
}
}
sendTWCC() {
if (Object.keys(this.extensionInfo).length === 0) return;
const extensionsArr = Object.values(this.extensionInfo).sort((a, b) => a.tsn - b.tsn);
const minTSN = extensionsArr[0].tsn;
const maxTSN = extensionsArr.slice(-1)[0].tsn;
const packetChunks = [];
const baseSequenceNumber = extensionsArr[0].tsn;
const packetStatusCount = uint16Add(maxTSN - minTSN, 1);
let referenceTime;
let lastPacketStatus;
const recvDeltas = [];
for (let i = minTSN; i <= maxTSN; i++) {
const timestamp = this.extensionInfo[i]?.timestamp;
if (timestamp) {
if (!this.lastTimestamp) this.lastTimestamp = timestamp;
if (!referenceTime) referenceTime = this.lastTimestamp;
const delta = timestamp - this.lastTimestamp;
this.lastTimestamp = timestamp;
const recvDelta = new RecvDelta({ delta: Number(delta) });
recvDelta.parseDelta();
recvDeltas.push(recvDelta);
if (lastPacketStatus != void 0 && lastPacketStatus.status !== recvDelta.type) {
packetChunks.push(new RunLengthChunk({
packetStatus: lastPacketStatus.status,
runLength: i - lastPacketStatus.minTSN
}));
lastPacketStatus = {
minTSN: i,
status: recvDelta.type
};
}
if (i === maxTSN) {
if (lastPacketStatus != void 0) packetChunks.push(new RunLengthChunk({
packetStatus: lastPacketStatus.status,
runLength: i - lastPacketStatus.minTSN + 1
}));
else packetChunks.push(new RunLengthChunk({
packetStatus: recvDelta.type,
runLength: 1
}));
}
if (lastPacketStatus == void 0) lastPacketStatus = {
minTSN: i,
status: recvDelta.type
};
}
}
if (!referenceTime) return;
const packet = new RtcpTransportLayerFeedback({ feedback: new TransportWideCC({
senderSsrc: this.rtcpSsrc,
mediaSourceSsrc: this.mediaSourceSsrc,
baseSequenceNumber,
packetStatusCount,
referenceTime: uint24(Math.floor(Number(referenceTime / 1000n / 64n))),
fbPktCount: this.fbPktCount,
recvDeltas,
packetChunks
}) });
this.dtlsTransport.sendRtcp([packet]).catch((err5) => {
log27(err5);
});
this.extensionInfo = {};
this.fbPktCount = uint8Add(this.fbPktCount, 1);
}
};
var StreamStatistics = class {
base_seq;
max_seq;
cycles = 0;
packets_received = 0;
bytesReceived = 0;
headerBytesReceived = 0;
lastPacketReceivedTimestamp;
clockRate;
jitter_q4 = 0;
last_arrival;
last_timestamp;
expected_prior = 0;
received_prior = 0;
constructor(clockRate) {
this.clockRate = clockRate;
}
add(packet, now = Date.now() / 1e3) {
const inOrder = this.max_seq == void 0 || uint16Gt(packet.header.sequenceNumber, this.max_seq);
this.packets_received++;
this.bytesReceived += packet.payload.length;
this.headerBytesReceived += packet.header.serializeSize;
this.lastPacketReceivedTimestamp = getStatsTimestamp();
if (this.base_seq == void 0) this.base_seq = packet.header.sequenceNumber;
if (inOrder) {
const arrival = int(now * this.clockRate);
if (this.max_seq != void 0 && packet.header.sequenceNumber < this.max_seq) this.cycles += 65536;
this.max_seq = packet.header.sequenceNumber;
if (packet.header.timestamp !== this.last_timestamp && this.packets_received > 1) {
const diff = Math.abs(arrival - (this.last_arrival ?? 0) - (packet.header.timestamp - (this.last_timestamp ?? 0)));
this.jitter_q4 += diff - (this.jitter_q4 + 8 >> 4);
}
this.last_arrival = arrival;
this.last_timestamp = packet.header.timestamp;
}
}
get fraction_lost() {
const expected_interval = this.packets_expected - this.expected_prior;
this.expected_prior = this.packets_expected;
const received_interval = this.packets_received - this.received_prior;
this.received_prior = this.packets_received;
const lost_interval = expected_interval - received_interval;
if (expected_interval == 0 || lost_interval <= 0) return 0;
else return Math.floor((lost_interval << 8) / expected_interval);
}
get jitter() {
return this.jitter_q4 >> 4;
}
get packets_expected() {
return this.cycles + (this.max_seq ?? 0) - (this.base_seq ?? 0) + 1;
}
get packets_lost() {
const lost = this.packets_expected - this.packets_received;
return lost < 0 ? 0 : lost;
}
};
var log28 = debug("werift:packages/webrtc/src/transport/dtls.ts");
function formatDtlsVersion(version) {
if (!version) return;
if (version.major === 254 && version.minor === 253) return "DTLS 1.2";
if (version.major === 254 && version.minor === 255) return "DTLS 1.0";
}
function formatSrtpCipher(profile) {
switch (profile) {
case 1: return "AES_CM_128_HMAC_SHA1_80";
case 7: return "AEAD_AES_128_GCM";
default: return;
}
}
var RTCDtlsTransport = class _RTCDtlsTransport {
constructor(config, iceTransport, localCertificate, srtpProfiles2 = []) {
this.config = config;
this.iceTransport = iceTransport;
this.localCertificate = localCertificate;
this.srtpProfiles = srtpProfiles2;
this.localCertificate ??= _RTCDtlsTransport.localCertificate;
}
id = randomUUID$1().toString();
state = "new";
role = "auto";
srtpStarted = false;
transportSequenceNumber = 0;
bytesSent = 0;
bytesReceived = 0;
packetsSent = 0;
packetsReceived = 0;
dataReceiver = () => {};
dtls;
srtp;
srtcp;
onStateChange = new Event2();
onRtcp = new Event2();
onRtp = new Event2();
events = new EventTarget();
onstatechange;
static localCertificate;
static localCertificatePromise;
remoteParameters;
addEventListener = (type, listener, options) => {
this.events.addEventListener(type, listener, options);
};
removeEventListener = (type, listener) => {
this.events.removeEventListener(type, listener);
};
dispatchEvent = (event) => this.events.dispatchEvent(event);
get localParameters() {
return new RTCDtlsParameters(this.localCertificate ? this.localCertificate.getFingerprints() : [], this.role);
}
static async SetupCertificate() {
if (this.localCertificate) return this.localCertificate;
if (this.localCertificatePromise) return this.localCertificatePromise;
this.localCertificatePromise = (async () => {
const { certPem, keyPem, signatureHash } = await CipherContext.createSelfSignedCertificateWithKey({
signature: SignatureAlgorithm.ecdsa_3,
hash: HashAlgorithm.sha256_4
}, NamedCurveAlgorithm.secp256r1_23);
this.localCertificate = new RTCCertificate(keyPem, certPem, signatureHash);
return this.localCertificate;
})();
return this.localCertificatePromise;
}
setRemoteParams(remoteParameters) {
const fingerprints = deduplicateFingerprints([...this.remoteParameters?.fingerprints ?? [], ...remoteParameters.fingerprints]);
const role = remoteParameters.role === "auto" && this.remoteParameters?.role ? this.remoteParameters.role : remoteParameters.role;
this.remoteParameters = new RTCDtlsParameters(fingerprints, role);
}
async start() {
if (this.state !== "new") throw new Error("state must be new");
if (!this.remoteParameters || this.remoteParameters.fingerprints.length === 0) throw new Error("remote fingerprint not exist");
if (this.role === "auto") {
if (this.iceTransport.role === "controlling") this.role = "server";
else this.role = "client";
}
this.setState("connecting");
await new Promise(async (r, f) => {
if (this.role === "server") this.dtls = new DtlsServer({
cert: this.localCertificate?.certPem,
key: this.localCertificate?.privateKey,
signatureHash: this.localCertificate?.signatureHash,
transport: createIceTransport(this.iceTransport.connection),
srtpProfiles: this.srtpProfiles,
extendedMasterSecret: true,
certificateRequest: true
});
else this.dtls = new DtlsClient({
cert: this.localCertificate?.certPem,
key: this.localCertificate?.privateKey,
signatureHash: this.localCertificate?.signatureHash,
transport: createIceTransport(this.iceTransport.connection),
srtpProfiles: this.srtpProfiles,
extendedMasterSecret: true
});
this.dtls.onData.subscribe((buf) => {
if (this.config.debug?.inboundPacketLoss && this.config.debug?.inboundPacketLoss / 100 < Math.random()) return;
this.dataReceiver(buf);
});
this.dtls.onClose.subscribe(() => {
if (this.state !== "failed") this.setState("closed");
});
this.dtls.onConnect.once(r);
this.dtls.onError.once((error) => {
this.setState("failed");
log28("dtls failed", error);
f(error);
});
if (this.dtls instanceof DtlsClient) {
await setTimeout$2(100);
this.dtls.connect().catch((error) => {
this.setState("failed");
log28("dtls connect failed", error);
f(error);
});
}
});
try {
this.verifyRemoteCertificateFingerprint();
} catch (error) {
this.setState("failed");
this.dtls?.close();
throw error;
}
if (this.srtpProfiles.length > 0) this.startSrtp();
this.setState("connected");
log28("dtls connected");
}
verifyRemoteCertificateFingerprint() {
if (!this.remoteParameters || this.remoteParameters.fingerprints.length === 0) throw new Error("remote fingerprint not exist");
const remoteCertificate = this.dtls?.remoteCertificate;
if (!remoteCertificate) throw new Error("remote certificate not available");
const supportedFingerprints = this.remoteParameters.fingerprints.flatMap(({ algorithm, value }) => {
const normalizedAlgorithm = normalizeFingerprintAlgorithm(algorithm);
if (!normalizedAlgorithm) return [];
const normalizedValue = normalizeFingerprintValue(value);
if (!normalizedValue) throw new Error("remote fingerprint value is empty");
return [{
normalizedAlgorithm,
normalizedValue
}];
});
if (supportedFingerprints.length === 0) throw new Error("no supported remote fingerprint algorithms");
const preferredAlgorithm = selectPreferredFingerprintAlgorithm(supportedFingerprints);
const expectedFingerprints = supportedFingerprints.filter(({ normalizedAlgorithm }) => normalizedAlgorithm === preferredAlgorithm);
const actualFingerprints = expectedFingerprints.reduce((acc, { normalizedAlgorithm }) => {
if (!acc.has(normalizedAlgorithm)) acc.set(normalizedAlgorithm, normalizeFingerprintValue(fingerprint(remoteCertificate, normalizedAlgorithm)));
return acc;
}, /* @__PURE__ */ new Map());
if (!expectedFingerprints.some(({ normalizedAlgorithm, normalizedValue }) => actualFingerprints.get(normalizedAlgorithm) === normalizedValue)) throw new Error("remote certificate fingerprint mismatch");
}
updateSrtpSession() {
if (!this.dtls) throw new Error();
const profile = this.dtls.srtp.srtpProfile;
if (!profile) throw new Error("need srtpProfile");
log28("selected SRTP Profile", profile);
const { localKey, localSalt, remoteKey, remoteSalt } = this.dtls.extractSessionKeys(keyLength(profile), saltLength(profile));
const config = {
keys: {
localMasterKey: localKey,
localMasterSalt: localSalt,
remoteMasterKey: remoteKey,
remoteMasterSalt: remoteSalt
},
profile
};
this.srtp = new SrtpSession(config);
this.srtcp = new SrtcpSession(config);
}
startSrtp() {
if (this.srtpStarted) return;
this.srtpStarted = true;
this.updateSrtpSession();
this.iceTransport.connection.onData.subscribe((data) => {
if (this.config.debug?.inboundPacketLoss && this.config.debug?.inboundPacketLoss / 100 < Math.random()) return;
if (!isMedia(data)) return;
this.bytesReceived += data.length;
this.packetsReceived++;
if (isRtcp(data)) {
let dec;
try {
dec = this.srtcp.decrypt(data);
} catch (error) {
if (error instanceof SrtpAuthenticationError) {
log28("dropping invalid SRTCP packet", error);
return;
}
throw error;
}
let rtcpPackets;
try {
rtcpPackets = RtcpPacketConverter.deSerialize(dec);
} catch (error) {
log28("dropping malformed SRTCP packet", error);
return;
}
for (const rtcp of rtcpPackets) try {
this.onRtcp.execute(rtcp);
} catch (error) {
log28("RTCP error", error);
}
} else {
let dec;
try {
dec = this.srtp.decrypt(data);
} catch (error) {
if (error instanceof SrtpAuthenticationError) {
log28("dropping invalid SRTP packet", error);
return;
}
throw error;
}
let rtp;
try {
rtp = RtpPacket.deSerialize(dec);
} catch (error) {
log28("dropping malformed SRTP packet", error);
return;
}
try {
this.onRtp.execute(rtp);
} catch (error) {
log28("RTP error", error);
}
}
});
}
sendData = async (data) => {
if (this.config.debug?.outboundPacketLoss && this.config.debug?.outboundPacketLoss / 100 < Math.random()) return;
if (!this.dtls) throw new Error("dtls not established");
await this.dtls.send(data);
};
async sendRtp(payload, header) {
try {
const enc = this.srtp.encrypt(payload, header);
if (this.config.debug?.outboundPacketLoss && this.config.debug?.outboundPacketLoss / 100 < Math.random()) return enc.length;
this.bytesSent += enc.length;
this.packetsSent++;
await this.iceTransport.connection.send(enc).catch(() => {});
return enc.length;
} catch (error) {
log28("failed to send", error);
return 0;
}
}
async sendRtcp(packets) {
const payload = Buffer.concat(packets.map((packet) => packet.serialize()));
const enc = this.srtcp.encrypt(payload);
if (this.config.debug?.outboundPacketLoss && this.config.debug?.outboundPacketLoss / 100 < Math.random()) return enc.length;
this.bytesSent += enc.length;
this.packetsSent++;
await this.iceTransport.connection.send(enc).catch(() => {});
}
setState(state, emitEvent = true) {
if (state != this.state) {
this.state = state;
this.onStateChange.execute(state);
if (emitEvent) {
this.onstatechange?.();
this.events.emit("statechange");
}
}
}
async stop() {
this.setState("closed", false);
await this.iceTransport.stop();
}
async getStats(timestamp = getStatsTimestamp()) {
const stats = [];
const transportId = generateStatsId("transport", this.id);
const transportStats = {
type: "transport",
id: transportId,
timestamp,
bytesSent: this.bytesSent,
bytesReceived: this.bytesReceived,
packetsSent: this.packetsSent,
packetsReceived: this.packetsReceived,
dtlsState: this.state,
iceState: this.iceTransport.state,
iceRole: this.iceTransport.role === "unknown" ? void 0 : this.iceTransport.role,
iceLocalUsernameFragment: this.iceTransport.localParameters.usernameFragment,
selectedCandidatePairId: this.iceTransport.connection.nominated ? generateStatsId("candidate-pair", this.iceTransport.connection.nominated.id) : void 0,
localCertificateId: this.localCertificate ? generateStatsId("certificate", this.id, "local") : void 0,
remoteCertificateId: this.dtls?.remoteCertificate ? generateStatsId("certificate", this.id, "remote") : void 0,
dtlsRole: this.role === "auto" ? void 0 : this.role,
tlsVersion: formatDtlsVersion(this.dtls?.dtls.version),
dtlsCipher: this.dtls?.cipher.cipher?.name,
srtpCipher: formatSrtpCipher(this.dtls?.srtp.srtpProfile),
iceRestarts: this.iceTransport.iceRestarts
};
stats.push(transportStats);
if (this.localCertificate) {
const fingerprints = this.localCertificate.getFingerprints();
if (fingerprints.length > 0) {
const certStats = {
type: "certificate",
id: generateStatsId("certificate", this.id, "local"),
timestamp,
fingerprint: fingerprints[0].value,
fingerprintAlgorithm: fingerprints[0].algorithm,
base64Certificate: Buffer.from(this.localCertificate.certPem).toString("base64")
};
stats.push(certStats);
}
}
if (this.remoteParameters && this.remoteParameters.fingerprints.length > 0 && this.dtls?.remoteCertificate) {
const certStats = {
type: "certificate",
id: generateStatsId("certificate", this.id, "remote"),
timestamp,
fingerprint: this.remoteParameters.fingerprints[0].value,
fingerprintAlgorithm: this.remoteParameters.fingerprints[0].algorithm,
base64Certificate: Buffer.from(this.dtls.remoteCertificate).toString("base64")
};
stats.push(certStats);
}
const iceStats = await this.iceTransport.getStats(timestamp, transportId);
stats.push(...iceStats);
return stats;
}
};
var DtlsStates = [
"new",
"connecting",
"connected",
"closed",
"failed"
];
var RTCCertificate = class {
constructor(privateKeyPem, certPem, signatureHash) {
this.certPem = certPem;
this.signatureHash = signatureHash;
const cert = import_build.Certificate.fromPEM(Buffer.from(certPem));
this.publicKey = cert.publicKey.toPEM();
this.privateKey = import_build.PrivateKey.fromPEM(Buffer.from(privateKeyPem)).toPEM();
}
publicKey;
privateKey;
getFingerprints() {
return [new RTCDtlsFingerprint("sha-256", fingerprint(import_build.Certificate.fromPEM(Buffer.from(this.certPem)).raw, "sha256"))];
}
};
var RTCDtlsFingerprint = class {
constructor(algorithm, value) {
this.algorithm = algorithm;
this.value = value;
}
};
var RTCDtlsParameters = class {
constructor(fingerprints = [], role) {
this.fingerprints = fingerprints;
this.role = role;
}
};
var deduplicateFingerprints = (fingerprints) => {
const seen = /* @__PURE__ */ new Set();
return fingerprints.filter(({ algorithm, value }) => {
const key = `${normalizeFingerprintAlgorithm(algorithm) ?? algorithm.trim().toLowerCase()}:${normalizeFingerprintValue(value)}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
};
var preferredFingerprintAlgorithms = [
"sha512",
"sha384",
"sha256",
"sha224",
"sha1"
];
var selectPreferredFingerprintAlgorithm = (fingerprints) => {
return preferredFingerprintAlgorithms.find((algorithm) => fingerprints.some(({ normalizedAlgorithm }) => normalizedAlgorithm === algorithm)) ?? fingerprints[0].normalizedAlgorithm;
};
var IceTransport = class {
constructor(ice) {
this.ice = ice;
ice.onData.subscribe((buf) => {
if (isDtls(buf)) {
if (this.onData) this.onData(buf);
}
});
}
closed = false;
onData = () => {};
get address() {
return {};
}
type = "ice";
send = (data) => {
return this.ice.send(data);
};
async close() {
this.closed = true;
this.ice.close();
}
};
var createIceTransport = (ice) => new IceTransport(ice);
var log29 = debug("werift:packages/webrtc/src/transport/ice.ts");
function mapCandidatePairState(state) {
switch (state) {
case 0: return "frozen";
case 1: return "waiting";
case 2: return "in-progress";
case 3: return "succeeded";
case 4: return "failed";
default: return "failed";
}
}
var RTCIceTransport = class {
constructor(iceGather) {
this.iceGather = iceGather;
this.connection = this.iceGather.connection;
this.connection.stateChanged.subscribe((state) => {
this.setState(state);
});
this.iceGather.onIceCandidate = (candidate) => {
this.onIceCandidate.execute(candidate);
};
this.iceGather.onGatheringStateChange.subscribe(() => {
this.ongatheringstatechange?.();
this.events.emit("gatheringstatechange");
});
}
id = randomUUID$1().toString();
connection;
state = "new";
component = "rtp";
iceRestarts = 0;
waitStart;
renominating = false;
events = new EventTarget();
onstatechange;
ongatheringstatechange;
onStateChange = new Event2();
onIceCandidate = new Event2();
onNegotiationNeeded = new Event2();
addEventListener = (type, listener, options) => {
this.events.addEventListener(type, listener, options);
};
removeEventListener = (type, listener) => {
this.events.removeEventListener(type, listener);
};
dispatchEvent = (event) => this.events.dispatchEvent(event);
get role() {
if (!this.connection.remoteUsername || !this.connection.remotePassword) return "unknown";
if (this.connection.iceControlling) return "controlling";
else return "controlled";
}
get gatheringState() {
return this.iceGather.gatheringState;
}
get localCandidates() {
return this.iceGather.localCandidates;
}
get localParameters() {
return this.iceGather.localParameters;
}
getRemoteCandidates() {
return this.connection.remoteCandidates.filter((candidate) => candidate.type !== "prflx").map((candidate) => candidateFromIce(candidate).toJSON());
}
getLocalCandidates() {
return this.connection.localCandidates.map((candidate) => candidateFromIce(candidate).toJSON());
}
getSelectedCandidatePair() {
const pair = this.connection.candidatePairs.find((candidate) => candidate.nominated) ?? this.connection.candidatePairs.find((candidate) => candidate.state === 3);
if (!pair) return null;
return {
local: candidateFromIce(pair.localCandidate).toJSON(),
remote: candidateFromIce(pair.remoteCandidate).toJSON()
};
}
getLocalParameters() {
return this.localParameters ?? null;
}
getRemoteParameters() {
if (!this.connection.remoteUsername || !this.connection.remotePassword) return null;
return new RTCIceParameters({
iceLite: this.connection.remoteIsLite,
password: this.connection.remotePassword,
usernameFragment: this.connection.remoteUsername
});
}
setState(state, emitEvent = true) {
if (state !== this.state) {
this.state = state;
this.onStateChange.execute(state);
if (emitEvent) {
this.onstatechange?.();
this.events.emit("statechange");
}
}
}
gather() {
return this.iceGather.gather();
}
addRemoteCandidate = (candidate) => {
if (!this.connection.remoteCandidatesEnd) return !candidate ? this.connection.addRemoteCandidate(void 0) : this.connection.addRemoteCandidate(candidateToIce(candidate));
};
setRemoteParams(remoteParameters, renomination = false) {
if (renomination) this.renominating = true;
if (this.connection.remoteUsername && this.connection.remotePassword && (this.connection.remoteUsername !== remoteParameters.usernameFragment || this.connection.remotePassword !== remoteParameters.password)) {
if (this.renominating) {
log29("renomination", remoteParameters);
this.connection.resetNominatedPair();
this.renominating = false;
} else {
log29("restart", remoteParameters);
this.restart();
}
}
this.connection.setRemoteParams(remoteParameters);
}
restart() {
this.iceRestarts++;
this.connection.restart();
this.setState("new");
this.iceGather.gatheringState = "new";
this.waitStart = void 0;
this.onNegotiationNeeded.execute();
}
async start() {
if (this.state === "closed") throw new Error("RTCIceTransport is closed");
if (!this.connection.remotePassword || !this.connection.remoteUsername) throw new Error("remoteParams missing");
if (this.waitStart) await this.waitStart.asPromise();
this.waitStart = new Event2();
this.setState("checking");
try {
await this.connection.connect();
} catch (error) {
this.setState("failed");
throw error;
}
this.waitStart.execute();
this.waitStart.complete();
this.waitStart = void 0;
}
async stop() {
if (this.state !== "closed") {
this.setState("closed", false);
await this.connection.close();
}
this.onStateChange.complete();
this.onIceCandidate.complete();
this.onNegotiationNeeded.complete();
}
async getStats(timestamp = getStatsTimestamp(), transportId = generateStatsId("transport", this.id)) {
const stats = [];
for (const candidate of this.connection.localCandidates) {
const candidateStats = {
type: "local-candidate",
id: generateStatsId("local-candidate", candidate.id),
timestamp,
transportId,
address: candidate.host,
port: candidate.port,
protocol: candidate.transport,
candidateType: candidate.type,
priority: candidate.priority,
foundation: candidate.foundation,
relatedAddress: candidate.relatedAddress,
relatedPort: candidate.relatedPort,
usernameFragment: candidate.ufrag,
tcpType: candidate.tcptype
};
stats.push(candidateStats);
}
for (const candidate of this.connection.remoteCandidates) {
const candidateStats = {
type: "remote-candidate",
id: generateStatsId("remote-candidate", candidate.id),
timestamp,
transportId,
address: candidate.host,
port: candidate.port,
protocol: candidate.transport,
candidateType: candidate.type,
priority: candidate.priority,
foundation: candidate.foundation,
relatedAddress: candidate.relatedAddress,
relatedPort: candidate.relatedPort,
usernameFragment: candidate.ufrag,
tcpType: candidate.tcptype
};
stats.push(candidateStats);
}
const pairs = this.connection?.candidatePairs ? [...this.connection.candidatePairs.filter((p) => p.nominated), ...this.connection.candidatePairs.filter((p) => !p.nominated)] : [];
for (const pair of pairs) {
const pairStats = {
type: "candidate-pair",
id: generateStatsId("candidate-pair", pair.id),
timestamp,
transportId,
localCandidateId: generateStatsId("local-candidate", pair.localCandidate.id),
remoteCandidateId: generateStatsId("remote-candidate", pair.remoteCandidate.id),
state: mapCandidatePairState(pair.state),
nominated: pair.nominated,
packetsSent: pair.packetsSent,
packetsReceived: pair.packetsReceived,
bytesSent: pair.bytesSent,
bytesReceived: pair.bytesReceived,
currentRoundTripTime: pair.rtt,
totalRoundTripTime: pair.totalRoundTripTime,
roundTripTimeMeasurements: pair.roundTripTimeMeasurements,
requestsReceived: pair.requestsReceived,
requestsSent: pair.requestsSent,
responsesReceived: pair.responsesReceived,
responsesSent: pair.responsesSent,
retransmissionsReceived: pair.retransmissionsReceived,
retransmissionsSent: pair.retransmissionsSent,
consentRequestsSent: pair.consentRequestsSent
};
stats.push(pairStats);
}
return stats;
}
};
var IceTransportStates = [
"new",
"checking",
"connected",
"completed",
"disconnected",
"failed",
"closed"
];
var IceGathererStates = [
"new",
"gathering",
"complete"
];
var RTCIceGatherer = class {
constructor(options = {}) {
this.options = options;
this.connection = new Connection(false, this.options);
this.connection.onIceCandidate.subscribe((candidate) => {
this.onIceCandidate(candidateFromIce(candidate));
});
}
onIceCandidate = () => {};
gatheringState = "new";
connection;
onGatheringStateChange = new Event2();
async gather() {
if (this.gatheringState === "new") {
this.setState("gathering");
await this.connection.gatherCandidates();
this.onIceCandidate(void 0);
this.setState("complete");
}
}
get localCandidates() {
return this.connection.localCandidates.map(candidateFromIce);
}
get localParameters() {
return new RTCIceParameters({
iceLite: this.connection.iceLite,
usernameFragment: this.connection.localUsername,
password: this.connection.localPassword
});
}
setState(state) {
if (state !== this.gatheringState) {
this.gatheringState = state;
this.onGatheringStateChange.execute(state);
}
}
};
function candidateFromIce(c) {
const candidate = new IceCandidate(c.component, c.foundation, c.host, c.port, c.priority, c.transport, c.type, c.generation, c.ufrag);
candidate.relatedAddress = c.relatedAddress;
candidate.relatedPort = c.relatedPort;
candidate.tcpType = c.tcptype;
return candidate;
}
function candidateToIce(x) {
return new Candidate(x.foundation, x.component, x.protocol, x.priority, x.ip, x.port, x.type, x.relatedAddress, x.relatedPort, x.tcpType, x.generation, x.ufrag);
}
var RTCIceCandidate = class {
candidate;
sdpMid;
sdpMLineIndex;
usernameFragment;
constructor(props) {
Object.assign(this, props);
}
static fromSdp(sdp) {
return candidateFromIce(Candidate.fromSdp(sdp)).toJSON();
}
static isThis(o) {
if (typeof o?.candidate === "string") return true;
}
toJSON() {
return {
candidate: this.candidate,
sdpMid: this.sdpMid,
sdpMLineIndex: this.sdpMLineIndex,
usernameFragment: this.usernameFragment
};
}
};
var IceCandidate = class {
constructor(component, foundation, ip, port, priority, protocol, type, generation, ufrag) {
this.component = component;
this.foundation = foundation;
this.ip = ip;
this.port = port;
this.priority = priority;
this.protocol = protocol;
this.type = type;
this.generation = generation;
this.ufrag = ufrag;
}
relatedAddress;
relatedPort;
sdpMid;
sdpMLineIndex;
tcpType;
toJSON() {
return new RTCIceCandidate({
candidate: candidateToSdp(this),
sdpMLineIndex: this.sdpMLineIndex,
sdpMid: this.sdpMid,
usernameFragment: this.ufrag
});
}
static fromJSON(data) {
try {
if (!data.candidate) throw new Error("candidate is required");
const candidate = candidateFromSdp(data.candidate.startsWith("candidate:") ? data.candidate.slice(10) : data.candidate);
candidate.sdpMLineIndex = data.sdpMLineIndex ?? void 0;
candidate.sdpMid = data.sdpMid ?? void 0;
return candidate;
} catch (error) {}
}
};
var RTCIceParameters = class {
iceLite = false;
usernameFragment;
password;
constructor(props = {}) {
Object.assign(this, props);
}
};
var Chunk = class _Chunk {
constructor(flags = 0, _body = Buffer.from("")) {
this.flags = flags;
this._body = _body;
}
get body() {
return this._body;
}
set body(value) {
this._body = value;
}
static type = -1;
get type() {
return _Chunk.type;
}
get bytes() {
if (!this.body) throw new Error();
const header = Buffer.alloc(4);
header.writeUInt8(this.type, 0);
header.writeUInt8(this.flags, 1);
header.writeUInt16BE(this.body.length + 4, 2);
return Buffer.concat([
header,
this.body,
...[...Array(padL(this.body.length))].map(() => Buffer.from("\0"))
]);
}
};
var BaseInitChunk = class extends Chunk {
constructor(flags = 0, body) {
super(flags, body);
this.flags = flags;
if (body) {
this.initiateTag = body.readUInt32BE(0);
this.advertisedRwnd = body.readUInt32BE(4);
this.outboundStreams = body.readUInt16BE(8);
this.inboundStreams = body.readUInt16BE(10);
this.initialTsn = body.readUInt32BE(12);
this.params = decodeParams(body.slice(16));
} else {
this.initiateTag = 0;
this.advertisedRwnd = 0;
this.outboundStreams = 0;
this.inboundStreams = 0;
this.initialTsn = 0;
this.params = [];
}
}
initiateTag;
advertisedRwnd;
outboundStreams;
inboundStreams;
initialTsn;
params;
get body() {
const body = Buffer.alloc(16);
body.writeUInt32BE(this.initiateTag, 0);
body.writeUInt32BE(this.advertisedRwnd, 4);
body.writeUInt16BE(this.outboundStreams, 8);
body.writeUInt16BE(this.inboundStreams, 10);
body.writeUInt32BE(this.initialTsn, 12);
return Buffer.concat([body, encodeParams(this.params)]);
}
};
var InitChunk = class _InitChunk extends BaseInitChunk {
static type = 1;
get type() {
return _InitChunk.type;
}
};
var InitAckChunk = class _InitAckChunk extends BaseInitChunk {
static type = 2;
get type() {
return _InitAckChunk.type;
}
};
var ReConfigChunk = class _ReConfigChunk extends BaseInitChunk {
static type = 130;
get type() {
return _ReConfigChunk.type;
}
};
var ForwardTsnChunk = class _ForwardTsnChunk extends Chunk {
constructor(flags = 0, body) {
super(flags, body);
this.flags = flags;
if (body) {
this.cumulativeTsn = body.readUInt32BE(0);
let pos = 4;
while (pos < body.length) {
this.streams.push([body.readUInt16BE(pos), body.readUInt16BE(pos + 2)]);
pos += 4;
}
} else this.cumulativeTsn = 0;
}
static type = 192;
streams = [];
cumulativeTsn;
get type() {
return _ForwardTsnChunk.type;
}
set body(_) {}
get body() {
const body = Buffer.alloc(4);
body.writeUInt32BE(this.cumulativeTsn, 0);
return Buffer.concat([body, ...this.streams.map(([id, seq]) => {
const streamBuffer = Buffer.alloc(4);
streamBuffer.writeUInt16BE(id, 0);
streamBuffer.writeUInt16BE(seq, 2);
return streamBuffer;
})]);
}
};
var DataChunk = class _DataChunk extends Chunk {
constructor(flags = 0, body) {
super(flags, body);
this.flags = flags;
if (body) {
this.tsn = body.readUInt32BE(0);
this.streamId = body.readUInt16BE(4);
this.streamSeqNum = body.readUInt16BE(6);
this.protocol = body.readUInt32BE(8);
this.userData = body.slice(12);
}
}
static type = 0;
get type() {
return _DataChunk.type;
}
tsn = 0;
streamId = 0;
streamSeqNum = 0;
protocol = 0;
userData = Buffer.from("");
abandoned = false;
acked = false;
misses = 0;
retransmit = false;
sentCount = 0;
bookSize = 0;
expiry;
maxRetransmits;
sentTime;
get bytes() {
const length = 16 + this.userData.length;
const header = Buffer.alloc(16);
header.writeUInt8(this.type, 0);
header.writeUInt8(this.flags, 1);
header.writeUInt16BE(length, 2);
header.writeUInt32BE(this.tsn, 4);
header.writeUInt16BE(this.streamId, 8);
header.writeUInt16BE(this.streamSeqNum, 10);
header.writeUInt32BE(this.protocol, 12);
let data = Buffer.concat([header, this.userData]);
if (length % 4) data = Buffer.concat([data, ...[...Array(padL(length))].map(() => Buffer.from("\0"))]);
return data;
}
};
var CookieEchoChunk = class _CookieEchoChunk extends Chunk {
static type = 10;
get type() {
return _CookieEchoChunk.type;
}
};
var CookieAckChunk = class _CookieAckChunk extends Chunk {
static type = 11;
get type() {
return _CookieAckChunk.type;
}
};
var BaseParamsChunk = class extends Chunk {
constructor(flags = 0, body = void 0) {
super(flags, body);
this.flags = flags;
if (body) this.params = decodeParams(body);
}
params = [];
get body() {
return encodeParams(this.params);
}
};
var AbortChunk = class _AbortChunk extends BaseParamsChunk {
static type = 6;
get type() {
return _AbortChunk.type;
}
};
var ErrorChunk = class _ErrorChunk extends BaseParamsChunk {
static type = 9;
static CODE = {
InvalidStreamIdentifier: 1,
MissingMandatoryParameter: 2,
StaleCookieError: 3,
OutofResource: 4,
UnresolvableAddress: 5,
UnrecognizedChunkType: 6,
InvalidMandatoryParameter: 7,
UnrecognizedParameters: 8,
NoUserData: 9,
CookieReceivedWhileShuttingDown: 10,
RestartofanAssociationwithNewAddresses: 11,
UserInitiatedAbort: 12,
ProtocolViolation: 13
};
get type() {
return _ErrorChunk.type;
}
get descriptions() {
return this.params.map(([code, body]) => {
return {
name: (Object.entries(_ErrorChunk.CODE).find(([, num]) => num === code) || [])[0],
body
};
});
}
};
var HeartbeatChunk = class _HeartbeatChunk extends BaseParamsChunk {
static type = 4;
get type() {
return _HeartbeatChunk.type;
}
};
var HeartbeatAckChunk = class _HeartbeatAckChunk extends BaseParamsChunk {
static type = 5;
get type() {
return _HeartbeatAckChunk.type;
}
};
var ReconfigChunk = class _ReconfigChunk extends BaseParamsChunk {
static type = 130;
get type() {
return _ReconfigChunk.type;
}
};
var SackChunk = class _SackChunk extends Chunk {
constructor(flags = 0, body) {
super(flags, body);
this.flags = flags;
if (body) {
this.cumulativeTsn = body.readUInt32BE(0);
this.advertisedRwnd = body.readUInt32BE(4);
const nbGaps = body.readUInt16BE(8);
const nbDuplicates = body.readUInt16BE(10);
let pos = 12;
[...Array(nbGaps)].forEach(() => {
this.gaps.push([body.readUInt16BE(pos), body.readUInt16BE(pos + 2)]);
pos += 4;
});
[...Array(nbDuplicates)].forEach(() => {
this.duplicates.push(body.readUInt32BE(pos));
pos += 4;
});
}
}
static type = 3;
get type() {
return _SackChunk.type;
}
gaps = [];
duplicates = [];
cumulativeTsn = 0;
advertisedRwnd = 0;
get bytes() {
const length = 16 + 4 * (this.gaps.length + this.duplicates.length);
const header = Buffer.alloc(16);
header.writeUInt8(this.type, 0);
header.writeUInt8(this.flags, 1);
header.writeUInt16BE(length, 2);
header.writeUInt32BE(this.cumulativeTsn, 4);
header.writeUInt32BE(this.advertisedRwnd, 8);
header.writeUInt16BE(this.gaps.length, 12);
header.writeUInt16BE(this.duplicates.length, 14);
let data = Buffer.concat([header, ...this.gaps.map((gap) => {
const gapBuffer = Buffer.alloc(4);
gapBuffer.writeUInt16BE(gap[0], 0);
gapBuffer.writeUInt16BE(gap[1], 2);
return gapBuffer;
})]);
data = Buffer.concat([data, ...this.duplicates.map((tsn) => {
const tsnBuffer = Buffer.alloc(4);
tsnBuffer.writeUInt32BE(tsn, 0);
return tsnBuffer;
})]);
return data;
}
};
var ShutdownChunk = class _ShutdownChunk extends Chunk {
constructor(flags = 0, body) {
super(flags, body);
this.flags = flags;
if (body) this.cumulativeTsn = body.readUInt32BE(0);
}
static type = 7;
get type() {
return _ShutdownChunk.type;
}
cumulativeTsn = 0;
get body() {
const body = Buffer.alloc(4);
body.writeUInt32BE(this.cumulativeTsn, 0);
return body;
}
};
var ShutdownAckChunk = class _ShutdownAckChunk extends Chunk {
static type = 8;
get type() {
return _ShutdownAckChunk.type;
}
};
var ShutdownCompleteChunk = class _ShutdownCompleteChunk extends Chunk {
static type = 14;
get type() {
return _ShutdownCompleteChunk.type;
}
};
var CHUNK_BY_TYPE = [
DataChunk,
InitChunk,
InitAckChunk,
SackChunk,
HeartbeatChunk,
HeartbeatAckChunk,
AbortChunk,
ShutdownChunk,
ShutdownAckChunk,
ErrorChunk,
CookieEchoChunk,
CookieAckChunk,
ShutdownCompleteChunk,
ReconfigChunk,
ForwardTsnChunk
].reduce((acc, cur) => {
acc[cur.type] = cur;
return acc;
}, {});
function padL(l) {
const m = l % 4;
return m ? 4 - m : 0;
}
function encodeParams(params) {
let body = Buffer.from("");
let padding = Buffer.from("");
params.forEach(([type, value]) => {
const length = value.length + 4;
const paramHeader = Buffer.alloc(4);
paramHeader.writeUInt16BE(type, 0);
paramHeader.writeUInt16BE(length, 2);
body = Buffer.concat([
body,
padding,
paramHeader,
value
]);
padding = Buffer.concat([...Array(padL(length))].map(() => Buffer.from("\0")));
});
return body;
}
function decodeParams(body) {
const params = [];
let pos = 0;
while (pos <= body.length - 4) {
const type = body.readUInt16BE(pos);
const length = body.readUInt16BE(pos + 2);
params.push([type, body.slice(pos + 4, pos + length)]);
pos += length + padL(length);
}
return params;
}
function parsePacket2(data) {
if (data.length < 12) throw new Error("SCTP packet length is less than 12 bytes");
const sourcePort = data.readUInt16BE(0);
const destinationPort = data.readUInt16BE(2);
const verificationTag = data.readUInt32BE(4);
if (data.readUInt32LE(8) !== crc32c(Buffer.concat([
data.slice(0, 8),
Buffer.from("\0\0\0\0"),
data.slice(12)
]))) throw new Error("SCTP packet has invalid checksum");
const chunks = [];
let pos = 12;
while (pos + 4 <= data.length) {
const chunkType = data.readUInt8(pos);
const chunkFlags = data.readUInt8(pos + 1);
const chunkLength = data.readUInt16BE(pos + 2);
const chunkBody = data.slice(pos + 4, pos + chunkLength);
const ChunkClass = CHUNK_BY_TYPE[chunkType.toString()];
if (ChunkClass) chunks.push(new ChunkClass(chunkFlags, chunkBody));
else throw new Error("unknown");
pos += chunkLength + padL(chunkLength);
}
return [
sourcePort,
destinationPort,
verificationTag,
chunks
];
}
function serializePacket(sourcePort, destinationPort, verificationTag, chunk) {
const header = Buffer.alloc(8);
header.writeUInt16BE(sourcePort, 0);
header.writeUInt16BE(destinationPort, 2);
header.writeUInt32BE(verificationTag, 4);
const body = chunk.bytes;
const checksum = crc32c(Buffer.concat([
header,
Buffer.from("\0\0\0\0"),
body
]));
const checkSumBuf = Buffer.alloc(4);
checkSumBuf.writeUInt32LE(checksum, 0);
return Buffer.concat([
header,
checkSumBuf,
body
]);
}
function enumerate3(arr) {
return arr.map((v, i) => [i, v]);
}
function createEventsFromList(list) {
return list.reduce((acc, cur) => {
acc[cur] = new Event2();
return acc;
}, {});
}
var OutgoingSSNResetRequestParam = class _OutgoingSSNResetRequestParam {
constructor(requestSequence, responseSequence, lastTsn, streams) {
this.requestSequence = requestSequence;
this.responseSequence = responseSequence;
this.lastTsn = lastTsn;
this.streams = streams;
}
static type = 13;
get type() {
return _OutgoingSSNResetRequestParam.type;
}
get bytes() {
const data = Buffer.allocUnsafe(12);
data.writeUInt32BE(this.requestSequence, 0);
data.writeUInt32BE(this.responseSequence, 4);
data.writeUInt32BE(this.lastTsn, 8);
return Buffer.concat([data, ...this.streams.map((stream) => {
const buf = Buffer.allocUnsafe(2);
buf.writeUInt16BE(stream, 0);
return buf;
})]);
}
static parse(data) {
const requestSequence = data.readUInt32BE(0);
const responseSequence = data.readUInt32BE(4);
const lastTsn = data.readUInt32BE(8);
const stream = [];
for (let pos = 12; pos < data.length; pos += 2) stream.push(data.readUInt16BE(pos));
return new _OutgoingSSNResetRequestParam(requestSequence, responseSequence, lastTsn, stream);
}
};
var StreamAddOutgoingParam = class _StreamAddOutgoingParam {
constructor(requestSequence, newStreams) {
this.requestSequence = requestSequence;
this.newStreams = newStreams;
}
static type = 17;
get type() {
return _StreamAddOutgoingParam.type;
}
get bytes() {
const buf = Buffer.allocUnsafe(8);
buf.writeUInt32BE(this.requestSequence, 0);
buf.writeUInt16BE(this.newStreams, 4);
buf.writeUInt16BE(0, 6);
return buf;
}
static parse(data) {
const requestSequence = data.readUInt32BE(0);
const newStreams = data.readUInt16BE(4);
return new _StreamAddOutgoingParam(requestSequence, newStreams);
}
};
var reconfigResult = {
ReconfigResultSuccessPerformed: 1,
BadSequenceNumber: 5
};
var ReconfigResponseParam = class _ReconfigResponseParam {
constructor(responseSequence, result) {
this.responseSequence = responseSequence;
this.result = result;
}
static type = 16;
get type() {
return _ReconfigResponseParam.type;
}
get bytes() {
const buf = Buffer.allocUnsafe(8);
buf.writeUInt32BE(this.responseSequence, 0);
buf.writeUInt32BE(this.result, 4);
return buf;
}
static parse(data) {
const requestSequence = data.readUInt32BE(0);
const result = data.readUInt32BE(4);
return new _ReconfigResponseParam(requestSequence, result);
}
};
var RECONFIG_PARAM_BY_TYPES = {
13: OutgoingSSNResetRequestParam,
16: ReconfigResponseParam,
17: StreamAddOutgoingParam
};
var log30 = debug("werift/sctp/sctp");
var COOKIE_LENGTH = 24;
var COOKIE_LIFETIME = 60;
var MAX_STREAMS = 65535;
var USERDATA_MAX_LENGTH = 1200;
var SCTP_DATA_LAST_FRAG = 1;
var SCTP_DATA_FIRST_FRAG = 2;
var SCTP_DATA_UNORDERED = 4;
var SCTP_MAX_ASSOCIATION_RETRANS = 10;
var SCTP_MAX_INIT_RETRANS = 8;
var SCTP_RTO_ALPHA = 1 / 8;
var SCTP_RTO_BETA = 1 / 4;
var SCTP_RTO_INITIAL = 3;
var SCTP_RTO_MIN = 1;
var SCTP_RTO_MAX = 60;
var SCTP_TSN_MODULO = 2 ** 32;
var SCTP_SACK_DELAY_MS = 200;
var SCTP_HEARTBEAT_INTERVAL = 30;
var RECONFIG_MAX_STREAMS = 135;
var SCTP_STATE_COOKIE = 7;
var SCTP_SUPPORTED_CHUNK_EXT = 32776;
var SCTP_PRSCTP_SUPPORTED = 49152;
var SCTPConnectionStates = [
"new",
"closed",
"connected",
"connecting"
];
var SCTP = class _SCTP {
constructor(transport, port = 5e3) {
this.transport = transport;
this.port = port;
this.localPort = this.port;
this.transport.onData = (buf) => {
this.handleData(buf);
};
}
flush = new Event2();
stateChanged = createEventsFromList(SCTPConnectionStates);
onReconfigStreams = new Event2();
/**streamId: number, ppId: number, data: Buffer */
onReceive = new Event2();
onSackReceived = async () => {};
associationState = 1;
started = false;
state = "new";
isServer = true;
isStopping = false;
isClosed = false;
hmacKey = randomBytes$1(16);
localPartialReliability = true;
localPort;
localVerificationTag = random32();
remoteExtensions = [];
remotePartialReliability = true;
remotePort;
remoteVerificationTag = 0;
advertisedRwnd = 1048576;
peerAdvertisedRwnd = this.advertisedRwnd;
get peerRwnd() {
return Math.max(0, this.peerAdvertisedRwnd - this.flightSize);
}
inboundStreams = {};
_inboundStreamsCount = 0;
_inboundStreamsMax = MAX_STREAMS;
lastReceivedTsn;
sackDuplicates = [];
sackMisOrdered = /* @__PURE__ */ new Set();
sackNeeded = false;
sackPacketCount = 0;
sackHasNewDataInPacket = false;
sackImmediate = false;
sackTimeout;
cwnd = 3 * USERDATA_MAX_LENGTH;
fastRecoveryExit;
fastRecoveryTransmit = false;
forwardTsnChunk;
flightSize = 0;
outboundQueue = [];
outboundStreamSeq = {};
_outboundStreamsCount = MAX_STREAMS;
/**local transmission sequence number */
localTsn = Number(random32());
lastSackedTsn = tsnMinusOne(this.localTsn);
advancedPeerAckTsn = tsnMinusOne(this.localTsn);
partialBytesAcked = 0;
sentQueue = [];
transmitting = false;
transmitRequested = false;
/**初期TSNと同じ値に初期化される単調に増加する数です. これは、新しいre-configuration requestパラメーターを送信するたびに1ずつ増加します */
reconfigRequestSeq = this.localTsn;
/**このフィールドは、incoming要求のre-configuration requestシーケンス番号を保持します. 他の場合では、次に予想されるre-configuration requestシーケンス番号から1を引いた値が保持されます */
reconfigResponseSeq = 0;
reconfigRequest;
reconfigQueue = [];
srtt;
rttvar;
rto = SCTP_RTO_INITIAL;
/**t1 is wait for initAck or cookieAck */
timer1Handle;
timer1Chunk;
timer1Failures = 0;
/**t2 is wait for shutdown */
timer2Handle;
timer2Chunk;
timer2Failures = 0;
/**t3 is wait for data sack */
timer3Handle;
/**Re-configuration Timer */
timerReconfigHandle;
timerReconfigFailures = 0;
timerHeartbeatHandle;
heartbeatInterval = SCTP_HEARTBEAT_INTERVAL;
ssthresh;
get isStopped() {
return this.isStopping || this.isClosed;
}
get maxChannels() {
if (this._inboundStreamsCount > 0) return Math.min(this._inboundStreamsCount, this._outboundStreamsCount);
}
static client(transport, port = 5e3) {
const sctp = new _SCTP(transport, port);
sctp.isServer = false;
return sctp;
}
static server(transport, port = 5e3) {
const sctp = new _SCTP(transport, port);
sctp.isServer = true;
return sctp;
}
async handleData(data) {
if (this.isStopped) return;
let expectedTag;
const [, , verificationTag, chunks] = parsePacket2(data);
if (chunks.filter((v) => v.type === InitChunk.type).length > 0) {
if (chunks.length != 1) throw new Error();
expectedTag = 0;
} else expectedTag = this.localVerificationTag;
if (verificationTag !== expectedTag) return;
this.sackHasNewDataInPacket = false;
for (const chunk of chunks) await this.receiveChunk(chunk);
if (this.sackNeeded) {
if (this.sackHasNewDataInPacket) this.sackPacketCount++;
if (this.sackPacketCount >= 2) this.sackImmediate = true;
await this.scheduleSack();
}
}
async scheduleSack() {
if (this.isStopped) return;
if (!this.sackNeeded) return;
if (this.sackImmediate) {
if (this.sackTimeout) {
clearTimeout(this.sackTimeout);
this.sackTimeout = void 0;
}
await this.sendSack();
return;
}
if (this.sackTimeout) return;
this.sackTimeout = setTimeout(() => {
this.sackTimeout = void 0;
this.sendSack().catch((err5) => {
log30("send delayed sack failed", err5.message);
});
}, SCTP_SACK_DELAY_MS);
}
async sendSack() {
if (this.isStopped) return;
if (!this.sackNeeded) return;
const gaps = [];
let gapNext;
[...this.sackMisOrdered].sort().forEach((tsn) => {
const pos = (tsn - this.lastReceivedTsn) % SCTP_TSN_MODULO;
if (tsn === gapNext) gaps[gaps.length - 1][1] = pos;
else gaps.push([pos, pos]);
gapNext = tsnPlusOne(tsn);
});
const sack = new SackChunk(0, void 0);
sack.cumulativeTsn = this.lastReceivedTsn;
sack.advertisedRwnd = Math.max(0, this.advertisedRwnd);
sack.duplicates = [...this.sackDuplicates];
sack.gaps = gaps;
await this.sendChunk(sack).catch((err5) => {
log30("send sack failed", err5.message);
});
this.sackDuplicates = [];
this.sackNeeded = false;
this.sackPacketCount = 0;
this.sackImmediate = false;
}
async receiveChunk(chunk) {
switch (chunk.type) {
case DataChunk.type:
this.receiveDataChunk(chunk);
break;
case InitChunk.type:
{
if (!this.isServer) return;
const init = chunk;
log30("receive init", init);
this.lastReceivedTsn = tsnMinusOne(init.initialTsn);
this.reconfigResponseSeq = tsnMinusOne(init.initialTsn);
this.remoteVerificationTag = init.initiateTag;
this.ssthresh = init.advertisedRwnd;
this.peerAdvertisedRwnd = init.advertisedRwnd;
this.getExtensions(init.params);
this._inboundStreamsCount = Math.min(init.outboundStreams, this._inboundStreamsMax);
this._outboundStreamsCount = Math.min(this._outboundStreamsCount, init.inboundStreams);
const ack = new InitAckChunk();
ack.initiateTag = this.localVerificationTag;
ack.advertisedRwnd = this.advertisedRwnd;
ack.outboundStreams = this._outboundStreamsCount;
ack.inboundStreams = this._inboundStreamsCount;
ack.initialTsn = this.localTsn;
this.setExtensions(ack.params);
const time = Math.floor(Date.now() / 1e3);
const cookieTime = Buffer.allocUnsafe(4);
cookieTime.writeUInt32BE(time, 0);
let cookie = cookieTime;
cookie = Buffer.concat([cookie, createHmac$1("sha1", this.hmacKey).update(cookie).digest()]);
ack.params.push([SCTP_STATE_COOKIE, cookie]);
log30("send initAck", ack);
await this.sendChunk(ack).catch((err5) => {
log30("send initAck failed", err5.message);
});
}
break;
case InitAckChunk.type:
{
if (this.associationState != 2) return;
const initAck = chunk;
this.timer1Cancel();
this.lastReceivedTsn = tsnMinusOne(initAck.initialTsn);
this.reconfigResponseSeq = tsnMinusOne(initAck.initialTsn);
this.remoteVerificationTag = initAck.initiateTag;
this.ssthresh = initAck.advertisedRwnd;
this.peerAdvertisedRwnd = initAck.advertisedRwnd;
this.getExtensions(initAck.params);
this._inboundStreamsCount = Math.min(initAck.outboundStreams, this._inboundStreamsMax);
this._outboundStreamsCount = Math.min(this._outboundStreamsCount, initAck.inboundStreams);
const echo = new CookieEchoChunk();
for (const [k, v] of initAck.params) if (k === SCTP_STATE_COOKIE) {
echo.body = v;
break;
}
await this.sendChunk(echo).catch((err5) => {
log30("send echo failed", err5.message);
});
this.timer1Start(echo);
this.setState(3);
}
break;
case SackChunk.type:
await this.receiveSackChunk(chunk);
break;
case HeartbeatChunk.type:
{
const ack = new HeartbeatAckChunk();
ack.params = chunk.params;
await this.sendChunk(ack).catch((err5) => {
log30("send heartbeat ack failed", err5.message);
});
}
break;
case AbortChunk.type:
this.setState(1);
break;
case ShutdownChunk.type:
{
this.timer2Cancel();
this.setState(7);
const ack = new ShutdownAckChunk();
await this.sendChunk(ack).catch((err5) => {
log30("send shutdown ack failed", err5.message);
});
this.t2Start(ack);
this.setState(6);
}
break;
case ErrorChunk.type:
log30("ErrorChunk", chunk.descriptions);
break;
case CookieEchoChunk.type:
{
if (!this.isServer) return;
const cookie = chunk.body;
const digest = createHmac$1("sha1", this.hmacKey).update(cookie.slice(0, 4)).digest();
if (cookie?.length != COOKIE_LENGTH || !cookie.slice(4).equals(digest)) {
log30("x State cookie is invalid");
return;
}
const now = Math.floor(Date.now() / 1e3);
const stamp = cookie.readUInt32BE(0);
if (stamp < now - COOKIE_LIFETIME || stamp > now) {
const error = new ErrorChunk(0, void 0);
error.params.push([ErrorChunk.CODE.StaleCookieError, Buffer.concat([...Array(8)].map(() => Buffer.from("\0")))]);
await this.sendChunk(error).catch((err5) => {
log30("send errorChunk failed", err5.message);
});
return;
}
const ack = new CookieAckChunk();
await this.sendChunk(ack).catch((err5) => {
log30("send cookieAck failed", err5.message);
});
this.setState(4);
}
break;
case CookieAckChunk.type:
if (this.associationState != 3) return;
this.timer1Cancel();
this.setState(4);
break;
case ShutdownCompleteChunk.type:
if (this.associationState != 8) return;
this.timer2Cancel();
this.setState(1);
break;
case ReconfigChunk.type:
{
if (this.associationState != 4) return;
const reconfig = chunk;
for (const [type, body] of reconfig.params) {
const target = RECONFIG_PARAM_BY_TYPES[type];
if (target) await this.receiveReconfigParam(target.parse(body));
}
}
break;
case ForwardTsnChunk.type: this.receiveForwardTsnChunk(chunk);
}
}
getExtensions(params) {
for (const [k, v] of params) if (k === SCTP_PRSCTP_SUPPORTED) this.remotePartialReliability = true;
else if (k === SCTP_SUPPORTED_CHUNK_EXT) this.remoteExtensions = [...v];
}
async receiveReconfigParam(param) {
log30("receiveReconfigParam", RECONFIG_PARAM_BY_TYPES[param.type]);
switch (param.type) {
case OutgoingSSNResetRequestParam.type:
{
const p = param;
const response = new ReconfigResponseParam(p.requestSequence, reconfigResult.ReconfigResultSuccessPerformed);
this.reconfigResponseSeq = p.requestSequence;
await this.sendReconfigParam(response);
await Promise.all(p.streams.map(async (streamId) => {
delete this.inboundStreams[streamId];
if (this.outboundStreamSeq[streamId]) {
if (!this.reconfigQueue.includes(streamId)) this.reconfigQueue.push(streamId);
}
}));
await this.transmitReconfigRequest();
this.onReconfigStreams.execute(p.streams);
}
break;
case ReconfigResponseParam.type:
{
const reset = param;
if (reset.result !== reconfigResult.ReconfigResultSuccessPerformed) log30("OutgoingSSNResetRequestParam failed", Object.keys(reconfigResult).find((key) => reconfigResult[key] === reset.result));
else if (reset.responseSequence === this.reconfigRequest?.requestSequence) {
const streamIds = this.reconfigRequest.streams.map((streamId) => {
delete this.outboundStreamSeq[streamId];
return streamId;
});
this.onReconfigStreams.execute(streamIds);
this.reconfigRequest = void 0;
this.timerReconfigCancel();
this.rto = SCTP_RTO_INITIAL;
this.timerReconfigFailures = 0;
if (this.reconfigQueue.length > 0) await this.transmitReconfigRequest();
}
}
break;
case StreamAddOutgoingParam.type: {
const add = param;
this._inboundStreamsCount += add.newStreams;
const res = new ReconfigResponseParam(add.requestSequence, 1);
this.reconfigResponseSeq = add.requestSequence;
await this.sendReconfigParam(res);
}
}
}
receiveDataChunk(chunk) {
this.sackNeeded = true;
if (this.markReceived(chunk.tsn)) {
this.sackImmediate = true;
return;
}
this.sackHasNewDataInPacket = true;
this.sackImmediate = true;
if ((chunk.flags & SCTP_DATA_LAST_FRAG) === 0) this.sackImmediate = true;
if (this.sackMisOrdered.size > 0) this.sackImmediate = true;
const inboundStream = this.getInboundStream(chunk.streamId);
inboundStream.addChunk(chunk);
this.advertisedRwnd -= chunk.userData.length;
for (const message of inboundStream.popMessages()) {
this.advertisedRwnd += message[2].length;
this.receive(...message);
}
}
async receiveSackChunk(chunk) {
if (uint32Gt(this.lastSackedTsn, chunk.cumulativeTsn)) return;
const receivedTime = Date.now() / 1e3;
this.lastSackedTsn = chunk.cumulativeTsn;
const cwndFullyUtilized = this.flightSize >= this.cwnd;
let done = 0, doneBytes = 0;
while (this.sentQueue.length > 0 && uint32Gte(this.lastSackedTsn, this.sentQueue[0].tsn)) {
const sChunk = this.sentQueue.shift();
done++;
if (!sChunk?.acked) {
doneBytes += sChunk.bookSize;
this.flightSizeDecrease(sChunk);
}
if (done === 1 && sChunk.sentCount === 1) this.updateRto(receivedTime - sChunk.sentTime);
}
if (!this.sentQueue.length) this.sentQueue = [];
let loss = false;
if (chunk.gaps.length > 0) {
const seen = /* @__PURE__ */ new Set();
let highestSeenTsn;
chunk.gaps.forEach((gap) => {
for (let pos = gap[0]; pos < gap[1] + 1; pos++) {
highestSeenTsn = (chunk.cumulativeTsn + pos) % SCTP_TSN_MODULO;
seen.add(highestSeenTsn);
}
});
let highestNewlyAcked = chunk.cumulativeTsn;
for (const sChunk of this.sentQueue) {
if (uint32Gt(sChunk.tsn, highestSeenTsn)) break;
if (seen.has(sChunk.tsn) && !sChunk.acked) {
doneBytes += sChunk.bookSize;
sChunk.acked = true;
this.flightSizeDecrease(sChunk);
highestNewlyAcked = sChunk.tsn;
}
}
for (const sChunk of this.sentQueue) {
if (uint32Gt(sChunk.tsn, highestNewlyAcked)) break;
if (!seen.has(sChunk.tsn)) {
sChunk.misses++;
if (sChunk.misses === 3) {
sChunk.misses = 0;
if (!this.maybeAbandon(sChunk)) sChunk.retransmit = true;
sChunk.acked = false;
this.flightSizeDecrease(sChunk);
loss = true;
}
}
}
}
if (this.fastRecoveryExit === void 0) {
if (done && cwndFullyUtilized) {
if (this.cwnd <= this.ssthresh) this.cwnd += Math.min(doneBytes, USERDATA_MAX_LENGTH);
else {
this.partialBytesAcked += doneBytes;
if (this.partialBytesAcked >= this.cwnd) {
this.partialBytesAcked -= this.cwnd;
this.cwnd += USERDATA_MAX_LENGTH;
}
}
}
if (loss) {
this.ssthresh = Math.max(Math.floor(this.cwnd / 2), 4 * USERDATA_MAX_LENGTH);
this.cwnd = this.ssthresh;
this.partialBytesAcked = 0;
this.fastRecoveryExit = this.sentQueue[this.sentQueue.length - 1].tsn;
this.fastRecoveryTransmit = true;
}
} else if (uint32Gte(chunk.cumulativeTsn, this.fastRecoveryExit)) this.fastRecoveryExit = void 0;
if (this.sentQueue.length === 0) this.timer3Cancel();
else if (done > 0) this.timer3Restart();
this.peerAdvertisedRwnd = chunk.advertisedRwnd;
this.updateAdvancedPeerAckPoint();
await this.onSackReceived();
await this.transmit();
}
receiveForwardTsnChunk(chunk) {
this.sackNeeded = true;
this.sackImmediate = true;
if (uint32Gte(this.lastReceivedTsn, chunk.cumulativeTsn)) return;
const isObsolete = (x) => uint32Gt(x, this.lastReceivedTsn);
this.lastReceivedTsn = chunk.cumulativeTsn;
this.sackMisOrdered = new Set([...this.sackMisOrdered].filter(isObsolete));
for (const tsn of [...this.sackMisOrdered].sort()) if (tsn === tsnPlusOne(this.lastReceivedTsn)) this.lastReceivedTsn = tsn;
else break;
this.sackDuplicates = this.sackDuplicates.filter(isObsolete);
this.sackMisOrdered = new Set([...this.sackMisOrdered].filter(isObsolete));
for (const [streamId, streamSeqNum] of chunk.streams) {
const inboundStream = this.getInboundStream(streamId);
inboundStream.streamSequenceNumber = uint16Add(streamSeqNum, 1);
for (const message of inboundStream.popMessages()) {
this.advertisedRwnd += message[2].length;
this.receive(...message);
}
}
Object.values(this.inboundStreams).forEach((inboundStream) => {
this.advertisedRwnd += inboundStream.pruneChunks(this.lastReceivedTsn);
});
}
updateRto(R) {
if (!this.srtt) {
this.rttvar = R / 2;
this.srtt = R;
} else {
this.rttvar = (1 - SCTP_RTO_BETA) * this.rttvar + SCTP_RTO_BETA * Math.abs(this.srtt - R);
this.srtt = (1 - SCTP_RTO_ALPHA) * this.srtt + SCTP_RTO_ALPHA * R;
}
this.rto = Math.max(SCTP_RTO_MIN, Math.min(this.srtt + 4 * this.rttvar, SCTP_RTO_MAX));
}
receive(streamId, ppId, data) {
this.onReceive.execute(streamId, ppId, data);
}
getInboundStream(streamId) {
if (!this.inboundStreams[streamId]) this.inboundStreams[streamId] = new InboundStream();
return this.inboundStreams[streamId];
}
markReceived(tsn) {
if (uint32Gte(this.lastReceivedTsn, tsn) || this.sackMisOrdered.has(tsn)) {
this.sackDuplicates.push(tsn);
return true;
}
this.sackMisOrdered.add(tsn);
for (const tsn2 of [...this.sackMisOrdered].sort()) if (tsn2 === tsnPlusOne(this.lastReceivedTsn)) this.lastReceivedTsn = tsn2;
else break;
const isObsolete = (x) => uint32Gt(x, this.lastReceivedTsn);
this.sackDuplicates = this.sackDuplicates.filter(isObsolete);
this.sackMisOrdered = new Set([...this.sackMisOrdered].filter(isObsolete));
return false;
}
send = async (streamId, ppId, userData, { expiry, maxRetransmits, ordered } = {
expiry: void 0,
maxRetransmits: void 0,
ordered: true
}) => {
const streamSeqNum = ordered ? this.outboundStreamSeq[streamId] || 0 : 0;
const fragments = Math.ceil(userData.length / USERDATA_MAX_LENGTH);
let pos = 0;
const chunks = [];
for (let fragment = 0; fragment < fragments; fragment++) {
const chunk = new DataChunk(0, void 0);
chunk.flags = 0;
if (!ordered) chunk.flags = SCTP_DATA_UNORDERED;
if (fragment === 0) chunk.flags |= SCTP_DATA_FIRST_FRAG;
if (fragment === fragments - 1) chunk.flags |= SCTP_DATA_LAST_FRAG;
chunk.tsn = this.localTsn;
chunk.streamId = streamId;
chunk.streamSeqNum = streamSeqNum;
chunk.protocol = ppId;
chunk.userData = userData.slice(pos, pos + USERDATA_MAX_LENGTH);
chunk.bookSize = chunk.userData.length;
chunk.expiry = expiry;
chunk.maxRetransmits = maxRetransmits;
pos += USERDATA_MAX_LENGTH;
this.localTsn = tsnPlusOne(this.localTsn);
chunks.push(chunk);
}
chunks.forEach((chunk) => {
this.outboundQueue.push(chunk);
});
if (ordered) this.outboundStreamSeq[streamId] = uint16Add(streamSeqNum, 1);
await this.transmit();
while (this.outboundQueue.length) await this.flush.asPromise();
};
async transmit() {
if (this.isStopped) return;
if (this.transmitting) {
this.transmitRequested = true;
return;
}
this.transmitting = true;
try {
do {
this.transmitRequested = false;
await this.transmitOnce();
} while (this.transmitRequested);
} finally {
this.transmitting = false;
}
}
async transmitOnce() {
if (this.isStopped) return;
if (this.forwardTsnChunk) {
await this.sendChunk(this.forwardTsnChunk).catch((err5) => {
log30("send forwardTsn failed", err5.message);
});
this.forwardTsnChunk = void 0;
if (!this.timer3Handle) this.timer3Start();
}
const burstSize = this.fastRecoveryExit != void 0 ? 2 * USERDATA_MAX_LENGTH : 4 * USERDATA_MAX_LENGTH;
const cwnd = Math.min(this.flightSize + burstSize, this.cwnd);
let retransmitEarliest = true;
for (const dataChunk of this.sentQueue) {
if (dataChunk.retransmit) {
if (this.fastRecoveryTransmit) this.fastRecoveryTransmit = false;
else if (this.flightSize >= cwnd) break;
this.flightSizeIncrease(dataChunk);
dataChunk.misses = 0;
dataChunk.retransmit = false;
dataChunk.sentCount++;
await this.sendChunk(dataChunk).catch((err5) => {
log30("send data failed", err5.message);
});
if (retransmitEarliest) this.timer3Restart();
}
retransmitEarliest = false;
}
while (this.outboundQueue.length > 0 && this.flightSize < cwnd && this.peerRwnd > 0) {
const chunk = this.outboundQueue.shift();
if (!chunk) break;
if (chunk.bookSize > this.peerRwnd && this.flightSize > 0) {
this.outboundQueue.unshift(chunk);
break;
}
this.sentQueue.push(chunk);
this.flightSizeIncrease(chunk);
chunk.sentCount++;
chunk.sentTime = Date.now() / 1e3;
await this.sendChunk(chunk).catch((err5) => {
log30("send data outboundQueue failed", err5.message);
});
if (!this.timer3Handle) this.timer3Start();
}
if (!this.outboundQueue.length) this.outboundQueue = [];
this.flush.execute();
}
async transmitReconfigRequest() {
if (this.reconfigQueue.length > 0 && this.associationState === 4 && !this.reconfigRequest) {
const uniqueStreams = [...new Set(this.reconfigQueue)];
const streams = uniqueStreams.slice(0, RECONFIG_MAX_STREAMS);
this.reconfigQueue = uniqueStreams.slice(RECONFIG_MAX_STREAMS);
const param = new OutgoingSSNResetRequestParam(this.reconfigRequestSeq, this.reconfigResponseSeq, tsnMinusOne(this.localTsn), streams);
this.reconfigRequestSeq = tsnPlusOne(this.reconfigRequestSeq);
this.reconfigRequest = param;
await this.sendReconfigParam(param);
this.timerReconfigHandleStart();
}
}
async sendReconfigParam(param) {
log30("sendReconfigParam", param);
const chunk = new ReconfigChunk();
chunk.params.push([param.type, param.bytes]);
await this.sendChunk(chunk).catch((err5) => {
log30("send reconfig failed", err5.message);
});
}
async sendResetRequest(streamId) {
log30("sendResetRequest", streamId);
const chunk = new DataChunk(0, void 0);
chunk.streamId = streamId;
this.outboundQueue.push(chunk);
if (!this.timer3Handle) await this.transmit();
}
flightSizeIncrease(chunk) {
this.flightSize += chunk.bookSize;
}
flightSizeDecrease(chunk) {
this.flightSize = Math.max(0, this.flightSize - chunk.bookSize);
}
/**t1 is wait for initAck or cookieAck */
timer1Start(chunk) {
if (this.timer1Handle) throw new Error();
this.timer1Chunk = chunk;
this.timer1Failures = 0;
this.timer1Handle = setTimeout(this.timer1Expired, this.rto * 1e3);
}
timer1Expired = () => {
if (this.isStopped) return;
this.timer1Failures++;
this.timer1Handle = void 0;
if (this.timer1Failures > SCTP_MAX_INIT_RETRANS) this.setState(1);
else {
setImmediate(() => {
if (this.isStopped) return;
this.sendChunk(this.timer1Chunk).catch((err5) => {
log30("send timer1 chunk failed", err5.message);
});
});
if (this.isStopped) return;
this.timer1Handle = setTimeout(this.timer1Expired, this.rto * 1e3);
}
};
timer1Cancel() {
if (this.timer1Handle) {
clearTimeout(this.timer1Handle);
this.timer1Handle = void 0;
this.timer1Chunk = void 0;
}
}
/**t2 is wait for shutdown */
t2Start(chunk) {
if (this.timer2Handle) throw new Error();
this.timer2Chunk = chunk;
this.timer2Failures = 0;
this.timer2Handle = setTimeout(this.timer2Expired, this.rto * 1e3);
}
timer2Expired = () => {
if (this.isStopped) return;
this.timer2Failures++;
this.timer2Handle = void 0;
if (this.timer2Failures > SCTP_MAX_ASSOCIATION_RETRANS) this.setState(1);
else {
setImmediate(() => {
if (this.isStopped) return;
this.sendChunk(this.timer2Chunk).catch((err5) => {
log30("send timer2Chunk failed", err5.message);
});
});
if (this.isStopped) return;
this.timer2Handle = setTimeout(this.timer2Expired, this.rto * 1e3);
}
};
timer2Cancel() {
if (this.timer2Handle) {
clearTimeout(this.timer2Handle);
this.timer2Handle = void 0;
this.timer2Chunk = void 0;
}
}
/**t3 is wait for data sack */
timer3Start() {
if (this.isStopped) return;
if (this.timer3Handle) throw new Error();
this.timer3Handle = setTimeout(this.timer3Expired, this.rto * 1e3);
}
timer3Restart() {
if (this.isStopped) return;
this.timer3Cancel();
this.timer3Handle = setTimeout(this.timer3Expired, this.rto * 1e3);
}
timer3Expired = () => {
if (this.isStopped) return;
this.timer3Handle = void 0;
this.sentQueue.forEach((chunk) => {
if (!this.maybeAbandon(chunk)) chunk.retransmit = true;
});
this.updateAdvancedPeerAckPoint();
this.fastRecoveryExit = void 0;
this.flightSize = 0;
this.partialBytesAcked = 0;
this.ssthresh = Math.max(Math.floor(this.cwnd / 2), 4 * USERDATA_MAX_LENGTH);
this.cwnd = USERDATA_MAX_LENGTH;
this.transmit();
};
timer3Cancel() {
if (this.timer3Handle) {
clearTimeout(this.timer3Handle);
this.timer3Handle = void 0;
}
}
/**Re-configuration Timer */
timerReconfigHandleStart() {
if (this.isStopped) return;
if (this.timerReconfigHandle) return;
log30("timerReconfigHandleStart", { rto: this.rto });
this.timerReconfigFailures = 0;
this.timerReconfigHandle = setTimeout(this.timerReconfigHandleExpired, this.rto * 1e3);
}
timerReconfigHandleExpired = async () => {
if (this.isStopped) return;
this.timerReconfigFailures++;
this.rto = Math.ceil(this.rto * 1.5);
if (this.timerReconfigFailures > SCTP_MAX_ASSOCIATION_RETRANS) {
log30("timerReconfigFailures", this.timerReconfigFailures);
this.setState(1);
this.timerReconfigHandle = void 0;
} else if (this.reconfigRequest) {
log30("timerReconfigHandleExpired", this.timerReconfigFailures, this.rto);
await this.sendReconfigParam(this.reconfigRequest);
if (this.isStopped) return;
this.timerReconfigHandle = setTimeout(this.timerReconfigHandleExpired, this.rto * 1e3);
}
};
timerReconfigCancel() {
if (this.timerReconfigHandle) {
log30("timerReconfigCancel");
clearTimeout(this.timerReconfigHandle);
this.timerReconfigHandle = void 0;
this.timerReconfigFailures = 0;
}
}
heartbeatStart() {
if (this.timerHeartbeatHandle || this.associationState !== 4) return;
this.timerHeartbeatHandle = setTimeout(this.timerHeartbeatExpired, (this.rto + this.heartbeatInterval) * 1e3);
}
heartbeatRestart() {
this.heartbeatCancel();
this.heartbeatStart();
}
heartbeatCancel() {
if (this.timerHeartbeatHandle) {
clearTimeout(this.timerHeartbeatHandle);
this.timerHeartbeatHandle = void 0;
}
}
timerHeartbeatExpired = async () => {
this.timerHeartbeatHandle = void 0;
if (this.associationState !== 4) return;
if (this.flightSize === 0 && this.outboundQueue.length === 0) {
const heartbeat = new HeartbeatChunk();
const heartbeatTime = Buffer.allocUnsafe(4);
heartbeatTime.writeUInt32BE(Math.floor(Date.now() / 1e3), 0);
heartbeat.params.push([1, heartbeatTime]);
await this.sendChunk(heartbeat).catch((err5) => {
log30("send heartbeat failed", err5.message);
});
}
this.heartbeatStart();
};
setHeartbeatInterval(interval) {
if (interval <= 0) throw new Error("heartbeat interval must be > 0");
this.heartbeatInterval = interval;
this.heartbeatRestart();
}
updateAdvancedPeerAckPoint() {
if (uint32Gt(this.lastSackedTsn, this.advancedPeerAckTsn)) this.advancedPeerAckTsn = this.lastSackedTsn;
let done = 0;
const streams = {};
while (this.sentQueue.length > 0 && this.sentQueue[0].abandoned) {
const chunk = this.sentQueue.shift();
this.advancedPeerAckTsn = chunk.tsn;
done++;
if (!(chunk.flags & SCTP_DATA_UNORDERED)) streams[chunk.streamId] = chunk.streamSeqNum;
}
if (!this.sentQueue.length) this.sentQueue = [];
if (done) {
this.forwardTsnChunk = new ForwardTsnChunk(0, void 0);
this.forwardTsnChunk.cumulativeTsn = this.advancedPeerAckTsn;
this.forwardTsnChunk.streams = Object.entries(streams).map(([k, v]) => [Number(k), v]);
}
}
maybeAbandon(chunk) {
if (chunk.abandoned) return true;
if (!(!!chunk.maxRetransmits && chunk.maxRetransmits < chunk.sentCount || !!chunk.expiry && chunk.expiry < Date.now() / 1e3)) return false;
const chunkPos = this.sentQueue.findIndex((v) => v.type === chunk.type);
for (let pos = chunkPos; pos >= 0; pos--) {
const oChunk = this.sentQueue[pos];
oChunk.abandoned = true;
oChunk.retransmit = false;
if (oChunk.flags & SCTP_DATA_LAST_FRAG) break;
}
for (let pos = chunkPos; pos < this.sentQueue.length; pos++) {
const oChunk = this.sentQueue[pos];
oChunk.abandoned = true;
oChunk.retransmit = false;
if (oChunk.flags & SCTP_DATA_LAST_FRAG) break;
}
return true;
}
static getCapabilities() {
return new RTCSctpCapabilities(65536);
}
setRemotePort(port) {
this.remotePort = port;
}
async start(remotePort) {
if (!this.started) {
this.started = true;
this.setConnectionState("connecting");
if (remotePort) this.setRemotePort(remotePort);
if (!this.isServer) await this.init();
}
}
async init() {
const init = new InitChunk();
init.initiateTag = this.localVerificationTag;
init.advertisedRwnd = this.advertisedRwnd;
init.outboundStreams = this._outboundStreamsCount;
init.inboundStreams = this._inboundStreamsMax;
init.initialTsn = this.localTsn;
this.setExtensions(init.params);
log30("send init", init);
try {
await this.sendChunk(init);
this.timer1Start(init);
this.setState(2);
} catch (error) {
log30("send init failed", error.message);
}
}
setExtensions(params) {
const extensions = [];
if (this.localPartialReliability) {
params.push([SCTP_PRSCTP_SUPPORTED, Buffer.from("")]);
extensions.push(ForwardTsnChunk.type);
}
extensions.push(ReConfigChunk.type);
params.push([SCTP_SUPPORTED_CHUNK_EXT, Buffer.from(extensions)]);
}
async sendChunk(chunk) {
if (this.state === "closed") return;
if (this.remotePort === void 0) throw new Error("invalid remote port");
const packet = serializePacket(this.localPort, this.remotePort, this.remoteVerificationTag, chunk);
await this.transport.send(packet);
}
setState(state) {
if (state != this.associationState) this.associationState = state;
if (state === 4) {
this.isStopping = false;
this.isClosed = false;
this.setConnectionState("connected");
this.heartbeatStart();
} else if (state === 1) {
this.isClosed = true;
this.timer1Cancel();
this.timer2Cancel();
this.timer3Cancel();
this.timerReconfigCancel();
this.heartbeatCancel();
if (this.sackTimeout) {
clearTimeout(this.sackTimeout);
this.sackTimeout = void 0;
}
this.setConnectionState("closed");
this.removeAllListeners();
}
}
setConnectionState(state) {
this.state = state;
log30("setConnectionState", state);
this.stateChanged[state].execute();
}
async stop() {
if (this.isStopped) {
this.setState(1);
return;
}
this.isStopping = true;
this.transport.onData = void 0;
if (this.sackTimeout) {
clearTimeout(this.sackTimeout);
this.sackTimeout = void 0;
}
if (this.associationState !== 1) await this.abort();
this.setState(1);
clearTimeout(this.timer1Handle);
clearTimeout(this.timer2Handle);
clearTimeout(this.timer3Handle);
clearTimeout(this.timerReconfigHandle);
clearTimeout(this.timerHeartbeatHandle);
clearTimeout(this.sackTimeout);
}
async abort() {
const abort = new AbortChunk();
await this.sendChunk(abort).catch((err5) => {
log30("send abort failed", err5.message);
});
}
removeAllListeners() {
Object.values(this.stateChanged).forEach((v) => v.allUnsubscribe());
}
};
var InboundStream = class {
reassembly = [];
streamSequenceNumber = 0;
constructor() {}
addChunk(chunk) {
if (this.reassembly.length === 0 || uint32Gt(chunk.tsn, this.reassembly[this.reassembly.length - 1].tsn)) {
this.reassembly.push(chunk);
return;
}
for (const [i, v] of enumerate3(this.reassembly)) {
if (v.tsn === chunk.tsn) throw new Error("duplicate chunk in reassembly");
if (uint32Gt(v.tsn, chunk.tsn)) {
this.reassembly.splice(i, 0, chunk);
break;
}
}
}
*popMessages() {
let pos = 0;
let startPos;
let expectedTsn;
let ordered;
while (pos < this.reassembly.length) {
const chunk = this.reassembly[pos];
if (startPos === void 0) {
ordered = !(chunk.flags & SCTP_DATA_UNORDERED);
if (!(chunk.flags & SCTP_DATA_FIRST_FRAG)) {
if (ordered) break;
else {
pos++;
continue;
}
}
if (ordered && uint16Gt(chunk.streamSeqNum, this.streamSequenceNumber)) break;
expectedTsn = chunk.tsn;
startPos = pos;
} else if (chunk.tsn !== expectedTsn) {
if (ordered) break;
else {
startPos = void 0;
pos++;
continue;
}
}
if (chunk.flags & SCTP_DATA_LAST_FRAG) {
const arr = this.reassembly.slice(startPos, pos + 1).map((c) => c.userData).reduce((acc, cur) => {
acc.push(cur);
acc.push(Buffer.from(""));
return acc;
}, []);
arr.pop();
const userData = Buffer.concat(arr);
this.reassembly = [...this.reassembly.slice(0, startPos), ...this.reassembly.slice(pos + 1)];
if (ordered && chunk.streamSeqNum === this.streamSequenceNumber) this.streamSequenceNumber = uint16Add(this.streamSequenceNumber, 1);
pos = startPos;
yield [
chunk.streamId,
chunk.protocol,
userData
];
} else pos++;
expectedTsn = tsnPlusOne(expectedTsn);
}
}
pruneChunks(tsn) {
let pos = -1, size = 0;
for (const [i, chunk] of this.reassembly.entries()) if (uint32Gte(tsn, chunk.tsn)) {
pos = i;
size += chunk.userData.length;
} else break;
this.reassembly = this.reassembly.slice(pos + 1);
return size;
}
};
var RTCSctpCapabilities = class {
constructor(maxMessageSize) {
this.maxMessageSize = maxMessageSize;
}
};
function tsnMinusOne(a) {
return (a - 1) % SCTP_TSN_MODULO;
}
function tsnPlusOne(a) {
return (a + 1) % SCTP_TSN_MODULO;
}
var log31 = debug("werift:packages/webrtc/src/transport/sctp.ts");
var DEFAULT_MAX_MESSAGE_SIZE = 65536;
var RTCSctpTransport = class _RTCSctpTransport {
constructor(port = 5e3, maxMessageSize = DEFAULT_MAX_MESSAGE_SIZE) {
this.port = port;
this.maxMessageSize = maxMessageSize;
}
dtlsTransport;
sctp;
onDataChannel = new Event2();
id = randomUUID$1().toString();
mid;
mLineIndex;
bundled = false;
dataChannels = {};
remoteMaxMessageSize = DEFAULT_MAX_MESSAGE_SIZE;
dataChannelQueue = [];
dataChannelId;
eventDisposer = [];
get transport() {
return this.dtlsTransport;
}
setDtlsTransport(dtlsTransport) {
if (this.dtlsTransport && this.dtlsTransport.id === dtlsTransport.id) return;
this.eventDisposer.forEach((dispose) => dispose());
this.dtlsTransport = dtlsTransport;
this.sctp = new SCTP(new BridgeDtls(this.dtlsTransport), this.port);
this.eventDisposer = [...[
this.sctp.onReceive.subscribe(this.datachannelReceive),
this.sctp.onReconfigStreams.subscribe((ids) => {
ids.forEach((id) => {
const dc = this.dataChannels[id];
if (!dc) return;
dc.setReadyState("closing");
dc.setReadyState("closed");
delete this.dataChannels[id];
});
}),
this.sctp.stateChanged.connected.subscribe(() => {
Object.values(this.dataChannels).forEach((channel) => {
if (channel.negotiated && channel.readyState !== "open") channel.setReadyState("open");
});
this.dataChannelFlush();
}),
this.sctp.stateChanged.closed.subscribe(() => {
Object.values(this.dataChannels).forEach((dc) => {
dc.setReadyState("closed");
});
this.dataChannels = {};
}),
this.dtlsTransport.onStateChange.subscribe((state) => {
if (state === "closed") this.sctp.setState(1);
})
].map((e) => e.unSubscribe), () => this.sctp.onSackReceived = async () => {}];
this.sctp.onSackReceived = async () => {
await this.dataChannelFlush();
};
}
get isServer() {
return this.dtlsTransport.iceTransport.role !== "controlling";
}
channelByLabel(label) {
return Object.values(this.dataChannels).find((d) => d.label === label);
}
datachannelReceive = async (streamId, ppId, data) => {
if (ppId === WEBRTC_DCEP && data.length > 0) {
log31("DCEP", streamId, ppId, data);
switch (data[0]) {
case DATA_CHANNEL_OPEN:
{
if (data.length < 12) {
log31("DATA_CHANNEL_OPEN data.length not enough");
return;
}
if (!Object.keys(this.dataChannels).includes(streamId.toString())) {
const channelType = data.readUInt8(1);
const reliability = data.readUInt32BE(4);
const labelLength = data.readUInt16BE(8);
const protocolLength = data.readUInt16BE(10);
let pos = 12;
const label = data.slice(pos, pos + labelLength).toString("utf8");
pos += labelLength;
const protocol = data.slice(pos, pos + protocolLength).toString("utf8");
log31("DATA_CHANNEL_OPEN", {
channelType,
reliability,
streamId,
label,
protocol
});
const maxRetransmits = (channelType & 3) === 1 ? reliability : void 0;
const maxPacketLifeTime = (channelType & 3) === 2 ? reliability : void 0;
const parameters = new RTCDataChannelParameters({
label,
ordered: (channelType & 128) === 0,
maxPacketLifeTime,
maxRetransmits,
protocol,
id: streamId
});
const channel2 = new RTCDataChannel(this, parameters, false);
channel2.isCreatedByRemote = true;
this.dataChannels[streamId] = channel2;
this.onDataChannel.execute(channel2);
channel2.setReadyState("open");
} else log31("datachannel already opened", "retransmit ack");
const channel = this.dataChannels[streamId];
const ack = Buffer.allocUnsafe(1);
ack.writeUInt8(DATA_CHANNEL_ACK, 0);
this.dataChannelQueue.push([
channel,
WEBRTC_DCEP,
ack
]);
await this.dataChannelFlush();
}
break;
case DATA_CHANNEL_ACK: {
log31("DATA_CHANNEL_ACK", streamId, ppId);
const channel = this.dataChannels[streamId];
if (!channel) throw new Error("channel not found");
channel.setReadyState("open");
}
}
} else {
const channel = this.dataChannels[streamId];
if (channel) {
const msg = (() => {
switch (ppId) {
case WEBRTC_STRING: return data.toString("utf8");
case WEBRTC_STRING_EMPTY: return "";
case WEBRTC_BINARY: return data;
case WEBRTC_BINARY_EMPTY: return Buffer.from([]);
default: throw new Error();
}
})();
channel.messagesReceived++;
channel.bytesReceived += data.length;
channel.onMessage.execute(msg);
channel.emit("message", { data: msg });
if (channel.onmessage) channel.onmessage({ data: msg });
}
}
};
dataChannelAddNegotiated(channel) {
if (channel.id == void 0) throw new Error();
if (this.dataChannels[channel.id]) throw new Error();
this.dataChannels[channel.id] = channel;
if (this.sctp.associationState === 4) channel.setReadyState("open");
}
dataChannelOpen(channel) {
if (channel.id !== void 0) {
if (this.dataChannels[channel.id]) throw new Error(`Data channel with ID ${channel.id} already registered`);
this.dataChannels[channel.id] = channel;
}
let channelType = DATA_CHANNEL_RELIABLE;
const priority = 0;
let reliability = 0;
if (!channel.ordered) channelType = 128;
if (channel.maxRetransmits !== null) {
channelType = 1;
reliability = channel.maxRetransmits;
} else if (channel.maxPacketLifeTime !== null) {
channelType = 2;
reliability = channel.maxPacketLifeTime;
}
const data = Buffer.allocUnsafe(12);
data.writeUInt8(DATA_CHANNEL_OPEN, 0);
data.writeUInt8(channelType, 1);
data.writeUInt16BE(priority, 2);
data.writeUInt32BE(reliability, 4);
data.writeUInt16BE(channel.label.length, 8);
data.writeUInt16BE(channel.protocol.length, 10);
const send = Buffer.concat([
data,
Buffer.from(channel.label, "utf8"),
Buffer.from(channel.protocol, "utf8")
]);
this.dataChannelQueue.push([
channel,
WEBRTC_DCEP,
send
]);
this.dataChannelFlush();
}
async dataChannelFlush() {
if (this.sctp.associationState != 4) return;
while (this.dataChannelQueue.length > 0) {
const [channel, protocol, userData] = this.dataChannelQueue.shift();
let streamId = channel.id;
if (streamId === void 0) {
streamId = this.dataChannelId;
while (Object.keys(this.dataChannels).includes(streamId.toString())) streamId += 2;
this.dataChannels[streamId] = channel;
channel.setId(streamId);
}
if (protocol === WEBRTC_DCEP) await this.sctp.send(streamId, protocol, userData, { ordered: true });
else {
const expiry = channel.maxPacketLifeTime !== null ? Date.now() + channel.maxPacketLifeTime / 1e3 : void 0;
await this.sctp.send(streamId, protocol, userData, {
expiry,
maxRetransmits: channel.maxRetransmits ?? void 0,
ordered: channel.ordered
});
channel.addBufferedAmount(-userData.length);
}
}
this.dataChannelQueue = [];
}
assertSendableMessageSize(size) {
if (this.remoteMaxMessageSize !== 0 && size > this.remoteMaxMessageSize) throw new Error(`max-message-size exceeded: ${size} > ${this.remoteMaxMessageSize}`);
}
datachannelSend = (channel, data) => {
const userData = Buffer.isBuffer(data) ? data : Buffer.from(data);
const size = getDataChannelMessageSize(data);
this.assertSendableMessageSize(size);
channel.addBufferedAmount(size);
this.dataChannelQueue.push(typeof data === "string" ? [
channel,
WEBRTC_STRING,
userData
] : [
channel,
WEBRTC_BINARY,
userData
]);
if (this.sctp.associationState !== 4) log31("sctp not established", this.sctp.associationState);
this.dataChannelFlush();
return size;
};
getCapabilities() {
return _RTCSctpTransport.getCapabilities(this.maxMessageSize);
}
static getCapabilities(maxMessageSize = DEFAULT_MAX_MESSAGE_SIZE) {
return new RTCSctpCapabilities2(maxMessageSize);
}
setRemoteMaxMessageSize(maxMessageSize) {
this.remoteMaxMessageSize = maxMessageSize ?? 65536;
}
setRemotePort(port) {
this.sctp.setRemotePort(port);
}
async start(remotePort) {
if (this.isServer) this.dataChannelId = 0;
else this.dataChannelId = 1;
this.sctp.isServer = this.isServer;
await this.sctp.start(remotePort);
}
async stop() {
this.dtlsTransport.dataReceiver = () => {};
await this.sctp.stop();
}
dataChannelClose(channel) {
if (!["closing", "closed"].includes(channel.readyState)) {
channel.setReadyState("closing");
if (this.sctp.associationState === 4) {
if (!this.sctp.reconfigQueue.includes(channel.id)) this.sctp.reconfigQueue.push(channel.id);
if (this.sctp.reconfigQueue.length === 1) this.sctp.transmitReconfigRequest();
} else {
this.dataChannelQueue = this.dataChannelQueue.filter((queueItem) => queueItem[0].id !== channel.id);
this.sctp.reconfigQueue = this.sctp.reconfigQueue.filter((streamId) => streamId !== channel.id);
if (channel.id !== void 0) delete this.dataChannels[channel.id];
channel.setReadyState("closed");
}
}
}
};
var RTCSctpCapabilities2 = class {
constructor(maxMessageSize) {
this.maxMessageSize = maxMessageSize;
}
};
var BridgeDtls = class {
constructor(dtls) {
this.dtls = dtls;
}
set onData(onData) {
this.dtls.dataReceiver = onData;
}
send = (data) => {
return this.dtls.sendData(data);
};
close() {}
};
var SessionDescription = class _SessionDescription {
version = 0;
origin;
name = "-";
time = "0 0";
host;
group = [];
extMapAllowMixed = true;
msidSemantic = [];
media = [];
type;
dtlsRole;
iceOptions;
iceLite;
icePassword;
iceUsernameFragment;
dtlsFingerprints = [];
cachedJson;
static parse(sdp) {
const [sessionLines, mediaGroups] = groupLines(sdp);
const session = new _SessionDescription();
sessionLines.forEach((line) => {
if (line.startsWith("v=")) session.version = Number.parseInt(line.slice(2), 10);
else if (line.startsWith("o=")) session.origin = line.slice(2);
else if (line.startsWith("s=")) session.name = line.slice(2);
else if (line.startsWith("c=")) session.host = ipAddressFromSdp(line.slice(2));
else if (line.startsWith("t=")) session.time = line.slice(2);
else if (line.startsWith("a=")) {
const [attr, value] = parseAttr(line);
switch (attr) {
case "fingerprint":
{
const [algorithm, fingerprint2] = value?.split(" ") || [];
session.dtlsFingerprints.push(new RTCDtlsFingerprint(algorithm, fingerprint2));
}
break;
case "ice-lite":
session.iceLite = true;
break;
case "ice-options":
session.iceOptions = value;
break;
case "ice-pwd":
session.icePassword = value;
break;
case "ice-ufrag":
session.iceUsernameFragment = value;
break;
case "group":
parseGroup(session.group, value);
break;
case "msid-semantic":
parseGroup(session.msidSemantic, value);
break;
case "setup":
session.dtlsRole = DTLS_SETUP_ROLE[value];
break;
case "extmap-allow-mixed": session.extMapAllowMixed = true;
}
}
});
const bundle = session.group.find((g) => g.semantic === "BUNDLE");
mediaGroups.forEach((mediaLines) => {
const m = mediaLines[0].match(/^m=([^ ]+) ([0-9]+) ([A-Z/]+) (.+)/);
if (!m) throw new Error("m line not found");
const kind = m[1];
const fmt = m[4].split(" ");
const fmtInt = ["audio", "video"].includes(kind) ? fmt.map((v) => Number(v)) : void 0;
const currentMedia = new MediaDescription(kind, Number.parseInt(m[2]), m[3], fmtInt || fmt);
currentMedia.dtlsParams = new RTCDtlsParameters([...session.dtlsFingerprints], session.dtlsRole);
currentMedia.iceParams = new RTCIceParameters({
iceLite: session.iceLite,
usernameFragment: session.iceUsernameFragment,
password: session.icePassword
});
currentMedia.iceOptions = session.iceOptions;
session.media.push(currentMedia);
mediaLines.slice(1).forEach((line) => {
if (line.startsWith("c=")) currentMedia.host = ipAddressFromSdp(line.slice(2));
else if (line.startsWith("a=")) {
const [attr, value] = parseAttr(line);
switch (attr) {
case "candidate":
if (!value) throw new Error();
currentMedia.iceCandidates.push(candidateFromSdp(value));
break;
case "end-of-candidates":
currentMedia.iceCandidatesComplete = true;
break;
case "extmap":
{
let [extId, extUri] = value.split(" ");
if (extId.includes("/")) [extId] = extId.split("/");
currentMedia.rtp.headerExtensions.push(new RTCRtpHeaderExtensionParameters({
id: Number.parseInt(extId),
uri: extUri
}));
}
break;
case "fingerprint":
{
if (!value) throw new Error();
const [algorithm, fingerprint2] = value.split(" ");
currentMedia.dtlsParams?.fingerprints.push(new RTCDtlsFingerprint(algorithm, fingerprint2));
}
break;
case "ice-options":
currentMedia.iceOptions = value;
break;
case "ice-pwd":
currentMedia.iceParams.password = value;
break;
case "ice-ufrag":
currentMedia.iceParams.usernameFragment = value;
break;
case "ice-lite":
currentMedia.iceParams.iceLite = true;
break;
case "max-message-size":
currentMedia.sctpCapabilities = new RTCSctpCapabilities2(Number.parseInt(value, 10));
break;
case "mid":
currentMedia.rtp.muxId = value;
break;
case "msid":
currentMedia.msids.push(value);
break;
case "rtcp":
{
const [port, rest] = divide(value, " ");
currentMedia.rtcpPort = Number.parseInt(port);
currentMedia.rtcpHost = ipAddressFromSdp(rest);
}
break;
case "rtcp-mux":
currentMedia.rtcpMux = true;
break;
case "setup":
currentMedia.dtlsParams.role = DTLS_SETUP_ROLE[value];
break;
case "recvonly":
case "sendonly":
case "sendrecv":
case "inactive":
currentMedia.direction = attr;
break;
case "rtpmap":
{
const [formatId, formatDesc] = divide(value, " ");
const [type, clock, channel] = formatDesc.split("/");
let channels;
if (currentMedia.kind === "audio") channels = channel ? Number.parseInt(channel) : 1;
const codec = new RTCRtpCodecParameters({
mimeType: currentMedia.kind + "/" + type,
channels,
clockRate: Number.parseInt(clock),
payloadType: Number.parseInt(formatId)
});
currentMedia.rtp.codecs.push(codec);
}
break;
case "sctpmap":
{
if (!value) throw new Error();
const [formatId, formatDesc] = divide(value, " ");
currentMedia.sctpMap[Number.parseInt(formatId)] = formatDesc;
currentMedia.sctpPort = Number.parseInt(formatId);
}
break;
case "sctp-port":
if (!value) throw new Error();
currentMedia.sctpPort = Number.parseInt(value);
break;
case "ssrc":
{
const [ssrcStr, ssrcDesc] = divide(value, " ");
const ssrc = Number.parseInt(ssrcStr);
const [ssrcAttr, ssrcValue] = divide(ssrcDesc, ":");
let ssrcInfo = currentMedia.ssrc.find((v) => v.ssrc === ssrc);
if (!ssrcInfo) {
ssrcInfo = new SsrcDescription({ ssrc });
currentMedia.ssrc.push(ssrcInfo);
}
if (SSRC_INFO_ATTRS.includes(ssrcAttr)) ssrcInfo[ssrcAttr] = ssrcValue;
}
break;
case "ssrc-group":
parseGroup(currentMedia.ssrcGroup, value);
break;
case "rid": {
const [rid, direction] = divide(value, " ");
currentMedia.simulcastParameters.push(new RTCRtpSimulcastParameters({
rid,
direction
}));
}
}
}
});
if (!currentMedia.iceParams.usernameFragment || !currentMedia.iceParams.password) {
if (currentMedia.rtp.muxId && bundle && bundle.items.includes(currentMedia.rtp.muxId)) for (let i = 0; i < bundle.items.length; i++) {
if (!bundle.items.includes(i.toString())) continue;
const check = session.media[i];
if (check.iceParams?.usernameFragment && check.iceParams.password) {
currentMedia.iceParams = { ...check.iceParams };
break;
}
}
}
if (!currentMedia.dtlsParams.role) currentMedia.dtlsParams = void 0;
const findCodec = (pt) => currentMedia.rtp.codecs.find((v) => v.payloadType === pt);
mediaLines.slice(1).forEach((line) => {
if (line.startsWith("a=")) {
const [attr, value] = parseAttr(line);
if (attr === "fmtp") {
const [formatId, formatDesc] = divide(value, " ");
const codec = findCodec(Number(formatId));
codec.parameters = formatDesc;
} else if (attr === "rtcp-fb") {
const [payloadType, feedbackType, feedbackParam] = value.split(" ");
currentMedia.rtp.codecs.forEach((codec) => {
if (["*", codec.payloadType.toString()].includes(payloadType)) codec.rtcpFeedback.push(new RTCRtcpFeedback({
type: feedbackType,
parameter: feedbackParam
}));
});
}
}
});
});
return session;
}
webrtcTrackId(media) {
if (media.msid?.includes(" ")) {
const bits = media.msid.split(" ");
for (const group of this.msidSemantic) if (group.semantic === "WMS" && (group.items.includes(bits[0]) || group.items.includes("*"))) return bits[1];
}
}
get string() {
const lines = [
`v=${this.version}`,
`o=${this.origin}`,
`s=${this.name}`
];
if (this.host) lines.push(`c=${ipAddressToSdp(this.host)}`);
lines.push(`t=${this.time}`);
this.group.forEach((group) => lines.push(`a=group:${group.str}`));
if (this.extMapAllowMixed) lines.push(`a=extmap-allow-mixed`);
this.msidSemantic.forEach((group) => lines.push(`a=msid-semantic:${group.str}`));
const media = this.media.map((m) => m.toString()).join("");
return lines.join("\r\n") + "\r\n" + media;
}
toJSON() {
const sdp = this.string;
if (!this.cachedJson || this.cachedJson.sdp !== sdp || this.cachedJson.type !== this.type) this.cachedJson = new RTCSessionDescription(sdp, this.type);
return this.cachedJson;
}
toSdp() {
return {
type: this.type,
sdp: this.string
};
}
};
var MediaDescription = class {
constructor(kind, port, profile, fmt) {
this.kind = kind;
this.port = port;
this.profile = profile;
this.fmt = fmt;
}
host;
direction;
msids = [];
rtcpPort;
rtcpHost;
rtcpMux = false;
ssrc = [];
ssrcGroup = [];
rtp = {
codecs: [],
headerExtensions: []
};
sctpCapabilities;
sctpMap = {};
sctpPort;
dtlsParams;
iceParams;
iceCandidates = [];
iceCandidatesComplete = false;
iceOptions;
simulcastParameters = [];
get msid() {
return this.msids[0];
}
set msid(value) {
this.msids = value ? [value] : [];
}
toString() {
const lines = [];
lines.push(`m=${this.kind} ${this.port} ${this.profile} ${this.fmt.map((v) => v.toString()).join(" ")}`);
if (this.host) lines.push(`c=${ipAddressToSdp(this.host)}`);
this.iceCandidates.forEach((candidate) => {
lines.push(`a=candidate:${candidateToSdp(candidate)}`);
});
if (this.iceCandidatesComplete) lines.push("a=end-of-candidates");
if (this.iceParams?.usernameFragment) lines.push(`a=ice-ufrag:${this.iceParams.usernameFragment}`);
if (this.iceParams?.password) lines.push(`a=ice-pwd:${this.iceParams.password}`);
if (this.iceParams?.iceLite) lines.push(`a=ice-lite`);
if (this.iceOptions) lines.push(`a=ice-options:${this.iceOptions}`);
if (this.dtlsParams) {
this.dtlsParams.fingerprints.forEach((fingerprint2) => {
lines.push(`a=fingerprint:${fingerprint2.algorithm} ${fingerprint2.value}`);
});
lines.push(`a=setup:${DTLS_ROLE_SETUP[this.dtlsParams.role]}`);
}
if (this.direction) lines.push(`a=${this.direction}`);
if (this.rtp.muxId) lines.push(`a=mid:${this.rtp.muxId}`);
this.msids.forEach((msid) => lines.push(`a=msid:${msid}`));
if (this.rtcpPort && this.rtcpHost) {
lines.push(`a=rtcp:${this.rtcpPort} ${ipAddressToSdp(this.rtcpHost)}`);
if (this.rtcpMux) lines.push("a=rtcp-mux");
}
this.ssrcGroup.forEach((group) => {
lines.push(`a=ssrc-group:${group.str}`);
});
this.ssrc.forEach((ssrcInfo) => {
SSRC_INFO_ATTRS.forEach((ssrcAttr) => {
const ssrcValue = ssrcInfo[ssrcAttr];
if (ssrcValue !== void 0) lines.push(`a=ssrc:${ssrcInfo.ssrc} ${ssrcAttr}:${ssrcValue}`);
});
});
this.rtp.codecs.forEach((codec) => {
lines.push(`a=rtpmap:${codec.payloadType} ${codec.str}`);
codec.rtcpFeedback.forEach((feedback) => {
let value = feedback.type;
if (feedback.parameter) value += ` ${feedback.parameter}`;
lines.push(`a=rtcp-fb:${codec.payloadType} ${value}`);
});
if (codec.parameters) lines.push(`a=fmtp:${codec.payloadType} ${codec.parameters}`);
});
Object.keys(this.sctpMap).forEach((k) => {
const v = this.sctpMap[Number(k)];
lines.push(`a=sctpmap:${k} ${v}`);
});
if (this.sctpPort) lines.push(`a=sctp-port:${this.sctpPort}`);
if (this.sctpCapabilities) lines.push(`a=max-message-size:${this.sctpCapabilities.maxMessageSize}`);
this.rtp.headerExtensions.forEach((extension) => lines.push(`a=extmap:${extension.id} ${extension.uri}`));
if (this.simulcastParameters.length) {
this.simulcastParameters.forEach((param) => {
lines.push(`a=rid:${param.rid} ${param.direction}`);
});
let line = `a=simulcast:`;
const recv = this.simulcastParameters.filter((v) => v.direction === "recv");
if (recv.length) line += `recv ${recv.map((v) => v.rid).join(";")} `;
const send = this.simulcastParameters.filter((v) => v.direction === "send");
if (send.length) line += `send ${send.map((v) => v.rid).join(";")}`;
lines.push(line);
}
return lines.join("\r\n") + "\r\n";
}
};
var GroupDescription = class {
constructor(semantic, items) {
this.semantic = semantic;
this.items = items;
}
get str() {
return `${this.semantic} ${this.items.join(" ")}`;
}
};
function ipAddressFromSdp(sdp) {
const m = sdp.match(/^IN (IP4|IP6) ([^ ]+)$/);
if (!m) throw new Error("exception");
return m[2];
}
function ipAddressToSdp(addr) {
return `IN IP${isIPv4$1(addr) ? 4 : 6} ${addr}`;
}
function candidateToSdp(c) {
let sdp = `${c.foundation} ${c.component} ${c.protocol} ${c.priority} ${c.ip} ${c.port} typ ${c.type}`;
if (c.relatedAddress != void 0) sdp += ` raddr ${c.relatedAddress}`;
if (c.relatedPort != void 0) sdp += ` rport ${c.relatedPort}`;
if (c.tcpType != void 0) sdp += ` tcptype ${c.tcpType}`;
if (c.generation != void 0) sdp += ` generation ${c.generation}`;
if (c.ufrag != void 0) sdp += ` ufrag ${c.ufrag}`;
return sdp;
}
function groupLines(sdp) {
const session = [];
const media = [];
let lines = sdp.split("\r\n");
if (lines.length === 1) lines = sdp.split("\n");
lines.forEach((line) => {
if (line.startsWith("m=")) media.push([line]);
else if (media.length > 0) media[media.length - 1].push(line);
else session.push(line);
});
return [session, media];
}
function parseAttr(line) {
if (line.includes(":")) {
const bits = divide(line.slice(2), ":");
return [bits[0], bits[1]];
} else return [line.slice(2), void 0];
}
function parseGroup(dest, value, type = (v) => v.toString()) {
const bits = value.split(" ");
if (bits.length > 0) dest.push(new GroupDescription(bits[0], bits.slice(1).map(type)));
}
function candidateFromSdp(sdp) {
return candidateFromIce(Candidate.fromSdp(sdp));
}
var RTCSessionDescription = class {
sdp;
type;
constructor(sdp, type) {
Object.defineProperties(this, {
sdp: {
configurable: true,
enumerable: true,
value: sdp,
writable: false
},
type: {
configurable: true,
enumerable: true,
value: type,
writable: false
}
});
}
static isThis(o) {
if (typeof o?.sdp === "string") return true;
}
toSdp() {
return {
sdp: this.sdp,
type: this.type
};
}
};
function addSDPHeader(type, description) {
description.origin = `- ${randomBytes$1(8).readBigUInt64BE(0).toString().slice(0, 8)} 0 IN IP4 0.0.0.0`;
description.msidSemantic.push(new GroupDescription("WMS", ["*"]));
description.type = type;
}
function codecParametersFromString(str) {
const parameters = {};
str.split(";").forEach((param) => {
if (param.includes("=")) {
const [k, v] = divide(param, "=");
if (FMTP_INT_PARAMETERS.includes(k)) parameters[k] = Number(v);
else parameters[k] = v;
} else if (param.includes(":")) {
const [k, v] = param.split(":");
parameters[k] = Number.isNaN(Number(v)) ? v : Number(v);
} else parameters[param] = void 0;
});
return parameters;
}
function codecParametersToString(parameters, joint = "=") {
const params = Object.entries(parameters).map(([k, v]) => {
if (v) return `${k}${joint}${v}`;
else return k;
});
if (params.length > 0) return params.join(";");
}
var SsrcDescription = class {
ssrc;
cname;
msid;
msLabel;
label;
constructor(props) {
Object.assign(this, props);
}
};
var log32 = debug("werift:packages/webrtc/src/media/rtpReceiver.ts");
var RTCRtpReceiver = class {
constructor(config, kind, rtcpSsrc) {
this.config = config;
this.kind = kind;
this.rtcpSsrc = rtcpSsrc;
this.defaultTrack = new MediaStreamTrack({
kind,
remote: true
});
this.onPacketLost.subscribe((nack) => {
this.nackCountBySsrc[nack.mediaSourceSsrc] = (this.nackCountBySsrc[nack.mediaSourceSsrc] ?? 0) + 1;
});
}
codecs = {};
defaultTrack;
get codecArray() {
return Object.values(this.codecs).sort((a, b) => a.payloadType - b.payloadType);
}
ssrcByRtx = {};
nack = new NackHandler(this);
audioRedHandler = new RedHandler();
type = "receiver";
uuid = randomUUID$1().toString();
tracks = [];
trackBySSRC = {};
trackByRID = {};
/**last sender Report Timestamp
* compactNtp
*/
lastSRtimestamp = {};
/**seconds */
receiveLastSRTimestamp = {};
onPacketLost = this.nack.onPacketLost;
onRtcp = new Event2();
dtlsTransport;
sdesMid;
latestRid;
latestRepairedRid;
receiverTWCC;
stopped = false;
remoteStreamId;
remoteStreamIds = [];
remoteTrackId;
rtcpRunning = false;
rtcpCancel = new AbortController();
remoteStreams = {};
senderReportsReceivedBySsrc = {};
remoteTimestampsBySsrc = {};
remotePacketCountBySsrc = {};
remoteOctetCountBySsrc = {};
nackCountBySsrc = {};
pliCountBySsrc = {};
get transport() {
return this.dtlsTransport ?? null;
}
setDtlsTransport(dtls) {
this.dtlsTransport = dtls;
}
get track() {
return this.tracks[0] ?? this.defaultTrack;
}
get nackEnabled() {
return this.codecArray[0]?.rtcpFeedback.find((f) => f.type === "nack");
}
get twccEnabled() {
return this.codecArray[0]?.rtcpFeedback.find((f) => f.type === useTWCC().type);
}
get pliEnabled() {
return this.codecArray[0]?.rtcpFeedback.find((f) => f.type === usePLI().type);
}
prepareReceive(params) {
params.codecs.forEach((c) => {
this.codecs[c.payloadType] = c;
});
params.encodings.forEach((e) => {
if (e.rtx) this.ssrcByRtx[e.rtx.ssrc] = e.ssrc;
});
}
/**
* setup TWCC if supported
*/
setupTWCC(mediaSourceSsrc) {
if (this.twccEnabled && !this.receiverTWCC) this.receiverTWCC = new ReceiverTWCC(this.dtlsTransport, this.rtcpSsrc, mediaSourceSsrc);
}
addTrack(track) {
if (this.tracks.find((t) => {
if (t.rid) return t.rid === track.rid;
if (t.ssrc) return t.ssrc === track.ssrc;
})) return false;
this.tracks.push(track);
if (track.ssrc) this.trackBySSRC[track.ssrc] = track;
if (track.rid) this.trackByRID[track.rid] = track;
return true;
}
stop() {
this.stopped = true;
this.rtcpRunning = false;
this.rtcpCancel.abort();
if (this.receiverTWCC) this.receiverTWCC.twccRunning = false;
this.nack.close();
}
async runRtcp() {
if (this.rtcpRunning || this.stopped) return;
this.rtcpRunning = true;
try {
while (this.rtcpRunning) {
await setTimeout$2(500 + Math.random() * 1e3, void 0, { signal: this.rtcpCancel.signal });
const reports = Object.entries(this.remoteStreams).map(([ssrc, stream]) => {
let lastSRtimestamp = 0, delaySinceLastSR = 0;
if (this.lastSRtimestamp[ssrc]) {
lastSRtimestamp = this.lastSRtimestamp[ssrc];
const delaySeconds = timestampSeconds() - this.receiveLastSRTimestamp[ssrc];
if (delaySeconds > 0 && delaySeconds < 65536) delaySinceLastSR = int(delaySeconds * 65536);
}
return new RtcpReceiverInfo({
ssrc: Number(ssrc),
fractionLost: stream.fraction_lost,
packetsLost: stream.packets_lost,
highestSequence: stream.max_seq,
jitter: stream.jitter,
lsr: lastSRtimestamp,
dlsr: delaySinceLastSR
});
});
const packet = new RtcpRrPacket({
ssrc: this.rtcpSsrc,
reports
});
try {
if (this.config.debug.receiverReportDelay) await setTimeout$2(this.config.debug.receiverReportDelay);
await this.dtlsTransport.sendRtcp([packet]);
} catch (error) {
log32("sendRtcp failed", error);
await setTimeout$2(500 + Math.random() * 1e3);
}
}
} catch (error) {}
}
getInboundRtpStatsId(track) {
return generateStatsId("inbound-rtp", track.id ?? track.uuid);
}
getRemoteOutboundRtpStatsId(track) {
return generateStatsId("remote-outbound-rtp", track.id ?? track.uuid);
}
getStatsRootIds(selector) {
return this.tracks.filter((track) => !selector ? true : track === selector).filter((track) => track.ssrc).map((track) => this.getInboundRtpStatsId(track));
}
collectStats(timestamp) {
const stats = [];
const transportId = this.dtlsTransport ? generateStatsId("transport", this.dtlsTransport.id) : void 0;
const activeCodec = this.codecArray[0];
const emittedCodecIds = /* @__PURE__ */ new Set();
for (const track of this.tracks) {
if (!track.ssrc) continue;
const streamStats = this.remoteStreams[track.ssrc];
const hasRemoteTimestamp = this.remoteTimestampsBySsrc[track.ssrc] !== void 0;
const remoteId = this.lastSRtimestamp[track.ssrc] !== void 0 || hasRemoteTimestamp ? this.getRemoteOutboundRtpStatsId(track) : void 0;
const codecId = activeCodec && transportId ? generateCodecStatsId(transportId, activeCodec.payloadType, track.id ?? track.uuid) : void 0;
if (activeCodec && transportId && codecId && !emittedCodecIds.has(codecId)) {
emittedCodecIds.add(codecId);
const codecStats = {
type: "codec",
id: codecId,
timestamp,
payloadType: activeCodec.payloadType,
transportId,
mimeType: activeCodec.mimeType,
clockRate: activeCodec.clockRate,
channels: activeCodec.channels,
sdpFmtpLine: activeCodec.parameters
};
stats.push(codecStats);
}
const inboundRtpStats = {
type: "inbound-rtp",
id: this.getInboundRtpStatsId(track),
timestamp,
ssrc: track.ssrc,
kind: this.kind,
transportId,
codecId,
mid: this.sdesMid,
trackIdentifier: track.id ?? track.uuid,
packetsReceived: streamStats?.packets_received ?? 0,
bytesReceived: streamStats?.bytesReceived ?? 0,
headerBytesReceived: streamStats?.headerBytesReceived ?? 0,
packetsLost: streamStats?.packets_lost ?? 0,
jitter: streamStats?.clockRate ? streamStats.jitter / streamStats.clockRate : void 0,
lastPacketReceivedTimestamp: streamStats?.lastPacketReceivedTimestamp,
remoteId,
nackCount: this.nackCountBySsrc[track.ssrc] || void 0,
pliCount: this.pliCountBySsrc[track.ssrc] || void 0
};
stats.push(inboundRtpStats);
if (remoteId) {
const remoteOutboundStats = {
type: "remote-outbound-rtp",
id: this.getRemoteOutboundRtpStatsId(track),
timestamp,
ssrc: track.ssrc,
kind: this.kind,
transportId,
codecId: inboundRtpStats.codecId,
localId: inboundRtpStats.id,
remoteTimestamp: this.remoteTimestampsBySsrc[track.ssrc],
reportsSent: this.senderReportsReceivedBySsrc[track.ssrc] ?? 0,
packetsSent: this.remotePacketCountBySsrc[track.ssrc],
bytesSent: this.remoteOctetCountBySsrc[track.ssrc]
};
stats.push(remoteOutboundStats);
}
}
return stats;
}
async getStats() {
const timestamp = getStatsTimestamp();
const stats = this.collectStats(timestamp);
if (this.dtlsTransport) stats.push(...await this.dtlsTransport.getStats(timestamp));
return buildStatsReport(stats, this.getStatsRootIds());
}
async sendRtcpPLI(mediaSsrc) {
if (!this.pliEnabled) {
log32("pli not supported", { mediaSsrc });
return;
}
if (this.stopped) return;
log32("sendRtcpPLI", { mediaSsrc });
const packet = new RtcpPayloadSpecificFeedback({ feedback: new PictureLossIndication({
senderSsrc: this.rtcpSsrc,
mediaSsrc
}) });
try {
this.pliCountBySsrc[mediaSsrc] = (this.pliCountBySsrc[mediaSsrc] ?? 0) + 1;
await this.dtlsTransport.sendRtcp([packet]);
} catch (error) {
log32(error);
}
}
handleRtcpPacket(packet) {
switch (packet.type) {
case RtcpSrPacket.type: {
const sr = packet;
this.lastSRtimestamp[sr.ssrc] = compactNtp(sr.senderInfo.ntpTimestamp);
this.receiveLastSRTimestamp[sr.ssrc] = timestampSeconds();
this.senderReportsReceivedBySsrc[sr.ssrc] = (this.senderReportsReceivedBySsrc[sr.ssrc] ?? 0) + 1;
this.remoteTimestampsBySsrc[sr.ssrc] = ntpTimeToEpochMs(sr.senderInfo.ntpTimestamp);
this.remotePacketCountBySsrc[sr.ssrc] = sr.senderInfo.packetCount;
this.remoteOctetCountBySsrc[sr.ssrc] = sr.senderInfo.octetCount;
const track = this.trackBySSRC[packet.ssrc];
if (track) track.onReceiveRtcp.execute(packet);
}
}
this.onRtcp.execute(packet);
}
handleRtpBySsrc = (packet, extensions) => {
const track = this.trackBySSRC[packet.header.ssrc];
this.handleRTP(packet, extensions, track);
};
handleRtpByRid = (packet, rid, extensions) => {
const track = this.trackByRID[rid];
if (!this.trackBySSRC[packet.header.ssrc]) this.trackBySSRC[packet.header.ssrc] = track;
this.handleRTP(packet, extensions, track);
};
handleRTP(packet, extensions, track) {
if (this.stopped) return;
const codec = this.codecs[packet.header.payloadType];
if (!codec) return;
this.remoteStreams[packet.header.ssrc] = this.remoteStreams[packet.header.ssrc] ?? new StreamStatistics(codec.clockRate);
this.remoteStreams[packet.header.ssrc].add(packet);
if (this.receiverTWCC) {
const transportSequenceNumber = extensions[RTP_EXTENSION_URI.transportWideCC];
if (!transportSequenceNumber == void 0) throw new Error("undefined");
this.receiverTWCC.handleTWCC(transportSequenceNumber);
} else if (this.twccEnabled) this.setupTWCC(packet.header.ssrc);
if (codec.name.toLowerCase() === "rtx") {
const originalSsrc = this.ssrcByRtx[packet.header.ssrc];
const codecParams = codecParametersFromString(codec.parameters ?? "");
const rtxCodec = this.codecs[codecParams["apt"]];
if (packet.payload.length < 2) return;
packet = unwrapRtx(packet, rtxCodec.payloadType, originalSsrc);
track = this.trackBySSRC[originalSsrc];
}
let red;
if (codec.name.toLowerCase() === "red") {
red = Red.deSerialize(packet.payload);
if (!Object.keys(this.codecs).includes(red.header.fields[0].blockPT.toString())) return;
}
if (track?.kind === "video" && this.nackEnabled) this.nack.addPacket(packet);
if (track) {
if (red) {
if (track.kind === "audio") {
const payloads = this.audioRedHandler.push(red, packet);
for (const packet2 of payloads) track.onReceiveRtp.execute(packet2.clone(), extensions);
}
} else track.onReceiveRtp.execute(packet.clone(), extensions);
}
this.runRtcp();
}
};
var log33 = debug("werift:packages/webrtc/src/media/router.ts");
var RtpRouter = class {
ssrcTable = {};
ridTable = {};
extIdUriMap = {};
constructor() {}
registerRtpSender(sender) {
this.ssrcTable[sender.ssrc] = sender;
}
registerRtpReceiver(receiver, ssrc) {
log33("registerRtpReceiver", ssrc);
this.ssrcTable[ssrc] = receiver;
}
registerRtpReceiverBySsrc(transceiver, params) {
log33("registerRtpReceiverBySsrc", params);
params.encodings.filter((e) => e.ssrc != void 0).forEach((encode20, i) => {
this.registerRtpReceiver(transceiver.receiver, encode20.ssrc);
transceiver.addTrack(new MediaStreamTrack({
ssrc: encode20.ssrc,
kind: transceiver.kind,
id: transceiver.sender.trackId,
remote: true,
codec: params.codecs[i]
}));
if (encode20.rtx) this.registerRtpReceiver(transceiver.receiver, encode20.rtx.ssrc);
});
params.headerExtensions.forEach((extension) => {
this.extIdUriMap[extension.id] = extension.uri;
});
}
registerRtpReceiverByRid(transceiver, param, params) {
const [codec] = params.codecs;
log33("registerRtpReceiverByRid", param);
transceiver.addTrack(new MediaStreamTrack({
rid: param.rid,
kind: transceiver.kind,
id: transceiver.sender.trackId,
remote: true,
codec
}));
this.ridTable[param.rid] = transceiver.receiver;
}
routeRtp = (packet) => {
const extensions = rtpHeaderExtensionsParser(packet.header.extensions, this.extIdUriMap);
let rtpReceiver = this.ssrcTable[packet.header.ssrc];
const rid = extensions[RTP_EXTENSION_URI.sdesRTPStreamID];
if (typeof rid === "string") {
rtpReceiver = this.ridTable[rid];
rtpReceiver.latestRid = rid;
rtpReceiver.handleRtpByRid(packet, rid, extensions);
} else if (rtpReceiver) rtpReceiver.handleRtpBySsrc(packet, extensions);
else {
rtpReceiver = Object.values(this.ridTable).filter((r) => r instanceof RTCRtpReceiver).find((r) => r.trackBySSRC[packet.header.ssrc]);
if (rtpReceiver) {
log33("simulcast register receiver by ssrc", packet.header.ssrc);
this.registerRtpReceiver(rtpReceiver, packet.header.ssrc);
rtpReceiver.handleRtpBySsrc(packet, extensions);
}
}
if (!rtpReceiver) {
log33("ssrcReceiver not found");
return;
}
const sdesMid = extensions[RTP_EXTENSION_URI.sdesMid];
if (typeof sdesMid === "string") rtpReceiver.sdesMid = sdesMid;
const repairedRid = extensions[RTP_EXTENSION_URI.repairedRtpStreamId];
if (typeof repairedRid === "string") rtpReceiver.latestRepairedRid = repairedRid;
};
routeRtcp = (packet) => {
const recipients = [];
switch (packet.type) {
case RtcpSrPacket.type:
packet = packet;
recipients.push(this.ssrcTable[packet.ssrc]);
break;
case RtcpRrPacket.type:
packet = packet;
packet.reports.forEach((report) => {
recipients.push(this.ssrcTable[report.ssrc]);
});
break;
case RtcpSourceDescriptionPacket.type: break;
case RtcpTransportLayerFeedback.type:
{
const rtpfb = packet;
if (rtpfb.feedback) recipients.push(this.ssrcTable[rtpfb.feedback.mediaSourceSsrc]);
}
break;
case RtcpPayloadSpecificFeedback.type: {
const psfb = packet;
switch (psfb.feedback.count) {
case ReceiverEstimatedMaxBitrate.count:
{
const remb = psfb.feedback;
recipients.push(this.ssrcTable[remb.ssrcFeedbacks[0]]);
}
break;
default: recipients.push(this.ssrcTable[psfb.feedback.senderSsrc] || this.ssrcTable[psfb.feedback.mediaSsrc]);
}
}
}
recipients.filter((v) => v).forEach((recipient) => recipient.handleRtcpPacket(packet));
};
};
var CumulativeResult = class {
numPackets = 0;
/**byte */
totalSize = 0;
firstPacketSentAtMs = 0;
lastPacketSentAtMs = 0;
firstPacketReceivedAtMs = 0;
lastPacketReceivedAtMs = 0;
/**
*
* @param size byte
* @param sentAtMs
* @param receivedAtMs
*/
addPacket(size, sentAtMs, receivedAtMs) {
if (this.numPackets === 0) {
this.firstPacketSentAtMs = sentAtMs;
this.firstPacketReceivedAtMs = receivedAtMs;
this.lastPacketSentAtMs = sentAtMs;
this.lastPacketReceivedAtMs = receivedAtMs;
} else {
if (sentAtMs < this.firstPacketSentAtMs) this.firstPacketSentAtMs = sentAtMs;
if (receivedAtMs < this.firstPacketReceivedAtMs) this.firstPacketReceivedAtMs = receivedAtMs;
if (sentAtMs > this.lastPacketSentAtMs) this.lastPacketSentAtMs = sentAtMs;
if (receivedAtMs > this.lastPacketReceivedAtMs) this.lastPacketReceivedAtMs = receivedAtMs;
}
this.numPackets++;
this.totalSize += size;
}
reset() {
this.numPackets = 0;
this.totalSize = 0;
this.firstPacketSentAtMs = 0;
this.lastPacketSentAtMs = 0;
this.firstPacketReceivedAtMs = 0;
this.lastPacketReceivedAtMs = 0;
}
get receiveBitrate() {
const recvIntervalMs = this.lastPacketReceivedAtMs - this.firstPacketReceivedAtMs;
return Int(this.totalSize / recvIntervalMs * 8 * 1e3);
}
get sendBitrate() {
const sendIntervalMs = this.lastPacketSentAtMs - this.firstPacketSentAtMs;
return Int(this.totalSize / sendIntervalMs * 8 * 1e3);
}
};
var COUNTER_MAX = 20;
var SCORE_MAX = 10;
var SenderBandwidthEstimator = class {
congestion = false;
onAvailableBitrate = new Event2();
/**congestion occur or not */
onCongestion = new Event2();
onCongestionScore = new Event2();
congestionCounter = 0;
cumulativeResult = new CumulativeResult();
sentInfos = {};
_congestionScore = 1;
/**1~10 big is worth*/
get congestionScore() {
return this._congestionScore;
}
set congestionScore(v) {
this._congestionScore = v;
this.onCongestionScore.execute(v);
}
_availableBitrate = 0;
get availableBitrate() {
return this._availableBitrate;
}
set availableBitrate(v) {
this._availableBitrate = v;
this.onAvailableBitrate.execute(v);
}
constructor() {}
receiveTWCC(feedback) {
const elapsedMs = milliTime() - this.cumulativeResult.firstPacketSentAtMs;
if (elapsedMs > 1e3) {
this.cumulativeResult.reset();
if (this.congestionCounter < COUNTER_MAX) this.congestionCounter++;
else if (this.congestionScore < SCORE_MAX) this.congestionScore++;
if (this.congestionCounter >= COUNTER_MAX && !this.congestion) {
this.congestion = true;
this.onCongestion.execute(this.congestion);
}
}
for (const result of feedback.packetResults) {
if (!result.received) continue;
const wideSeq = result.sequenceNumber;
const info = this.sentInfos[wideSeq];
if (!info) continue;
if (!result.receivedAtMs) continue;
this.cumulativeResult.addPacket(info.size, info.sendingAtMs, result.receivedAtMs);
}
if (elapsedMs >= 100 && this.cumulativeResult.numPackets >= 20) {
this.availableBitrate = Math.min(this.cumulativeResult.sendBitrate, this.cumulativeResult.receiveBitrate);
this.cumulativeResult.reset();
if (this.congestionCounter > -COUNTER_MAX) {
const maxBonus = Int(COUNTER_MAX / 2) + 1;
const bonus = maxBonus - (maxBonus - (Int(COUNTER_MAX / 4) + 1)) / 10 * this.congestionScore;
this.congestionCounter = this.congestionCounter - bonus;
}
if (this.congestionCounter <= -COUNTER_MAX) {
if (this.congestionScore > 1) {
this.congestionScore--;
this.onCongestion.execute(false);
}
this.congestionCounter = 0;
}
if (this.congestionCounter <= 0 && this.congestion) {
this.congestion = false;
this.onCongestion.execute(this.congestion);
}
}
}
rtpPacketSent(sentInfo) {
Object.keys(sentInfo).map((v) => Number(v)).sort().filter((seq) => seq < sentInfo.wideSeq).forEach((seq) => {
delete this.sentInfos[seq];
});
this.sentInfos[sentInfo.wideSeq] = sentInfo;
}
};
var log34 = debug("werift:packages/webrtc/src/media/rtpSender.ts");
var RTP_HISTORY_SIZE = 128;
var RTT_ALPHA = .85;
var RTCRtpSender = class {
constructor(trackOrKind) {
this.trackOrKind = trackOrKind;
this.kind = typeof this.trackOrKind === "string" ? this.trackOrKind : this.trackOrKind.kind;
if (typeof trackOrKind !== "string") this.registerTrack(trackOrKind);
}
type = "sender";
kind;
ssrc = randomBytes$1(4).readUInt32BE(0);
rtxSsrc = randomBytes$1(4).readUInt32BE(0);
trackId = randomUUID$1().toString();
onReady = new Event2();
onRtcp = new Event2();
onPictureLossIndication = new Event2();
onGenericNack = new Event2();
senderBWE = new SenderBandwidthEstimator();
cname;
mid;
rtpStreamId;
repairedRtpStreamId;
rtxPayloadType;
rtxSequenceNumber = random16();
redRedundantPayloadType;
_redDistance = 2;
redEncoder = new RedEncoder(this._redDistance);
headerExtensions = [];
disposeTrack;
sendEncodings = [{}];
lastSRtimestamp;
lastSentSRTimestamp;
ntpTimestamp = 0n;
rtpTimestamp = 0;
octetCount = 0;
packetCount = 0;
headerBytesSent = 0;
rtt;
totalRoundTripTime = 0;
roundTripTimeMeasurements = 0;
retransmittedPacketsSent = 0;
retransmittedBytesSent = 0;
nackCount = 0;
pliCount = 0;
firCount = 0;
remotePacketsLost;
remoteFractionLost;
receiverEstimatedMaxBitrate = 0n;
sequenceNumber;
timestamp;
timestampOffset = 0;
seqOffset = 0;
rtpCache = [];
codec;
dtlsTransport;
dtlsDisposer = [];
track = null;
streamIds = [];
stopped = false;
rtcpRunning = false;
rtcpCancel = new AbortController();
get transport() {
return this.dtlsTransport ?? null;
}
get streamId() {
return this.streamIds[0];
}
set streamId(value) {
this.streamIds = value ? [value] : [];
}
setDtlsTransport(dtlsTransport) {
if (this.dtlsTransport) this.dtlsDisposer.forEach((dispose) => dispose());
this.dtlsTransport = dtlsTransport;
this.dtlsDisposer = [this.dtlsTransport.onStateChange.subscribe((state) => {
if (state === "connected") this.onReady.execute();
}).unSubscribe];
}
get redDistance() {
return this._redDistance;
}
set redDistance(n) {
this._redDistance = n;
this.redEncoder.distance = n;
}
prepareSend(params) {
this.cname = params.rtcp?.cname;
this.mid = params.muxId;
this.headerExtensions = params.headerExtensions;
this.rtpStreamId = params.rtpStreamId;
this.repairedRtpStreamId = params.repairedRtpStreamId;
this.codec = params.codecs[0];
if (this.track) this.track.codec = this.codec;
params.codecs.forEach((codec) => {
const codecParams = codecParametersFromString(codec.parameters ?? "");
if (codec.name.toLowerCase() === "rtx" && codecParams["apt"] === this.codec?.payloadType) this.rtxPayloadType = codec.payloadType;
if (codec.name.toLowerCase() === "red") this.redRedundantPayloadType = Number((codec.parameters ?? "").split("/")[0]);
});
}
registerTrack(track) {
if (track.stopped) throw new Error("track is ended");
if (this.disposeTrack) this.disposeTrack();
track.id = this.trackId;
const { unSubscribe } = track.onReceiveRtp.subscribe(async (rtp) => {
await this.sendRtp(rtp);
});
this.track = track;
this.disposeTrack = unSubscribe;
if (this.codec) track.codec = this.codec;
track.onSourceChanged.subscribe((header) => {
this.replaceRTP(header);
});
}
setStreams(streams = []) {
this.streamIds = [...new Set(streams.map((stream) => stream.id))];
}
setSendEncodings(encodings = []) {
this.sendEncodings = encodings.length > 0 ? encodings.map((encoding) => ({ ...encoding })) : [{}];
}
async replaceTrack(track) {
if (track === null) {
if (this.disposeTrack) this.disposeTrack();
this.track = null;
return;
}
if (track.stopped) throw new Error("track is ended");
if (this.sequenceNumber != void 0) {
const header = track.header || (await track.onReceiveRtp.asPromise())[0].header;
this.replaceRTP(header);
}
this.registerTrack(track);
log34("replaceTrack", "ssrc", track.ssrc, "rid", track.rid);
}
stop() {
this.stopped = true;
this.rtcpRunning = false;
this.rtcpCancel.abort();
if (this.disposeTrack) this.disposeTrack();
this.track = null;
}
async runRtcp() {
if (this.rtcpRunning || this.stopped) return;
this.rtcpRunning = true;
try {
while (this.rtcpRunning) {
await setTimeout$2(500 + Math.random() * 1e3, void 0, { signal: this.rtcpCancel.signal });
const packets = [new RtcpSrPacket({
ssrc: this.ssrc,
senderInfo: new RtcpSenderInfo({
ntpTimestamp: this.ntpTimestamp,
rtpTimestamp: this.rtpTimestamp,
packetCount: this.packetCount,
octetCount: this.octetCount
})
})];
this.lastSRtimestamp = compactNtp(this.ntpTimestamp);
this.lastSentSRTimestamp = timestampSeconds();
if (this.cname) packets.push(new RtcpSourceDescriptionPacket({ chunks: [new SourceDescriptionChunk({
source: this.ssrc,
items: [new SourceDescriptionItem({
type: 1,
text: this.cname
})]
})] }));
try {
await this.dtlsTransport.sendRtcp(packets);
} catch (error) {
log34("sendRtcp failed", error);
await setTimeout$2(500 + Math.random() * 1e3);
}
}
} catch (error) {}
}
replaceRTP({ sequenceNumber, timestamp }, discontinuity = false) {
if (this.sequenceNumber != void 0) {
this.seqOffset = uint16Add(this.sequenceNumber, -sequenceNumber);
if (discontinuity) this.seqOffset = uint16Add(this.seqOffset, 2);
}
if (this.timestamp != void 0) {
this.timestampOffset = uint32Add(this.timestamp, -timestamp);
if (discontinuity) this.timestampOffset = uint16Add(this.timestampOffset, 1);
}
this.rtpCache = [];
log34("replaceRTP", this.sequenceNumber, sequenceNumber, this.seqOffset);
}
async sendRtp(rtp) {
if (this.dtlsTransport.state !== "connected" || !this.codec) return;
rtp = Buffer.isBuffer(rtp) ? RtpPacket.deSerialize(rtp) : rtp;
const { header, payload } = rtp;
header.ssrc = this.ssrc;
header.payloadType = this.codec.payloadType;
header.timestamp = uint32Add(header.timestamp, this.timestampOffset);
header.sequenceNumber = uint16Add(header.sequenceNumber, this.seqOffset);
this.timestamp = header.timestamp;
this.sequenceNumber = header.sequenceNumber;
const ntpTimestamp = ntpTime();
const originalHeaderExtensions = [...header.extensions];
header.extensions = this.headerExtensions.map((extension) => {
const payload2 = (() => {
switch (extension.uri) {
case RTP_EXTENSION_URI.sdesMid:
if (this.mid) return serializeSdesMid(this.mid);
return;
case RTP_EXTENSION_URI.sdesRTPStreamID:
if (this.rtpStreamId) return serializeSdesRTPStreamID(this.rtpStreamId);
return;
case RTP_EXTENSION_URI.repairedRtpStreamId:
if (this.repairedRtpStreamId) return serializeRepairedRtpStreamId(this.repairedRtpStreamId);
return;
case RTP_EXTENSION_URI.transportWideCC:
this.dtlsTransport.transportSequenceNumber = uint16Add(this.dtlsTransport.transportSequenceNumber, 1);
return serializeTransportWideCC(this.dtlsTransport.transportSequenceNumber);
case RTP_EXTENSION_URI.absSendTime: return serializeAbsSendTime(ntpTimestamp);
}
})();
if (payload2) return {
id: extension.id,
payload: payload2
};
}).filter((v) => v);
for (const ext of originalHeaderExtensions) {
const exist = header.extensions.find((v) => v.id === ext.id);
if (exist) exist.payload = ext.payload;
else header.extensions.push(ext);
}
header.extensions = header.extensions.sort((a, b) => a.id - b.id);
this.ntpTimestamp = ntpTimestamp;
this.rtpTimestamp = header.timestamp;
this.octetCount += payload.length;
this.headerBytesSent += header.serializeSize;
this.packetCount = uint32Add(this.packetCount, 1);
this.rtpCache[header.sequenceNumber % RTP_HISTORY_SIZE] = rtp;
let rtpPayload = payload;
if (this.redRedundantPayloadType) {
this.redEncoder.push({
block: rtpPayload,
timestamp: header.timestamp,
blockPT: this.redRedundantPayloadType
});
rtpPayload = this.redEncoder.build().serialize();
}
const size = await this.dtlsTransport.sendRtp(rtpPayload, header);
this.runRtcp();
const millitime = milliTime();
const sentInfo = {
wideSeq: this.dtlsTransport.transportSequenceNumber,
size,
sendingAtMs: millitime,
sentAtMs: millitime
};
this.senderBWE.rtpPacketSent(sentInfo);
}
handleRtcpPacket(rtcpPacket) {
switch (rtcpPacket.type) {
case RtcpSrPacket.type:
case RtcpRrPacket.type:
rtcpPacket.reports.filter((report) => report.ssrc === this.ssrc).forEach((report) => {
this.remotePacketsLost = report.packetsLost;
this.remoteFractionLost = report.fractionLost / 256;
if (this.lastSRtimestamp === report.lsr && report.dlsr) {
if (this.lastSentSRTimestamp) {
const rtt = timestampSeconds() - this.lastSentSRTimestamp - report.dlsr / 65536;
this.totalRoundTripTime += rtt;
this.roundTripTimeMeasurements++;
if (this.rtt === void 0) this.rtt = rtt;
else this.rtt = RTT_ALPHA * this.rtt + (1 - RTT_ALPHA) * rtt;
}
}
});
break;
case RtcpTransportLayerFeedback.type:
{
const packet = rtcpPacket;
switch (packet.feedback.count) {
case TransportWideCC.count:
{
const feedback = packet.feedback;
this.senderBWE.receiveTWCC(feedback);
}
break;
case GenericNack.count: {
const feedback = packet.feedback;
this.nackCount++;
feedback.lost.forEach(async (seqNum) => {
let packet2 = this.rtpCache[seqNum % RTP_HISTORY_SIZE];
if (packet2 && packet2.header.sequenceNumber !== seqNum) packet2 = void 0;
if (packet2) {
if (this.rtxPayloadType != void 0) {
packet2 = wrapRtx(packet2, this.rtxPayloadType, this.rtxSequenceNumber, this.rtxSsrc);
this.rtxSequenceNumber = uint16Add(this.rtxSequenceNumber, 1);
}
this.retransmittedPacketsSent++;
this.retransmittedBytesSent += packet2.payload.length;
this.headerBytesSent += packet2.header.serializeSize;
await this.dtlsTransport.sendRtp(packet2.payload, packet2.header);
}
});
this.onGenericNack.execute(feedback);
}
}
}
break;
case RtcpPayloadSpecificFeedback.type: {
const packet = rtcpPacket;
switch (packet.feedback.count) {
case ReceiverEstimatedMaxBitrate.count:
{
const feedback = packet.feedback;
this.receiverEstimatedMaxBitrate = feedback.bitrate;
}
break;
case PictureLossIndication.count:
this.pliCount++;
this.onPictureLossIndication.execute();
}
}
}
this.onRtcp.execute(rtcpPacket);
}
getParameters() {
return { encodings: this.sendEncodings.map((encoding) => ({ ...encoding })) };
}
setParameters(params) {
if (params.encodings) this.setSendEncodings(params.encodings);
}
get outboundRtpStatsId() {
return generateStatsId("outbound-rtp", this.trackId);
}
get mediaSourceStatsId() {
return generateStatsId("media-source", this.trackId);
}
get remoteInboundRtpStatsId() {
return generateStatsId("remote-inbound-rtp", this.trackId);
}
getStatsRootIds() {
return [this.outboundRtpStatsId];
}
collectStats(timestamp) {
const stats = [];
const transportId = this.dtlsTransport ? generateStatsId("transport", this.dtlsTransport.id) : void 0;
const codecId = this.codec && transportId ? generateCodecStatsId(transportId, this.codec.payloadType, this.trackId) : void 0;
const outboundRtpStats = {
type: "outbound-rtp",
id: this.outboundRtpStatsId,
timestamp,
ssrc: this.ssrc,
kind: this.kind,
transportId,
codecId,
mid: this.mid,
packetsSent: this.packetCount,
bytesSent: this.octetCount,
headerBytesSent: this.headerBytesSent,
retransmittedPacketsSent: this.retransmittedPacketsSent || void 0,
retransmittedBytesSent: this.retransmittedBytesSent || void 0,
rtxSsrc: this.rtxPayloadType ? this.rtxSsrc : void 0,
mediaSourceId: this.track ? this.mediaSourceStatsId : void 0,
remoteId: this.rtt !== void 0 || this.remotePacketsLost !== void 0 || this.remoteFractionLost !== void 0 ? this.remoteInboundRtpStatsId : void 0,
nackCount: this.nackCount || void 0,
pliCount: this.pliCount || void 0,
firCount: this.firCount || void 0
};
stats.push(outboundRtpStats);
if (this.track) {
const mediaSourceStats = {
type: "media-source",
id: this.mediaSourceStatsId,
timestamp,
trackIdentifier: this.track.id ?? this.trackId,
kind: this.kind
};
stats.push(mediaSourceStats);
}
if (this.codec && transportId) {
const codecStats = {
type: "codec",
id: codecId,
timestamp,
payloadType: this.codec.payloadType,
transportId,
mimeType: this.codec.mimeType,
clockRate: this.codec.clockRate,
channels: this.codec.channels,
sdpFmtpLine: this.codec.parameters
};
stats.push(codecStats);
}
if (this.rtt !== void 0 || this.remotePacketsLost !== void 0 || this.remoteFractionLost !== void 0) {
const remoteInboundStats = {
type: "remote-inbound-rtp",
id: this.remoteInboundRtpStatsId,
timestamp,
ssrc: this.ssrc,
kind: this.kind,
transportId,
codecId: outboundRtpStats.codecId,
localId: outboundRtpStats.id,
roundTripTime: this.rtt,
totalRoundTripTime: this.totalRoundTripTime,
roundTripTimeMeasurements: this.roundTripTimeMeasurements,
packetsLost: this.remotePacketsLost,
fractionLost: this.remoteFractionLost
};
stats.push(remoteInboundStats);
}
return stats;
}
async getStats() {
const timestamp = getStatsTimestamp();
const stats = this.collectStats(timestamp);
if (this.dtlsTransport) stats.push(...await this.dtlsTransport.getStats(timestamp));
return buildStatsReport(stats, this.getStatsRootIds());
}
};
function createWebRtcDomException(name, message = name) {
return new DOMException(message, name);
}
function createWebRtcTypeError(message) {
return new TypeError(message);
}
var log35 = debug("werift:packages/webrtc/src/transport/sctpManager.ts");
var SctpTransportManager = class {
sctpTransport;
sctpRemotePort;
dataChannelsOpened = 0;
dataChannelsClosed = 0;
dataChannels = [];
onDataChannel = new Event2();
constructor() {}
createSctpTransport(maxMessageSize) {
const sctp = new RTCSctpTransport(5e3, maxMessageSize);
sctp.mid = void 0;
sctp.onDataChannel.subscribe((channel) => {
this.dataChannelsOpened++;
this.dataChannels.push(channel);
this.onDataChannel.execute(channel);
});
this.sctpTransport = sctp;
return sctp;
}
createDataChannel(label, options = {}) {
const maxPacketLifeTime = coerceUnsignedShortOption(options.maxPacketLifeTime, "maxPacketLifeTime");
const maxRetransmits = coerceUnsignedShortOption(options.maxRetransmits, "maxRetransmits");
const settings = {
protocol: "",
ordered: true,
negotiated: false,
...options,
maxPacketLifeTime,
maxRetransmits
};
if (settings.maxPacketLifeTime != null && settings.maxRetransmits != null) throw createWebRtcTypeError("maxPacketLifeTime and maxRetransmits cannot both be set");
if (!this.sctpTransport) this.sctpTransport = this.createSctpTransport();
const parameters = new RTCDataChannelParameters({
id: settings.id,
label,
maxPacketLifeTime: settings.maxPacketLifeTime,
maxRetransmits: settings.maxRetransmits,
negotiated: settings.negotiated,
ordered: settings.ordered,
protocol: settings.protocol
});
const channel = new RTCDataChannel(this.sctpTransport, parameters);
this.dataChannelsOpened++;
this.dataChannels.push(channel);
channel.stateChange.subscribe((state) => {
if (state === "closed") {
this.dataChannelsClosed++;
const index = this.dataChannels.indexOf(channel);
if (index !== -1) this.dataChannels.splice(index, 1);
}
});
return channel;
}
async connectSctp() {
if (!this.sctpTransport || !this.sctpRemotePort) return;
await this.sctpTransport.start(this.sctpRemotePort);
await this.sctpTransport.sctp.stateChanged.connected.asPromise();
log35("sctp connected");
}
setRemoteSCTP(remoteMedia, mLineIndex) {
if (!this.sctpTransport) return;
this.sctpTransport.setRemoteMaxMessageSize(remoteMedia.sctpCapabilities?.maxMessageSize);
this.sctpRemotePort = remoteMedia.sctpPort;
if (!this.sctpRemotePort) throw new Error("sctpRemotePort not exist");
this.sctpTransport.setRemotePort(this.sctpRemotePort);
this.sctpTransport.mLineIndex = mLineIndex;
if (!this.sctpTransport.mid) this.sctpTransport.mid = remoteMedia.rtp.muxId;
}
async close() {
if (this.sctpTransport) await this.sctpTransport.stop();
this.onDataChannel.allUnsubscribe();
}
async getStats(timestamp = getStatsTimestamp()) {
const stats = [];
for (const channel of this.dataChannels) {
const channelStats = {
type: "data-channel",
id: generateStatsId("data-channel", channel.id ?? channel.statsId),
timestamp,
label: channel.label,
protocol: channel.protocol,
dataChannelIdentifier: channel.id ?? void 0,
state: channel.readyState,
messagesSent: channel.messagesSent || 0,
bytesSent: channel.bytesSent || 0,
messagesReceived: channel.messagesReceived || 0,
bytesReceived: channel.bytesReceived || 0
};
stats.push(channelStats);
}
return stats;
}
};
function coerceUnsignedShortOption(value, name) {
if (value === void 0) return;
const coerced = Number(value);
if (!Number.isFinite(coerced) || !Number.isInteger(coerced) || coerced < 0 || coerced > 65535) throw createWebRtcTypeError(`${name} must be an unsigned short`);
return coerced;
}
var SDPManager = class {
currentLocalDescription;
currentRemoteDescription;
pendingLocalDescription;
pendingRemoteDescription;
cname;
midSuffix;
bundlePolicy;
seenMid = /* @__PURE__ */ new Set();
constructor({ cname, midSuffix, bundlePolicy }) {
this.cname = cname;
this.midSuffix = midSuffix ?? false;
this.bundlePolicy = bundlePolicy;
}
get localDescription() {
if (!this._localDescription) return;
return this._localDescription.toJSON();
}
get remoteDescription() {
if (!this._remoteDescription) return;
return this._remoteDescription.toJSON();
}
/**@private */
get _localDescription() {
return this.pendingLocalDescription || this.currentLocalDescription;
}
/**@private */
get _remoteDescription() {
return this.pendingRemoteDescription || this.currentRemoteDescription;
}
get inactiveRemoteMedia() {
return this._remoteDescription?.media?.find?.((m) => m.direction === "inactive");
}
/**
* MediaDescriptionをトランシーバー用に作成
*/
createMediaDescriptionForTransceiver(transceiver, direction) {
const media = new MediaDescription(transceiver.kind, 9, "UDP/TLS/RTP/SAVPF", transceiver.codecs.map((c) => c.payloadType));
media.direction = direction;
media.msids = transceiver.msids;
media.rtp = {
codecs: transceiver.codecs,
headerExtensions: transceiver.headerExtensions,
muxId: transceiver.mid ?? void 0
};
media.rtcpHost = "0.0.0.0";
media.rtcpPort = 9;
media.rtcpMux = true;
media.ssrc = [new SsrcDescription({
ssrc: transceiver.sender.ssrc,
cname: this.cname
})];
if (transceiver.options.simulcast) media.simulcastParameters = transceiver.options.simulcast.map((o) => new RTCRtpSimulcastParameters(o));
if (media.rtp.codecs.find((c) => c.name.toLowerCase() === "rtx")) {
media.ssrc.push(new SsrcDescription({
ssrc: transceiver.sender.rtxSsrc,
cname: this.cname
}));
media.ssrcGroup = [new GroupDescription("FID", [transceiver.sender.ssrc.toString(), transceiver.sender.rtxSsrc.toString()])];
}
this.addTransportDescription(media, transceiver.dtlsTransport);
return media;
}
/**
* MediaDescriptionをSCTP用に作成
*/
createMediaDescriptionForSctp(sctp) {
const media = new MediaDescription("application", DISCARD_PORT, "UDP/DTLS/SCTP", ["webrtc-datachannel"]);
media.sctpPort = sctp.port;
media.rtp.muxId = sctp.mid;
media.sctpCapabilities = sctp.getCapabilities();
this.addTransportDescription(media, sctp.dtlsTransport);
return media;
}
/**
* トランスポートの情報をMediaDescriptionに追加
*/
addTransportDescription(media, dtlsTransport) {
const iceTransport = dtlsTransport.iceTransport;
media.iceCandidates = iceTransport.localCandidates;
media.iceCandidatesComplete = iceTransport.gatheringState === "complete";
media.iceParams = iceTransport.localParameters;
media.iceOptions = "trickle";
media.host = DISCARD_HOST;
media.port = DISCARD_PORT;
if (media.direction === "inactive") {
media.port = 0;
media.msids = [];
}
if (!media.dtlsParams) {
media.dtlsParams = dtlsTransport.localParameters;
if (!media.dtlsParams.fingerprints) media.dtlsParams.fingerprints = dtlsTransport.localParameters.fingerprints;
}
}
/**
* 一意のMIDを割り当て
*/
allocateMid(type = "") {
let mid = "";
for (let i = 0;;) {
mid = (i++).toString() + type;
if (!this.seenMid.has(mid)) break;
}
this.seenMid.add(mid);
return mid;
}
parseSdp({ sdp, isLocal, signalingState, type }) {
const description = SessionDescription.parse(sdp);
this.validateDescription({
description,
isLocal,
signalingState,
type
});
description.type = type;
return description;
}
validateDescription({ description, isLocal, signalingState, type }) {
if (isLocal) {
if (type === "offer") {
if (!["stable", "have-local-offer"].includes(signalingState)) throw createWebRtcDomException("InvalidStateError", "Cannot handle offer in signaling state");
} else if (["answer", "pranswer"].includes(type)) {
if (!["have-remote-offer", "have-local-pranswer"].includes(signalingState)) throw createWebRtcDomException("InvalidStateError", "Cannot handle answer in signaling state");
}
} else if (type === "offer") {
if (![
"stable",
"have-remote-offer",
"have-local-offer"
].includes(signalingState)) throw createWebRtcDomException("InvalidStateError", "Cannot handle offer in signaling state");
} else if (["answer", "pranswer"].includes(type)) {
if (!["have-local-offer", "have-remote-pranswer"].includes(signalingState)) throw createWebRtcDomException("InvalidStateError", "Cannot handle answer in signaling state");
}
}
/**
* オファーSDPを構築
*/
buildOfferSdp(transceivers, sctpTransport) {
const description = new SessionDescription();
addSDPHeader("offer", description);
(this.currentLocalDescription?.media ?? []).forEach((m, i) => {
const mid = m.rtp.muxId;
if (!mid) return;
if (m.kind === "application") {
if (!sctpTransport) throw new Error("sctpTransport not found");
sctpTransport.mLineIndex = i;
description.media.push(this.createMediaDescriptionForSctp(sctpTransport));
} else {
const transceiver = transceivers.find((t) => t.mid === mid);
if (!transceiver) {
if (m.direction === "inactive") {
description.media.push(m);
return;
}
throw new Error("transceiver not found");
}
transceiver.mLineIndex = i;
description.media.push(this.createMediaDescriptionForTransceiver(transceiver, transceiver.direction));
}
});
for (const transceiver of transceivers.filter((t) => !description.media.find((m) => m.rtp.muxId === t.mid))) {
if (transceiver.mid == void 0) transceiver.mid = this.allocateMid(this.midSuffix ? "av" : "");
const mediaDescription = this.createMediaDescriptionForTransceiver(transceiver, transceiver.direction);
if (transceiver.mLineIndex === void 0) {
transceiver.mLineIndex = description.media.length;
description.media.push(mediaDescription);
} else description.media[transceiver.mLineIndex] = mediaDescription;
}
if (sctpTransport && !description.media.find((m) => m.kind === "application")) {
sctpTransport.mLineIndex = description.media.length;
if (sctpTransport.mid == void 0) sctpTransport.mid = this.allocateMid(this.midSuffix ? "dc" : "");
description.media.push(this.createMediaDescriptionForSctp(sctpTransport));
}
if (this.bundlePolicy !== "disable") {
const mids = description.media.map((m) => m.rtp.muxId).filter((v) => v);
if (mids.length) {
const bundle = new GroupDescription("BUNDLE", mids);
description.group.push(bundle);
}
}
return description;
}
/**
* アンサーSDPを構築
*/
buildAnswerSdp({ transceivers, sctpTransport, signalingState }) {
if (!["have-remote-offer", "have-local-pranswer"].includes(signalingState)) throw new Error("createAnswer failed");
if (!this._remoteDescription) throw new Error("wrong state");
const description = new SessionDescription();
addSDPHeader("answer", description);
for (const remoteMedia of this._remoteDescription.media) {
let dtlsTransport;
let media;
if (["audio", "video"].includes(remoteMedia.kind)) {
const transceiver = transceivers.find((t) => t.mid === remoteMedia.rtp.muxId);
if (!transceiver) throw new Error(`Transceiver with mid=${remoteMedia.rtp.muxId} not found`);
media = this.createMediaDescriptionForTransceiver(transceiver, andDirection(transceiver.direction, transceiver.offerDirection));
dtlsTransport = transceiver.dtlsTransport;
} else if (remoteMedia.kind === "application") {
if (!sctpTransport || !sctpTransport.mid) throw new Error("sctpTransport not found");
media = this.createMediaDescriptionForSctp(sctpTransport);
dtlsTransport = sctpTransport.dtlsTransport;
} else throw new Error("invalid kind");
if (media.dtlsParams) {
if (dtlsTransport.role === "auto") media.dtlsParams.role = "client";
else media.dtlsParams.role = dtlsTransport.role;
}
if (remoteMedia.simulcastParameters && remoteMedia.simulcastParameters.length > 0) media.simulcastParameters = remoteMedia.simulcastParameters.map((v) => ({
...v,
direction: v.direction === "send" ? "recv" : "send"
}));
description.media.push(media);
}
if (this.bundlePolicy !== "disable") {
const bundle = new GroupDescription("BUNDLE", []);
for (const media of description.media) if (media.rtp.muxId) bundle.items.push(media.rtp.muxId);
description.group.push(bundle);
}
return description;
}
setLocalDescription(description) {
if (description.type === "offer" || description.type === "pranswer") {
this.pendingLocalDescription = description;
return;
}
this.currentLocalDescription = description;
if (this.pendingRemoteDescription) this.currentRemoteDescription = this.pendingRemoteDescription;
this.pendingLocalDescription = void 0;
this.pendingRemoteDescription = void 0;
}
setRemoteDescription(sessionDescription, signalingState) {
if (!sessionDescription.type) throw new Error("invalid sessionDescription");
if (sessionDescription.type === "rollback") {
if (!["have-remote-offer", "have-local-pranswer"].includes(signalingState)) throw createWebRtcDomException("InvalidStateError", "Cannot rollback remote description in signaling state");
this.pendingLocalDescription = void 0;
this.pendingRemoteDescription = void 0;
return;
}
if (!sessionDescription.sdp) throw new Error("invalid sessionDescription");
const remoteSdp = this.parseSdp({
sdp: sessionDescription.sdp,
isLocal: false,
signalingState,
type: sessionDescription.type
});
if (remoteSdp.type === "offer" || remoteSdp.type === "pranswer") this.pendingRemoteDescription = remoteSdp;
else {
if (this.pendingLocalDescription) this.currentLocalDescription = this.pendingLocalDescription;
this.currentRemoteDescription = remoteSdp;
this.pendingRemoteDescription = void 0;
this.pendingLocalDescription = void 0;
}
return remoteSdp;
}
rollbackLocalDescription(signalingState) {
if (!["have-local-offer", "have-local-pranswer"].includes(signalingState)) throw createWebRtcDomException("InvalidStateError", "Cannot rollback local description in signaling state");
this.pendingLocalDescription = void 0;
this.pendingRemoteDescription = void 0;
}
registerMid(mid) {
this.seenMid.add(mid);
}
get remoteIsBundled() {
const remoteSdp = this._remoteDescription;
if (!remoteSdp) return;
return remoteSdp.group.find((g) => g.semantic === "BUNDLE" && this.bundlePolicy !== "disable");
}
/**
* ローカルセッション記述を設定し、トランスポート情報を追加する
*/
setLocal(description, transceivers, sctpTransport) {
const transceiverByMLineIndex = new Map(transceivers.map((transceiver) => [transceiver?.mLineIndex, transceiver]));
const fallbackDtlsTransport = transceivers.find((transceiver) => transceiver?.dtlsTransport)?.dtlsTransport ?? sctpTransport?.dtlsTransport;
description.media.filter((m) => ["audio", "video"].includes(m.kind)).forEach((m, i) => {
const dtlsTransport = (transceiverByMLineIndex.get(i) ?? transceivers[i])?.dtlsTransport ?? fallbackDtlsTransport;
if (!dtlsTransport) throw new Error(`dtls transport not found for media index ${i}`);
this.addTransportDescription(m, dtlsTransport);
});
const sctpMedia = description.media.find((m) => m.kind === "application");
if (sctpTransport && sctpMedia) this.addTransportDescription(sctpMedia, sctpTransport.dtlsTransport);
this.setLocalDescription(description);
}
};
var log36 = debug("werift:packages/webrtc/src/transport/secureTransportManager.ts");
var SecureTransportManager = class {
connectionState = "new";
iceConnectionState = "new";
iceGatheringState = "new";
certificate;
iceGatheringStateChange = new Event2();
iceConnectionStateChange = new Event2();
onIceCandidate = new Event2();
connectionStateChange = new Event2();
config;
transceiverManager;
sctpManager;
constructor({ config, transceiverManager, sctpManager }) {
this.config = config;
this.transceiverManager = transceiverManager;
this.sctpManager = sctpManager;
if (this.config.dtls) {
const { keys } = this.config.dtls;
if (this.config.certificates[0]) this.certificate = this.config.certificates[0];
else if (keys) this.setupCertificate(keys);
}
}
get dtlsTransports() {
return [...this.transceiverManager.getTransceivers().map((t) => t?.dtlsTransport), this.sctpManager.sctpTransport?.dtlsTransport].filter((t) => t != void 0).reduce((acc, cur) => {
if (!acc.map((d) => d.id).includes(cur.id)) acc.push(cur);
return acc;
}, []);
}
get iceTransports() {
return this.dtlsTransports.map((d) => d.iceTransport);
}
setupCertificate(keys) {
this.certificate = new RTCCertificate(keys.keyPem, keys.certPem, keys.signatureHash);
}
createTransport() {
const existing = this.iceTransports.find((transport) => transport.state !== "closed");
const iceServerOptions = parseIceServers(this.config.iceServers);
const turnTransport = resolveTurnTransport({
parsedTurnTransport: iceServerOptions.turnTransport,
configuredTurnTransport: this.config.turnTransport,
forceTurnTCP: this.config.forceTurnTCP
});
const iceGatherer = new RTCIceGatherer({
...iceServerOptions,
iceLite: this.config.iceLite,
forceTurn: this.config.iceTransportPolicy === "relay",
portRange: this.config.icePortRange,
interfaceAddresses: this.config.iceInterfaceAddresses,
additionalHostAddresses: this.config.iceAdditionalHostAddresses,
filterStunResponse: this.config.iceFilterStunResponse,
filterCandidatePair: this.config.iceFilterCandidatePair,
localPasswordPrefix: this.config.icePasswordPrefix,
useIpv4: this.config.iceUseIpv4,
useIpv6: this.config.iceUseIpv6,
useTcp: this.config.iceUseTcp,
turnTransport,
turnTlsOptions: this.config.turnTlsOptions,
useLinkLocalAddress: this.config.iceUseLinkLocalAddress
});
if (existing) {
iceGatherer.connection.localUsername = existing.connection.localUsername;
iceGatherer.connection.localPassword = existing.connection.localPassword;
}
iceGatherer.onGatheringStateChange.subscribe(() => {
this.updateIceGatheringState();
});
this.updateIceGatheringState();
const iceTransport = new RTCIceTransport(iceGatherer);
iceTransport.onStateChange.subscribe(() => {
this.updateIceConnectionState();
});
return new RTCDtlsTransport(this.config, iceTransport, this.certificate, srtpProfiles);
}
handleNewIceCandidate({ candidate, media, remoteIsBundled, transceiver, sctpTransport, bundlePolicy }) {
if (bundlePolicy === "max-bundle" || remoteIsBundled) {
candidate.sdpMLineIndex = 0;
if (media) candidate.sdpMid = media.rtp.muxId;
} else {
if (transceiver) {
candidate.sdpMLineIndex = transceiver.mLineIndex;
candidate.sdpMid = transceiver.mid ?? void 0;
}
if (sctpTransport) {
candidate.sdpMLineIndex = sctpTransport.mLineIndex;
candidate.sdpMid = sctpTransport.mid;
}
}
if (candidate.foundation && !candidate.foundation.startsWith("candidate:")) candidate.foundation = "candidate:" + candidate.foundation;
this.onIceCandidate.execute(candidate);
return candidate;
}
async addIceCandidate(sdp, candidateMessage) {
const candidateText = candidateMessage?.candidate;
const sdpMid = candidateMessage?.sdpMid;
const sdpMLineIndex = candidateMessage?.sdpMLineIndex;
const usernameFragment = candidateMessage?.usernameFragment;
const isEndOfCandidates = candidateMessage == null || candidateText == null || candidateText === "";
const mediaIndices = this.resolveCandidateMediaIndices({
sdp,
isEndOfCandidates,
sdpMid,
sdpMLineIndex,
usernameFragment
});
if (isEndOfCandidates) {
const candidateTarget = mediaIndices.map((index) => this.getTransportByMLineIndex(sdp, index)).filter((iceTransport2) => !!iceTransport2).reduce((acc, transport) => {
if (!acc.find(({ id }) => id === transport.id)) acc.push(transport);
return acc;
}, []);
await Promise.all(candidateTarget.map((iceTransport2) => iceTransport2.addRemoteCandidate(void 0)));
return {
kind: "end-of-candidates",
mediaIndices
};
}
const candidate = IceCandidate.fromJSON(candidateMessage);
if (!candidate) throw createWebRtcDomException("OperationError", "Failed to parse ICE candidate");
const targetMediaIndex = mediaIndices[0];
const targetMedia = sdp.media[targetMediaIndex];
if (!targetMedia) throw createWebRtcDomException("OperationError", "ICE media section not found");
candidate.sdpMid = targetMedia.rtp.muxId ?? void 0;
candidate.sdpMLineIndex = targetMediaIndex;
const iceTransport = this.getTransportByMLineIndex(sdp, targetMediaIndex);
if (!iceTransport) throw createWebRtcDomException("OperationError", "ICE transport not found for candidate");
await iceTransport.addRemoteCandidate(candidate);
return {
kind: "candidate",
candidate,
mediaIndices: [targetMediaIndex]
};
}
resolveCandidateMediaIndices({ sdp, isEndOfCandidates, sdpMid, sdpMLineIndex, usernameFragment }) {
let mediaIndices;
if (typeof sdpMid === "string") {
const mediaIndex = sdp.media.findIndex((media) => media.rtp.muxId === sdpMid);
if (mediaIndex < 0) throw createWebRtcDomException("OperationError", "Media section for sdpMid was not found");
mediaIndices = [mediaIndex];
} else if (typeof sdpMLineIndex === "number") {
if (sdpMLineIndex < 0 || sdpMLineIndex >= sdp.media.length) throw createWebRtcDomException("OperationError", "Media section for sdpMLineIndex was not found");
mediaIndices = [sdpMLineIndex];
} else if (isEndOfCandidates) mediaIndices = sdp.media.map((_, index) => index);
else throw createWebRtcTypeError("sdpMid or sdpMLineIndex must be provided with a candidate");
if (typeof usernameFragment === "string") {
const matchingIndices = mediaIndices.filter((index) => sdp.media[index]?.iceParams?.usernameFragment === usernameFragment);
if (matchingIndices.length === 0) throw createWebRtcDomException("OperationError", "No media section matched the ICE usernameFragment");
mediaIndices = matchingIndices;
}
return mediaIndices;
}
getTransportByMid(mid) {
if (!mid) return;
let iceTransport;
const transceiver = this.transceiverManager.getTransceivers().find((t) => t.mid === mid);
if (transceiver) iceTransport = transceiver.dtlsTransport.iceTransport;
else if (!iceTransport && this.sctpManager.sctpTransport?.mid === mid) iceTransport = this.sctpManager.sctpTransport.dtlsTransport.iceTransport;
return iceTransport;
}
getTransportByMLineIndex(sdp, index) {
const media = sdp.media[index];
if (!media) return;
return this.getTransportByMid(media.rtp.muxId);
}
restartIce() {
for (const transport of this.iceTransports) transport.restart();
}
setLocalRole({ type, role }) {
for (const dtlsTransport of this.dtlsTransports) {
const iceTransport = dtlsTransport.iceTransport;
if (iceTransport.connection.iceLite) iceTransport.connection.iceControlling = false;
else if (iceTransport.connection.remoteIsLite) iceTransport.connection.iceControlling = true;
else if (type === "offer") iceTransport.connection.iceControlling = true;
else iceTransport.connection.iceControlling = false;
if (type === "answer") {
if (role) dtlsTransport.role = role;
}
}
}
updateIceGatheringState() {
const all = this.iceTransports;
function allMatch(...state) {
return all.filter((check) => state.includes(check.gatheringState)).length === all.length;
}
let newState;
if (all.length && allMatch("complete")) newState = "complete";
else if (!all.length || allMatch("new", "complete")) newState = "new";
else if (all.map((check) => check.gatheringState).includes("gathering")) newState = "gathering";
else newState = "new";
if (this.iceGatheringState === newState) return;
this.iceGatheringState = newState;
this.iceGatheringStateChange.execute(newState);
}
updateIceConnectionState() {
const all = this.iceTransports;
let newState;
function allMatch(...state) {
return all.filter((check) => state.includes(check.state)).length === all.length;
}
function anyMatch(...state) {
return all.some((check) => state.includes(check.state));
}
if (this.connectionState === "closed") newState = "closed";
else if (anyMatch("failed")) newState = "failed";
else if (anyMatch("disconnected")) newState = "disconnected";
else if (allMatch("new", "closed")) newState = "new";
else if (anyMatch("new", "checking")) newState = "checking";
else if (allMatch("completed", "closed")) newState = "completed";
else if (allMatch("connected", "completed", "closed")) newState = "connected";
else newState = "new";
if (this.iceConnectionState === newState) return;
log36("iceConnectionStateChange", newState);
this.iceConnectionState = newState;
this.iceConnectionStateChange.execute(newState);
if (newState === "failed" && this.connectionState !== "closed") this.setConnectionState("failed");
else if (newState === "disconnected" && this.connectionState === "connected") this.setConnectionState("disconnected");
}
async gatherCandidates(remoteIsBundled) {
const connected = this.iceTransports.find((transport) => transport.state === "connected" || transport.state === "completed");
if (remoteIsBundled && connected) log36("skipping ICE gathering for bundled connection");
else await Promise.allSettled(this.iceTransports.map((iceTransport) => iceTransport.gather())).catch((e) => {
log36("gatherCandidates failed", e);
});
}
setConnectionState(state) {
if (this.connectionState === state) return;
log36("connectionStateChange", state);
this.connectionState = state;
this.connectionStateChange.execute(state);
}
async getStats(timestamp) {
const stats = [];
for (const dtlsTransport of this.dtlsTransports) {
const transportStats = await dtlsTransport.getStats(timestamp);
if (transportStats) stats.push(...transportStats);
}
return stats;
}
async ensureCerts() {
if (!this.certificate) this.certificate = await RTCDtlsTransport.SetupCertificate();
for (const dtlsTransport of this.dtlsTransports) dtlsTransport.localCertificate = this.certificate;
}
async close() {
this.setConnectionState("closed");
await Promise.allSettled([...this.dtlsTransports.map((t) => t.stop())]);
this.iceGatheringStateChange.allUnsubscribe();
this.iceConnectionStateChange.allUnsubscribe();
this.onIceCandidate.allUnsubscribe();
this.connectionStateChange.allUnsubscribe();
}
};
var srtpProfiles = [SRTP_PROFILE.SRTP_AEAD_AES_128_GCM, SRTP_PROFILE.SRTP_AES128_CM_HMAC_SHA1_80];
var log37 = debug("werift:packages/webrtc/src/peerConnection.ts");
var RTCPeerConnection = class extends EventTarget {
id = randomUUID$1().toString();
cname = randomUUID$1().toString();
config = generateDefaultPeerConfig();
signalingState = "stable";
negotiationneeded = false;
needRestart = false;
router = new RtpRouter();
sdpManager;
transceiverManager;
sctpManager;
secureManager;
isClosed = false;
shouldNegotiationneeded = false;
lastCreatedAnswer;
lastCreatedOffer;
pendingRemoteCandidates = [];
iceGatheringStateChange = new Event2();
iceConnectionStateChange = new Event2();
signalingStateChange = new Event2();
connectionStateChange = new Event2();
onDataChannel = new Event2();
onRemoteTransceiverAdded = new Event2();
onTransceiverAdded = new Event2();
onIceCandidate = new Event2();
onNegotiationneeded = new Event2();
onTrack = new Event2();
eventHandlers = {};
get ondatachannel() {
return this.eventHandlers.ondatachannel ?? null;
}
set ondatachannel(value) {
this.eventHandlers.ondatachannel = value ?? void 0;
}
get onicecandidate() {
return this.eventHandlers.onicecandidate ?? null;
}
set onicecandidate(value) {
this.eventHandlers.onicecandidate = value ?? void 0;
}
get onicecandidateerror() {
return this.eventHandlers.onicecandidateerror ?? null;
}
set onicecandidateerror(value) {
this.eventHandlers.onicecandidateerror = value ?? void 0;
}
get onicegatheringstatechange() {
return this.eventHandlers.onicegatheringstatechange ?? null;
}
set onicegatheringstatechange(value) {
this.eventHandlers.onicegatheringstatechange = value ?? void 0;
}
get onnegotiationneeded() {
return this.eventHandlers.onnegotiationneeded ?? null;
}
set onnegotiationneeded(value) {
this.eventHandlers.onnegotiationneeded = value ?? void 0;
}
get onsignalingstatechange() {
return this.eventHandlers.onsignalingstatechange ?? null;
}
set onsignalingstatechange(value) {
this.eventHandlers.onsignalingstatechange = value ?? void 0;
}
get ontrack() {
return this.eventHandlers.ontrack ?? null;
}
set ontrack(value) {
this.eventHandlers.ontrack = value ?? void 0;
}
get onconnectionstatechange() {
return this.eventHandlers.onconnectionstatechange ?? null;
}
set onconnectionstatechange(value) {
this.eventHandlers.onconnectionstatechange = value ?? void 0;
}
get oniceconnectionstatechange() {
return this.eventHandlers.oniceconnectionstatechange ?? null;
}
set oniceconnectionstatechange(value) {
this.eventHandlers.oniceconnectionstatechange = value ?? void 0;
}
constructor(config = {}) {
super();
this.setConfiguration(config);
this.sdpManager = new SDPManager({
cname: this.cname,
bundlePolicy: this.config.bundlePolicy
});
this.transceiverManager = new TransceiverManager(this.cname, this.config, this.router);
this.transceiverManager.onTransceiverAdded.pipe(this.onTransceiverAdded);
this.transceiverManager.onRemoteTransceiverAdded.pipe(this.onRemoteTransceiverAdded);
this.transceiverManager.onTrack.subscribe(({ track, streams, transceiver }) => {
const event = new RTCTrackEvent({
track,
streams,
transceiver,
receiver: transceiver.receiver
});
this.onTrack.execute(track);
this.emit("track", event);
if (this.ontrack) this.ontrack(event);
});
this.transceiverManager.onNegotiationNeeded.subscribe(() => this.needNegotiation());
this.sctpManager = new SctpTransportManager();
this.sctpManager.onDataChannel.subscribe((channel) => {
this.onDataChannel.execute(channel);
const event = {
type: "datachannel",
channel
};
this.ondatachannel?.(event);
this.emit("datachannel", event);
});
this.secureManager = new SecureTransportManager({
config: this.config,
sctpManager: this.sctpManager,
transceiverManager: this.transceiverManager
});
this.secureManager.iceGatheringStateChange.subscribe((state) => {
this.iceGatheringStateChange.execute(state);
this.onicegatheringstatechange?.(new globalThis.Event("icegatheringstatechange"));
this.emit("icegatheringstatechange");
});
this.secureManager.iceConnectionStateChange.subscribe((state) => {
if (state === "closed") this.close();
this.iceConnectionStateChange.execute(state);
this.oniceconnectionstatechange?.();
this.emit("iceconnectionstatechange");
});
this.secureManager.connectionStateChange.subscribe((state) => {
this.connectionStateChange.execute(state);
this.onconnectionstatechange?.();
this.emit("connectionstatechange");
});
this.secureManager.onIceCandidate.subscribe((candidate) => {
const iceCandidate = candidate ? candidate.toJSON() : void 0;
this.onIceCandidate.execute(iceCandidate);
const event = {
type: "icecandidate",
candidate: iceCandidate
};
this.onicecandidate?.(event);
this.emit("icecandidate", event);
});
}
get connectionState() {
return this.secureManager.connectionState;
}
get iceConnectionState() {
return this.secureManager.iceConnectionState;
}
get iceGathererState() {
return this.secureManager.iceGatheringState;
}
get iceGatheringState() {
return this.secureManager.iceGatheringState;
}
get dtlsTransports() {
return this.secureManager.dtlsTransports;
}
get sctpTransport() {
return this.sctpManager.sctpTransport;
}
get sctp() {
return this.sctpTransport ?? null;
}
get sctpRemotePort() {
return this.sctpManager.sctpRemotePort;
}
get iceTransports() {
return this.secureManager.iceTransports;
}
get extIdUriMap() {
return this.router.extIdUriMap;
}
get iceGeneration() {
return this.iceTransports[0].connection.generation;
}
get localDescription() {
return this.sdpManager.localDescription ?? null;
}
get currentLocalDescription() {
return this.sdpManager.currentLocalDescription?.toJSON() ?? null;
}
get pendingLocalDescription() {
return this.sdpManager.pendingLocalDescription?.toJSON() ?? null;
}
get remoteDescription() {
return this.sdpManager.remoteDescription ?? null;
}
get currentRemoteDescription() {
return this.sdpManager.currentRemoteDescription?.toJSON() ?? null;
}
get pendingRemoteDescription() {
return this.sdpManager.pendingRemoteDescription?.toJSON() ?? null;
}
get canTrickleIceCandidates() {
const remoteDescription = this.sdpManager._remoteDescription;
if (!remoteDescription) return null;
return [remoteDescription.iceOptions, ...remoteDescription.media.map((media) => media.iceOptions)].filter((value) => !!value).join(" ").split(/\s+/).includes("trickle");
}
get remoteIsBundled() {
return this.sdpManager.remoteIsBundled;
}
/**@private */
get _localDescription() {
return this.sdpManager._localDescription;
}
/**@private */
get _remoteDescription() {
return this.sdpManager._remoteDescription;
}
getTransceivers() {
return this.transceiverManager.getTransceivers();
}
getSenders() {
return this.transceiverManager.getSenders();
}
getReceivers() {
return this.transceiverManager.getReceivers();
}
setConfiguration(config) {
const normalizedConfig = normalizePeerConfiguration(config);
const isReconfiguration = !!this.sdpManager;
if (normalizedConfig.rtcpMuxPolicy && normalizedConfig.rtcpMuxPolicy !== "require") throw new Error("rtcpMuxPolicy must be require");
if (normalizedConfig.iceCandidatePoolSize !== void 0 && (!Number.isInteger(normalizedConfig.iceCandidatePoolSize) || normalizedConfig.iceCandidatePoolSize < 0)) throw new Error("iceCandidatePoolSize must be a non-negative integer");
if (isReconfiguration && normalizedConfig.bundlePolicy !== void 0 && normalizedConfig.bundlePolicy !== this.config.bundlePolicy) throw new Error("bundlePolicy cannot be changed");
if (isReconfiguration && normalizedConfig.rtcpMuxPolicy !== void 0 && normalizedConfig.rtcpMuxPolicy !== this.config.rtcpMuxPolicy) throw new Error("rtcpMuxPolicy cannot be changed");
if (isReconfiguration && normalizedConfig.certificates !== void 0 && !hasSameCertificates(normalizedConfig.certificates, this.config.certificates)) throw new Error("certificates cannot be changed");
if (isReconfiguration && normalizedConfig.iceCandidatePoolSize !== void 0 && this.localDescription && normalizedConfig.iceCandidatePoolSize !== this.config.iceCandidatePoolSize) throw new Error("iceCandidatePoolSize cannot be changed after setLocalDescription");
if ((normalizedConfig.iceCandidatePoolSize ?? 0) > 0) throw new Error("iceCandidatePoolSize > 0 is not supported");
deepMerge(this.config, normalizedConfig);
if (this.config.icePortRange) {
const [min, max] = this.config.icePortRange;
if (min === max) throw new Error("should not be same value");
if (min >= max) throw new Error("The min must be less than max");
}
if (!Number.isInteger(this.config.maxMessageSize) || this.config.maxMessageSize < 0) throw new Error("maxMessageSize must be a non-negative integer");
if (this.sctpManager?.sctpTransport) this.sctpManager.sctpTransport.maxMessageSize = this.config.maxMessageSize;
for (const [i, codecParams] of enumerate2([...this.config.codecs.audio || [], ...this.config.codecs.video || []])) {
if (codecParams.payloadType != void 0) continue;
codecParams.payloadType = 96 + i;
switch (codecParams.name.toLowerCase()) {
case "rtx":
codecParams.parameters = `apt=${codecParams.payloadType - 1}`;
break;
case "red": if (codecParams.contentType === "audio") {
const redundant = codecParams.payloadType + 1;
codecParams.parameters = `${redundant}/${redundant}`;
codecParams.payloadType = 63;
}
}
}
[...this.config.headerExtensions.audio || [], ...this.config.headerExtensions.video || []].forEach((v, i) => {
v.id = 1 + i;
});
}
getConfiguration() {
return clonePeerConfiguration(this.config);
}
async createOffer({ iceRestart } = {}) {
if (iceRestart || this.needRestart) {
this.needRestart = false;
this.secureManager.restartIce();
}
await this.secureManager.ensureCerts();
for (const transceiver of this.transceiverManager.getTransceivers()) {
if (transceiver.codecs.length === 0) this.transceiverManager.assignTransceiverCodecs(transceiver);
if (transceiver.headerExtensions.length === 0) transceiver.headerExtensions = this.config.headerExtensions[transceiver.kind] ?? [];
}
const createdOffer = this.sdpManager.buildOfferSdp(this.transceiverManager.getTransceivers(), this.sctpTransport).toJSON();
this.lastCreatedOffer = createdOffer;
return createdOffer;
}
createSctpTransport() {
const sctp = this.sctpManager.createSctpTransport(this.config.maxMessageSize);
const dtlsTransport = this.findOrCreateTransport();
sctp.setDtlsTransport(dtlsTransport);
return sctp;
}
createDataChannel(label, options = {}) {
if (!this.sctpTransport) {
this.createSctpTransport();
this.needNegotiation();
}
const channel = this.sctpManager.createDataChannel(label, options);
if (!channel.sctp.dtlsTransport) {
const dtlsTransport = this.findOrCreateTransport();
channel.sctp.setDtlsTransport(dtlsTransport);
}
return channel;
}
removeTrack(sender) {
if (this.isClosed) throw createWebRtcDomException("InvalidStateError", "peer closed");
this.transceiverManager.removeTrack(sender);
this.needNegotiation();
}
needNegotiation = async () => {
this.invalidateLastCreatedDescriptions();
this.shouldNegotiationneeded = true;
if (this.negotiationneeded || this.signalingState !== "stable") return;
this.shouldNegotiationneeded = false;
setImmediate(() => {
this.negotiationneeded = true;
this.onNegotiationneeded.execute();
if (this.onnegotiationneeded) this.onnegotiationneeded(new globalThis.Event("negotiationneeded"));
this.emit("negotiationneeded");
});
};
invalidateLastCreatedDescriptions() {
this.lastCreatedAnswer = void 0;
this.lastCreatedOffer = void 0;
}
async waitForPendingDescriptionTask() {
this.assertNotClosed();
await Promise.resolve();
if (this.isClosed) await new Promise(() => void 0);
}
findOrCreateTransport() {
const existingDtlsTransport = this.dtlsTransports.find((transport) => transport.state !== "closed");
existingDtlsTransport?.iceTransport;
if (this.sdpManager.bundlePolicy === "max-bundle" || this.sdpManager.bundlePolicy !== "disable" && this.remoteIsBundled) {
if (existingDtlsTransport) return existingDtlsTransport;
}
const dtlsTransport = this.secureManager.createTransport();
dtlsTransport.onRtp.subscribe((rtp) => {
this.router.routeRtp(rtp);
});
dtlsTransport.onRtcp.subscribe((rtcp) => {
this.router.routeRtcp(rtcp);
});
const iceTransport = dtlsTransport.iceTransport;
iceTransport.onNegotiationNeeded.subscribe(() => {
this.needNegotiation();
});
iceTransport.onIceCandidate.subscribe((candidate) => {
if (!this.localDescription) {
log37("localDescription not found when ice candidate was gathered");
return;
}
if (!candidate) {
this.sdpManager.setLocal(this._localDescription, this.transceiverManager.getTransceivers(), this.sctpTransport);
this.onIceCandidate.execute(void 0);
if (this.onicecandidate) this.onicecandidate({ candidate: void 0 });
this.emit("icecandidate", { candidate: void 0 });
return;
}
if (!this._localDescription) {
log37("localDescription not found when ice candidate was gathered");
return;
}
this.secureManager.handleNewIceCandidate({
candidate,
bundlePolicy: this.sdpManager.bundlePolicy,
remoteIsBundled: !!this.sdpManager.remoteIsBundled,
media: this._localDescription.media[0],
transceiver: this.transceiverManager.getTransceivers().find((t) => t?.dtlsTransport?.iceTransport.id === iceTransport.id),
sctpTransport: this.sctpTransport?.dtlsTransport.iceTransport.id === iceTransport.id ? this.sctpTransport : void 0
});
});
return dtlsTransport;
}
async setLocalDescription(sessionDescription) {
const implicitOfferState = [
"stable",
"have-local-offer",
"have-remote-pranswer"
];
await this.waitForPendingDescriptionTask();
if (sessionDescription?.type === "rollback") {
this.sdpManager.rollbackLocalDescription(this.signalingState);
this.setSignalingState("stable");
if (this.shouldNegotiationneeded) this.needNegotiation();
this.invalidateLastCreatedDescriptions();
return;
}
const generatedDescription = !sessionDescription?.type || !sessionDescription.sdp || sessionDescription.sdp.length === 0 ? sessionDescription?.type === "offer" ? this.lastCreatedOffer ?? await this.createOffer() : sessionDescription?.type === "answer" || sessionDescription?.type === "pranswer" ? this.lastCreatedAnswer ?? await this.createAnswer() : implicitOfferState.includes(this.signalingState) ? this.lastCreatedOffer ?? await this.createOffer() : this.lastCreatedAnswer ?? await this.createAnswer() : void 0;
sessionDescription = {
type: sessionDescription?.type ?? generatedDescription.type,
sdp: sessionDescription?.sdp && sessionDescription.sdp.length > 0 ? sessionDescription.sdp : generatedDescription.sdp
};
if (sessionDescription.type === "offer" && this.lastCreatedOffer && sessionDescription.sdp !== this.lastCreatedOffer.sdp) throw createWebRtcDomException("InvalidModificationError", "setLocalDescription must use the latest created offer");
const descriptionType = sessionDescription.type;
const descriptionSdp = sessionDescription.sdp;
const description = this.sdpManager.parseSdp({
sdp: descriptionSdp,
isLocal: true,
signalingState: this.signalingState,
type: descriptionType
});
if (description.type === "offer") this.setSignalingState("have-local-offer");
else if (description.type === "answer") this.setSignalingState("stable");
else if (description.type === "pranswer") this.setSignalingState("have-local-pranswer");
for (const [i, media] of enumerate2(description.media)) {
const mid = media.rtp.muxId;
this.sdpManager.registerMid(mid);
if (["audio", "video"].includes(media.kind)) {
const transceiver = this.transceiverManager.getTransceiverByMLineIndex(i);
if (transceiver) transceiver.mid = mid;
}
if (media.kind === "application" && this.sctpTransport) this.sctpTransport.mid = mid;
}
const role = description.media.find((media) => media.dtlsParams)?.dtlsParams?.role;
this.secureManager.setLocalRole({
type: description.type === "offer" ? "offer" : "answer",
role
});
if (["answer", "pranswer"].includes(description.type)) for (const t of this.transceiverManager.getTransceivers()) {
const direction = andDirection(t.direction, t.offerDirection);
t.setCurrentDirection(direction);
}
this.sdpManager.setLocal(description, this.transceiverManager.getTransceivers(), this.sctpTransport);
await this.gatherCandidates().catch((e) => {
log37("gatherCandidates failed", e);
});
if (description.type === "answer") this.connect().catch((err5) => {
log37("connect failed", err5);
this.secureManager.setConnectionState("failed");
});
this.sdpManager.setLocal(description, this.transceiverManager.getTransceivers(), this.sctpTransport);
if (this.shouldNegotiationneeded) this.needNegotiation();
this.invalidateLastCreatedDescriptions();
return description;
}
async gatherCandidates() {
await this.secureManager.gatherCandidates(!!this.sdpManager.remoteIsBundled);
}
async addIceCandidate(candidateMessage = {}) {
if (this.isClosed) throw createWebRtcDomException("InvalidStateError", "is closed");
if (!this.remoteDescription || !this.sdpManager._remoteDescription) {
this.pendingRemoteCandidates.push(candidateMessage);
return;
}
await this.applyRemoteIceCandidate(candidateMessage);
}
async applyRemoteIceCandidate(candidateMessage) {
const sdp = this.sdpManager._remoteDescription;
if (!sdp) return;
const appliedCandidate = await this.secureManager.addIceCandidate(sdp, candidateMessage);
const remoteDescription = this.sdpManager._remoteDescription;
if (!remoteDescription || !appliedCandidate) return;
if (appliedCandidate.kind === "end-of-candidates") {
for (const mediaIndex of appliedCandidate.mediaIndices) {
const media = remoteDescription.media[mediaIndex];
if (media) media.iceCandidatesComplete = true;
}
return;
}
for (const mediaIndex of appliedCandidate.mediaIndices) {
const media = remoteDescription.media[mediaIndex];
if (!media) continue;
media.iceCandidates.push(appliedCandidate.candidate);
}
}
async flushPendingRemoteCandidates() {
while (this.pendingRemoteCandidates.length > 0 && this.remoteDescription && this.sdpManager._remoteDescription) {
const candidate = this.pendingRemoteCandidates.shift();
await this.applyRemoteIceCandidate(candidate ?? null);
}
}
async connect() {
log37("start connect");
if ((await Promise.allSettled(this.dtlsTransports.map(async (dtlsTransport) => {
const { iceTransport } = dtlsTransport;
if (iceTransport.state === "connected") return;
const checkDtlsConnected = () => dtlsTransport.state === "connected";
if (checkDtlsConnected()) return;
this.secureManager.setConnectionState("connecting");
await iceTransport.start().catch((err5) => {
log37("iceTransport.start failed", err5);
throw err5;
});
if (checkDtlsConnected()) return;
await dtlsTransport.start().catch((err5) => {
log37("dtlsTransport.start failed", err5);
throw err5;
});
if (this.sctpTransport && this.sctpTransport.dtlsTransport.id === dtlsTransport.id) await this.sctpManager.connectSctp();
}))).find((r) => r.status === "rejected")) this.secureManager.setConnectionState("failed");
else this.secureManager.setConnectionState("connected");
}
restartIce() {
this.needRestart = true;
this.needNegotiation();
}
async setRemoteDescription(sessionDescription) {
if (sessionDescription instanceof SessionDescription) sessionDescription = sessionDescription.toSdp();
await this.waitForPendingDescriptionTask();
if (sessionDescription.type === "offer" && ["have-local-offer", "have-local-pranswer"].includes(this.signalingState)) {
this.sdpManager.rollbackLocalDescription(this.signalingState);
this.shouldNegotiationneeded = true;
this.setSignalingState("stable");
await Promise.resolve();
}
const remoteSdp = this.sdpManager.setRemoteDescription(sessionDescription, this.signalingState);
if (!remoteSdp) {
this.setSignalingState("stable");
if (this.shouldNegotiationneeded) this.needNegotiation();
this.invalidateLastCreatedDescriptions();
return;
}
let bundleTransport;
const matchTransceiverWithMedia = (transceiver, media) => transceiver.kind === media.kind && [null, media.rtp.muxId].includes(transceiver.mid);
let transports = remoteSdp.media.map((remoteMedia, i) => {
let dtlsTransport;
if (["audio", "video"].includes(remoteMedia.kind)) {
let transceiver = this.transceiverManager.getTransceivers().find((t) => matchTransceiverWithMedia(t, remoteMedia));
if (!transceiver) {
transceiver = this.addTransceiver(remoteMedia.kind, { direction: "recvonly" });
transceiver.mid = remoteMedia.rtp.muxId ?? null;
this.onRemoteTransceiverAdded.execute(transceiver);
} else if (transceiver.direction === "inactive" && transceiver.stopping) {
transceiver.stopped = true;
if (sessionDescription.type === "answer") transceiver.setCurrentDirection("inactive");
return;
}
if (this.sdpManager.remoteIsBundled) {
if (!bundleTransport) bundleTransport = transceiver.dtlsTransport;
else transceiver.setDtlsTransport(bundleTransport);
}
dtlsTransport = transceiver.dtlsTransport;
this.transceiverManager.setRemoteRTP(transceiver, remoteMedia, remoteSdp.type, i);
} else if (remoteMedia.kind === "application") {
let sctpTransport = this.sctpTransport;
if (!sctpTransport) {
sctpTransport = this.createSctpTransport();
sctpTransport.mid = remoteMedia.rtp.muxId;
}
if (this.sdpManager.remoteIsBundled) {
if (!bundleTransport) bundleTransport = sctpTransport.dtlsTransport;
else sctpTransport.setDtlsTransport(bundleTransport);
}
dtlsTransport = sctpTransport.dtlsTransport;
this.sctpManager.setRemoteSCTP(remoteMedia, i);
} else throw new Error("invalid media kind");
const iceTransport = dtlsTransport.iceTransport;
if (remoteMedia.iceParams) {
const renomination = !!this.sdpManager.inactiveRemoteMedia;
iceTransport.setRemoteParams(remoteMedia.iceParams, renomination);
if (remoteMedia.iceParams.iceLite && !iceTransport.connection.iceLite) iceTransport.connection.iceControlling = true;
}
if (remoteMedia.dtlsParams) dtlsTransport.setRemoteParams(remoteMedia.dtlsParams);
remoteMedia.iceCandidates.forEach(iceTransport.addRemoteCandidate);
if (remoteMedia.iceCandidatesComplete) iceTransport.addRemoteCandidate(void 0);
if (remoteSdp.type === "answer" && remoteMedia.dtlsParams?.role) dtlsTransport.role = remoteMedia.dtlsParams.role === "client" ? "server" : "client";
return iceTransport;
});
transports = transports.filter((iceTransport) => !!iceTransport);
const removedTransceivers = this.transceiverManager.getTransceivers().filter((t) => remoteSdp.media.find((m) => matchTransceiverWithMedia(t, m)) == void 0);
if (sessionDescription.type === "answer") for (const transceiver of removedTransceivers) {
transceiver.stop();
transceiver.stopped = true;
}
if (remoteSdp.type === "offer") this.setSignalingState("have-remote-offer");
else if (remoteSdp.type === "answer") this.setSignalingState("stable");
else if (remoteSdp.type === "pranswer") this.setSignalingState("have-remote-pranswer");
await this.flushPendingRemoteCandidates();
if (remoteSdp.type === "answer") {
log37("caller start connect");
this.connect().catch((err5) => {
log37("connect failed", err5);
this.secureManager.setConnectionState("failed");
});
}
this.negotiationneeded = false;
if (this.shouldNegotiationneeded) this.needNegotiation();
this.invalidateLastCreatedDescriptions();
}
addTransceiver(trackOrKind, options = {}) {
const dtlsTransport = this.findOrCreateTransport();
const transceiver = this.transceiverManager.addTransceiver(trackOrKind, dtlsTransport, options);
this.secureManager.updateIceConnectionState();
this.needNegotiation();
return transceiver;
}
addTrack(track, ...streams) {
if (this.isClosed) throw createWebRtcDomException("InvalidStateError", "is closed");
const transceiver = this.transceiverManager.addTrack(track, streams);
if (!transceiver.dtlsTransport) {
const dtlsTransport = this.findOrCreateTransport();
transceiver.setDtlsTransport(dtlsTransport);
}
this.needNegotiation();
return transceiver.sender;
}
async createAnswer() {
this.assertNotClosed();
await this.secureManager.ensureCerts();
const createdAnswer = this.sdpManager.buildAnswerSdp({
transceivers: this.transceiverManager.getTransceivers(),
sctpTransport: this.sctpTransport,
signalingState: this.signalingState
}).toJSON();
this.lastCreatedAnswer = createdAnswer;
return createdAnswer;
}
assertNotClosed() {
if (this.isClosed) throw createWebRtcDomException("InvalidStateError", "RTCPeerConnection is closed");
}
setSignalingState(state) {
if (this.signalingState === state) return;
log37("signalingStateChange", state);
this.signalingState = state;
this.signalingStateChange.execute(state);
if (this.onsignalingstatechange) this.onsignalingstatechange(new globalThis.Event("signalingstatechange"));
this.emit("signalingstatechange");
}
createPeerConnectionStats(timestamp) {
return {
type: "peer-connection",
id: generateStatsId("peer-connection", this.id),
timestamp,
dataChannelsOpened: this.sctpManager.dataChannelsOpened,
dataChannelsClosed: this.sctpManager.dataChannelsClosed
};
}
async getStats(selector) {
const timestamp = getStatsTimestamp();
const stats = [];
if (!selector) stats.push(this.createPeerConnectionStats(timestamp));
stats.push(...this.transceiverManager.collectStats(timestamp));
const transportStats = await this.secureManager.getStats(timestamp);
stats.push(...transportStats);
if (!selector && this.sctpTransport) {
const dataChannelStats = await this.sctpManager.getStats(timestamp);
if (dataChannelStats) stats.push(...dataChannelStats);
}
if (!selector) return buildStatsReport(stats);
return buildStatsReport(stats, this.transceiverManager.getStatsRootIds(selector));
}
async close() {
if (this.isClosed) return;
this.isClosed = true;
this.pendingRemoteCandidates.length = 0;
this.setSignalingState("closed");
this.transceiverManager.close();
await this.secureManager.close();
await this.sctpManager.close();
this.completePeerEvents();
log37("peerConnection closed");
}
completePeerEvents() {
const events = [
this.onDataChannel,
this.iceGatheringStateChange,
this.iceConnectionStateChange,
this.signalingStateChange,
this.connectionStateChange,
this.onTransceiverAdded,
this.onRemoteTransceiverAdded,
this.onIceCandidate,
this.onNegotiationneeded
];
for (const event of events) if (!event.ended) event.complete();
}
};
var findCodecByMimeType = (codecs, target) => codecs.find((localCodec) => localCodec.mimeType.toLowerCase() === target.mimeType.toLowerCase()) ? target : void 0;
function generateDefaultPeerConfig() {
return {
codecs: {
audio: [useOPUS(), usePCMU()],
video: [useVP8()]
},
headerExtensions: {
audio: [],
video: []
},
iceTransportPolicy: "all",
iceLite: false,
iceServers: [{ urls: "stun:stun.l.google.com:19302" }],
icePortRange: void 0,
iceInterfaceAddresses: void 0,
iceAdditionalHostAddresses: void 0,
iceUseIpv4: true,
iceUseIpv6: true,
iceUseTcp: false,
turnTransport: void 0,
turnTlsOptions: void 0,
iceFilterStunResponse: void 0,
iceFilterCandidatePair: void 0,
icePasswordPrefix: void 0,
iceUseLinkLocalAddress: void 0,
dtls: {},
bundlePolicy: "max-compat",
rtcpMuxPolicy: "require",
iceCandidatePoolSize: 0,
certificates: [],
debug: {},
midSuffix: false,
forceTurnTCP: false,
maxMessageSize: DEFAULT_MAX_MESSAGE_SIZE
};
}
var defaultPeerConfig = generateDefaultPeerConfig();
function normalizePeerConfiguration(config) {
const input = Object(config ?? {});
const normalizedConfig = { ...input };
if (input.bundlePolicy === "balanced") normalizedConfig.bundlePolicy = "max-compat";
if ("certificates" in input) {
if (input.certificates === void 0) normalizedConfig.certificates = void 0;
else if (!Array.isArray(input.certificates) || input.certificates.some((certificate) => certificate == null)) throw createWebRtcTypeError("certificates must be an array of RTCCertificate");
else normalizedConfig.certificates = [...input.certificates];
}
if ("iceCandidatePoolSize" in input) normalizedConfig.iceCandidatePoolSize = coerceUnsignedShort(input.iceCandidatePoolSize, "iceCandidatePoolSize");
return normalizedConfig;
}
function coerceUnsignedShort(value, name) {
const coerced = Number(value);
if (!Number.isFinite(coerced) || !Number.isInteger(coerced) || coerced < 0 || coerced > 65535) throw createWebRtcTypeError(`${name} must be an unsigned short`);
return coerced;
}
function hasSameCertificates(left, right) {
return left.length === right.length && left.every((certificate, index) => certificate === right[index]);
}
function clonePeerConfiguration(config) {
return {
...config,
codecs: {
audio: config.codecs.audio ? [...config.codecs.audio] : void 0,
video: config.codecs.video ? [...config.codecs.video] : void 0
},
headerExtensions: {
audio: config.headerExtensions.audio ? [...config.headerExtensions.audio] : void 0,
video: config.headerExtensions.video ? [...config.headerExtensions.video] : void 0
},
iceServers: config.iceServers.map((server) => ({
...server,
urls: Array.isArray(server.urls) ? [...server.urls] : server.urls
})),
icePortRange: config.icePortRange ? [...config.icePortRange] : void 0,
iceAdditionalHostAddresses: config.iceAdditionalHostAddresses ? [...config.iceAdditionalHostAddresses] : void 0,
dtls: { ...config.dtls },
certificates: [...config.certificates],
debug: { ...config.debug }
};
}
var RTCTrackEvent = class {
type = "track";
track;
streams;
transceiver;
receiver;
constructor(init) {
this.track = init.track;
this.streams = [...init.streams];
this.transceiver = init.transceiver;
this.receiver = init.receiver;
}
};
var log38 = debug("werift:packages/webrtc/src/media/rtpTransceiverManager.ts");
var TransceiverManager = class {
constructor(cname, config, router) {
this.cname = cname;
this.config = config;
this.router = router;
}
transceivers = [];
onTransceiverAdded = new Event2();
onRemoteTransceiverAdded = new Event2();
onTrack = new Event2();
onNegotiationNeeded = new Event2();
getTransceivers() {
return this.transceivers;
}
getSenders() {
return this.getTransceivers().map((t) => t.sender);
}
getReceivers() {
return this.getTransceivers().map((t) => t.receiver);
}
getTransceiverByMLineIndex(index) {
return this.transceivers.find((transceiver) => transceiver.mLineIndex === index);
}
pushTransceiver(t) {
this.transceivers.push(t);
}
replaceTransceiver(t, index) {
this.transceivers[index] = t;
}
addTransceiver(trackOrKind, dtlsTransport, options = {}) {
const kind = typeof trackOrKind === "string" ? trackOrKind : trackOrKind.kind;
const direction = options.direction || "sendrecv";
const sender = new RTCRtpSender(trackOrKind);
const newTransceiver = new RTCRtpTransceiver(kind, dtlsTransport, new RTCRtpReceiver(this.config, kind, sender.ssrc), sender, direction);
newTransceiver.options = options;
newTransceiver.sender.setStreams(options.streams ?? []);
newTransceiver.sender.setSendEncodings((options.sendEncodings ?? []).map((encoding) => ({ ...encoding })));
this.router.registerRtpSender(newTransceiver.sender);
const inactiveTransceiverIndex = this.transceivers.findIndex((t) => t.currentDirection === "inactive" && !t.usedForSender);
const inactiveTransceiver = this.transceivers.find((t) => t.currentDirection === "inactive" && !t.usedForSender);
if (inactiveTransceiverIndex > -1 && inactiveTransceiver) {
this.replaceTransceiver(newTransceiver, inactiveTransceiverIndex);
newTransceiver.mLineIndex = inactiveTransceiver.mLineIndex;
newTransceiver.mid = inactiveTransceiver.mid;
inactiveTransceiver.setCurrentDirection(void 0);
} else this.pushTransceiver(newTransceiver);
this.onTransceiverAdded.execute(newTransceiver);
return newTransceiver;
}
addTrack(track, streams = []) {
if (this.getSenders().find((sender) => sender.track?.uuid === track.uuid)) throw createWebRtcDomException("InvalidAccessError", "Track already added");
const emptyTrackSenderTransceiver = this.transceivers.find((t) => t.sender.track == void 0 && t.kind === track.kind && SenderDirections.includes(t.direction) === true);
if (emptyTrackSenderTransceiver) {
const sender = emptyTrackSenderTransceiver.sender;
sender.setStreams(streams);
sender.registerTrack(track);
emptyTrackSenderTransceiver.options = {
...emptyTrackSenderTransceiver.options,
streams
};
return emptyTrackSenderTransceiver;
}
const notSendTransceiver = this.transceivers.find((t) => t.sender.track == void 0 && t.kind === track.kind && SenderDirections.includes(t.direction) === false && !t.usedForSender);
if (notSendTransceiver) {
const sender = notSendTransceiver.sender;
sender.setStreams(streams);
sender.registerTrack(track);
notSendTransceiver.options = {
...notSendTransceiver.options,
streams
};
switch (notSendTransceiver.direction) {
case "recvonly":
notSendTransceiver.setDirection("sendrecv");
break;
case "inactive": notSendTransceiver.setDirection("sendonly");
}
return notSendTransceiver;
} else return this.addTransceiver(track, void 0, {
direction: "sendrecv",
streams
});
}
removeTrack(sender) {
if (!this.getSenders().find(({ ssrc }) => sender.ssrc === ssrc)) throw createWebRtcDomException("InvalidAccessError", "Sender does not exist");
const transceiver = this.transceivers.find(({ sender: { ssrc } }) => sender.ssrc === ssrc);
if (!transceiver) throw new Error("No matching transceiver found");
if (transceiver.stopping || transceiver.stopped) return;
sender.stop();
if (["recvonly", "inactive"].includes(transceiver.currentDirection ?? "")) {
this.onNegotiationNeeded.execute();
return;
}
if (transceiver.direction === "sendrecv") transceiver.setDirection("recvonly");
else if (transceiver.direction === "sendonly" || transceiver.direction === "recvonly") transceiver.setDirection("inactive");
}
assignTransceiverCodecs(transceiver) {
transceiver.codecs = this.config.codecs[transceiver.kind].filter((codecCandidate) => {
switch (codecCandidate.direction) {
case "recvonly":
if (ReceiverDirection.includes(transceiver.direction)) return true;
return false;
case "sendonly":
if (SenderDirections.includes(transceiver.direction)) return true;
return false;
case "sendrecv":
if ([
"sendrecv",
"recvonly",
"sendonly"
].includes(transceiver.direction)) return true;
return false;
case "all": return true;
default: return false;
}
});
}
getLocalRtpParams(transceiver) {
if (transceiver.mid == void 0) throw new Error("mid not assigned");
return {
codecs: transceiver.codecs,
muxId: transceiver.mid,
headerExtensions: transceiver.headerExtensions,
rtcp: {
cname: this.cname,
ssrc: transceiver.sender.ssrc,
mux: true
}
};
}
getRemoteRtpParams(media, transceiver) {
return {
muxId: media.rtp.muxId,
rtcp: media.rtp.rtcp,
codecs: transceiver.codecs,
headerExtensions: transceiver.headerExtensions,
encodings: Object.values(transceiver.codecs.reduce((acc, codec) => {
if (codec.name.toLowerCase() === "rtx") {
const apt = acc[codecParametersFromString(codec.parameters ?? "")["apt"]];
if (apt && media.ssrc.length === 2) apt.rtx = new RTCRtpRtxParameters({ ssrc: media.ssrc[1].ssrc });
return acc;
}
acc[codec.payloadType] = new RTCRtpCodingParameters({
ssrc: media.ssrc[0]?.ssrc,
payloadType: codec.payloadType
});
return acc;
}, {}))
};
}
setRemoteRTP(transceiver, remoteMedia, type, mLineIndex) {
if (!transceiver.mid) transceiver.mid = remoteMedia.rtp.muxId ?? null;
transceiver.mLineIndex = mLineIndex;
transceiver.codecs = remoteMedia.rtp.codecs.filter((remoteCodec) => {
const localCodecs = this.config.codecs[remoteMedia.kind] || [];
const existCodec = findCodecByMimeType(localCodecs, remoteCodec);
if (!existCodec) return false;
if (existCodec?.name.toLowerCase() === "rtx") {
const pt = codecParametersFromString(existCodec.parameters ?? "")["apt"];
const origin = remoteMedia.rtp.codecs.find((c) => c.payloadType === pt);
if (!origin) return false;
return !!findCodecByMimeType(localCodecs, origin);
}
return true;
});
log38("negotiated codecs", transceiver.codecs);
if (transceiver.codecs.length === 0) throw new Error("negotiate codecs failed.");
transceiver.headerExtensions = remoteMedia.rtp.headerExtensions.filter((extension) => (this.config.headerExtensions[remoteMedia.kind] || []).find((v) => v.uri === extension.uri));
const mediaDirection = remoteMedia.direction ?? "inactive";
const direction = reverseDirection(mediaDirection);
if (["answer", "pranswer"].includes(type)) transceiver.setCurrentDirection(direction);
else transceiver.offerDirection = direction;
const localParams = this.getLocalRtpParams(transceiver);
transceiver.sender.prepareSend(localParams);
if (["recvonly", "sendrecv"].includes(transceiver.direction)) {
const remotePrams = this.getRemoteRtpParams(remoteMedia, transceiver);
for (const param of remoteMedia.simulcastParameters) this.router.registerRtpReceiverByRid(transceiver, param, remotePrams);
transceiver.receiver.prepareReceive(remotePrams);
this.router.registerRtpReceiverBySsrc(transceiver, remotePrams);
}
if (remoteMedia.port !== 0 && ["sendonly", "sendrecv"].includes(mediaDirection)) {
const remoteStreamIds = [...new Set(remoteMedia.msids.map((msid) => msid.split(" ")[0]))];
const remoteTrackId = remoteMedia.msids[0]?.split(" ")[1];
transceiver.receiver.remoteStreamId = remoteStreamIds[0];
transceiver.receiver.remoteStreamIds = remoteStreamIds;
transceiver.receiver.remoteTrackId = remoteTrackId;
this.onTrack.execute({
track: transceiver.receiver.track,
transceiver,
streams: remoteStreamIds.map((id) => new MediaStream({
id,
tracks: [transceiver.receiver.track]
}))
});
}
if (remoteMedia.ssrc[0]?.ssrc) transceiver.receiver.setupTWCC(remoteMedia.ssrc[0].ssrc);
}
collectStats(timestamp) {
const stats = [];
for (const transceiver of this.transceivers) {
if (transceiver.sender) stats.push(...transceiver.sender.collectStats(timestamp));
if (transceiver.receiver) stats.push(...transceiver.receiver.collectStats(timestamp));
const codecStats = transceiver.collectCodecStats(timestamp);
if (codecStats) stats.push(...codecStats);
}
return stats;
}
getStatsRootIds(selector) {
if (!selector) return [];
const rootIds = [];
for (const transceiver of this.transceivers) {
if (transceiver.sender.track === selector) rootIds.push(...transceiver.sender.getStatsRootIds());
if (transceiver.receiver.tracks.includes(selector)) rootIds.push(...transceiver.receiver.getStatsRootIds(selector));
}
return rootIds;
}
/**
* 全トランシーバーのreceiver/senderのstopを呼ぶcloseメソッド
*/
close() {
for (const transceiver of this.transceivers) transceiver.forceStop();
this.onTransceiverAdded.allUnsubscribe();
this.onRemoteTransceiverAdded.allUnsubscribe();
this.onTrack.allUnsubscribe();
this.onNegotiationNeeded.allUnsubscribe();
}
};
var SignalingStates = [
"stable",
"have-local-offer",
"have-remote-offer",
"have-local-pranswer",
"have-remote-pranswer",
"closed"
];
var ConnectionStates = [
"closed",
"failed",
"disconnected",
"new",
"connecting",
"connected"
];
//#endregion
export { AV1Obu, AV1RtpPayload, AttributeKeys, BitStream, BitWriter, BitWriter2, BufferChain, CONSENT_FAILURES, CONSENT_INTERVAL, CONSENT_RESPONSE_TIMEOUT, CONSENT_RESPONSE_TIMEOUT_MIN, CONSENT_TIMEOUT, COOKIE, Candidate, CandidatePair, CandidatePairState, CipherContext, CipherSuite, CipherSuiteList, Connection, ConnectionStates, CurveType, DEFAULT_MAX_MESSAGE_SIZE, DePacketizerBase, Directions, DtlsClient, DtlsServer, DtlsSocket, DtlsStates, Event2 as Event, EventDisposer, ExtensionProfiles, FINGERPRINT_LENGTH, FINGERPRINT_XOR, GenericNack, GroupDescription, H264RtpPayload, HEADER_LENGTH, HashAlgorithm, ICE_COMPLETED, ICE_FAILED, INTEGRITY_LENGTH, IPV4_PROTOCOL, IPV6_PROTOCOL, IceCandidate, IceGathererStates, IceTransportStates, Inactive, Int, MediaDescription, MediaStream, MediaStreamTrack, MediaStreamTrackFactory, Message, NalUnitType, NamedCurveAlgorithm, NamedCurveAlgorithmList, OpusRtpPayload, PacketChunk, PacketResult, PacketStatus, PictureLossIndication, Profiles, PromiseQueue, ProtectionProfileAeadAes128Gcm, ProtectionProfileAes128CmHmacSha1_80, RETRY_MAX, RETRY_RTO, RTCCertificate, RTCDataChannel, RTCDataChannelParameters, RTCDtlsFingerprint, RTCDtlsParameters, RTCDtlsTransport, RTCIceCandidate, RTCIceGatherer, RTCIceParameters, RTCIceTransport, RTCP_HEADER_SIZE, RTCPeerConnection, RTCRtcpFeedback, RTCRtcpParameters, RTCRtpCodecParameters, RTCRtpCodingParameters, RTCRtpHeaderExtensionParameters, RTCRtpReceiver, RTCRtpRtxParameters, RTCRtpSender, RTCRtpSimulcastParameters, RTCRtpTransceiver, RTCSctpCapabilities2 as RTCSctpCapabilities, RTCSctpTransport, RTCSessionDescription, RTCStatsReport, RTCTrackEvent, RTP_EXTENSION_URI, ReceiverEstimatedMaxBitrate, RecvDelta, Recvonly, Red, RedEncoder, RedHandler, RedHeader, RtcpHeader, RtcpPacketConverter, RtcpPayloadSpecificFeedback, RtcpReceiverInfo, RtcpRrPacket, RtcpSenderInfo, RtcpSourceDescriptionPacket, RtcpSrPacket, RtcpTransportLayerFeedback, RtpBuilder, RtpHeader, RtpPacket, RtpRouter, RunLengthChunk, SDPManager, Sendonly, Sendrecv, SessionDescription, SignalingStates, SignatureAlgorithm, SignatureScheme, SourceDescriptionChunk, SourceDescriptionItem, SrtcpSession, SrtpAuthenticationError, SrtpContext, SrtpSession, SsrcDescription, StatusVectorChunk, StunOverTurnProtocol, StunProtocol, TcpActiveProtocol, TcpPassiveProtocol, TcpTransport, TlsTransport, TransceiverManager, TransportWideCC, TurnProtocol, UdpTransport, Vp8RtpPayload, Vp9RtpPayload, WeriftError, addSDPHeader, andDirection, buffer2ArrayBuffer, bufferArrayXor, bufferReader, bufferWriter, bufferWriterLE, bufferXor, buildStatsReport, candidateFoundation, candidateFromIce, candidateFromSdp, candidateLocalPreference, candidatePairPriority, candidatePriority, candidateToIce, candidateToSdp, certificateTypes, classes, codecParametersFromString, codecParametersToString, compactNtp, consentResponseTimeoutMs, crc32, crc32c, createBufferWriter, createSelfSignedCertificate, createStunOverTurnClient, createTurnClient, dePacketizeRtpPackets, debug, deepMerge, defaultOptions, defaultPeerConfig, depacketizerCodecs, deserializeAbsSendTime, deserializeAudioLevelIndication, deserializeString, deserializeUint16BE, deserializeVideoOrientation, dumpBuffer, encodeTcpFrame, enumerate, findCodecByMimeType, findPort, fingerprint, generateCodecStatsId, generateStatsId, getBit, getDataChannelMessageSize, getGlobalIp, getHostAddresses, getReferencedStatsIds, getStatsTimestamp, growBufferSize, int, interfaceAddress, isComprehensionRequiredAttribute, isDtls, isLinkLocalAddress, isMedia, isRtcp, isStunMessage, keyLength, leb128decode, makeIntegrityKey, methods, microTime, milliTime, nodeIpAddress, normalizeFamilyNodeV18, normalizeFingerprintAlgorithm, normalizeFingerprintValue, ntpTime, ntpTime2Sec, ntpTimeToEpochMs, paddingBits, paddingByte, paddingLength, parseGroup, parseIceServers, parseMessage, random16, random32, randomPort, randomPorts, remoteTcpTypeForIncoming, resolveTurnTransport, reverseDirection, reverseSimulcastDirection, rtpHeaderExtensionsParser, saltLength, serializeAbsSendTime, serializeAudioLevelIndication, serializeRepairedRtpStreamId, serializeSdesMid, serializeSdesRTPStreamID, serializeTransportWideCC, serverReflexiveCandidate, signatures, sortCandidatePairs, splitTcpFrames, supportedAudioCodecs, supportedCodecs, supportedVideoCodecs, timer, timestampSeconds, uint16Add, uint16Gt, uint16Gte, uint24, uint32Add, uint32Gt, uint32Gte, uint8Add, unwrapRtx, url2Address, useAV1X, useAbsSendTime, useAudioLevelIndication, useDependencyDescriptor, useFIR, useH264, useNACK, useOPUS, usePCMU, usePLI, useREMB, useRepairedRtpStreamId, useSdesMid, useSdesRTPStreamId, useTWCC, useTransportWideCC, useVP8, useVP9, useVideoOrientation, validateAddress, validateRemoteCandidate, wrapRtx };