Delete 100 files via Git Manager GUI
This commit is contained in:
-2
@@ -1,2 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
-74
@@ -1,74 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.convert = void 0;
|
||||
const index_js_1 = require("../bytes/index.js");
|
||||
const index_js_2 = require("../encoding/index.js");
|
||||
const defaults_js_1 = require("./defaults.js");
|
||||
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,
|
||||
};
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
"use strict";
|
||||
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/index.js");
|
||||
const index_js_2 = require("../pem/index.js");
|
||||
var index_js_3 = require("../pem/index.js");
|
||||
Object.defineProperty(exports, "pemConverter", { enumerable: true, get: function () { return index_js_3.pemConverter; } });
|
||||
const registry_js_1 = require("./registry.js");
|
||||
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);
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
"use strict";
|
||||
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.js");
|
||||
Object.defineProperty(exports, "createConverterRegistry", { enumerable: true, get: function () { return registry_js_1.createConverterRegistry; } });
|
||||
var defaults_js_1 = require("./defaults.js");
|
||||
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.js");
|
||||
Object.defineProperty(exports, "convert", { enumerable: true, get: function () { return convert_js_1.convert; } });
|
||||
-188
@@ -1,188 +0,0 @@
|
||||
"use strict";
|
||||
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 0.95;
|
||||
}
|
||||
if (/[a-f]/.test(trimmed) || /[A-F]/.test(trimmed)) {
|
||||
return 0.8;
|
||||
}
|
||||
return 0.45;
|
||||
}
|
||||
case "base64url":
|
||||
if (/[-_]/.test(trimmed)) {
|
||||
return 0.95;
|
||||
}
|
||||
if (/=/.test(trimmed)) {
|
||||
return 0.1;
|
||||
}
|
||||
return 0.6;
|
||||
case "base64":
|
||||
if (/[+/=]/.test(trimmed)) {
|
||||
return 0.9;
|
||||
}
|
||||
return 0.55;
|
||||
case "binary":
|
||||
case "utf8":
|
||||
case "utf16be":
|
||||
case "utf16le":
|
||||
return 0;
|
||||
default:
|
||||
return accepted && decodable ? 0.75 : 0.5;
|
||||
}
|
||||
}
|
||||
function createConverterRegistry(initialConverters = []) {
|
||||
const converters = new Map();
|
||||
const primaryNames = 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 = 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 = 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;
|
||||
}
|
||||
-2
@@ -1,2 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.base64 = void 0;
|
||||
exports.normalize = normalize;
|
||||
exports.pad = pad;
|
||||
exports.is = is;
|
||||
exports.encode = encode;
|
||||
exports.decode = decode;
|
||||
const index_js_1 = require("../bytes/index.js");
|
||||
const binary_js_1 = require("./binary.js");
|
||||
const BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
|
||||
function nodeBuffer() {
|
||||
return globalThis.Buffer;
|
||||
}
|
||||
function normalize(text) {
|
||||
return text.replace(/[\n\r\t ]/g, "");
|
||||
}
|
||||
function pad(text) {
|
||||
const remainder = text.length % 4;
|
||||
return remainder ? text + "=".repeat(4 - remainder) : text;
|
||||
}
|
||||
function is(text) {
|
||||
if (typeof text !== "string") {
|
||||
return false;
|
||||
}
|
||||
const normalized = normalize(text);
|
||||
return normalized === "" || BASE64_REGEX.test(normalized);
|
||||
}
|
||||
function encode(data, _options) {
|
||||
const bytes = (0, index_js_1.toUint8Array)(data);
|
||||
const buffer = nodeBuffer();
|
||||
if (buffer) {
|
||||
return buffer.from(bytes).toString("base64");
|
||||
}
|
||||
return btoa((0, binary_js_1.encode)(bytes));
|
||||
}
|
||||
function decode(text, _options) {
|
||||
const normalized = normalize(text);
|
||||
if (!is(normalized)) {
|
||||
throw new TypeError("Input is not valid Base64 text");
|
||||
}
|
||||
const buffer = nodeBuffer();
|
||||
if (buffer) {
|
||||
return new Uint8Array(buffer.from(normalized, "base64"));
|
||||
}
|
||||
return (0, binary_js_1.decode)(atob(normalized));
|
||||
}
|
||||
exports.base64 = { encode, decode, is, normalize, pad };
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.base64url = void 0;
|
||||
exports.normalize = normalize;
|
||||
exports.is = is;
|
||||
exports.encode = encode;
|
||||
exports.decode = decode;
|
||||
const base64_js_1 = require("./base64.js");
|
||||
const BASE64URL_REGEX = /^[A-Za-z0-9_-]*$/;
|
||||
function normalize(text) {
|
||||
return text.replace(/[\n\r\t ]/g, "");
|
||||
}
|
||||
function is(text) {
|
||||
return typeof text === "string" && BASE64URL_REGEX.test(normalize(text));
|
||||
}
|
||||
function encode(data, _options) {
|
||||
return base64_js_1.base64.encode(data).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
||||
}
|
||||
function decode(text, _options) {
|
||||
const normalized = normalize(text);
|
||||
if (!is(normalized)) {
|
||||
throw new TypeError("Input is not valid Base64Url text");
|
||||
}
|
||||
return base64_js_1.base64.decode(base64_js_1.base64.pad(normalized.replace(/-/g, "+").replace(/_/g, "/")));
|
||||
}
|
||||
exports.base64url = { encode, decode, is, normalize };
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.binary = void 0;
|
||||
exports.encode = encode;
|
||||
exports.decode = decode;
|
||||
exports.is = is;
|
||||
const index_js_1 = require("../bytes/index.js");
|
||||
function encode(data) {
|
||||
const bytes = (0, index_js_1.toUint8Array)(data);
|
||||
let result = "";
|
||||
for (const byte of bytes) {
|
||||
result += String.fromCharCode(byte);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function decode(text) {
|
||||
const result = new Uint8Array(text.length);
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
result[i] = text.charCodeAt(i) & 0xff;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function is(text) {
|
||||
return typeof text === "string";
|
||||
}
|
||||
exports.binary = { encode, decode, is };
|
||||
-229
@@ -1,229 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.hex = exports.formats = void 0;
|
||||
exports.normalize = normalize;
|
||||
exports.is = is;
|
||||
exports.encode = encode;
|
||||
exports.decode = decode;
|
||||
exports.parse = parse;
|
||||
exports.format = format;
|
||||
const index_js_1 = require("../bytes/index.js");
|
||||
const HEX_CHARACTER_REGEX = /^[0-9a-f]$/i;
|
||||
const COMMON_SEPARATORS = [" ", "\t", "\n", "\r", ":", "-", "."];
|
||||
function resolveSeparators(options) {
|
||||
if (options.separators === "none") {
|
||||
return [];
|
||||
}
|
||||
if (!options.separators || options.separators === "common") {
|
||||
return COMMON_SEPARATORS;
|
||||
}
|
||||
return options.separators;
|
||||
}
|
||||
function validateSeparator(separator) {
|
||||
if (!separator) {
|
||||
throw new TypeError("Hex separators must be non-empty strings");
|
||||
}
|
||||
}
|
||||
function matchSeparator(text, index, separators) {
|
||||
for (const separator of separators) {
|
||||
if (text.startsWith(separator, index)) {
|
||||
return separator;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
function detectCase(text) {
|
||||
const hasUpper = /[A-F]/.test(text);
|
||||
const hasLower = /[a-f]/.test(text);
|
||||
return hasUpper && !hasLower ? "upper" : "lower";
|
||||
}
|
||||
function detectLineSeparator(text) {
|
||||
const match = /\r\n|\n/.exec(text);
|
||||
if (!match) {
|
||||
return undefined;
|
||||
}
|
||||
return match[0] === "\r\n" ? "\r\n" : "\n";
|
||||
}
|
||||
function compactForDetection(text) {
|
||||
return text.replace(/[^0-9a-f]/gi, "");
|
||||
}
|
||||
function detectGroup(text) {
|
||||
const segments = text.match(/[0-9A-Fa-f]+|[^0-9A-Fa-f]+/g) ?? [];
|
||||
if (segments.length < 3) {
|
||||
return undefined;
|
||||
}
|
||||
const hexSegments = segments.filter((_, index) => index % 2 === 0);
|
||||
const separators = segments.filter((_, index) => index % 2 === 1);
|
||||
const separator = separators[0];
|
||||
if (!separator || separators.some((item) => item !== separator)) {
|
||||
return undefined;
|
||||
}
|
||||
if (hexSegments.some((segment) => segment.length === 0 || segment.length % 2 !== 0)) {
|
||||
return undefined;
|
||||
}
|
||||
const firstLength = hexSegments[0]?.length ?? 0;
|
||||
if (!firstLength) {
|
||||
return undefined;
|
||||
}
|
||||
if (hexSegments.slice(0, -1).some((segment) => segment.length !== firstLength)) {
|
||||
return undefined;
|
||||
}
|
||||
if ((hexSegments[hexSegments.length - 1]?.length ?? 0) > firstLength) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
size: firstLength / 2,
|
||||
separator,
|
||||
};
|
||||
}
|
||||
function detectFormat(text) {
|
||||
const trimmed = text.trim();
|
||||
const prefix = /^0x/i.test(trimmed) ? "0x" : "";
|
||||
const body = prefix ? trimmed.slice(2) : trimmed;
|
||||
const lineSeparator = detectLineSeparator(body);
|
||||
const lines = body.split(/\r\n|\n/).filter((line) => line.length > 0);
|
||||
const sampleLine = lines[0]?.trim() ?? "";
|
||||
const group = detectGroup(sampleLine);
|
||||
const format = {
|
||||
case: detectCase(trimmed),
|
||||
prefix,
|
||||
};
|
||||
if (group) {
|
||||
format.group = group;
|
||||
}
|
||||
if (lineSeparator && lines.length > 1) {
|
||||
const firstLineBytes = compactForDetection(lines[0] ?? "").length / 2;
|
||||
if (firstLineBytes > 0 && lines.slice(0, -1).every((line) => compactForDetection(line).length / 2 === firstLineBytes)) {
|
||||
format.line = {
|
||||
bytesPerLine: firstLineBytes,
|
||||
separator: lineSeparator,
|
||||
};
|
||||
}
|
||||
}
|
||||
return format;
|
||||
}
|
||||
function normalizeText(text, options) {
|
||||
const allowPrefix = options.allowPrefix ?? true;
|
||||
const separators = [...resolveSeparators(options)].sort((left, right) => right.length - left.length);
|
||||
for (const separator of separators) {
|
||||
validateSeparator(separator);
|
||||
}
|
||||
let working = text.trim();
|
||||
if (/^0x/i.test(working)) {
|
||||
if (!allowPrefix) {
|
||||
throw new TypeError("Hexadecimal text must not include a 0x prefix");
|
||||
}
|
||||
working = working.slice(2);
|
||||
}
|
||||
let normalized = "";
|
||||
let lastTokenWasSeparator = false;
|
||||
for (let index = 0; index < working.length;) {
|
||||
const character = working[index] ?? "";
|
||||
if (HEX_CHARACTER_REGEX.test(character)) {
|
||||
normalized += character;
|
||||
lastTokenWasSeparator = false;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
const separator = matchSeparator(working, index, separators);
|
||||
if (!separator) {
|
||||
throw new TypeError("Input is not valid hexadecimal text");
|
||||
}
|
||||
if (options.strict && (lastTokenWasSeparator || normalized.length === 0)) {
|
||||
throw new TypeError("Hexadecimal text contains misplaced separators");
|
||||
}
|
||||
lastTokenWasSeparator = true;
|
||||
index += separator.length;
|
||||
}
|
||||
if (options.strict && lastTokenWasSeparator && normalized.length > 0) {
|
||||
throw new TypeError("Hexadecimal text must not end with a separator");
|
||||
}
|
||||
if (normalized.length % 2 !== 0) {
|
||||
if (!options.allowOddLength) {
|
||||
throw new TypeError("Hexadecimal text must contain an even number of characters");
|
||||
}
|
||||
normalized = `0${normalized}`;
|
||||
}
|
||||
return normalized.toLowerCase();
|
||||
}
|
||||
function groupPairs(pairs, group) {
|
||||
if (!group) {
|
||||
return pairs.join("");
|
||||
}
|
||||
if (!Number.isInteger(group.size) || group.size < 1) {
|
||||
throw new RangeError("Hex group size must be a positive integer");
|
||||
}
|
||||
const chunks = [];
|
||||
for (let index = 0; index < pairs.length; index += group.size) {
|
||||
chunks.push(pairs.slice(index, index + group.size).join(""));
|
||||
}
|
||||
return chunks.join(group.separator);
|
||||
}
|
||||
function normalize(text, options = {}) {
|
||||
return normalizeText(text, options);
|
||||
}
|
||||
function is(text, options = {}) {
|
||||
if (typeof text !== "string") {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
normalize(text, options);
|
||||
return true;
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
function encode(data, options = {}) {
|
||||
const bytes = (0, index_js_1.toUint8Array)(data);
|
||||
const casing = options.case ?? "lower";
|
||||
const pairs = Array.from(bytes, (byte) => {
|
||||
const text = byte.toString(16).padStart(2, "0");
|
||||
return casing === "upper" ? text.toUpperCase() : text;
|
||||
});
|
||||
let body = "";
|
||||
if (options.line) {
|
||||
const bytesPerLine = options.line.bytesPerLine;
|
||||
if (!Number.isInteger(bytesPerLine) || bytesPerLine < 1) {
|
||||
throw new RangeError("Hex bytesPerLine must be a positive integer");
|
||||
}
|
||||
const separator = options.line.separator ?? "\n";
|
||||
const lines = [];
|
||||
for (let index = 0; index < pairs.length; index += bytesPerLine) {
|
||||
lines.push(groupPairs(pairs.slice(index, index + bytesPerLine), options.group));
|
||||
}
|
||||
body = lines.join(separator);
|
||||
}
|
||||
else {
|
||||
body = groupPairs(pairs, options.group);
|
||||
}
|
||||
return `${options.prefix ?? ""}${body}`;
|
||||
}
|
||||
function decode(text, options = {}) {
|
||||
const normalized = normalize(text, options);
|
||||
const result = new Uint8Array(normalized.length / 2);
|
||||
for (let i = 0; i < normalized.length; i += 2) {
|
||||
result[i / 2] = Number.parseInt(normalized.slice(i, i + 2), 16);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
function parse(text, options = {}) {
|
||||
const normalized = normalize(text, options);
|
||||
return {
|
||||
bytes: decode(normalized),
|
||||
format: detectFormat(text),
|
||||
normalized,
|
||||
};
|
||||
}
|
||||
function format(data, value) {
|
||||
return encode(data, value);
|
||||
}
|
||||
exports.formats = {
|
||||
compact: Object.freeze({}),
|
||||
upper: Object.freeze({ case: "upper" }),
|
||||
colon: Object.freeze({ group: { size: 1, separator: ":" } }),
|
||||
colonUpper: Object.freeze({ case: "upper", group: { size: 1, separator: ":" } }),
|
||||
groupsOf4: Object.freeze({ group: { size: 4, separator: " " } }),
|
||||
prefixed: Object.freeze({ prefix: "0x" }),
|
||||
};
|
||||
exports.hex = { encode, decode, format, formats: exports.formats, is, normalize, parse };
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.base64url = exports.base64 = exports.utf16 = exports.utf8 = exports.hex = exports.binary = void 0;
|
||||
const tslib_1 = require("tslib");
|
||||
exports.binary = tslib_1.__importStar(require("./binary.js"));
|
||||
exports.hex = tslib_1.__importStar(require("./hex.js"));
|
||||
exports.utf8 = tslib_1.__importStar(require("./utf8.js"));
|
||||
exports.utf16 = tslib_1.__importStar(require("./utf16.js"));
|
||||
exports.base64 = tslib_1.__importStar(require("./base64.js"));
|
||||
exports.base64url = tslib_1.__importStar(require("./base64url.js"));
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.utf16 = void 0;
|
||||
exports.encode = encode;
|
||||
exports.decode = decode;
|
||||
const index_js_1 = require("../bytes/index.js");
|
||||
function encode(text, options = {}) {
|
||||
const result = new ArrayBuffer(text.length * 2);
|
||||
const view = new DataView(result);
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
view.setUint16(i * 2, text.charCodeAt(i), options.littleEndian ?? false);
|
||||
}
|
||||
return new Uint8Array(result);
|
||||
}
|
||||
function decode(data, options = {}) {
|
||||
const buffer = (0, index_js_1.toArrayBuffer)(data);
|
||||
const view = new DataView(buffer);
|
||||
let result = "";
|
||||
for (let i = 0; i < buffer.byteLength; i += 2) {
|
||||
result += String.fromCharCode(view.getUint16(i, options.littleEndian ?? false));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
exports.utf16 = { encode, decode };
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.utf8 = void 0;
|
||||
exports.encode = encode;
|
||||
exports.decode = decode;
|
||||
const index_js_1 = require("../bytes/index.js");
|
||||
function encode(text) {
|
||||
return new TextEncoder().encode(text);
|
||||
}
|
||||
function decode(data) {
|
||||
return new TextDecoder("utf-8", { fatal: false }).decode((0, index_js_1.toUint8Array)(data));
|
||||
}
|
||||
exports.utf8 = { encode, decode };
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.bytes = void 0;
|
||||
const tslib_1 = require("tslib");
|
||||
tslib_1.__exportStar(require("./bytes/index.js"), exports);
|
||||
exports.bytes = tslib_1.__importStar(require("./bytes/index.js"));
|
||||
tslib_1.__exportStar(require("./encoding/index.js"), exports);
|
||||
tslib_1.__exportStar(require("./pem/index.js"), exports);
|
||||
tslib_1.__exportStar(require("./converters/index.js"), exports);
|
||||
tslib_1.__exportStar(require("./legacy/index.js"), exports);
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.BufferSourceConverter = void 0;
|
||||
const index_js_1 = require("../bytes/index.js");
|
||||
class BufferSourceConverter {
|
||||
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;
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.Convert = void 0;
|
||||
const index_js_1 = require("../converters/index.js");
|
||||
function normalizeTextEncoding(encoding) {
|
||||
return encoding === "ascii" ? "binary" : encoding;
|
||||
}
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
exports.Convert = Convert;
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.assign = assign;
|
||||
exports.combine = combine;
|
||||
exports.isEqual = isEqual;
|
||||
const index_js_1 = require("../bytes/index.js");
|
||||
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);
|
||||
}
|
||||
-11
@@ -1,11 +0,0 @@
|
||||
"use strict";
|
||||
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.js");
|
||||
Object.defineProperty(exports, "BufferSourceConverter", { enumerable: true, get: function () { return buffer_source_converter_js_1.BufferSourceConverter; } });
|
||||
var convert_js_1 = require("./convert.js");
|
||||
Object.defineProperty(exports, "Convert", { enumerable: true, get: function () { return convert_js_1.Convert; } });
|
||||
var functions_js_1 = require("./functions.js");
|
||||
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; } });
|
||||
-3
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"type": "commonjs"
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
"use strict";
|
||||
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.js");
|
||||
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; } });
|
||||
-140
@@ -1,140 +0,0 @@
|
||||
"use strict";
|
||||
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("../encoding/base64.js");
|
||||
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 normalized = body.trim().replace(/\r\n/g, "\n");
|
||||
const lines = normalized.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 : undefined,
|
||||
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,
|
||||
};
|
||||
-2
@@ -1,2 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
-101
@@ -1,101 +0,0 @@
|
||||
const ARRAY_BUFFER_TAG = "[object ArrayBuffer]";
|
||||
const SHARED_ARRAY_BUFFER_TAG = "[object SharedArrayBuffer]";
|
||||
function tagOf(value) {
|
||||
return Object.prototype.toString.call(value);
|
||||
}
|
||||
function isDataViewConstructor(type) {
|
||||
return type === DataView || type.prototype instanceof DataView;
|
||||
}
|
||||
function bytesPerElement(type) {
|
||||
if (isDataViewConstructor(type)) {
|
||||
return 1;
|
||||
}
|
||||
const value = type.BYTES_PER_ELEMENT;
|
||||
return value ?? 1;
|
||||
}
|
||||
function isArrayBufferViewLike(value) {
|
||||
if (ArrayBuffer.isView(value)) {
|
||||
return true;
|
||||
}
|
||||
if (!value || typeof value !== "object") {
|
||||
return false;
|
||||
}
|
||||
const view = value;
|
||||
return typeof view.byteOffset === "number"
|
||||
&& typeof view.byteLength === "number"
|
||||
&& isArrayBufferLike(view.buffer);
|
||||
}
|
||||
function copyBytes(data) {
|
||||
const view = toUint8Array(data);
|
||||
const copy = new Uint8Array(view.byteLength);
|
||||
copy.set(view);
|
||||
return copy;
|
||||
}
|
||||
export function isArrayBuffer(value) {
|
||||
return tagOf(value) === ARRAY_BUFFER_TAG;
|
||||
}
|
||||
export function isSharedArrayBuffer(value) {
|
||||
return typeof SharedArrayBuffer !== "undefined" && tagOf(value) === SHARED_ARRAY_BUFFER_TAG;
|
||||
}
|
||||
export function isArrayBufferLike(value) {
|
||||
return isArrayBuffer(value) || isSharedArrayBuffer(value);
|
||||
}
|
||||
export function isArrayBufferView(value) {
|
||||
return isArrayBufferViewLike(value);
|
||||
}
|
||||
export function isBufferSource(value) {
|
||||
return isArrayBufferLike(value) || isArrayBufferView(value);
|
||||
}
|
||||
export function assertBufferSource(value) {
|
||||
if (!isBufferSource(value)) {
|
||||
throw new TypeError("Expected ArrayBuffer, SharedArrayBuffer, or ArrayBufferView");
|
||||
}
|
||||
}
|
||||
export function toUint8Array(data) {
|
||||
assertBufferSource(data);
|
||||
if (isArrayBufferLike(data)) {
|
||||
return new Uint8Array(data);
|
||||
}
|
||||
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
||||
}
|
||||
export function toUint8ArrayCopy(data) {
|
||||
return copyBytes(data);
|
||||
}
|
||||
export function toArrayBuffer(data) {
|
||||
assertBufferSource(data);
|
||||
if (isArrayBuffer(data)) {
|
||||
return data;
|
||||
}
|
||||
const buffer = new ArrayBuffer(data.byteLength);
|
||||
new Uint8Array(buffer).set(toUint8Array(data));
|
||||
return buffer;
|
||||
}
|
||||
export function toArrayBufferLike(data) {
|
||||
assertBufferSource(data);
|
||||
if (isArrayBufferLike(data)) {
|
||||
return data;
|
||||
}
|
||||
if (data.byteOffset === 0 && data.byteLength === data.buffer.byteLength) {
|
||||
return data.buffer;
|
||||
}
|
||||
return copyBytes(data).buffer;
|
||||
}
|
||||
export function toView(data, type) {
|
||||
assertBufferSource(data);
|
||||
if (ArrayBuffer.isView(data) && data.constructor === type) {
|
||||
return data;
|
||||
}
|
||||
const view = toUint8Array(data);
|
||||
const elementSize = bytesPerElement(type);
|
||||
if (view.byteOffset % elementSize !== 0 || view.byteLength % elementSize !== 0) {
|
||||
throw new RangeError(`Cannot create ${type.name} over unaligned byte range`);
|
||||
}
|
||||
if (isDataViewConstructor(type)) {
|
||||
return new type(view.buffer, view.byteOffset, view.byteLength);
|
||||
}
|
||||
return new type(view.buffer, view.byteOffset, view.byteLength / elementSize);
|
||||
}
|
||||
export function toViewCopy(data, type) {
|
||||
const copy = toUint8ArrayCopy(data);
|
||||
return toView(copy, type);
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
import { isBufferSource, toUint8Array, toView } from "./buffer-source.js";
|
||||
export function concatToUint8Array(buffers) {
|
||||
const views = [];
|
||||
let length = 0;
|
||||
for (const buffer of buffers) {
|
||||
const view = toUint8Array(buffer);
|
||||
views.push(view);
|
||||
length += view.byteLength;
|
||||
}
|
||||
const result = new Uint8Array(length);
|
||||
let offset = 0;
|
||||
for (const view of views) {
|
||||
result.set(view, offset);
|
||||
offset += view.byteLength;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export function concat(first, second, ...rest) {
|
||||
let buffers;
|
||||
let type;
|
||||
if (typeof second === "function") {
|
||||
buffers = Array.from(first);
|
||||
type = second;
|
||||
}
|
||||
else if (isBufferSource(first)) {
|
||||
buffers = [first, second, ...rest].filter(isBufferSource);
|
||||
}
|
||||
else {
|
||||
buffers = Array.from(first);
|
||||
if (second) {
|
||||
buffers.push(second);
|
||||
}
|
||||
buffers.push(...rest);
|
||||
}
|
||||
const bytes = concatToUint8Array(buffers);
|
||||
return type ? toView(bytes, type) : bytes.buffer;
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
import { toUint8Array } from "./buffer-source.js";
|
||||
export function equal(a, b, options = {}) {
|
||||
const left = toUint8Array(a);
|
||||
const right = toUint8Array(b);
|
||||
if (!options.constantTime && left.byteLength !== right.byteLength) {
|
||||
return false;
|
||||
}
|
||||
const length = Math.max(left.byteLength, right.byteLength);
|
||||
let diff = left.byteLength ^ right.byteLength;
|
||||
for (let i = 0; i < length; i++) {
|
||||
diff |= (left[i] ?? 0) ^ (right[i] ?? 0);
|
||||
}
|
||||
return diff === 0;
|
||||
}
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
export { assertBufferSource, isArrayBuffer, isArrayBufferLike, isArrayBufferView, isBufferSource, isSharedArrayBuffer, toArrayBuffer, toArrayBufferLike, toUint8Array, toUint8ArrayCopy, toView, toViewCopy, } from "./buffer-source.js";
|
||||
export { concat, concatToUint8Array } from "./concat.js";
|
||||
export { equal } from "./equal.js";
|
||||
export { compare, copy, endsWith, includes, indexOf, lastIndexOf, slice, startsWith, tail, } from "./sequence.js";
|
||||
-150
@@ -1,150 +0,0 @@
|
||||
import { toUint8Array, toUint8ArrayCopy } from "./buffer-source.js";
|
||||
function clampIndex(value, fallback, length) {
|
||||
const normalized = Number.isFinite(value) ? Math.trunc(value) : fallback;
|
||||
if (normalized <= 0) {
|
||||
return 0;
|
||||
}
|
||||
if (normalized >= length) {
|
||||
return length;
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
function normalizeForwardRange(length, options) {
|
||||
const start = clampIndex(options?.start, 0, length);
|
||||
const end = clampIndex(options?.end, length, length);
|
||||
return end >= start ? [start, end] : [start, start];
|
||||
}
|
||||
function normalizeReverseRange(length, options) {
|
||||
const start = clampIndex(options?.start, length, length);
|
||||
const end = clampIndex(options?.end, 0, length);
|
||||
return start >= end ? [end, start] : [start, start];
|
||||
}
|
||||
function normalizeSliceIndex(value, fallback, length) {
|
||||
const normalized = Number.isFinite(value) ? Math.trunc(value) : fallback;
|
||||
if (normalized < 0) {
|
||||
return Math.max(length + normalized, 0);
|
||||
}
|
||||
if (normalized > length) {
|
||||
return length;
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
function encodeAscii(text) {
|
||||
const bytes = new Uint8Array(text.length);
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
bytes[i] = text.charCodeAt(i) & 0xff;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
function encodeUtf8(text) {
|
||||
return new TextEncoder().encode(text);
|
||||
}
|
||||
function toPatternBytes(pattern, options) {
|
||||
if (typeof pattern === "string") {
|
||||
return options?.encoding === "utf8" ? encodeUtf8(pattern) : encodeAscii(pattern);
|
||||
}
|
||||
return toUint8Array(pattern);
|
||||
}
|
||||
function bytesEqualAt(data, pattern, offset) {
|
||||
for (let index = 0; index < pattern.byteLength; index++) {
|
||||
if (data[offset + index] !== pattern[index]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
export function indexOf(data, pattern, options) {
|
||||
const bytes = toUint8Array(data);
|
||||
const needle = toPatternBytes(pattern, options);
|
||||
const [start, end] = normalizeForwardRange(bytes.byteLength, options);
|
||||
if (needle.byteLength === 0) {
|
||||
return start;
|
||||
}
|
||||
const lastOffset = end - needle.byteLength;
|
||||
if (lastOffset < start) {
|
||||
return -1;
|
||||
}
|
||||
for (let offset = start; offset <= lastOffset; offset++) {
|
||||
if (bytesEqualAt(bytes, needle, offset)) {
|
||||
return offset;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
export function lastIndexOf(data, pattern, options) {
|
||||
const bytes = toUint8Array(data);
|
||||
const needle = toPatternBytes(pattern, options);
|
||||
const [end, start] = normalizeReverseRange(bytes.byteLength, options);
|
||||
if (needle.byteLength === 0) {
|
||||
return start;
|
||||
}
|
||||
const firstOffset = start - needle.byteLength;
|
||||
if (firstOffset < end) {
|
||||
return -1;
|
||||
}
|
||||
for (let offset = firstOffset; offset >= end; offset--) {
|
||||
if (bytesEqualAt(bytes, needle, offset)) {
|
||||
return offset;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
export function includes(data, pattern, options) {
|
||||
return indexOf(data, pattern, options) !== -1;
|
||||
}
|
||||
export function startsWith(data, pattern, options) {
|
||||
const bytes = toUint8Array(data);
|
||||
const needle = toPatternBytes(pattern, options);
|
||||
if (needle.byteLength > bytes.byteLength) {
|
||||
return false;
|
||||
}
|
||||
return bytesEqualAt(bytes, needle, 0);
|
||||
}
|
||||
export function endsWith(data, pattern, options) {
|
||||
const bytes = toUint8Array(data);
|
||||
const needle = toPatternBytes(pattern, options);
|
||||
if (needle.byteLength > bytes.byteLength) {
|
||||
return false;
|
||||
}
|
||||
return bytesEqualAt(bytes, needle, bytes.byteLength - needle.byteLength);
|
||||
}
|
||||
export function slice(data, start, end) {
|
||||
const bytes = toUint8Array(data);
|
||||
const normalizedStart = normalizeSliceIndex(start, 0, bytes.byteLength);
|
||||
const normalizedEnd = normalizeSliceIndex(end, bytes.byteLength, bytes.byteLength);
|
||||
if (normalizedEnd <= normalizedStart) {
|
||||
return bytes.subarray(normalizedStart, normalizedStart);
|
||||
}
|
||||
return bytes.subarray(normalizedStart, normalizedEnd);
|
||||
}
|
||||
export function tail(data, length) {
|
||||
const bytes = toUint8Array(data);
|
||||
const normalizedLength = Number.isFinite(length) ? Math.max(0, Math.trunc(length)) : 0;
|
||||
if (normalizedLength >= bytes.byteLength) {
|
||||
return bytes;
|
||||
}
|
||||
return bytes.subarray(bytes.byteLength - normalizedLength);
|
||||
}
|
||||
export function copy(data) {
|
||||
return toUint8ArrayCopy(data);
|
||||
}
|
||||
export function compare(a, b) {
|
||||
const left = toUint8Array(a);
|
||||
const right = toUint8Array(b);
|
||||
const limit = Math.min(left.byteLength, right.byteLength);
|
||||
for (let index = 0; index < limit; index++) {
|
||||
if (left[index] < right[index]) {
|
||||
return -1;
|
||||
}
|
||||
if (left[index] > right[index]) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
if (left.byteLength < right.byteLength) {
|
||||
return -1;
|
||||
}
|
||||
if (left.byteLength > right.byteLength) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
-1
@@ -1 +0,0 @@
|
||||
export {};
|
||||
-71
@@ -1,71 +0,0 @@
|
||||
import { toArrayBuffer } from "../bytes/index.js";
|
||||
import { base64, base64url, binary, hex, utf8, utf16 } from "../encoding/index.js";
|
||||
import { defaultConverterRegistry } from "./defaults.js";
|
||||
function encode(name, data, ...args) {
|
||||
return defaultConverterRegistry.encode(name, data, ...args);
|
||||
}
|
||||
function decode(name, text, ...args) {
|
||||
return defaultConverterRegistry.decode(name, text, ...args);
|
||||
}
|
||||
function tryDecode(name, text, ...args) {
|
||||
return defaultConverterRegistry.tryDecode(name, text, ...args);
|
||||
}
|
||||
function normalize(name, text, ...args) {
|
||||
return defaultConverterRegistry.normalize(name, text, ...args);
|
||||
}
|
||||
function parse(name, text, ...args) {
|
||||
return defaultConverterRegistry.parse(name, text, ...args);
|
||||
}
|
||||
function format(name, data, value) {
|
||||
return defaultConverterRegistry.format(name, data, value);
|
||||
}
|
||||
function transcode(text, options) {
|
||||
return defaultConverterRegistry.transcode(text, options);
|
||||
}
|
||||
function detect(text, options) {
|
||||
return defaultConverterRegistry.detect(text, options);
|
||||
}
|
||||
function normalizeEncodingName(encoding) {
|
||||
return encoding.toLowerCase();
|
||||
}
|
||||
export const 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 toArrayBuffer(hex.decode(text, { allowOddLength: true }));
|
||||
}
|
||||
return toArrayBuffer(decode(encoding, text));
|
||||
},
|
||||
toBase64: base64.encode,
|
||||
fromBase64: (text) => toArrayBuffer(base64.decode(text)),
|
||||
toBase64Url: base64url.encode,
|
||||
fromBase64Url: (text) => toArrayBuffer(base64url.decode(text)),
|
||||
toHex: hex.encode,
|
||||
fromHex: (text) => toArrayBuffer(hex.decode(text, { allowOddLength: true })),
|
||||
toBinary: binary.encode,
|
||||
fromBinary: (text) => toArrayBuffer(binary.decode(text)),
|
||||
toUtf8String: utf8.decode,
|
||||
fromUtf8String: (text) => toArrayBuffer(utf8.encode(text)),
|
||||
toUtf16String: (data, littleEndian = false) => utf16.decode(data, { littleEndian }),
|
||||
fromUtf16String: (text, littleEndian = false) => toArrayBuffer(utf16.encode(text, { littleEndian })),
|
||||
isHex: hex.is,
|
||||
isBase64: base64.is,
|
||||
isBase64Url: base64url.is,
|
||||
formatString: base64.normalize,
|
||||
};
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
import { base64, base64url, binary, hex, utf8, utf16 } from "../encoding/index.js";
|
||||
import { pemConverter } from "../pem/index.js";
|
||||
export { pemConverter } from "../pem/index.js";
|
||||
import { createConverterRegistry } from "./registry.js";
|
||||
export const binaryConverter = {
|
||||
name: "binary",
|
||||
aliases: ["latin1"],
|
||||
encode: binary.encode,
|
||||
decode: binary.decode,
|
||||
is: binary.is,
|
||||
};
|
||||
export const hexConverter = {
|
||||
name: "hex",
|
||||
encode: hex.encode,
|
||||
decode: hex.decode,
|
||||
format: hex.format,
|
||||
is: hex.is,
|
||||
normalize: hex.normalize,
|
||||
parse: hex.parse,
|
||||
};
|
||||
export const base64Converter = {
|
||||
name: "base64",
|
||||
aliases: ["b64"],
|
||||
encode: base64.encode,
|
||||
decode: base64.decode,
|
||||
is: base64.is,
|
||||
normalize: base64.normalize,
|
||||
};
|
||||
export const base64urlConverter = {
|
||||
name: "base64url",
|
||||
aliases: ["base64-url", "b64url"],
|
||||
encode: base64url.encode,
|
||||
decode: base64url.decode,
|
||||
is: base64url.is,
|
||||
normalize: base64url.normalize,
|
||||
};
|
||||
export const utf8Converter = {
|
||||
name: "utf8",
|
||||
aliases: ["utf-8"],
|
||||
encode: (data) => utf8.decode(data),
|
||||
decode: (text) => utf8.encode(text),
|
||||
is: (text) => typeof text === "string",
|
||||
};
|
||||
export const utf16beConverter = {
|
||||
name: "utf16be",
|
||||
aliases: ["utf16", "utf-16", "utf-16be"],
|
||||
encode: (data) => utf16.decode(data),
|
||||
decode: (text) => utf16.encode(text),
|
||||
is: (text) => typeof text === "string",
|
||||
};
|
||||
export const utf16leConverter = {
|
||||
name: "utf16le",
|
||||
aliases: ["utf-16le", "ucs2", "usc2"],
|
||||
encode: (data) => utf16.decode(data, { littleEndian: true }),
|
||||
decode: (text) => utf16.encode(text, { littleEndian: true }),
|
||||
is: (text) => typeof text === "string",
|
||||
};
|
||||
export const defaultConverters = [
|
||||
binaryConverter,
|
||||
hexConverter,
|
||||
base64Converter,
|
||||
base64urlConverter,
|
||||
utf8Converter,
|
||||
utf16beConverter,
|
||||
utf16leConverter,
|
||||
pemConverter,
|
||||
];
|
||||
export const defaultConverterRegistry = createConverterRegistry(defaultConverters);
|
||||
-3
@@ -1,3 +0,0 @@
|
||||
export { createConverterRegistry } from "./registry.js";
|
||||
export { base64Converter, base64urlConverter, binaryConverter, defaultConverterRegistry, defaultConverters, hexConverter, pemConverter, utf16beConverter, utf16leConverter, utf8Converter, } from "./defaults.js";
|
||||
export { convert } from "./convert.js";
|
||||
-185
@@ -1,185 +0,0 @@
|
||||
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 0.95;
|
||||
}
|
||||
if (/[a-f]/.test(trimmed) || /[A-F]/.test(trimmed)) {
|
||||
return 0.8;
|
||||
}
|
||||
return 0.45;
|
||||
}
|
||||
case "base64url":
|
||||
if (/[-_]/.test(trimmed)) {
|
||||
return 0.95;
|
||||
}
|
||||
if (/=/.test(trimmed)) {
|
||||
return 0.1;
|
||||
}
|
||||
return 0.6;
|
||||
case "base64":
|
||||
if (/[+/=]/.test(trimmed)) {
|
||||
return 0.9;
|
||||
}
|
||||
return 0.55;
|
||||
case "binary":
|
||||
case "utf8":
|
||||
case "utf16be":
|
||||
case "utf16le":
|
||||
return 0;
|
||||
default:
|
||||
return accepted && decodable ? 0.75 : 0.5;
|
||||
}
|
||||
}
|
||||
export function createConverterRegistry(initialConverters = []) {
|
||||
const converters = new Map();
|
||||
const primaryNames = 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 = 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 = 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;
|
||||
}
|
||||
-1
@@ -1 +0,0 @@
|
||||
export {};
|
||||
-40
@@ -1,40 +0,0 @@
|
||||
import { toUint8Array } from "../bytes/index.js";
|
||||
import { encode as encodeBinary, decode as decodeBinary } from "./binary.js";
|
||||
const BASE64_REGEX = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
|
||||
function nodeBuffer() {
|
||||
return globalThis.Buffer;
|
||||
}
|
||||
export function normalize(text) {
|
||||
return text.replace(/[\n\r\t ]/g, "");
|
||||
}
|
||||
export function pad(text) {
|
||||
const remainder = text.length % 4;
|
||||
return remainder ? text + "=".repeat(4 - remainder) : text;
|
||||
}
|
||||
export function is(text) {
|
||||
if (typeof text !== "string") {
|
||||
return false;
|
||||
}
|
||||
const normalized = normalize(text);
|
||||
return normalized === "" || BASE64_REGEX.test(normalized);
|
||||
}
|
||||
export function encode(data, _options) {
|
||||
const bytes = toUint8Array(data);
|
||||
const buffer = nodeBuffer();
|
||||
if (buffer) {
|
||||
return buffer.from(bytes).toString("base64");
|
||||
}
|
||||
return btoa(encodeBinary(bytes));
|
||||
}
|
||||
export function decode(text, _options) {
|
||||
const normalized = normalize(text);
|
||||
if (!is(normalized)) {
|
||||
throw new TypeError("Input is not valid Base64 text");
|
||||
}
|
||||
const buffer = nodeBuffer();
|
||||
if (buffer) {
|
||||
return new Uint8Array(buffer.from(normalized, "base64"));
|
||||
}
|
||||
return decodeBinary(atob(normalized));
|
||||
}
|
||||
export const base64 = { encode, decode, is, normalize, pad };
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
import { base64 } from "./base64.js";
|
||||
const BASE64URL_REGEX = /^[A-Za-z0-9_-]*$/;
|
||||
export function normalize(text) {
|
||||
return text.replace(/[\n\r\t ]/g, "");
|
||||
}
|
||||
export function is(text) {
|
||||
return typeof text === "string" && BASE64URL_REGEX.test(normalize(text));
|
||||
}
|
||||
export function encode(data, _options) {
|
||||
return base64.encode(data).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
||||
}
|
||||
export function decode(text, _options) {
|
||||
const normalized = normalize(text);
|
||||
if (!is(normalized)) {
|
||||
throw new TypeError("Input is not valid Base64Url text");
|
||||
}
|
||||
return base64.decode(base64.pad(normalized.replace(/-/g, "+").replace(/_/g, "/")));
|
||||
}
|
||||
export const base64url = { encode, decode, is, normalize };
|
||||
-20
@@ -1,20 +0,0 @@
|
||||
import { toUint8Array } from "../bytes/index.js";
|
||||
export function encode(data) {
|
||||
const bytes = toUint8Array(data);
|
||||
let result = "";
|
||||
for (const byte of bytes) {
|
||||
result += String.fromCharCode(byte);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export function decode(text) {
|
||||
const result = new Uint8Array(text.length);
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
result[i] = text.charCodeAt(i) & 0xff;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export function is(text) {
|
||||
return typeof text === "string";
|
||||
}
|
||||
export const binary = { encode, decode, is };
|
||||
-220
@@ -1,220 +0,0 @@
|
||||
import { toUint8Array } from "../bytes/index.js";
|
||||
const HEX_CHARACTER_REGEX = /^[0-9a-f]$/i;
|
||||
const COMMON_SEPARATORS = [" ", "\t", "\n", "\r", ":", "-", "."];
|
||||
function resolveSeparators(options) {
|
||||
if (options.separators === "none") {
|
||||
return [];
|
||||
}
|
||||
if (!options.separators || options.separators === "common") {
|
||||
return COMMON_SEPARATORS;
|
||||
}
|
||||
return options.separators;
|
||||
}
|
||||
function validateSeparator(separator) {
|
||||
if (!separator) {
|
||||
throw new TypeError("Hex separators must be non-empty strings");
|
||||
}
|
||||
}
|
||||
function matchSeparator(text, index, separators) {
|
||||
for (const separator of separators) {
|
||||
if (text.startsWith(separator, index)) {
|
||||
return separator;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
function detectCase(text) {
|
||||
const hasUpper = /[A-F]/.test(text);
|
||||
const hasLower = /[a-f]/.test(text);
|
||||
return hasUpper && !hasLower ? "upper" : "lower";
|
||||
}
|
||||
function detectLineSeparator(text) {
|
||||
const match = /\r\n|\n/.exec(text);
|
||||
if (!match) {
|
||||
return undefined;
|
||||
}
|
||||
return match[0] === "\r\n" ? "\r\n" : "\n";
|
||||
}
|
||||
function compactForDetection(text) {
|
||||
return text.replace(/[^0-9a-f]/gi, "");
|
||||
}
|
||||
function detectGroup(text) {
|
||||
const segments = text.match(/[0-9A-Fa-f]+|[^0-9A-Fa-f]+/g) ?? [];
|
||||
if (segments.length < 3) {
|
||||
return undefined;
|
||||
}
|
||||
const hexSegments = segments.filter((_, index) => index % 2 === 0);
|
||||
const separators = segments.filter((_, index) => index % 2 === 1);
|
||||
const separator = separators[0];
|
||||
if (!separator || separators.some((item) => item !== separator)) {
|
||||
return undefined;
|
||||
}
|
||||
if (hexSegments.some((segment) => segment.length === 0 || segment.length % 2 !== 0)) {
|
||||
return undefined;
|
||||
}
|
||||
const firstLength = hexSegments[0]?.length ?? 0;
|
||||
if (!firstLength) {
|
||||
return undefined;
|
||||
}
|
||||
if (hexSegments.slice(0, -1).some((segment) => segment.length !== firstLength)) {
|
||||
return undefined;
|
||||
}
|
||||
if ((hexSegments[hexSegments.length - 1]?.length ?? 0) > firstLength) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
size: firstLength / 2,
|
||||
separator,
|
||||
};
|
||||
}
|
||||
function detectFormat(text) {
|
||||
const trimmed = text.trim();
|
||||
const prefix = /^0x/i.test(trimmed) ? "0x" : "";
|
||||
const body = prefix ? trimmed.slice(2) : trimmed;
|
||||
const lineSeparator = detectLineSeparator(body);
|
||||
const lines = body.split(/\r\n|\n/).filter((line) => line.length > 0);
|
||||
const sampleLine = lines[0]?.trim() ?? "";
|
||||
const group = detectGroup(sampleLine);
|
||||
const format = {
|
||||
case: detectCase(trimmed),
|
||||
prefix,
|
||||
};
|
||||
if (group) {
|
||||
format.group = group;
|
||||
}
|
||||
if (lineSeparator && lines.length > 1) {
|
||||
const firstLineBytes = compactForDetection(lines[0] ?? "").length / 2;
|
||||
if (firstLineBytes > 0 && lines.slice(0, -1).every((line) => compactForDetection(line).length / 2 === firstLineBytes)) {
|
||||
format.line = {
|
||||
bytesPerLine: firstLineBytes,
|
||||
separator: lineSeparator,
|
||||
};
|
||||
}
|
||||
}
|
||||
return format;
|
||||
}
|
||||
function normalizeText(text, options) {
|
||||
const allowPrefix = options.allowPrefix ?? true;
|
||||
const separators = [...resolveSeparators(options)].sort((left, right) => right.length - left.length);
|
||||
for (const separator of separators) {
|
||||
validateSeparator(separator);
|
||||
}
|
||||
let working = text.trim();
|
||||
if (/^0x/i.test(working)) {
|
||||
if (!allowPrefix) {
|
||||
throw new TypeError("Hexadecimal text must not include a 0x prefix");
|
||||
}
|
||||
working = working.slice(2);
|
||||
}
|
||||
let normalized = "";
|
||||
let lastTokenWasSeparator = false;
|
||||
for (let index = 0; index < working.length;) {
|
||||
const character = working[index] ?? "";
|
||||
if (HEX_CHARACTER_REGEX.test(character)) {
|
||||
normalized += character;
|
||||
lastTokenWasSeparator = false;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
const separator = matchSeparator(working, index, separators);
|
||||
if (!separator) {
|
||||
throw new TypeError("Input is not valid hexadecimal text");
|
||||
}
|
||||
if (options.strict && (lastTokenWasSeparator || normalized.length === 0)) {
|
||||
throw new TypeError("Hexadecimal text contains misplaced separators");
|
||||
}
|
||||
lastTokenWasSeparator = true;
|
||||
index += separator.length;
|
||||
}
|
||||
if (options.strict && lastTokenWasSeparator && normalized.length > 0) {
|
||||
throw new TypeError("Hexadecimal text must not end with a separator");
|
||||
}
|
||||
if (normalized.length % 2 !== 0) {
|
||||
if (!options.allowOddLength) {
|
||||
throw new TypeError("Hexadecimal text must contain an even number of characters");
|
||||
}
|
||||
normalized = `0${normalized}`;
|
||||
}
|
||||
return normalized.toLowerCase();
|
||||
}
|
||||
function groupPairs(pairs, group) {
|
||||
if (!group) {
|
||||
return pairs.join("");
|
||||
}
|
||||
if (!Number.isInteger(group.size) || group.size < 1) {
|
||||
throw new RangeError("Hex group size must be a positive integer");
|
||||
}
|
||||
const chunks = [];
|
||||
for (let index = 0; index < pairs.length; index += group.size) {
|
||||
chunks.push(pairs.slice(index, index + group.size).join(""));
|
||||
}
|
||||
return chunks.join(group.separator);
|
||||
}
|
||||
export function normalize(text, options = {}) {
|
||||
return normalizeText(text, options);
|
||||
}
|
||||
export function is(text, options = {}) {
|
||||
if (typeof text !== "string") {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
normalize(text, options);
|
||||
return true;
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
export function encode(data, options = {}) {
|
||||
const bytes = toUint8Array(data);
|
||||
const casing = options.case ?? "lower";
|
||||
const pairs = Array.from(bytes, (byte) => {
|
||||
const text = byte.toString(16).padStart(2, "0");
|
||||
return casing === "upper" ? text.toUpperCase() : text;
|
||||
});
|
||||
let body = "";
|
||||
if (options.line) {
|
||||
const bytesPerLine = options.line.bytesPerLine;
|
||||
if (!Number.isInteger(bytesPerLine) || bytesPerLine < 1) {
|
||||
throw new RangeError("Hex bytesPerLine must be a positive integer");
|
||||
}
|
||||
const separator = options.line.separator ?? "\n";
|
||||
const lines = [];
|
||||
for (let index = 0; index < pairs.length; index += bytesPerLine) {
|
||||
lines.push(groupPairs(pairs.slice(index, index + bytesPerLine), options.group));
|
||||
}
|
||||
body = lines.join(separator);
|
||||
}
|
||||
else {
|
||||
body = groupPairs(pairs, options.group);
|
||||
}
|
||||
return `${options.prefix ?? ""}${body}`;
|
||||
}
|
||||
export function decode(text, options = {}) {
|
||||
const normalized = normalize(text, options);
|
||||
const result = new Uint8Array(normalized.length / 2);
|
||||
for (let i = 0; i < normalized.length; i += 2) {
|
||||
result[i / 2] = Number.parseInt(normalized.slice(i, i + 2), 16);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export function parse(text, options = {}) {
|
||||
const normalized = normalize(text, options);
|
||||
return {
|
||||
bytes: decode(normalized),
|
||||
format: detectFormat(text),
|
||||
normalized,
|
||||
};
|
||||
}
|
||||
export function format(data, value) {
|
||||
return encode(data, value);
|
||||
}
|
||||
export const formats = {
|
||||
compact: Object.freeze({}),
|
||||
upper: Object.freeze({ case: "upper" }),
|
||||
colon: Object.freeze({ group: { size: 1, separator: ":" } }),
|
||||
colonUpper: Object.freeze({ case: "upper", group: { size: 1, separator: ":" } }),
|
||||
groupsOf4: Object.freeze({ group: { size: 4, separator: " " } }),
|
||||
prefixed: Object.freeze({ prefix: "0x" }),
|
||||
};
|
||||
export const hex = { encode, decode, format, formats, is, normalize, parse };
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
export * as binary from "./binary.js";
|
||||
export * as hex from "./hex.js";
|
||||
export * as utf8 from "./utf8.js";
|
||||
export * as utf16 from "./utf16.js";
|
||||
export * as base64 from "./base64.js";
|
||||
export * as base64url from "./base64url.js";
|
||||
-19
@@ -1,19 +0,0 @@
|
||||
import { toArrayBuffer } from "../bytes/index.js";
|
||||
export function encode(text, options = {}) {
|
||||
const result = new ArrayBuffer(text.length * 2);
|
||||
const view = new DataView(result);
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
view.setUint16(i * 2, text.charCodeAt(i), options.littleEndian ?? false);
|
||||
}
|
||||
return new Uint8Array(result);
|
||||
}
|
||||
export function decode(data, options = {}) {
|
||||
const buffer = toArrayBuffer(data);
|
||||
const view = new DataView(buffer);
|
||||
let result = "";
|
||||
for (let i = 0; i < buffer.byteLength; i += 2) {
|
||||
result += String.fromCharCode(view.getUint16(i, options.littleEndian ?? false));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export const utf16 = { encode, decode };
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
import { toUint8Array } from "../bytes/index.js";
|
||||
export function encode(text) {
|
||||
return new TextEncoder().encode(text);
|
||||
}
|
||||
export function decode(data) {
|
||||
return new TextDecoder("utf-8", { fatal: false }).decode(toUint8Array(data));
|
||||
}
|
||||
export const utf8 = { encode, decode };
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
export * from "./bytes/index.js";
|
||||
export * as bytes from "./bytes/index.js";
|
||||
export * from "./encoding/index.js";
|
||||
export * from "./pem/index.js";
|
||||
export * from "./converters/index.js";
|
||||
export * from "./legacy/index.js";
|
||||
-33
@@ -1,33 +0,0 @@
|
||||
import { concat, equal, isArrayBuffer, isArrayBufferView, isBufferSource, toArrayBuffer, toUint8Array, toView, } from "../bytes/index.js";
|
||||
export class BufferSourceConverter {
|
||||
static isArrayBuffer(data) {
|
||||
return isArrayBuffer(data);
|
||||
}
|
||||
static toArrayBuffer(data) {
|
||||
return toArrayBuffer(data);
|
||||
}
|
||||
static toUint8Array(data) {
|
||||
return toUint8Array(data);
|
||||
}
|
||||
static toView(data, type) {
|
||||
return toView(data, type);
|
||||
}
|
||||
static isBufferSource(data) {
|
||||
return isBufferSource(data);
|
||||
}
|
||||
static isArrayBufferView(data) {
|
||||
return isArrayBufferView(data);
|
||||
}
|
||||
static isEqual(a, b) {
|
||||
return equal(a, b);
|
||||
}
|
||||
static concat(first, second, ...rest) {
|
||||
if (Array.isArray(first)) {
|
||||
return typeof second === "function"
|
||||
? concat(first, second)
|
||||
: concat(first);
|
||||
}
|
||||
const buffers = [first, second, ...rest].filter(Boolean);
|
||||
return concat(buffers);
|
||||
}
|
||||
}
|
||||
-68
@@ -1,68 +0,0 @@
|
||||
import { convert } from "../converters/index.js";
|
||||
function normalizeTextEncoding(encoding) {
|
||||
return encoding === "ascii" ? "binary" : encoding;
|
||||
}
|
||||
export class Convert {
|
||||
static DEFAULT_UTF8_ENCODING = "utf8";
|
||||
static isHex(data) {
|
||||
return convert.isHex(data);
|
||||
}
|
||||
static isBase64(data) {
|
||||
return convert.isBase64(data);
|
||||
}
|
||||
static isBase64Url(data) {
|
||||
return convert.isBase64Url(data);
|
||||
}
|
||||
static ToString(buffer, enc = "utf8") {
|
||||
return convert.toString(buffer, enc);
|
||||
}
|
||||
static FromString(str, enc = "utf8") {
|
||||
if (!str) {
|
||||
return new ArrayBuffer(0);
|
||||
}
|
||||
return convert.fromString(str, enc);
|
||||
}
|
||||
static ToBase64(buffer) {
|
||||
return convert.toBase64(buffer);
|
||||
}
|
||||
static FromBase64(base64) {
|
||||
return convert.fromBase64(base64);
|
||||
}
|
||||
static FromBase64Url(base64url) {
|
||||
return convert.fromBase64Url(base64url);
|
||||
}
|
||||
static ToBase64Url(data) {
|
||||
return convert.toBase64Url(data);
|
||||
}
|
||||
static FromUtf8String(text, encoding = Convert.DEFAULT_UTF8_ENCODING) {
|
||||
return convert.fromString(text, normalizeTextEncoding(encoding));
|
||||
}
|
||||
static ToUtf8String(buffer, encoding = Convert.DEFAULT_UTF8_ENCODING) {
|
||||
return convert.toString(buffer, normalizeTextEncoding(encoding));
|
||||
}
|
||||
static FromBinary(text) {
|
||||
return convert.fromBinary(text);
|
||||
}
|
||||
static ToBinary(buffer) {
|
||||
return convert.toBinary(buffer);
|
||||
}
|
||||
static ToHex(buffer) {
|
||||
return convert.toHex(buffer);
|
||||
}
|
||||
static FromHex(hexString) {
|
||||
return convert.fromHex(hexString);
|
||||
}
|
||||
static ToUtf16String(buffer, littleEndian = false) {
|
||||
return convert.toUtf16String(buffer, littleEndian);
|
||||
}
|
||||
static FromUtf16String(text, littleEndian = false) {
|
||||
return convert.fromUtf16String(text, littleEndian);
|
||||
}
|
||||
static Base64Padding(base64) {
|
||||
const padCount = 4 - (base64.length % 4);
|
||||
return padCount < 4 ? base64 + "=".repeat(padCount) : base64;
|
||||
}
|
||||
static formatString(data) {
|
||||
return convert.formatString(data);
|
||||
}
|
||||
}
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
import { concat, equal } from "../bytes/index.js";
|
||||
export function assign(target, ...sources) {
|
||||
for (const source of sources) {
|
||||
if (!source) {
|
||||
continue;
|
||||
}
|
||||
for (const prop in source) {
|
||||
target[prop] = source[prop];
|
||||
}
|
||||
}
|
||||
return target;
|
||||
}
|
||||
export function combine(...buf) {
|
||||
return concat(buf);
|
||||
}
|
||||
export function isEqual(bytes1, bytes2) {
|
||||
return equal(bytes1, bytes2);
|
||||
}
|
||||
-3
@@ -1,3 +0,0 @@
|
||||
export { BufferSourceConverter } from "./buffer-source-converter.js";
|
||||
export { Convert } from "./convert.js";
|
||||
export { assign, combine, isEqual } from "./functions.js";
|
||||
-1
@@ -1 +0,0 @@
|
||||
export { decode, decodeFirst, encode, encodeMany, find, findAll, format, parse, pem, pemConverter } from "./pem.js";
|
||||
-129
@@ -1,129 +0,0 @@
|
||||
import { base64 } from "../encoding/base64.js";
|
||||
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 normalized = body.trim().replace(/\r\n/g, "\n");
|
||||
const lines = normalized.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 : undefined,
|
||||
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.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;
|
||||
}
|
||||
export 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.encode(data), lineLength));
|
||||
lines.push(`-----END ${label}-----`);
|
||||
return `${lines.join(newline)}${newline}`;
|
||||
}
|
||||
export function encodeMany(blocks, options = {}) {
|
||||
return blocks.map((block) => encode(block.label, block.data, { ...options, headers: block.headers ?? options.headers })).join("");
|
||||
}
|
||||
export function decode(text, options = {}) {
|
||||
return collectBlocks(text, options).map(({ lineLength: _lineLength, newline: _newline, ...block }) => block);
|
||||
}
|
||||
export function find(text, label) {
|
||||
return decode(text, { label })[0];
|
||||
}
|
||||
export function findAll(text, label) {
|
||||
return decode(text, { label });
|
||||
}
|
||||
export function decodeFirst(text, label) {
|
||||
const [block] = decode(text, { label, strict: true });
|
||||
return block.data;
|
||||
}
|
||||
export 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),
|
||||
};
|
||||
}
|
||||
export function format(data, value) {
|
||||
return encode(value.label, data, value);
|
||||
}
|
||||
export const pem = { decode, decodeFirst, encode, encodeMany, find, findAll, format, parse };
|
||||
export const 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,
|
||||
};
|
||||
-1
@@ -1 +0,0 @@
|
||||
export {};
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
import type { ArrayBufferViewLike, BufferSourceLike, ViewConstructor } from "./types.js";
|
||||
/** Checks whether a value is an ArrayBuffer. */
|
||||
export declare function isArrayBuffer(value: unknown): value is ArrayBuffer;
|
||||
/** Checks whether a value is a SharedArrayBuffer. */
|
||||
export declare function isSharedArrayBuffer(value: unknown): value is SharedArrayBuffer;
|
||||
/** Checks whether a value is an ArrayBuffer-like object. */
|
||||
export declare function isArrayBufferLike(value: unknown): value is ArrayBufferLike;
|
||||
/** Checks whether a value is an ArrayBufferView. */
|
||||
export declare function isArrayBufferView(value: unknown): value is ArrayBufferViewLike;
|
||||
/** Checks whether a value can be treated as a buffer source. */
|
||||
export declare function isBufferSource(value: unknown): value is BufferSourceLike;
|
||||
/** Throws when a value is not a supported buffer source. */
|
||||
export declare function assertBufferSource(value: unknown): asserts value is BufferSourceLike;
|
||||
/** Returns a Uint8Array view over the input without copying. */
|
||||
export declare function toUint8Array(data: BufferSourceLike): Uint8Array;
|
||||
/** Returns a copied Uint8Array for the input buffer source. */
|
||||
export declare function toUint8ArrayCopy(data: BufferSourceLike): Uint8Array;
|
||||
/** Returns the underlying ArrayBuffer, copying when required. */
|
||||
export declare function toArrayBuffer(data: BufferSourceLike): ArrayBuffer;
|
||||
/** Returns an ArrayBuffer-like value, copying only when needed. */
|
||||
export declare function toArrayBufferLike(data: BufferSourceLike): ArrayBufferLike;
|
||||
/** Casts buffer data into the requested view type. */
|
||||
export declare function toView<T extends ArrayBufferViewLike>(data: BufferSourceLike, type: ViewConstructor<T>): T;
|
||||
/** Copies buffer data into the requested view type. */
|
||||
export declare function toViewCopy<T extends ArrayBufferViewLike>(data: BufferSourceLike, type: ViewConstructor<T>): T;
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
import type { ArrayBufferViewLike, BufferSourceLike, ViewConstructor } from "./types.js";
|
||||
/** Concatenates buffer sources into a new Uint8Array. */
|
||||
export declare function concatToUint8Array(buffers: Iterable<BufferSourceLike>): Uint8Array;
|
||||
/** Concatenates buffer sources and returns either an ArrayBufferLike or a typed view. */
|
||||
export declare function concat(...buffers: BufferSourceLike[]): ArrayBufferLike;
|
||||
export declare function concat(buffers: Iterable<BufferSourceLike>): ArrayBufferLike;
|
||||
export declare function concat<T extends ArrayBufferViewLike>(buffers: Iterable<BufferSourceLike>, type: ViewConstructor<T>): T;
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
import type { BufferSourceLike } from "./types.js";
|
||||
/** Options that control how byte comparisons are performed. */
|
||||
export interface EqualOptions {
|
||||
constantTime?: boolean;
|
||||
}
|
||||
/** Compares two buffer sources for byte equality. */
|
||||
export declare function equal(a: BufferSourceLike, b: BufferSourceLike, options?: EqualOptions): boolean;
|
||||
-8
@@ -1,8 +0,0 @@
|
||||
/** Barrel export for buffer-related types and helpers. */
|
||||
export type { ArrayBufferViewLike, ArrayBufferViewConstructor, BufferSource, BufferSourceLike, DataViewConstructorLike, StrictBufferSource, ViewConstructor, } from "./types.js";
|
||||
export { assertBufferSource, isArrayBuffer, isArrayBufferLike, isArrayBufferView, isBufferSource, isSharedArrayBuffer, toArrayBuffer, toArrayBufferLike, toUint8Array, toUint8ArrayCopy, toView, toViewCopy, } from "./buffer-source.js";
|
||||
export { concat, concatToUint8Array } from "./concat.js";
|
||||
export type { EqualOptions } from "./equal.js";
|
||||
export { equal } from "./equal.js";
|
||||
export type { BytePattern, ByteSearchOptions } from "./sequence.js";
|
||||
export { compare, copy, endsWith, includes, indexOf, lastIndexOf, slice, startsWith, tail, } from "./sequence.js";
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
import type { BufferSourceLike } from "./types.js";
|
||||
/** String or byte pattern accepted by the byte search helpers. */
|
||||
export type BytePattern = BufferSourceLike | string;
|
||||
/** Options shared by the stateless byte search helpers. */
|
||||
export interface ByteSearchOptions {
|
||||
/**
|
||||
* Start offset for forward search.
|
||||
* For reverse search this is the upper bound / starting point.
|
||||
*/
|
||||
start?: number;
|
||||
/**
|
||||
* End offset, exclusive.
|
||||
* For reverse search this is the lower bound.
|
||||
*/
|
||||
end?: number;
|
||||
/**
|
||||
* Encoding used when pattern is a string.
|
||||
* Defaults to ASCII for marker-style byte searches.
|
||||
*/
|
||||
encoding?: "ascii" | "utf8";
|
||||
}
|
||||
/**
|
||||
* Searches for the first occurrence of a byte pattern within the requested range.
|
||||
* Returns the absolute byte offset or `-1` when the pattern is not found.
|
||||
*/
|
||||
export declare function indexOf(data: BufferSourceLike, pattern: BytePattern, options?: ByteSearchOptions): number;
|
||||
/**
|
||||
* Searches backwards for the last occurrence of a byte pattern within the requested range.
|
||||
* Returns the absolute byte offset or `-1` when the pattern is not found.
|
||||
*/
|
||||
export declare function lastIndexOf(data: BufferSourceLike, pattern: BytePattern, options?: ByteSearchOptions): number;
|
||||
/** Returns `true` when the pattern exists anywhere in the requested range. */
|
||||
export declare function includes(data: BufferSourceLike, pattern: BytePattern, options?: ByteSearchOptions): boolean;
|
||||
/** Returns `true` when the byte sequence starts with the requested pattern. */
|
||||
export declare function startsWith(data: BufferSourceLike, pattern: BytePattern, options?: Pick<ByteSearchOptions, "encoding">): boolean;
|
||||
/** Returns `true` when the byte sequence ends with the requested pattern. */
|
||||
export declare function endsWith(data: BufferSourceLike, pattern: BytePattern, options?: Pick<ByteSearchOptions, "encoding">): boolean;
|
||||
/**
|
||||
* Returns a Uint8Array view over the requested byte range.
|
||||
* Negative indexes follow `Array.prototype.slice` semantics.
|
||||
*/
|
||||
export declare function slice(data: BufferSourceLike, start?: number, end?: number): Uint8Array;
|
||||
/** Returns the last `length` bytes of the input as a Uint8Array view. */
|
||||
export declare function tail(data: BufferSourceLike, length: number): Uint8Array;
|
||||
/** Returns a new Uint8Array copy that never shares memory with the input. */
|
||||
export declare function copy(data: BufferSourceLike): Uint8Array;
|
||||
/** Compares two byte sequences lexicographically. */
|
||||
export declare function compare(a: BufferSourceLike, b: BufferSourceLike): -1 | 0 | 1;
|
||||
-29
@@ -1,29 +0,0 @@
|
||||
/** Describes a buffer-backed view with offset and length metadata. */
|
||||
export interface ArrayBufferViewLike<TBuffer extends ArrayBufferLike = ArrayBufferLike> {
|
||||
readonly buffer: TBuffer;
|
||||
readonly byteOffset: number;
|
||||
readonly byteLength: number;
|
||||
}
|
||||
/** A buffer source backed by either an ArrayBuffer-like value or a view. */
|
||||
export type BufferSourceLike = ArrayBufferLike | ArrayBufferViewLike;
|
||||
/** Historical BufferSource alias preserved for compatibility. */
|
||||
export type BufferSource = BufferSourceLike;
|
||||
/** A strict buffer source limited to ArrayBuffer and ArrayBuffer-backed views. */
|
||||
export type StrictBufferSource = ArrayBuffer | ArrayBufferViewLike<ArrayBuffer>;
|
||||
/** Constructor shape for typed array-like views. */
|
||||
export interface ArrayBufferViewConstructor<T extends ArrayBufferViewLike = ArrayBufferViewLike> {
|
||||
readonly prototype: T;
|
||||
readonly BYTES_PER_ELEMENT?: number;
|
||||
readonly name: string;
|
||||
new (length: number): T;
|
||||
new (array: ArrayLike<number>): T;
|
||||
new (buffer: ArrayBufferLike, byteOffset?: number, length?: number): T;
|
||||
}
|
||||
/** Constructor shape for DataView-like views. */
|
||||
export interface DataViewConstructorLike<T extends ArrayBufferViewLike = ArrayBufferViewLike> {
|
||||
readonly prototype: T;
|
||||
readonly name: string;
|
||||
new (buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): T;
|
||||
}
|
||||
/** A constructor that can create a typed view over buffer data. */
|
||||
export type ViewConstructor<T extends ArrayBufferViewLike = ArrayBufferViewLike> = ArrayBufferViewConstructor<T> | DataViewConstructorLike<T>;
|
||||
-65
@@ -1,65 +0,0 @@
|
||||
import type { BufferSourceLike } from "../bytes/index.js";
|
||||
import type { DecodeOptionsFor, DetectOptions, EncodeOptionsFor, FormatDetection, FormatFor, OptionsArgument, ParsedBytes, TranscodeOptions, DecodeResult } from "./types.js";
|
||||
/** Text encodings supported by the legacy converter facade. */
|
||||
export type BufferEncoding = "utf8" | "utf-8" | "binary" | "latin1" | "base64" | "base64url" | "base64-url" | "hex" | "utf16" | "utf16be" | "utf16le" | string;
|
||||
/** Public converter facade backed by the default registry. */
|
||||
export interface ConvertFacade {
|
||||
/** Encodes bytes with a named converter. */
|
||||
encode<TName extends string>(name: TName, data: BufferSourceLike, ...args: OptionsArgument<EncodeOptionsFor<TName>>): string;
|
||||
/** Decodes text with a named converter. */
|
||||
decode<TName extends string>(name: TName, text: string, ...args: OptionsArgument<DecodeOptionsFor<TName>>): Uint8Array;
|
||||
/** Safely decodes text with a named converter. */
|
||||
tryDecode<TName extends string>(name: TName, text: string, ...args: OptionsArgument<DecodeOptionsFor<TName>>): DecodeResult;
|
||||
/** Normalizes text with a named converter. */
|
||||
normalize<TName extends string>(name: TName, text: string, ...args: OptionsArgument<DecodeOptionsFor<TName>>): string;
|
||||
/** Parses text while preserving formatting metadata. */
|
||||
parse<TName extends string>(name: TName, text: string, ...args: OptionsArgument<DecodeOptionsFor<TName>>): ParsedBytes<FormatFor<TName>>;
|
||||
/** Formats bytes using preserved formatting metadata. */
|
||||
format<TName extends string>(name: TName, data: BufferSourceLike, format: FormatFor<TName>): string;
|
||||
/** Converts text directly between registered formats. */
|
||||
transcode<TFrom extends string, TTo extends string>(text: string, options: TranscodeOptions<TFrom, TTo>): string;
|
||||
/** Detects likely formats for an input string. */
|
||||
detect<TName extends string = string>(text: string, options?: DetectOptions<TName>): FormatDetection[];
|
||||
/** @deprecated Use encode() instead. */
|
||||
to<TName extends string>(format: TName, data: BufferSourceLike, ...args: OptionsArgument<EncodeOptionsFor<TName>>): string;
|
||||
/** @deprecated Use decode() instead. */
|
||||
from<TName extends string>(format: TName, text: string, ...args: OptionsArgument<DecodeOptionsFor<TName>>): Uint8Array;
|
||||
/** Converts buffer data to a string using a known encoding. */
|
||||
toString(data: BufferSourceLike, encoding?: BufferEncoding): string;
|
||||
/** Converts a string to bytes using a known encoding. */
|
||||
fromString(text: string, encoding?: BufferEncoding): ArrayBufferLike;
|
||||
/** Encodes bytes as Base64 text. */
|
||||
toBase64(data: BufferSourceLike): string;
|
||||
/** Decodes Base64 text into bytes. */
|
||||
fromBase64(text: string): ArrayBufferLike;
|
||||
/** Encodes bytes as Base64Url text. */
|
||||
toBase64Url(data: BufferSourceLike): string;
|
||||
/** Decodes Base64Url text into bytes. */
|
||||
fromBase64Url(text: string): ArrayBufferLike;
|
||||
/** Encodes bytes as hexadecimal text. */
|
||||
toHex(data: BufferSourceLike): string;
|
||||
/** Decodes hexadecimal text into bytes. */
|
||||
fromHex(text: string): ArrayBufferLike;
|
||||
/** Encodes bytes as binary text. */
|
||||
toBinary(data: BufferSourceLike): string;
|
||||
/** Decodes binary text into bytes. */
|
||||
fromBinary(text: string): ArrayBufferLike;
|
||||
/** Decodes UTF-8 bytes into text. */
|
||||
toUtf8String(data: BufferSourceLike): string;
|
||||
/** Encodes UTF-8 text into bytes. */
|
||||
fromUtf8String(text: string): ArrayBufferLike;
|
||||
/** Decodes UTF-16 bytes into text. */
|
||||
toUtf16String(data: BufferSourceLike, littleEndian?: boolean): string;
|
||||
/** Encodes UTF-16 text into bytes. */
|
||||
fromUtf16String(text: string, littleEndian?: boolean): ArrayBufferLike;
|
||||
/** Checks whether a value is hexadecimal text. */
|
||||
isHex(text: unknown): text is string;
|
||||
/** Checks whether a value is Base64 text. */
|
||||
isBase64(text: unknown): text is string;
|
||||
/** Checks whether a value is Base64Url text. */
|
||||
isBase64Url(text: unknown): text is string;
|
||||
/** Normalizes whitespace in a Base64-style string. */
|
||||
formatString(text: string): string;
|
||||
}
|
||||
/** Converter helpers for common text and binary encodings. */
|
||||
export declare const convert: ConvertFacade;
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
export { pemConverter } from "../pem/index.js";
|
||||
import type { Converter } from "./types.js";
|
||||
/** Converter for binary text where each character maps to one byte. */
|
||||
export declare const binaryConverter: Converter;
|
||||
/** Converter for hexadecimal text. */
|
||||
export declare const hexConverter: Converter;
|
||||
/** Converter for standard Base64 text. */
|
||||
export declare const base64Converter: Converter;
|
||||
/** Converter for URL-safe Base64 text. */
|
||||
export declare const base64urlConverter: Converter;
|
||||
/** Converter for UTF-8 text. */
|
||||
export declare const utf8Converter: Converter;
|
||||
/** Converter for big-endian UTF-16 text. */
|
||||
export declare const utf16beConverter: Converter;
|
||||
/** Converter for little-endian UTF-16 text. */
|
||||
export declare const utf16leConverter: Converter;
|
||||
/** The built-in converter set shipped with the package. */
|
||||
export declare const defaultConverters: readonly [Converter<any, any, any>, Converter<any, any, any>, Converter<any, any, any>, Converter<any, any, any>, Converter<any, any, any>, Converter<any, any, any>, Converter<any, any, any>, Converter<import("../index.js").PemEncodeOptions & {
|
||||
label: string;
|
||||
}, import("../index.js").PemDecodeOptions, import("../index.js").PemFormat>];
|
||||
/** The default registry preloaded with the built-in converters. */
|
||||
export declare const defaultConverterRegistry: import("./types.js").ConverterRegistry;
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
/** Barrel export for converter registry types and default codecs. */
|
||||
export type { ByteDecoder, ByteEncoder, Converter, ConverterOptionsMap, ConverterRegistry, DecodeOptionsFor, DecodeResult, DetectOptions, EncodeOptionsFor, FormatDetection, FormatFor, OptionsArgument, ParsedBytes, RegisterOptions, TranscodeOptions, } from "./types.js";
|
||||
export { createConverterRegistry } from "./registry.js";
|
||||
export { base64Converter, base64urlConverter, binaryConverter, defaultConverterRegistry, defaultConverters, hexConverter, pemConverter, utf16beConverter, utf16leConverter, utf8Converter, } from "./defaults.js";
|
||||
export type { BufferEncoding, ConvertFacade } from "./convert.js";
|
||||
export { convert } from "./convert.js";
|
||||
-3
@@ -1,3 +0,0 @@
|
||||
import type { Converter, ConverterRegistry } from "./types.js";
|
||||
/** Creates a converter registry and optionally seeds it with converters. */
|
||||
export declare function createConverterRegistry(initialConverters?: Iterable<Converter>): ConverterRegistry;
|
||||
-141
@@ -1,141 +0,0 @@
|
||||
import type { BufferSourceLike } from "../bytes/index.js";
|
||||
import type { Base64DecodeOptions, Base64EncodeOptions } from "../encoding/base64.js";
|
||||
import type { Base64UrlDecodeOptions, Base64UrlEncodeOptions } from "../encoding/base64url.js";
|
||||
import type { HexDecodeOptions, HexEncodeOptions, HexFormat } from "../encoding/hex.js";
|
||||
import type { PemDecodeOptions, PemEncodeOptions, PemFormat } from "../pem/types.js";
|
||||
/** Converts buffer data into text using encoder-specific options. */
|
||||
export type ByteEncoder<TOptions = any> = (data: BufferSourceLike, options?: TOptions) => string;
|
||||
/** Converts text back into bytes using decoder-specific options. */
|
||||
export type ByteDecoder<TOptions = any> = (text: string, options?: TOptions) => Uint8Array;
|
||||
/** Parsed text that preserves both decoded bytes and the detected format metadata. */
|
||||
export interface ParsedBytes<TFormat = unknown> {
|
||||
/** Decoded bytes. */
|
||||
readonly bytes: Uint8Array;
|
||||
/** Detected formatting metadata. */
|
||||
readonly format: TFormat;
|
||||
/** Canonical normalized text representation. */
|
||||
readonly normalized: string;
|
||||
}
|
||||
/** Result of a safe decode operation that does not throw. */
|
||||
export type DecodeResult = {
|
||||
ok: true;
|
||||
bytes: Uint8Array;
|
||||
} | {
|
||||
ok: false;
|
||||
error: Error;
|
||||
};
|
||||
/** Ranked format detection candidate. */
|
||||
export interface FormatDetection {
|
||||
/** Registered converter name. */
|
||||
readonly format: string;
|
||||
/** Confidence score in the range from 0 to 1. */
|
||||
readonly confidence: number;
|
||||
}
|
||||
/** Open interface that standard and user converters can augment with typed options. */
|
||||
export interface ConverterOptionsMap {
|
||||
base64: {
|
||||
decode: Base64DecodeOptions;
|
||||
encode: Base64EncodeOptions;
|
||||
};
|
||||
base64url: {
|
||||
decode: Base64UrlDecodeOptions;
|
||||
encode: Base64UrlEncodeOptions;
|
||||
};
|
||||
hex: {
|
||||
decode: HexDecodeOptions;
|
||||
encode: HexEncodeOptions;
|
||||
format: HexFormat;
|
||||
};
|
||||
pem: {
|
||||
decode: PemDecodeOptions;
|
||||
encode: PemEncodeOptions & {
|
||||
label: string;
|
||||
};
|
||||
format: PemFormat;
|
||||
};
|
||||
}
|
||||
type KnownConverterName = Extract<keyof ConverterOptionsMap, string>;
|
||||
type EmptyObject = Record<never, never>;
|
||||
type RequiredKeys<T extends object> = {
|
||||
[TKey in keyof T]-?: EmptyObject extends Pick<T, TKey> ? never : TKey;
|
||||
}[keyof T];
|
||||
type NonUndefined<T> = Exclude<T, undefined>;
|
||||
type CapabilityOptions<TName extends string, TCapability extends "encode" | "decode" | "format"> = TName extends KnownConverterName ? ConverterOptionsMap[TName] extends Record<TCapability, infer TOptions> ? TOptions : unknown : unknown;
|
||||
/** Resolves typed encode options for a known converter name. */
|
||||
export type EncodeOptionsFor<TName extends string> = CapabilityOptions<TName, "encode">;
|
||||
/** Resolves typed decode options for a known converter name. */
|
||||
export type DecodeOptionsFor<TName extends string> = CapabilityOptions<TName, "decode">;
|
||||
/** Resolves typed format metadata for a known converter name. */
|
||||
export type FormatFor<TName extends string> = CapabilityOptions<TName, "format">;
|
||||
/** Builds an optional or required options tuple depending on the options type. */
|
||||
export type OptionsArgument<TOptions> = [TOptions] extends [never] ? [] : unknown extends TOptions ? [options?: TOptions] : [NonUndefined<TOptions>] extends [object] ? RequiredKeys<NonUndefined<TOptions>> extends never ? [options?: TOptions] : [options: TOptions] : [options: TOptions];
|
||||
/** Options for direct format-to-format transcoding. */
|
||||
export interface TranscodeOptions<TFrom extends string = string, TTo extends string = string> {
|
||||
/** Source format name. */
|
||||
readonly from: TFrom;
|
||||
/** Source decoder options. */
|
||||
readonly fromOptions?: DecodeOptionsFor<TFrom>;
|
||||
/** Destination format name. */
|
||||
readonly to: TTo;
|
||||
/** Destination encoder options. */
|
||||
readonly toOptions?: EncodeOptionsFor<TTo>;
|
||||
}
|
||||
/** Options for ranked format detection. */
|
||||
export interface DetectOptions<TName extends string = string> {
|
||||
/** Formats to check. Defaults to the registered non-generic codecs. */
|
||||
readonly formats?: readonly TName[];
|
||||
}
|
||||
/** Describes a named text converter with optional aliases and validation. */
|
||||
export interface Converter<TEncodeOptions = any, TDecodeOptions = any, TFormat = any> {
|
||||
/** The primary converter name. */
|
||||
readonly name: string;
|
||||
/** Additional names that resolve to the same converter. */
|
||||
readonly aliases?: readonly string[];
|
||||
/** Encodes buffer data into text. */
|
||||
readonly encode: ByteEncoder<TEncodeOptions>;
|
||||
/** Decodes text into bytes. */
|
||||
readonly decode: ByteDecoder<TDecodeOptions>;
|
||||
/** Normalizes input text into the canonical representation accepted by the converter. */
|
||||
readonly normalize?: (text: string, options?: TDecodeOptions) => string;
|
||||
/** Parses text into bytes while preserving formatting metadata. */
|
||||
readonly parse?: (text: string, options?: TDecodeOptions) => ParsedBytes<TFormat>;
|
||||
/** Formats bytes using previously detected formatting metadata. */
|
||||
readonly format?: (data: BufferSourceLike, format: TFormat) => string;
|
||||
/** Checks whether a text value is accepted by the converter. */
|
||||
readonly is?: (text: unknown) => text is string;
|
||||
}
|
||||
/** Options that control how a converter is registered. */
|
||||
export interface RegisterOptions {
|
||||
/** Replaces an existing converter with the same name or alias. */
|
||||
override?: boolean;
|
||||
}
|
||||
/** Registry API for looking up, registering, and using converters. */
|
||||
export interface ConverterRegistry {
|
||||
/** Registers a converter. */
|
||||
register(converter: Converter, options?: RegisterOptions): this;
|
||||
/** Removes a converter by name or alias. */
|
||||
unregister(name: string): boolean;
|
||||
/** Checks whether a converter is registered. */
|
||||
has(name: string): boolean;
|
||||
/** Returns a registered converter. */
|
||||
get(name: string): Converter;
|
||||
/** Returns the list of primary registered converters. */
|
||||
list(): readonly Converter[];
|
||||
/** Encodes buffer data with a named converter. */
|
||||
encode<TName extends string>(name: TName, data: BufferSourceLike, ...args: OptionsArgument<EncodeOptionsFor<TName>>): string;
|
||||
/** Decodes text with a named converter. */
|
||||
decode<TName extends string>(name: TName, text: string, ...args: OptionsArgument<DecodeOptionsFor<TName>>): Uint8Array;
|
||||
/** Safely decodes text with a named converter without throwing. */
|
||||
tryDecode<TName extends string>(name: TName, text: string, ...args: OptionsArgument<DecodeOptionsFor<TName>>): DecodeResult;
|
||||
/** Normalizes text with a named converter. */
|
||||
normalize<TName extends string>(name: TName, text: string, ...args: OptionsArgument<DecodeOptionsFor<TName>>): string;
|
||||
/** Parses text with a named converter. */
|
||||
parse<TName extends string>(name: TName, text: string, ...args: OptionsArgument<DecodeOptionsFor<TName>>): ParsedBytes<FormatFor<TName>>;
|
||||
/** Formats bytes with a named converter using preserved formatting metadata. */
|
||||
format<TName extends string>(name: TName, data: BufferSourceLike, format: FormatFor<TName>): string;
|
||||
/** Converts text directly from one registered format to another. */
|
||||
transcode<TFrom extends string, TTo extends string>(text: string, options: TranscodeOptions<TFrom, TTo>): string;
|
||||
/** Detects likely formats for the provided text. */
|
||||
detect<TName extends string = string>(text: string, options?: DetectOptions<TName>): FormatDetection[];
|
||||
}
|
||||
export {};
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
import type { BufferSourceLike } from "../bytes/index.js";
|
||||
/** Options that control Base64 encoding. */
|
||||
export interface Base64EncodeOptions {
|
||||
readonly __base64EncodeOptionsBrand?: never;
|
||||
}
|
||||
/** Options that control Base64 decoding. */
|
||||
export interface Base64DecodeOptions {
|
||||
readonly __base64DecodeOptionsBrand?: never;
|
||||
}
|
||||
/** Removes whitespace from Base64 text. */
|
||||
export declare function normalize(text: string): string;
|
||||
/** Pads Base64 text to a multiple of four characters. */
|
||||
export declare function pad(text: string): string;
|
||||
/** Checks whether a value is valid Base64 text. */
|
||||
export declare function is(text: unknown): text is string;
|
||||
/** Encodes buffer data as Base64 text. */
|
||||
export declare function encode(data: BufferSourceLike, _options?: Base64EncodeOptions): string;
|
||||
/** Decodes Base64 text into bytes. */
|
||||
export declare function decode(text: string, _options?: Base64DecodeOptions): Uint8Array;
|
||||
/** Base64 codec helpers. */
|
||||
export declare const base64: {
|
||||
readonly encode: typeof encode;
|
||||
readonly decode: typeof decode;
|
||||
readonly is: typeof is;
|
||||
readonly normalize: typeof normalize;
|
||||
readonly pad: typeof pad;
|
||||
};
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
import type { BufferSourceLike } from "../bytes/index.js";
|
||||
/** Options that control Base64Url encoding. */
|
||||
export interface Base64UrlEncodeOptions {
|
||||
readonly __base64UrlEncodeOptionsBrand?: never;
|
||||
}
|
||||
/** Options that control Base64Url decoding. */
|
||||
export interface Base64UrlDecodeOptions {
|
||||
readonly __base64UrlDecodeOptionsBrand?: never;
|
||||
}
|
||||
/** Removes whitespace from Base64Url text. */
|
||||
export declare function normalize(text: string): string;
|
||||
/** Checks whether a value is valid Base64Url text. */
|
||||
export declare function is(text: unknown): text is string;
|
||||
/** Encodes buffer data as Base64Url text. */
|
||||
export declare function encode(data: BufferSourceLike, _options?: Base64UrlEncodeOptions): string;
|
||||
/** Decodes Base64Url text into bytes. */
|
||||
export declare function decode(text: string, _options?: Base64UrlDecodeOptions): Uint8Array;
|
||||
/** Base64Url codec helpers. */
|
||||
export declare const base64url: {
|
||||
readonly encode: typeof encode;
|
||||
readonly decode: typeof decode;
|
||||
readonly is: typeof is;
|
||||
readonly normalize: typeof normalize;
|
||||
};
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
import type { BufferSourceLike } from "../bytes/index.js";
|
||||
/** Encodes bytes as a one-byte-per-character string. */
|
||||
export declare function encode(data: BufferSourceLike): string;
|
||||
/** Decodes a one-byte-per-character string into bytes. */
|
||||
export declare function decode(text: string): Uint8Array;
|
||||
/** Checks whether a value is a string suitable for binary text handling. */
|
||||
export declare function is(text: unknown): text is string;
|
||||
/** Binary codec helpers. */
|
||||
export declare const binary: {
|
||||
readonly encode: typeof encode;
|
||||
readonly decode: typeof decode;
|
||||
readonly is: typeof is;
|
||||
};
|
||||
-76
@@ -1,76 +0,0 @@
|
||||
import type { BufferSourceLike } from "../bytes/index.js";
|
||||
import type { ParsedBytes } from "../converters/types.js";
|
||||
/** Hex casing modes used by format-aware helpers. */
|
||||
export type HexCase = "lower" | "upper";
|
||||
/** Options that control hexadecimal decoding. */
|
||||
export interface HexDecodeOptions {
|
||||
allowPrefix?: boolean;
|
||||
allowOddLength?: boolean;
|
||||
separators?: readonly string[] | "common" | "none";
|
||||
strict?: boolean;
|
||||
}
|
||||
/** Grouping information for formatted hexadecimal output. */
|
||||
export interface HexGroupFormat {
|
||||
size: number;
|
||||
separator: string;
|
||||
}
|
||||
/** Line wrapping information for formatted hexadecimal output. */
|
||||
export interface HexLineFormat {
|
||||
bytesPerLine: number;
|
||||
separator?: "\n" | "\r\n";
|
||||
}
|
||||
/** Options that control hexadecimal encoding. */
|
||||
export interface HexEncodeOptions {
|
||||
case?: HexCase;
|
||||
prefix?: "" | "0x";
|
||||
group?: HexGroupFormat;
|
||||
line?: HexLineFormat;
|
||||
}
|
||||
/** Preserved formatting metadata for parsed hexadecimal text. */
|
||||
export interface HexFormat {
|
||||
case: HexCase;
|
||||
prefix: "" | "0x";
|
||||
group?: HexGroupFormat;
|
||||
line?: {
|
||||
bytesPerLine: number;
|
||||
separator: "\n" | "\r\n";
|
||||
};
|
||||
}
|
||||
/** Removes separators and normalizes hexadecimal text. */
|
||||
export declare function normalize(text: string, options?: HexDecodeOptions): string;
|
||||
/** Checks whether a value is normalized hexadecimal text. */
|
||||
export declare function is(text: unknown, options?: HexDecodeOptions): text is string;
|
||||
/** Encodes buffer data as formatted hexadecimal text. */
|
||||
export declare function encode(data: BufferSourceLike, options?: HexEncodeOptions): string;
|
||||
/** Decodes hexadecimal text into bytes. */
|
||||
export declare function decode(text: string, options?: HexDecodeOptions): Uint8Array;
|
||||
/** Parses hexadecimal text into bytes plus detected formatting metadata. */
|
||||
export declare function parse(text: string, options?: HexDecodeOptions): ParsedBytes<HexFormat>;
|
||||
/** Formats bytes using preserved hexadecimal formatting metadata. */
|
||||
export declare function format(data: BufferSourceLike, value: HexFormat): string;
|
||||
/** Reusable hexadecimal formatting presets. */
|
||||
export declare const formats: {
|
||||
readonly compact: Readonly<HexEncodeOptions>;
|
||||
readonly upper: Readonly<HexEncodeOptions>;
|
||||
readonly colon: Readonly<HexEncodeOptions>;
|
||||
readonly colonUpper: Readonly<HexEncodeOptions>;
|
||||
readonly groupsOf4: Readonly<HexEncodeOptions>;
|
||||
readonly prefixed: Readonly<HexEncodeOptions>;
|
||||
};
|
||||
/** Hexadecimal codec helpers. */
|
||||
export declare const hex: {
|
||||
readonly encode: typeof encode;
|
||||
readonly decode: typeof decode;
|
||||
readonly format: typeof format;
|
||||
readonly formats: {
|
||||
readonly compact: Readonly<HexEncodeOptions>;
|
||||
readonly upper: Readonly<HexEncodeOptions>;
|
||||
readonly colon: Readonly<HexEncodeOptions>;
|
||||
readonly colonUpper: Readonly<HexEncodeOptions>;
|
||||
readonly groupsOf4: Readonly<HexEncodeOptions>;
|
||||
readonly prefixed: Readonly<HexEncodeOptions>;
|
||||
};
|
||||
readonly is: typeof is;
|
||||
readonly normalize: typeof normalize;
|
||||
readonly parse: typeof parse;
|
||||
};
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
/** Barrel export for binary and text encoding helpers. */
|
||||
export * as binary from "./binary.js";
|
||||
export * as hex from "./hex.js";
|
||||
export * as utf8 from "./utf8.js";
|
||||
export * as utf16 from "./utf16.js";
|
||||
export * as base64 from "./base64.js";
|
||||
export * as base64url from "./base64url.js";
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
import type { BufferSourceLike } from "../bytes/index.js";
|
||||
/** Options that control UTF-16 endianness. */
|
||||
export interface Utf16Options {
|
||||
littleEndian?: boolean;
|
||||
}
|
||||
/** Encodes UTF-16 text into bytes. */
|
||||
export declare function encode(text: string, options?: Utf16Options): Uint8Array;
|
||||
/** Decodes UTF-16 bytes into text. */
|
||||
export declare function decode(data: BufferSourceLike, options?: Utf16Options): string;
|
||||
/** UTF-16 codec helpers. */
|
||||
export declare const utf16: {
|
||||
readonly encode: typeof encode;
|
||||
readonly decode: typeof decode;
|
||||
};
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
import type { BufferSourceLike } from "../bytes/index.js";
|
||||
/** Encodes UTF-8 text into bytes. */
|
||||
export declare function encode(text: string): Uint8Array;
|
||||
/** Decodes UTF-8 bytes into text. */
|
||||
export declare function decode(data: BufferSourceLike): string;
|
||||
/** UTF-8 codec helpers. */
|
||||
export declare const utf8: {
|
||||
readonly encode: typeof encode;
|
||||
readonly decode: typeof decode;
|
||||
};
|
||||
-7
@@ -1,7 +0,0 @@
|
||||
/** Public entry point for bytes, encodings, PEM helpers, converters, and legacy compatibility APIs. */
|
||||
export * from "./bytes/index.js";
|
||||
export * as bytes from "./bytes/index.js";
|
||||
export * from "./encoding/index.js";
|
||||
export * from "./pem/index.js";
|
||||
export * from "./converters/index.js";
|
||||
export * from "./legacy/index.js";
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
import type { ArrayBufferViewConstructor, ArrayBufferViewLike, BufferSourceLike, ViewConstructor } from "../bytes/index.js";
|
||||
/** Legacy static helpers for buffer source conversion.
|
||||
* @deprecated Use functions from `@peculiar/utils/bytes` instead.
|
||||
*/
|
||||
export declare class BufferSourceConverter {
|
||||
/** Checks whether a value is an ArrayBuffer. */
|
||||
static isArrayBuffer(data: unknown): data is ArrayBuffer;
|
||||
/** Converts buffer data to an ArrayBuffer. */
|
||||
static toArrayBuffer(data: BufferSourceLike): ArrayBuffer;
|
||||
/** Converts buffer data to a Uint8Array view. */
|
||||
static toUint8Array(data: BufferSourceLike): Uint8Array;
|
||||
/** Converts buffer data into the requested view type. */
|
||||
static toView<T extends ArrayBufferViewLike>(data: BufferSourceLike, type: ViewConstructor<T>): T;
|
||||
/** Checks whether a value can be treated as a buffer source. */
|
||||
static isBufferSource(data: unknown): data is BufferSourceLike;
|
||||
/** Checks whether a value is an ArrayBufferView. */
|
||||
static isArrayBufferView(data: unknown): data is ArrayBufferViewLike;
|
||||
/** Compares two buffer sources for byte equality. */
|
||||
static isEqual(a: BufferSourceLike, b: BufferSourceLike): boolean;
|
||||
/** Concatenates buffer sources into an ArrayBuffer or a typed view. */
|
||||
static concat(...buffers: BufferSourceLike[]): ArrayBufferLike;
|
||||
static concat(buffers: BufferSourceLike[]): ArrayBufferLike;
|
||||
static concat<T extends ArrayBufferViewLike>(buffers: BufferSourceLike[], type: ArrayBufferViewConstructor<T>): T;
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
import type { BufferSourceLike } from "../bytes/index.js";
|
||||
import { type BufferEncoding } from "../converters/index.js";
|
||||
import type { Utf16Options } from "../encoding/utf16.js";
|
||||
/** Legacy text encodings accepted by the deprecated facade. */
|
||||
export type TextEncoding = "ascii" | "utf8" | "utf16" | "utf16be" | "utf16le" | "usc2";
|
||||
/**
|
||||
* Legacy converter facade that mirrors the historical API surface.
|
||||
* @deprecated Use the camelCase `convert` object or specific encoding modules instead.
|
||||
*/
|
||||
export declare class Convert {
|
||||
/** Default UTF-8 encoding used by the legacy facade. */
|
||||
static DEFAULT_UTF8_ENCODING: TextEncoding;
|
||||
/** Checks whether the input is hexadecimal text. */
|
||||
static isHex(data: unknown): data is string;
|
||||
/** Checks whether the input is Base64 text. */
|
||||
static isBase64(data: unknown): data is string;
|
||||
/** Checks whether the input is Base64Url text. */
|
||||
static isBase64Url(data: unknown): data is string;
|
||||
/** Converts buffer data to text. */
|
||||
static ToString(buffer: BufferSourceLike, enc?: BufferEncoding): string;
|
||||
/** Converts text to bytes. */
|
||||
static FromString(str: string, enc?: BufferEncoding): ArrayBufferLike;
|
||||
/** Encodes bytes as Base64 text. */
|
||||
static ToBase64(buffer: BufferSourceLike): string;
|
||||
/** Decodes Base64 text into bytes. */
|
||||
static FromBase64(base64: string): ArrayBufferLike;
|
||||
/** Decodes Base64Url text into bytes. */
|
||||
static FromBase64Url(base64url: string): ArrayBufferLike;
|
||||
/** Encodes bytes as Base64Url text. */
|
||||
static ToBase64Url(data: BufferSourceLike): string;
|
||||
/** Converts UTF-8 or UTF-16 text to bytes. */
|
||||
static FromUtf8String(text: string, encoding?: TextEncoding): ArrayBufferLike;
|
||||
/** Converts bytes to UTF-8 or UTF-16 text. */
|
||||
static ToUtf8String(buffer: BufferSourceLike, encoding?: TextEncoding): string;
|
||||
/** Decodes binary text into bytes. */
|
||||
static FromBinary(text: string): ArrayBufferLike;
|
||||
/** Encodes bytes as binary text. */
|
||||
static ToBinary(buffer: BufferSourceLike): string;
|
||||
/** Encodes bytes as hexadecimal text. */
|
||||
static ToHex(buffer: BufferSourceLike): string;
|
||||
/** Decodes hexadecimal text into bytes. */
|
||||
static FromHex(hexString: string): ArrayBufferLike;
|
||||
/** Converts UTF-16 bytes into text. */
|
||||
static ToUtf16String(buffer: BufferSourceLike, littleEndian?: boolean): string;
|
||||
/** Converts UTF-16 text into bytes. */
|
||||
static FromUtf16String(text: string, littleEndian?: boolean): ArrayBufferLike;
|
||||
protected static Base64Padding(base64: string): string;
|
||||
/** Normalizes whitespace in Base64-style text. */
|
||||
static formatString(data: string): string;
|
||||
}
|
||||
/** Legacy text encoding aliases re-exported for compatibility. */
|
||||
export type { BufferEncoding, Utf16Options };
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
import type { BufferSourceLike } from "../bytes/index.js";
|
||||
/**
|
||||
* Assigns own properties from source objects into the target object.
|
||||
* @deprecated Prefer object spread or Object.assign.
|
||||
*/
|
||||
export declare function assign<T extends object>(target: T, ...sources: (Partial<T> | undefined | null)[]): T;
|
||||
/**
|
||||
* Concatenates buffer sources into a single ArrayBuffer.
|
||||
* @deprecated Use `concat` from `@peculiar/utils/bytes` instead.
|
||||
*/
|
||||
export declare function combine(...buf: BufferSourceLike[]): ArrayBufferLike;
|
||||
/**
|
||||
* Compares two buffer sources for equality.
|
||||
* @deprecated Use `equal` from `@peculiar/utils/bytes` instead.
|
||||
*/
|
||||
export declare function isEqual(bytes1: BufferSourceLike, bytes2: BufferSourceLike): boolean;
|
||||
-5
@@ -1,5 +0,0 @@
|
||||
/** Barrel export for the deprecated compatibility layer. */
|
||||
export { BufferSourceConverter } from "./buffer-source-converter.js";
|
||||
export { Convert } from "./convert.js";
|
||||
export type { BufferEncoding, TextEncoding } from "./convert.js";
|
||||
export { assign, combine, isEqual } from "./functions.js";
|
||||
-3
@@ -1,3 +0,0 @@
|
||||
/** Barrel export for PEM helpers, codecs, and related types. */
|
||||
export type { PemBlock, PemCodec, PemDecodeOptions, PemEncodeBlock, PemEncodeOptions, PemFormat } from "./types.js";
|
||||
export { decode, decodeFirst, encode, encodeMany, find, findAll, format, parse, pem, pemConverter } from "./pem.js";
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
import type { BufferSourceLike } from "../bytes/index.js";
|
||||
import type { ParsedBytes, Converter } from "../converters/types.js";
|
||||
import type { PemBlock, PemDecodeOptions, PemEncodeBlock, PemEncodeOptions, PemFormat } from "./types.js";
|
||||
/** Encodes buffer data into a PEM block. */
|
||||
export declare function encode(label: string, data: BufferSourceLike, options?: PemEncodeOptions): string;
|
||||
/** Encodes multiple PEM blocks into one PEM bundle. */
|
||||
export declare function encodeMany(blocks: readonly PemEncodeBlock[], options?: PemEncodeOptions): string;
|
||||
/** Decodes PEM text into the contained blocks. */
|
||||
export declare function decode(text: string, options?: PemDecodeOptions): PemBlock[];
|
||||
/** Finds the first PEM block with the requested label. */
|
||||
export declare function find(text: string, label: string): PemBlock | undefined;
|
||||
/** Finds all PEM blocks with the requested label. */
|
||||
export declare function findAll(text: string, label: string): PemBlock[];
|
||||
/** Decodes the first matching PEM block. */
|
||||
export declare function decodeFirst(text: string, label?: string): Uint8Array;
|
||||
/** Parses the first matching PEM block and preserves its formatting metadata. */
|
||||
export declare function parse(text: string, options?: PemDecodeOptions): ParsedBytes<PemFormat>;
|
||||
/** Formats bytes with preserved PEM metadata. */
|
||||
export declare function format(data: BufferSourceLike, value: PemFormat): string;
|
||||
/** PEM codec helpers. */
|
||||
export declare const pem: {
|
||||
readonly decode: typeof decode;
|
||||
readonly decodeFirst: typeof decodeFirst;
|
||||
readonly encode: typeof encode;
|
||||
readonly encodeMany: typeof encodeMany;
|
||||
readonly find: typeof find;
|
||||
readonly findAll: typeof findAll;
|
||||
readonly format: typeof format;
|
||||
readonly parse: typeof parse;
|
||||
};
|
||||
/** Converter wrapper for PEM text. */
|
||||
export declare const pemConverter: Converter<PemEncodeOptions & {
|
||||
label: string;
|
||||
}, PemDecodeOptions, PemFormat>;
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
import type { BufferSourceLike } from "../bytes/index.js";
|
||||
import type { ParsedBytes } from "../converters/types.js";
|
||||
/** Represents a decoded PEM block with label, data, and optional headers. */
|
||||
export interface PemBlock {
|
||||
readonly label: string;
|
||||
readonly data: Uint8Array;
|
||||
readonly headers?: Readonly<Record<string, string>>;
|
||||
}
|
||||
/** Options that control PEM encoding. */
|
||||
export interface PemEncodeOptions {
|
||||
lineLength?: number;
|
||||
newline?: "\n" | "\r\n";
|
||||
headers?: Readonly<Record<string, string>>;
|
||||
}
|
||||
/** Options that control PEM decoding. */
|
||||
export interface PemDecodeOptions {
|
||||
label?: string;
|
||||
strict?: boolean;
|
||||
}
|
||||
/** Format metadata that can be reused to re-encode PEM text. */
|
||||
export interface PemFormat extends PemEncodeOptions {
|
||||
readonly label: string;
|
||||
}
|
||||
/** Input block used by multi-block PEM encoding helpers. */
|
||||
export interface PemEncodeBlock {
|
||||
readonly label: string;
|
||||
readonly data: BufferSourceLike;
|
||||
readonly headers?: Readonly<Record<string, string>>;
|
||||
}
|
||||
/** Encodes and decodes PEM blocks. */
|
||||
export interface PemCodec {
|
||||
/** Encodes a buffer source into a PEM block. */
|
||||
encode(label: string, data: BufferSourceLike, options?: PemEncodeOptions): string;
|
||||
/** Encodes multiple PEM blocks into a single string. */
|
||||
encodeMany(blocks: readonly PemEncodeBlock[], options?: PemEncodeOptions): string;
|
||||
/** Decodes PEM text into blocks. */
|
||||
decode(text: string, options?: PemDecodeOptions): PemBlock[];
|
||||
/** Decodes the first matching PEM block. */
|
||||
decodeFirst(text: string, label?: string): Uint8Array;
|
||||
/** Finds the first PEM block with the requested label. */
|
||||
find(text: string, label: string): PemBlock | undefined;
|
||||
/** Finds all PEM blocks with the requested label. */
|
||||
findAll(text: string, label: string): PemBlock[];
|
||||
/** Parses the first matching PEM block and preserves the detected formatting. */
|
||||
parse(text: string, options?: PemDecodeOptions): ParsedBytes<PemFormat>;
|
||||
/** Formats bytes with previously detected PEM metadata. */
|
||||
format(data: BufferSourceLike, format: PemFormat): string;
|
||||
}
|
||||
-111
@@ -1,111 +0,0 @@
|
||||
{
|
||||
"name": "@peculiar/utils",
|
||||
"version": "2.0.3",
|
||||
"description": "Modern byte, encoding, converter registry, and PEM utilities for TypeScript projects.",
|
||||
"type": "module",
|
||||
"main": "./build/cjs/index.js",
|
||||
"module": "./build/esm/index.js",
|
||||
"types": "./build/types/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./build/types/index.d.ts",
|
||||
"import": "./build/esm/index.js",
|
||||
"require": "./build/cjs/index.js"
|
||||
},
|
||||
"./bytes": {
|
||||
"types": "./build/types/bytes/index.d.ts",
|
||||
"import": "./build/esm/bytes/index.js",
|
||||
"require": "./build/cjs/bytes/index.js"
|
||||
},
|
||||
"./encoding": {
|
||||
"types": "./build/types/encoding/index.d.ts",
|
||||
"import": "./build/esm/encoding/index.js",
|
||||
"require": "./build/cjs/encoding/index.js"
|
||||
},
|
||||
"./encoding/*": {
|
||||
"types": "./build/types/encoding/*.d.ts",
|
||||
"import": "./build/esm/encoding/*.js",
|
||||
"require": "./build/cjs/encoding/*.js"
|
||||
},
|
||||
"./converters": {
|
||||
"types": "./build/types/converters/index.d.ts",
|
||||
"import": "./build/esm/converters/index.js",
|
||||
"require": "./build/cjs/converters/index.js"
|
||||
},
|
||||
"./pem": {
|
||||
"types": "./build/types/pem/index.d.ts",
|
||||
"import": "./build/esm/pem/index.js",
|
||||
"require": "./build/cjs/pem/index.js"
|
||||
},
|
||||
"./legacy": {
|
||||
"types": "./build/types/legacy/index.d.ts",
|
||||
"import": "./build/esm/legacy/index.js",
|
||||
"require": "./build/cjs/legacy/index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"build/cjs/**/*.js",
|
||||
"build/cjs/package.json",
|
||||
"build/esm/**/*.js",
|
||||
"build/types/**/*.d.ts",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "vitest run",
|
||||
"coverage": "vitest run --coverage",
|
||||
"clear": "rimraf build",
|
||||
"rebuild": "npm run clear && npm run build",
|
||||
"build": "node scripts/prune-legacy-build-outputs.mjs && tsc -p tsconfig.build.types.json && tsc -p tsconfig.build.esm.json && tsc -p tsconfig.build.cjs.json && node scripts/write-cjs-package-json.mjs",
|
||||
"prepack": "npm run build",
|
||||
"publish:manual": "npm run check && npm run build && npm publish --ignore-scripts",
|
||||
"lint:check": "eslint . --fix-dry-run",
|
||||
"check": "npm run lint:check && tsc --noEmit && npm test",
|
||||
"lint": "eslint .",
|
||||
"lint:fix": "eslint . --fix"
|
||||
},
|
||||
"keywords": [
|
||||
"typescript",
|
||||
"utils",
|
||||
"buffer",
|
||||
"bytes",
|
||||
"convert",
|
||||
"encoding",
|
||||
"base64",
|
||||
"base64url",
|
||||
"hex",
|
||||
"utf8",
|
||||
"utf16",
|
||||
"pem",
|
||||
"pki",
|
||||
"peculiar"
|
||||
],
|
||||
"author": "PeculiarVentures",
|
||||
"contributors": [
|
||||
"Miroshin Stepan<microshine@mail.ru>"
|
||||
],
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/PeculiarVentures/pvtsutils"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/PeculiarVentures/pvtsutils/issues"
|
||||
},
|
||||
"homepage": "https://github.com/PeculiarVentures/pvtsutils#readme",
|
||||
"dependencies": {
|
||||
"tslib": "^2.8.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@peculiar/eslint-config-base": "^0.2.9",
|
||||
"@types/node": "^25.6.0",
|
||||
"@vitest/coverage-v8": "^4.1.5",
|
||||
"rimraf": "^6.1.3",
|
||||
"typescript": "^6.0.3",
|
||||
"vitest": "^4.1.5"
|
||||
}
|
||||
}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019-2026 Peculiar Ventures, LLC
|
||||
|
||||
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.
|
||||
-97
@@ -1,97 +0,0 @@
|
||||
<h1 align="center">
|
||||
@peculiar/webcrypto
|
||||
</h1>
|
||||
|
||||
<div align="center">
|
||||
|
||||

|
||||

|
||||
[](https://www.npmjs.com/package/@peculiar/webcrypto)
|
||||

|
||||
[](https://www.npmjs.com/package/@peculiar/webcrypto)
|
||||
|
||||
</div>
|
||||
|
||||
We wanted to be able to write Javascript that used crypto on both the client and the server but we did not want to rely on Javascript implementations of crypto. The only native cryptography available in browser is [Web Crypto](http://caniuse.com/#search=cryptography), this resulted in us creating a `@peculiar/webcrypto`.
|
||||
|
||||
## Table Of Contents
|
||||
|
||||
* [WARNING](#warning)
|
||||
* [Installing](#installing)
|
||||
* [Using](#using)
|
||||
* [Examples](#examples)
|
||||
* [Bug Reporting](#bug-reporting)
|
||||
* [Related](#related)
|
||||
|
||||
## WARNING
|
||||
|
||||
**At this time this solution should be considered suitable for research and experimentation, further code and security review is needed before utilization in a production application.**
|
||||
|
||||
**Module is based on the Node.js crypto API. It requires Node v14.18.0 or higher.**
|
||||
|
||||
## Installing
|
||||
|
||||
```
|
||||
npm install @peculiar/webcrypto
|
||||
```
|
||||
|
||||
## Supported algorithms
|
||||
|
||||
| Algorithm name | generateKey | digest | export/import | sign/verify | encrypt/decrypt | wrapKey/unwrapKey | derive |
|
||||
|-------------------|-------------|---------|---------------|-------------|-----------------|-------------------|---------|
|
||||
| SHA-1 | | X | | | | | |
|
||||
| SHA-256 | | X | | | | | |
|
||||
| SHA-384 | | X | | | | | |
|
||||
| SHA-512 | | X | | | | | |
|
||||
| HMAC | X | | X | X | | | |
|
||||
| RSASSA-PKCS1-v1_5 | X | | X | X | | | |
|
||||
| RSAES-PKCS1-v1_5<sup>2</sup>| X | | X | | X | X | |
|
||||
| RSA-PSS | X | | X | X | | | |
|
||||
| RSA-OAEP | X | | X | | X | X | |
|
||||
| AES-CMAC | X | | X | X | | | |
|
||||
| AES-CBC | X | | X | | X | X | |
|
||||
| AES-CTR | X | | X | | X | X | |
|
||||
| AES-ECB | X | | X | | X | X | |
|
||||
| AES-GCM | X | | X | | X | X | |
|
||||
| AES-KW | X | | X | | | X | |
|
||||
| ECDSA<sup>1</sup> | X | | X | X | | | |
|
||||
| ECDH<sup>1</sup> | X | | X | | | | X |
|
||||
| EdDSA<sup>2,3</sup> | X | | X | X | | | |
|
||||
| ECDH-ES<sup>2,4</sup> | X | | X | | | | X |
|
||||
| HKDF | | | X | | | | X |
|
||||
| PBKDF2 | | | X | | | | X |
|
||||
| DES-CBC<sup>2</sup>| X | | X | | X | X | |
|
||||
| DES-EDE3-CBC<sup>2</sup>| X | | X | | X | X | |
|
||||
| shake128<sup>2</sup>| | X | | | | | |
|
||||
| shake256<sup>2</sup>| | X | | | | | |
|
||||
|
||||
<sup>1</sup> Mechanism supports extended list of named curves `P-256`, `P-384`, `P-521`, `K-256`,
|
||||
`brainpoolP160r1`, `brainpoolP160t1`, `brainpoolP192r1`, `brainpoolP192t1`, `brainpoolP224r1`, `brainpoolP224t1`, `brainpoolP256r1`, `brainpoolP256t1`, `brainpoolP320r1`, `brainpoolP320t1`, `brainpoolP384r1`, `brainpoolP384t1`, `brainpoolP512r1`, and `brainpoolP512t1`
|
||||
|
||||
<sup>2</sup> Mechanism is not defined by the WebCrypto specifications. Use of mechanism in a safe way is hard, it was added for the purpose of enabling interoperability with an existing system. We recommend against its use unless needed for interoperability.
|
||||
|
||||
<sup>3</sup> Mechanism supports extended list of named curves `Ed25519`, and `Ed448`
|
||||
|
||||
<sup>4</sup> Mechanism supports extended list of named curves `X25519`, and `X448`
|
||||
|
||||
## Using
|
||||
|
||||
```javascript
|
||||
const { Crypto } = require("@peculiar/webcrypto");
|
||||
|
||||
const crypto = new Crypto();
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
See [WebCrypto Docs](https://github.com/PeculiarVentures/webcrypto-docs/blob/master/README.md) for examples
|
||||
|
||||
## Bug Reporting
|
||||
|
||||
Please report bugs either as pull requests or as issues in the issue tracker. `@peculiar/webcrypto` has a full disclosure vulnerability policy. Please do NOT attempt to report any security vulnerability in this code privately to anybody.
|
||||
|
||||
## Related
|
||||
|
||||
* [node-webcrypto-ossl](https://github.com/PeculiarVentures/node-webcrypto-ossl)
|
||||
* [node-webcrypto-p11](https://github.com/PeculiarVentures/node-webcrypto-p11)
|
||||
* [webcrypto-liner](https://github.com/PeculiarVentures/webcrypto-liner)
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
export declare class Crypto implements globalThis.Crypto {
|
||||
public subtle: SubtleCrypto;
|
||||
public getRandomValues<T extends ArrayBufferView | null>(array: T): T;
|
||||
randomUUID(): `${string}-${string}-${string}-${string}-${string}`;
|
||||
}
|
||||
|
||||
export declare class CryptoKey implements globalThis.CryptoKey {
|
||||
public algorithm: KeyAlgorithm;
|
||||
public extractable: boolean;
|
||||
public type: KeyType;
|
||||
public usages: KeyUsage[];
|
||||
}
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
{
|
||||
"name": "@peculiar/webcrypto",
|
||||
"version": "1.7.1",
|
||||
"description": "A WebCrypto Polyfill for NodeJS",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/PeculiarVentures/webcrypto"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./index.d.ts",
|
||||
"import": "./build/webcrypto.es.js",
|
||||
"require": "./build/webcrypto.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"build/**/*.{ts,js}",
|
||||
"index.d.ts",
|
||||
"README.md",
|
||||
"LICENSE.md"
|
||||
],
|
||||
"main": "build/webcrypto.js",
|
||||
"module": "build/webcrypto.es.js",
|
||||
"react-native": "build/webcrypto.es.js",
|
||||
"types": "index.d.ts",
|
||||
"scripts": {
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"coverage": "vitest --coverage",
|
||||
"build": "rollup -c",
|
||||
"clear": "rimraf build/*",
|
||||
"rebuild": "npm run clear && npm run build",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"lint": "eslint",
|
||||
"lint:fix": "eslint --fix"
|
||||
},
|
||||
"keywords": [
|
||||
"webcrypto",
|
||||
"crypto",
|
||||
"sha",
|
||||
"rsa",
|
||||
"ec",
|
||||
"aes",
|
||||
"des",
|
||||
"hmac",
|
||||
"pbkdf2",
|
||||
"eddsa",
|
||||
"x25519",
|
||||
"ed25519",
|
||||
"x448",
|
||||
"ed448",
|
||||
"shake128",
|
||||
"shake256"
|
||||
],
|
||||
"author": "PeculiarVentures",
|
||||
"contributors": [
|
||||
"Miroshin Stepan<microshine@mail.ru>"
|
||||
],
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/PeculiarVentures/webcrypto/issues"
|
||||
},
|
||||
"homepage": "https://github.com/PeculiarVentures/webcrypto#readme",
|
||||
"devDependencies": {
|
||||
"@peculiar/eslint-config-base": "^0.2.9",
|
||||
"@peculiar/webcrypto-test": "^2.0.0",
|
||||
"@rollup/plugin-typescript": "^12.3.0",
|
||||
"@types/node": "^25.6.0",
|
||||
"@vitest/coverage-v8": "^4.1.5",
|
||||
"rimraf": "^6.1.3",
|
||||
"rollup": "^4.60.2",
|
||||
"typescript": "^6.0.3",
|
||||
"vitest": "^4.1.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"@peculiar/asn1-schema": "^2.7.0",
|
||||
"@peculiar/json-schema": "^1.1.12",
|
||||
"@peculiar/utils": "^2.0.2",
|
||||
"tslib": "^2.8.1",
|
||||
"webcrypto-core": "^1.9.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.18.0"
|
||||
}
|
||||
}
|
||||
-232
@@ -1,232 +0,0 @@
|
||||
/// <reference types="node" />
|
||||
/// <reference lib="es2018" />
|
||||
/// <reference lib="dom" />
|
||||
import { Class, Falsy, TypedArray, ObservableLike, Primitive } from './types';
|
||||
declare const objectTypeNames: readonly ["Function", "Generator", "AsyncGenerator", "GeneratorFunction", "AsyncGeneratorFunction", "AsyncFunction", "Observable", "Array", "Buffer", "Blob", "Object", "RegExp", "Date", "Error", "Map", "Set", "WeakMap", "WeakSet", "ArrayBuffer", "SharedArrayBuffer", "DataView", "Promise", "URL", "FormData", "URLSearchParams", "HTMLElement", ...("Int8Array" | "Uint8Array" | "Uint8ClampedArray" | "Int16Array" | "Uint16Array" | "Int32Array" | "Uint32Array" | "Float32Array" | "Float64Array" | "BigInt64Array" | "BigUint64Array")[]];
|
||||
declare type ObjectTypeName = typeof objectTypeNames[number];
|
||||
declare const primitiveTypeNames: readonly ["null", "undefined", "string", "number", "bigint", "boolean", "symbol"];
|
||||
declare type PrimitiveTypeName = typeof primitiveTypeNames[number];
|
||||
export declare type TypeName = ObjectTypeName | PrimitiveTypeName;
|
||||
declare function is(value: unknown): TypeName;
|
||||
declare namespace is {
|
||||
var undefined: (value: unknown) => value is undefined;
|
||||
var string: (value: unknown) => value is string;
|
||||
var number: (value: unknown) => value is number;
|
||||
var bigint: (value: unknown) => value is bigint;
|
||||
var function_: (value: unknown) => value is Function;
|
||||
var null_: (value: unknown) => value is null;
|
||||
var class_: (value: unknown) => value is Class<unknown, any[]>;
|
||||
var boolean: (value: unknown) => value is boolean;
|
||||
var symbol: (value: unknown) => value is symbol;
|
||||
var numericString: (value: unknown) => value is string;
|
||||
var array: <T = unknown>(value: unknown, assertion?: ((value: T) => value is T) | undefined) => value is T[];
|
||||
var buffer: (value: unknown) => value is Buffer;
|
||||
var blob: (value: unknown) => value is Blob;
|
||||
var nullOrUndefined: (value: unknown) => value is null | undefined;
|
||||
var object: (value: unknown) => value is object;
|
||||
var iterable: <T = unknown>(value: unknown) => value is Iterable<T>;
|
||||
var asyncIterable: <T = unknown>(value: unknown) => value is AsyncIterable<T>;
|
||||
var generator: (value: unknown) => value is Generator<unknown, any, unknown>;
|
||||
var asyncGenerator: (value: unknown) => value is AsyncGenerator<unknown, any, unknown>;
|
||||
var nativePromise: <T = unknown>(value: unknown) => value is Promise<T>;
|
||||
var promise: <T = unknown>(value: unknown) => value is Promise<T>;
|
||||
var generatorFunction: (value: unknown) => value is GeneratorFunction;
|
||||
var asyncGeneratorFunction: (value: unknown) => value is (...args: any[]) => Promise<unknown>;
|
||||
var asyncFunction: <T = unknown>(value: unknown) => value is (...args: any[]) => Promise<T>;
|
||||
var boundFunction: (value: unknown) => value is Function;
|
||||
var regExp: (value: unknown) => value is RegExp;
|
||||
var date: (value: unknown) => value is Date;
|
||||
var error: (value: unknown) => value is Error;
|
||||
var map: <Key = unknown, Value = unknown>(value: unknown) => value is Map<Key, Value>;
|
||||
var set: <T = unknown>(value: unknown) => value is Set<T>;
|
||||
var weakMap: <Key extends object = object, Value = unknown>(value: unknown) => value is WeakMap<Key, Value>;
|
||||
var weakSet: (value: unknown) => value is WeakSet<object>;
|
||||
var int8Array: (value: unknown) => value is Int8Array;
|
||||
var uint8Array: (value: unknown) => value is Uint8Array;
|
||||
var uint8ClampedArray: (value: unknown) => value is Uint8ClampedArray;
|
||||
var int16Array: (value: unknown) => value is Int16Array;
|
||||
var uint16Array: (value: unknown) => value is Uint16Array;
|
||||
var int32Array: (value: unknown) => value is Int32Array;
|
||||
var uint32Array: (value: unknown) => value is Uint32Array;
|
||||
var float32Array: (value: unknown) => value is Float32Array;
|
||||
var float64Array: (value: unknown) => value is Float64Array;
|
||||
var bigInt64Array: (value: unknown) => value is BigInt64Array;
|
||||
var bigUint64Array: (value: unknown) => value is BigUint64Array;
|
||||
var arrayBuffer: (value: unknown) => value is ArrayBuffer;
|
||||
var sharedArrayBuffer: (value: unknown) => value is SharedArrayBuffer;
|
||||
var dataView: (value: unknown) => value is DataView;
|
||||
var enumCase: <T = unknown>(value: unknown, targetEnum: T) => boolean;
|
||||
var directInstanceOf: <T>(instance: unknown, class_: Class<T, any[]>) => instance is T;
|
||||
var urlInstance: (value: unknown) => value is URL;
|
||||
var urlString: (value: unknown) => value is string;
|
||||
var truthy: <T>(value: false | "" | 0 | 0n | T | null | undefined) => value is T;
|
||||
var falsy: <T>(value: false | "" | 0 | 0n | T | null | undefined) => value is Falsy;
|
||||
var nan: (value: unknown) => boolean;
|
||||
var primitive: (value: unknown) => value is Primitive;
|
||||
var integer: (value: unknown) => value is number;
|
||||
var safeInteger: (value: unknown) => value is number;
|
||||
var plainObject: <Value = unknown>(value: unknown) => value is Record<string | number | symbol, Value>;
|
||||
var typedArray: (value: unknown) => value is TypedArray;
|
||||
var arrayLike: <T = unknown>(value: unknown) => value is ArrayLike<T>;
|
||||
var inRange: (value: number, range: number | number[]) => value is number;
|
||||
var domElement: (value: unknown) => value is HTMLElement;
|
||||
var observable: (value: unknown) => value is ObservableLike;
|
||||
var nodeStream: (value: unknown) => value is NodeStream;
|
||||
var infinite: (value: unknown) => value is number;
|
||||
var evenInteger: (value: number) => value is number;
|
||||
var oddInteger: (value: number) => value is number;
|
||||
var emptyArray: (value: unknown) => value is never[];
|
||||
var nonEmptyArray: (value: unknown) => value is unknown[];
|
||||
var emptyString: (value: unknown) => value is "";
|
||||
var emptyStringOrWhitespace: (value: unknown) => value is string;
|
||||
var nonEmptyString: (value: unknown) => value is string;
|
||||
var nonEmptyStringAndNotWhitespace: (value: unknown) => value is string;
|
||||
var emptyObject: <Key extends string | number | symbol = string>(value: unknown) => value is Record<Key, never>;
|
||||
var nonEmptyObject: <Key extends string | number | symbol = string, Value = unknown>(value: unknown) => value is Record<Key, Value>;
|
||||
var emptySet: (value: unknown) => value is Set<never>;
|
||||
var nonEmptySet: <T = unknown>(value: unknown) => value is Set<T>;
|
||||
var emptyMap: (value: unknown) => value is Map<never, never>;
|
||||
var nonEmptyMap: <Key = unknown, Value = unknown>(value: unknown) => value is Map<Key, Value>;
|
||||
var propertyKey: (value: unknown) => value is string | number | symbol;
|
||||
var formData: (value: unknown) => value is FormData;
|
||||
var urlSearchParams: (value: unknown) => value is URLSearchParams;
|
||||
var any: (predicate: Predicate | Predicate[], ...values: unknown[]) => boolean;
|
||||
var all: (predicate: Predicate, ...values: unknown[]) => boolean;
|
||||
}
|
||||
export interface ArrayLike<T> {
|
||||
readonly [index: number]: T;
|
||||
readonly length: number;
|
||||
}
|
||||
export interface NodeStream extends NodeJS.EventEmitter {
|
||||
pipe<T extends NodeJS.WritableStream>(destination: T, options?: {
|
||||
end?: boolean;
|
||||
}): T;
|
||||
}
|
||||
export declare type Predicate = (value: unknown) => boolean;
|
||||
export declare const enum AssertionTypeDescription {
|
||||
class_ = "Class",
|
||||
numericString = "string with a number",
|
||||
nullOrUndefined = "null or undefined",
|
||||
iterable = "Iterable",
|
||||
asyncIterable = "AsyncIterable",
|
||||
nativePromise = "native Promise",
|
||||
urlString = "string with a URL",
|
||||
truthy = "truthy",
|
||||
falsy = "falsy",
|
||||
nan = "NaN",
|
||||
primitive = "primitive",
|
||||
integer = "integer",
|
||||
safeInteger = "integer",
|
||||
plainObject = "plain object",
|
||||
arrayLike = "array-like",
|
||||
typedArray = "TypedArray",
|
||||
domElement = "HTMLElement",
|
||||
nodeStream = "Node.js Stream",
|
||||
infinite = "infinite number",
|
||||
emptyArray = "empty array",
|
||||
nonEmptyArray = "non-empty array",
|
||||
emptyString = "empty string",
|
||||
emptyStringOrWhitespace = "empty string or whitespace",
|
||||
nonEmptyString = "non-empty string",
|
||||
nonEmptyStringAndNotWhitespace = "non-empty string and not whitespace",
|
||||
emptyObject = "empty object",
|
||||
nonEmptyObject = "non-empty object",
|
||||
emptySet = "empty set",
|
||||
nonEmptySet = "non-empty set",
|
||||
emptyMap = "empty map",
|
||||
nonEmptyMap = "non-empty map",
|
||||
evenInteger = "even integer",
|
||||
oddInteger = "odd integer",
|
||||
directInstanceOf = "T",
|
||||
inRange = "in range",
|
||||
any = "predicate returns truthy for any value",
|
||||
all = "predicate returns truthy for all values"
|
||||
}
|
||||
interface Assert {
|
||||
undefined: (value: unknown) => asserts value is undefined;
|
||||
string: (value: unknown) => asserts value is string;
|
||||
number: (value: unknown) => asserts value is number;
|
||||
bigint: (value: unknown) => asserts value is bigint;
|
||||
function_: (value: unknown) => asserts value is Function;
|
||||
null_: (value: unknown) => asserts value is null;
|
||||
class_: (value: unknown) => asserts value is Class;
|
||||
boolean: (value: unknown) => asserts value is boolean;
|
||||
symbol: (value: unknown) => asserts value is symbol;
|
||||
numericString: (value: unknown) => asserts value is string;
|
||||
array: <T = unknown>(value: unknown, assertion?: (element: unknown) => asserts element is T) => asserts value is T[];
|
||||
buffer: (value: unknown) => asserts value is Buffer;
|
||||
blob: (value: unknown) => asserts value is Blob;
|
||||
nullOrUndefined: (value: unknown) => asserts value is null | undefined;
|
||||
object: <Key extends keyof any = string, Value = unknown>(value: unknown) => asserts value is Record<Key, Value>;
|
||||
iterable: <T = unknown>(value: unknown) => asserts value is Iterable<T>;
|
||||
asyncIterable: <T = unknown>(value: unknown) => asserts value is AsyncIterable<T>;
|
||||
generator: (value: unknown) => asserts value is Generator;
|
||||
asyncGenerator: (value: unknown) => asserts value is AsyncGenerator;
|
||||
nativePromise: <T = unknown>(value: unknown) => asserts value is Promise<T>;
|
||||
promise: <T = unknown>(value: unknown) => asserts value is Promise<T>;
|
||||
generatorFunction: (value: unknown) => asserts value is GeneratorFunction;
|
||||
asyncGeneratorFunction: (value: unknown) => asserts value is AsyncGeneratorFunction;
|
||||
asyncFunction: (value: unknown) => asserts value is Function;
|
||||
boundFunction: (value: unknown) => asserts value is Function;
|
||||
regExp: (value: unknown) => asserts value is RegExp;
|
||||
date: (value: unknown) => asserts value is Date;
|
||||
error: (value: unknown) => asserts value is Error;
|
||||
map: <Key = unknown, Value = unknown>(value: unknown) => asserts value is Map<Key, Value>;
|
||||
set: <T = unknown>(value: unknown) => asserts value is Set<T>;
|
||||
weakMap: <Key extends object = object, Value = unknown>(value: unknown) => asserts value is WeakMap<Key, Value>;
|
||||
weakSet: <T extends object = object>(value: unknown) => asserts value is WeakSet<T>;
|
||||
int8Array: (value: unknown) => asserts value is Int8Array;
|
||||
uint8Array: (value: unknown) => asserts value is Uint8Array;
|
||||
uint8ClampedArray: (value: unknown) => asserts value is Uint8ClampedArray;
|
||||
int16Array: (value: unknown) => asserts value is Int16Array;
|
||||
uint16Array: (value: unknown) => asserts value is Uint16Array;
|
||||
int32Array: (value: unknown) => asserts value is Int32Array;
|
||||
uint32Array: (value: unknown) => asserts value is Uint32Array;
|
||||
float32Array: (value: unknown) => asserts value is Float32Array;
|
||||
float64Array: (value: unknown) => asserts value is Float64Array;
|
||||
bigInt64Array: (value: unknown) => asserts value is BigInt64Array;
|
||||
bigUint64Array: (value: unknown) => asserts value is BigUint64Array;
|
||||
arrayBuffer: (value: unknown) => asserts value is ArrayBuffer;
|
||||
sharedArrayBuffer: (value: unknown) => asserts value is SharedArrayBuffer;
|
||||
dataView: (value: unknown) => asserts value is DataView;
|
||||
enumCase: <T = unknown>(value: unknown, targetEnum: T) => asserts value is T[keyof T];
|
||||
urlInstance: (value: unknown) => asserts value is URL;
|
||||
urlString: (value: unknown) => asserts value is string;
|
||||
truthy: (value: unknown) => asserts value is unknown;
|
||||
falsy: (value: unknown) => asserts value is unknown;
|
||||
nan: (value: unknown) => asserts value is unknown;
|
||||
primitive: (value: unknown) => asserts value is Primitive;
|
||||
integer: (value: unknown) => asserts value is number;
|
||||
safeInteger: (value: unknown) => asserts value is number;
|
||||
plainObject: <Value = unknown>(value: unknown) => asserts value is Record<PropertyKey, Value>;
|
||||
typedArray: (value: unknown) => asserts value is TypedArray;
|
||||
arrayLike: <T = unknown>(value: unknown) => asserts value is ArrayLike<T>;
|
||||
domElement: (value: unknown) => asserts value is HTMLElement;
|
||||
observable: (value: unknown) => asserts value is ObservableLike;
|
||||
nodeStream: (value: unknown) => asserts value is NodeStream;
|
||||
infinite: (value: unknown) => asserts value is number;
|
||||
emptyArray: (value: unknown) => asserts value is never[];
|
||||
nonEmptyArray: (value: unknown) => asserts value is unknown[];
|
||||
emptyString: (value: unknown) => asserts value is '';
|
||||
emptyStringOrWhitespace: (value: unknown) => asserts value is string;
|
||||
nonEmptyString: (value: unknown) => asserts value is string;
|
||||
nonEmptyStringAndNotWhitespace: (value: unknown) => asserts value is string;
|
||||
emptyObject: <Key extends keyof any = string>(value: unknown) => asserts value is Record<Key, never>;
|
||||
nonEmptyObject: <Key extends keyof any = string, Value = unknown>(value: unknown) => asserts value is Record<Key, Value>;
|
||||
emptySet: (value: unknown) => asserts value is Set<never>;
|
||||
nonEmptySet: <T = unknown>(value: unknown) => asserts value is Set<T>;
|
||||
emptyMap: (value: unknown) => asserts value is Map<never, never>;
|
||||
nonEmptyMap: <Key = unknown, Value = unknown>(value: unknown) => asserts value is Map<Key, Value>;
|
||||
propertyKey: (value: unknown) => asserts value is PropertyKey;
|
||||
formData: (value: unknown) => asserts value is FormData;
|
||||
urlSearchParams: (value: unknown) => asserts value is URLSearchParams;
|
||||
evenInteger: (value: number) => asserts value is number;
|
||||
oddInteger: (value: number) => asserts value is number;
|
||||
directInstanceOf: <T>(instance: unknown, class_: Class<T>) => asserts instance is T;
|
||||
inRange: (value: number, range: number | number[]) => asserts value is number;
|
||||
any: (predicate: Predicate | Predicate[], ...values: unknown[]) => void | never;
|
||||
all: (predicate: Predicate, ...values: unknown[]) => void | never;
|
||||
}
|
||||
export declare const assert: Assert;
|
||||
export default is;
|
||||
export { Class, TypedArray, ObservableLike, Primitive } from './types';
|
||||
-434
@@ -1,434 +0,0 @@
|
||||
"use strict";
|
||||
/// <reference lib="es2018"/>
|
||||
/// <reference lib="dom"/>
|
||||
/// <reference types="node"/>
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const typedArrayTypeNames = [
|
||||
'Int8Array',
|
||||
'Uint8Array',
|
||||
'Uint8ClampedArray',
|
||||
'Int16Array',
|
||||
'Uint16Array',
|
||||
'Int32Array',
|
||||
'Uint32Array',
|
||||
'Float32Array',
|
||||
'Float64Array',
|
||||
'BigInt64Array',
|
||||
'BigUint64Array'
|
||||
];
|
||||
function isTypedArrayName(name) {
|
||||
return typedArrayTypeNames.includes(name);
|
||||
}
|
||||
const objectTypeNames = [
|
||||
'Function',
|
||||
'Generator',
|
||||
'AsyncGenerator',
|
||||
'GeneratorFunction',
|
||||
'AsyncGeneratorFunction',
|
||||
'AsyncFunction',
|
||||
'Observable',
|
||||
'Array',
|
||||
'Buffer',
|
||||
'Blob',
|
||||
'Object',
|
||||
'RegExp',
|
||||
'Date',
|
||||
'Error',
|
||||
'Map',
|
||||
'Set',
|
||||
'WeakMap',
|
||||
'WeakSet',
|
||||
'ArrayBuffer',
|
||||
'SharedArrayBuffer',
|
||||
'DataView',
|
||||
'Promise',
|
||||
'URL',
|
||||
'FormData',
|
||||
'URLSearchParams',
|
||||
'HTMLElement',
|
||||
...typedArrayTypeNames
|
||||
];
|
||||
function isObjectTypeName(name) {
|
||||
return objectTypeNames.includes(name);
|
||||
}
|
||||
const primitiveTypeNames = [
|
||||
'null',
|
||||
'undefined',
|
||||
'string',
|
||||
'number',
|
||||
'bigint',
|
||||
'boolean',
|
||||
'symbol'
|
||||
];
|
||||
function isPrimitiveTypeName(name) {
|
||||
return primitiveTypeNames.includes(name);
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
function isOfType(type) {
|
||||
return (value) => typeof value === type;
|
||||
}
|
||||
const { toString } = Object.prototype;
|
||||
const getObjectType = (value) => {
|
||||
const objectTypeName = toString.call(value).slice(8, -1);
|
||||
if (/HTML\w+Element/.test(objectTypeName) && is.domElement(value)) {
|
||||
return 'HTMLElement';
|
||||
}
|
||||
if (isObjectTypeName(objectTypeName)) {
|
||||
return objectTypeName;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
const isObjectOfType = (type) => (value) => getObjectType(value) === type;
|
||||
function is(value) {
|
||||
if (value === null) {
|
||||
return 'null';
|
||||
}
|
||||
switch (typeof value) {
|
||||
case 'undefined':
|
||||
return 'undefined';
|
||||
case 'string':
|
||||
return 'string';
|
||||
case 'number':
|
||||
return 'number';
|
||||
case 'boolean':
|
||||
return 'boolean';
|
||||
case 'function':
|
||||
return 'Function';
|
||||
case 'bigint':
|
||||
return 'bigint';
|
||||
case 'symbol':
|
||||
return 'symbol';
|
||||
default:
|
||||
}
|
||||
if (is.observable(value)) {
|
||||
return 'Observable';
|
||||
}
|
||||
if (is.array(value)) {
|
||||
return 'Array';
|
||||
}
|
||||
if (is.buffer(value)) {
|
||||
return 'Buffer';
|
||||
}
|
||||
const tagType = getObjectType(value);
|
||||
if (tagType) {
|
||||
return tagType;
|
||||
}
|
||||
if (value instanceof String || value instanceof Boolean || value instanceof Number) {
|
||||
throw new TypeError('Please don\'t use object wrappers for primitive types');
|
||||
}
|
||||
return 'Object';
|
||||
}
|
||||
is.undefined = isOfType('undefined');
|
||||
is.string = isOfType('string');
|
||||
const isNumberType = isOfType('number');
|
||||
is.number = (value) => isNumberType(value) && !is.nan(value);
|
||||
is.bigint = isOfType('bigint');
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
is.function_ = isOfType('function');
|
||||
is.null_ = (value) => value === null;
|
||||
is.class_ = (value) => is.function_(value) && value.toString().startsWith('class ');
|
||||
is.boolean = (value) => value === true || value === false;
|
||||
is.symbol = isOfType('symbol');
|
||||
is.numericString = (value) => is.string(value) && !is.emptyStringOrWhitespace(value) && !Number.isNaN(Number(value));
|
||||
is.array = (value, assertion) => {
|
||||
if (!Array.isArray(value)) {
|
||||
return false;
|
||||
}
|
||||
if (!is.function_(assertion)) {
|
||||
return true;
|
||||
}
|
||||
return value.every(assertion);
|
||||
};
|
||||
is.buffer = (value) => { var _a, _b, _c, _d; return (_d = (_c = (_b = (_a = value) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.isBuffer) === null || _c === void 0 ? void 0 : _c.call(_b, value)) !== null && _d !== void 0 ? _d : false; };
|
||||
is.blob = (value) => isObjectOfType('Blob')(value);
|
||||
is.nullOrUndefined = (value) => is.null_(value) || is.undefined(value);
|
||||
is.object = (value) => !is.null_(value) && (typeof value === 'object' || is.function_(value));
|
||||
is.iterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.iterator]); };
|
||||
is.asyncIterable = (value) => { var _a; return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a[Symbol.asyncIterator]); };
|
||||
is.generator = (value) => { var _a, _b; return is.iterable(value) && is.function_((_a = value) === null || _a === void 0 ? void 0 : _a.next) && is.function_((_b = value) === null || _b === void 0 ? void 0 : _b.throw); };
|
||||
is.asyncGenerator = (value) => is.asyncIterable(value) && is.function_(value.next) && is.function_(value.throw);
|
||||
is.nativePromise = (value) => isObjectOfType('Promise')(value);
|
||||
const hasPromiseAPI = (value) => {
|
||||
var _a, _b;
|
||||
return is.function_((_a = value) === null || _a === void 0 ? void 0 : _a.then) &&
|
||||
is.function_((_b = value) === null || _b === void 0 ? void 0 : _b.catch);
|
||||
};
|
||||
is.promise = (value) => is.nativePromise(value) || hasPromiseAPI(value);
|
||||
is.generatorFunction = isObjectOfType('GeneratorFunction');
|
||||
is.asyncGeneratorFunction = (value) => getObjectType(value) === 'AsyncGeneratorFunction';
|
||||
is.asyncFunction = (value) => getObjectType(value) === 'AsyncFunction';
|
||||
// eslint-disable-next-line no-prototype-builtins, @typescript-eslint/ban-types
|
||||
is.boundFunction = (value) => is.function_(value) && !value.hasOwnProperty('prototype');
|
||||
is.regExp = isObjectOfType('RegExp');
|
||||
is.date = isObjectOfType('Date');
|
||||
is.error = isObjectOfType('Error');
|
||||
is.map = (value) => isObjectOfType('Map')(value);
|
||||
is.set = (value) => isObjectOfType('Set')(value);
|
||||
is.weakMap = (value) => isObjectOfType('WeakMap')(value);
|
||||
is.weakSet = (value) => isObjectOfType('WeakSet')(value);
|
||||
is.int8Array = isObjectOfType('Int8Array');
|
||||
is.uint8Array = isObjectOfType('Uint8Array');
|
||||
is.uint8ClampedArray = isObjectOfType('Uint8ClampedArray');
|
||||
is.int16Array = isObjectOfType('Int16Array');
|
||||
is.uint16Array = isObjectOfType('Uint16Array');
|
||||
is.int32Array = isObjectOfType('Int32Array');
|
||||
is.uint32Array = isObjectOfType('Uint32Array');
|
||||
is.float32Array = isObjectOfType('Float32Array');
|
||||
is.float64Array = isObjectOfType('Float64Array');
|
||||
is.bigInt64Array = isObjectOfType('BigInt64Array');
|
||||
is.bigUint64Array = isObjectOfType('BigUint64Array');
|
||||
is.arrayBuffer = isObjectOfType('ArrayBuffer');
|
||||
is.sharedArrayBuffer = isObjectOfType('SharedArrayBuffer');
|
||||
is.dataView = isObjectOfType('DataView');
|
||||
is.enumCase = (value, targetEnum) => Object.values(targetEnum).includes(value);
|
||||
is.directInstanceOf = (instance, class_) => Object.getPrototypeOf(instance) === class_.prototype;
|
||||
is.urlInstance = (value) => isObjectOfType('URL')(value);
|
||||
is.urlString = (value) => {
|
||||
if (!is.string(value)) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
new URL(value); // eslint-disable-line no-new
|
||||
return true;
|
||||
}
|
||||
catch (_a) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
// Example: `is.truthy = (value: unknown): value is (not false | not 0 | not '' | not undefined | not null) => Boolean(value);`
|
||||
is.truthy = (value) => Boolean(value);
|
||||
// Example: `is.falsy = (value: unknown): value is (not true | 0 | '' | undefined | null) => Boolean(value);`
|
||||
is.falsy = (value) => !value;
|
||||
is.nan = (value) => Number.isNaN(value);
|
||||
is.primitive = (value) => is.null_(value) || isPrimitiveTypeName(typeof value);
|
||||
is.integer = (value) => Number.isInteger(value);
|
||||
is.safeInteger = (value) => Number.isSafeInteger(value);
|
||||
is.plainObject = (value) => {
|
||||
// From: https://github.com/sindresorhus/is-plain-obj/blob/main/index.js
|
||||
if (toString.call(value) !== '[object Object]') {
|
||||
return false;
|
||||
}
|
||||
const prototype = Object.getPrototypeOf(value);
|
||||
return prototype === null || prototype === Object.getPrototypeOf({});
|
||||
};
|
||||
is.typedArray = (value) => isTypedArrayName(getObjectType(value));
|
||||
const isValidLength = (value) => is.safeInteger(value) && value >= 0;
|
||||
is.arrayLike = (value) => !is.nullOrUndefined(value) && !is.function_(value) && isValidLength(value.length);
|
||||
is.inRange = (value, range) => {
|
||||
if (is.number(range)) {
|
||||
return value >= Math.min(0, range) && value <= Math.max(range, 0);
|
||||
}
|
||||
if (is.array(range) && range.length === 2) {
|
||||
return value >= Math.min(...range) && value <= Math.max(...range);
|
||||
}
|
||||
throw new TypeError(`Invalid range: ${JSON.stringify(range)}`);
|
||||
};
|
||||
const NODE_TYPE_ELEMENT = 1;
|
||||
const DOM_PROPERTIES_TO_CHECK = [
|
||||
'innerHTML',
|
||||
'ownerDocument',
|
||||
'style',
|
||||
'attributes',
|
||||
'nodeValue'
|
||||
];
|
||||
is.domElement = (value) => {
|
||||
return is.object(value) &&
|
||||
value.nodeType === NODE_TYPE_ELEMENT &&
|
||||
is.string(value.nodeName) &&
|
||||
!is.plainObject(value) &&
|
||||
DOM_PROPERTIES_TO_CHECK.every(property => property in value);
|
||||
};
|
||||
is.observable = (value) => {
|
||||
var _a, _b, _c, _d;
|
||||
if (!value) {
|
||||
return false;
|
||||
}
|
||||
// eslint-disable-next-line no-use-extend-native/no-use-extend-native
|
||||
if (value === ((_b = (_a = value)[Symbol.observable]) === null || _b === void 0 ? void 0 : _b.call(_a))) {
|
||||
return true;
|
||||
}
|
||||
if (value === ((_d = (_c = value)['@@observable']) === null || _d === void 0 ? void 0 : _d.call(_c))) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
is.nodeStream = (value) => is.object(value) && is.function_(value.pipe) && !is.observable(value);
|
||||
is.infinite = (value) => value === Infinity || value === -Infinity;
|
||||
const isAbsoluteMod2 = (remainder) => (value) => is.integer(value) && Math.abs(value % 2) === remainder;
|
||||
is.evenInteger = isAbsoluteMod2(0);
|
||||
is.oddInteger = isAbsoluteMod2(1);
|
||||
is.emptyArray = (value) => is.array(value) && value.length === 0;
|
||||
is.nonEmptyArray = (value) => is.array(value) && value.length > 0;
|
||||
is.emptyString = (value) => is.string(value) && value.length === 0;
|
||||
const isWhiteSpaceString = (value) => is.string(value) && !/\S/.test(value);
|
||||
is.emptyStringOrWhitespace = (value) => is.emptyString(value) || isWhiteSpaceString(value);
|
||||
// TODO: Use `not ''` when the `not` operator is available.
|
||||
is.nonEmptyString = (value) => is.string(value) && value.length > 0;
|
||||
// TODO: Use `not ''` when the `not` operator is available.
|
||||
is.nonEmptyStringAndNotWhitespace = (value) => is.string(value) && !is.emptyStringOrWhitespace(value);
|
||||
is.emptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length === 0;
|
||||
// TODO: Use `not` operator here to remove `Map` and `Set` from type guard:
|
||||
// - https://github.com/Microsoft/TypeScript/pull/29317
|
||||
is.nonEmptyObject = (value) => is.object(value) && !is.map(value) && !is.set(value) && Object.keys(value).length > 0;
|
||||
is.emptySet = (value) => is.set(value) && value.size === 0;
|
||||
is.nonEmptySet = (value) => is.set(value) && value.size > 0;
|
||||
is.emptyMap = (value) => is.map(value) && value.size === 0;
|
||||
is.nonEmptyMap = (value) => is.map(value) && value.size > 0;
|
||||
// `PropertyKey` is any value that can be used as an object key (string, number, or symbol)
|
||||
is.propertyKey = (value) => is.any([is.string, is.number, is.symbol], value);
|
||||
is.formData = (value) => isObjectOfType('FormData')(value);
|
||||
is.urlSearchParams = (value) => isObjectOfType('URLSearchParams')(value);
|
||||
const predicateOnArray = (method, predicate, values) => {
|
||||
if (!is.function_(predicate)) {
|
||||
throw new TypeError(`Invalid predicate: ${JSON.stringify(predicate)}`);
|
||||
}
|
||||
if (values.length === 0) {
|
||||
throw new TypeError('Invalid number of values');
|
||||
}
|
||||
return method.call(values, predicate);
|
||||
};
|
||||
is.any = (predicate, ...values) => {
|
||||
const predicates = is.array(predicate) ? predicate : [predicate];
|
||||
return predicates.some(singlePredicate => predicateOnArray(Array.prototype.some, singlePredicate, values));
|
||||
};
|
||||
is.all = (predicate, ...values) => predicateOnArray(Array.prototype.every, predicate, values);
|
||||
const assertType = (condition, description, value, options = {}) => {
|
||||
if (!condition) {
|
||||
const { multipleValues } = options;
|
||||
const valuesMessage = multipleValues ?
|
||||
`received values of types ${[
|
||||
...new Set(value.map(singleValue => `\`${is(singleValue)}\``))
|
||||
].join(', ')}` :
|
||||
`received value of type \`${is(value)}\``;
|
||||
throw new TypeError(`Expected value which is \`${description}\`, ${valuesMessage}.`);
|
||||
}
|
||||
};
|
||||
exports.assert = {
|
||||
// Unknowns.
|
||||
undefined: (value) => assertType(is.undefined(value), 'undefined', value),
|
||||
string: (value) => assertType(is.string(value), 'string', value),
|
||||
number: (value) => assertType(is.number(value), 'number', value),
|
||||
bigint: (value) => assertType(is.bigint(value), 'bigint', value),
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
function_: (value) => assertType(is.function_(value), 'Function', value),
|
||||
null_: (value) => assertType(is.null_(value), 'null', value),
|
||||
class_: (value) => assertType(is.class_(value), "Class" /* class_ */, value),
|
||||
boolean: (value) => assertType(is.boolean(value), 'boolean', value),
|
||||
symbol: (value) => assertType(is.symbol(value), 'symbol', value),
|
||||
numericString: (value) => assertType(is.numericString(value), "string with a number" /* numericString */, value),
|
||||
array: (value, assertion) => {
|
||||
const assert = assertType;
|
||||
assert(is.array(value), 'Array', value);
|
||||
if (assertion) {
|
||||
value.forEach(assertion);
|
||||
}
|
||||
},
|
||||
buffer: (value) => assertType(is.buffer(value), 'Buffer', value),
|
||||
blob: (value) => assertType(is.blob(value), 'Blob', value),
|
||||
nullOrUndefined: (value) => assertType(is.nullOrUndefined(value), "null or undefined" /* nullOrUndefined */, value),
|
||||
object: (value) => assertType(is.object(value), 'Object', value),
|
||||
iterable: (value) => assertType(is.iterable(value), "Iterable" /* iterable */, value),
|
||||
asyncIterable: (value) => assertType(is.asyncIterable(value), "AsyncIterable" /* asyncIterable */, value),
|
||||
generator: (value) => assertType(is.generator(value), 'Generator', value),
|
||||
asyncGenerator: (value) => assertType(is.asyncGenerator(value), 'AsyncGenerator', value),
|
||||
nativePromise: (value) => assertType(is.nativePromise(value), "native Promise" /* nativePromise */, value),
|
||||
promise: (value) => assertType(is.promise(value), 'Promise', value),
|
||||
generatorFunction: (value) => assertType(is.generatorFunction(value), 'GeneratorFunction', value),
|
||||
asyncGeneratorFunction: (value) => assertType(is.asyncGeneratorFunction(value), 'AsyncGeneratorFunction', value),
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
asyncFunction: (value) => assertType(is.asyncFunction(value), 'AsyncFunction', value),
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
boundFunction: (value) => assertType(is.boundFunction(value), 'Function', value),
|
||||
regExp: (value) => assertType(is.regExp(value), 'RegExp', value),
|
||||
date: (value) => assertType(is.date(value), 'Date', value),
|
||||
error: (value) => assertType(is.error(value), 'Error', value),
|
||||
map: (value) => assertType(is.map(value), 'Map', value),
|
||||
set: (value) => assertType(is.set(value), 'Set', value),
|
||||
weakMap: (value) => assertType(is.weakMap(value), 'WeakMap', value),
|
||||
weakSet: (value) => assertType(is.weakSet(value), 'WeakSet', value),
|
||||
int8Array: (value) => assertType(is.int8Array(value), 'Int8Array', value),
|
||||
uint8Array: (value) => assertType(is.uint8Array(value), 'Uint8Array', value),
|
||||
uint8ClampedArray: (value) => assertType(is.uint8ClampedArray(value), 'Uint8ClampedArray', value),
|
||||
int16Array: (value) => assertType(is.int16Array(value), 'Int16Array', value),
|
||||
uint16Array: (value) => assertType(is.uint16Array(value), 'Uint16Array', value),
|
||||
int32Array: (value) => assertType(is.int32Array(value), 'Int32Array', value),
|
||||
uint32Array: (value) => assertType(is.uint32Array(value), 'Uint32Array', value),
|
||||
float32Array: (value) => assertType(is.float32Array(value), 'Float32Array', value),
|
||||
float64Array: (value) => assertType(is.float64Array(value), 'Float64Array', value),
|
||||
bigInt64Array: (value) => assertType(is.bigInt64Array(value), 'BigInt64Array', value),
|
||||
bigUint64Array: (value) => assertType(is.bigUint64Array(value), 'BigUint64Array', value),
|
||||
arrayBuffer: (value) => assertType(is.arrayBuffer(value), 'ArrayBuffer', value),
|
||||
sharedArrayBuffer: (value) => assertType(is.sharedArrayBuffer(value), 'SharedArrayBuffer', value),
|
||||
dataView: (value) => assertType(is.dataView(value), 'DataView', value),
|
||||
enumCase: (value, targetEnum) => assertType(is.enumCase(value, targetEnum), 'EnumCase', value),
|
||||
urlInstance: (value) => assertType(is.urlInstance(value), 'URL', value),
|
||||
urlString: (value) => assertType(is.urlString(value), "string with a URL" /* urlString */, value),
|
||||
truthy: (value) => assertType(is.truthy(value), "truthy" /* truthy */, value),
|
||||
falsy: (value) => assertType(is.falsy(value), "falsy" /* falsy */, value),
|
||||
nan: (value) => assertType(is.nan(value), "NaN" /* nan */, value),
|
||||
primitive: (value) => assertType(is.primitive(value), "primitive" /* primitive */, value),
|
||||
integer: (value) => assertType(is.integer(value), "integer" /* integer */, value),
|
||||
safeInteger: (value) => assertType(is.safeInteger(value), "integer" /* safeInteger */, value),
|
||||
plainObject: (value) => assertType(is.plainObject(value), "plain object" /* plainObject */, value),
|
||||
typedArray: (value) => assertType(is.typedArray(value), "TypedArray" /* typedArray */, value),
|
||||
arrayLike: (value) => assertType(is.arrayLike(value), "array-like" /* arrayLike */, value),
|
||||
domElement: (value) => assertType(is.domElement(value), "HTMLElement" /* domElement */, value),
|
||||
observable: (value) => assertType(is.observable(value), 'Observable', value),
|
||||
nodeStream: (value) => assertType(is.nodeStream(value), "Node.js Stream" /* nodeStream */, value),
|
||||
infinite: (value) => assertType(is.infinite(value), "infinite number" /* infinite */, value),
|
||||
emptyArray: (value) => assertType(is.emptyArray(value), "empty array" /* emptyArray */, value),
|
||||
nonEmptyArray: (value) => assertType(is.nonEmptyArray(value), "non-empty array" /* nonEmptyArray */, value),
|
||||
emptyString: (value) => assertType(is.emptyString(value), "empty string" /* emptyString */, value),
|
||||
emptyStringOrWhitespace: (value) => assertType(is.emptyStringOrWhitespace(value), "empty string or whitespace" /* emptyStringOrWhitespace */, value),
|
||||
nonEmptyString: (value) => assertType(is.nonEmptyString(value), "non-empty string" /* nonEmptyString */, value),
|
||||
nonEmptyStringAndNotWhitespace: (value) => assertType(is.nonEmptyStringAndNotWhitespace(value), "non-empty string and not whitespace" /* nonEmptyStringAndNotWhitespace */, value),
|
||||
emptyObject: (value) => assertType(is.emptyObject(value), "empty object" /* emptyObject */, value),
|
||||
nonEmptyObject: (value) => assertType(is.nonEmptyObject(value), "non-empty object" /* nonEmptyObject */, value),
|
||||
emptySet: (value) => assertType(is.emptySet(value), "empty set" /* emptySet */, value),
|
||||
nonEmptySet: (value) => assertType(is.nonEmptySet(value), "non-empty set" /* nonEmptySet */, value),
|
||||
emptyMap: (value) => assertType(is.emptyMap(value), "empty map" /* emptyMap */, value),
|
||||
nonEmptyMap: (value) => assertType(is.nonEmptyMap(value), "non-empty map" /* nonEmptyMap */, value),
|
||||
propertyKey: (value) => assertType(is.propertyKey(value), 'PropertyKey', value),
|
||||
formData: (value) => assertType(is.formData(value), 'FormData', value),
|
||||
urlSearchParams: (value) => assertType(is.urlSearchParams(value), 'URLSearchParams', value),
|
||||
// Numbers.
|
||||
evenInteger: (value) => assertType(is.evenInteger(value), "even integer" /* evenInteger */, value),
|
||||
oddInteger: (value) => assertType(is.oddInteger(value), "odd integer" /* oddInteger */, value),
|
||||
// Two arguments.
|
||||
directInstanceOf: (instance, class_) => assertType(is.directInstanceOf(instance, class_), "T" /* directInstanceOf */, instance),
|
||||
inRange: (value, range) => assertType(is.inRange(value, range), "in range" /* inRange */, value),
|
||||
// Variadic functions.
|
||||
any: (predicate, ...values) => {
|
||||
return assertType(is.any(predicate, ...values), "predicate returns truthy for any value" /* any */, values, { multipleValues: true });
|
||||
},
|
||||
all: (predicate, ...values) => assertType(is.all(predicate, ...values), "predicate returns truthy for all values" /* all */, values, { multipleValues: true })
|
||||
};
|
||||
// Some few keywords are reserved, but we'll populate them for Node.js users
|
||||
// See https://github.com/Microsoft/TypeScript/issues/2536
|
||||
Object.defineProperties(is, {
|
||||
class: {
|
||||
value: is.class_
|
||||
},
|
||||
function: {
|
||||
value: is.function_
|
||||
},
|
||||
null: {
|
||||
value: is.null_
|
||||
}
|
||||
});
|
||||
Object.defineProperties(exports.assert, {
|
||||
class: {
|
||||
value: exports.assert.class_
|
||||
},
|
||||
function: {
|
||||
value: exports.assert.function_
|
||||
},
|
||||
null: {
|
||||
value: exports.assert.null_
|
||||
}
|
||||
});
|
||||
exports.default = is;
|
||||
// For CommonJS default export support
|
||||
module.exports = is;
|
||||
module.exports.default = is;
|
||||
module.exports.assert = exports.assert;
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
/**
|
||||
Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive).
|
||||
*/
|
||||
export declare type Primitive = null | undefined | string | number | boolean | symbol | bigint;
|
||||
/**
|
||||
Matches a [`class` constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes).
|
||||
*/
|
||||
export declare type Class<T = unknown, Arguments extends any[] = any[]> = new (...arguments_: Arguments) => T;
|
||||
/**
|
||||
Matches any [typed array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray), like `Uint8Array` or `Float64Array`.
|
||||
*/
|
||||
export declare type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;
|
||||
declare global {
|
||||
interface SymbolConstructor {
|
||||
readonly observable: symbol;
|
||||
}
|
||||
}
|
||||
/**
|
||||
Matches a value that is like an [Observable](https://github.com/tc39/proposal-observable).
|
||||
*/
|
||||
export interface ObservableLike {
|
||||
subscribe(observer: (value: unknown) => void): void;
|
||||
[Symbol.observable](): ObservableLike;
|
||||
}
|
||||
export declare type Falsy = false | 0 | 0n | '' | null | undefined;
|
||||
-3
@@ -1,3 +0,0 @@
|
||||
"use strict";
|
||||
// Extracted from https://github.com/sindresorhus/type-fest/blob/78019f42ea888b0cdceb41a4a78163868de57555/index.d.ts
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
|
||||
|
||||
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.
|
||||
-96
@@ -1,96 +0,0 @@
|
||||
{
|
||||
"name": "@sindresorhus/is",
|
||||
"version": "4.6.0",
|
||||
"description": "Type check values",
|
||||
"license": "MIT",
|
||||
"repository": "sindresorhus/is",
|
||||
"funding": "https://github.com/sindresorhus/is?sponsor=1",
|
||||
"author": {
|
||||
"name": "Sindre Sorhus",
|
||||
"email": "sindresorhus@gmail.com",
|
||||
"url": "https://sindresorhus.com"
|
||||
},
|
||||
"main": "dist/index.js",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "del dist && tsc",
|
||||
"test": "xo && ava",
|
||||
"prepare": "npm run build"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"keywords": [
|
||||
"type",
|
||||
"types",
|
||||
"is",
|
||||
"check",
|
||||
"checking",
|
||||
"validate",
|
||||
"validation",
|
||||
"utility",
|
||||
"util",
|
||||
"typeof",
|
||||
"instanceof",
|
||||
"object",
|
||||
"assert",
|
||||
"assertion",
|
||||
"test",
|
||||
"kind",
|
||||
"primitive",
|
||||
"verify",
|
||||
"compare",
|
||||
"typescript",
|
||||
"typeguards",
|
||||
"types"
|
||||
],
|
||||
"devDependencies": {
|
||||
"@sindresorhus/tsconfig": "^0.7.0",
|
||||
"@types/jsdom": "^16.1.0",
|
||||
"@types/node": "^14.0.13",
|
||||
"@types/zen-observable": "^0.8.0",
|
||||
"@typescript-eslint/eslint-plugin": "^2.20.0",
|
||||
"@typescript-eslint/parser": "^2.20.0",
|
||||
"ava": "^3.3.0",
|
||||
"del-cli": "^2.0.0",
|
||||
"eslint-config-xo-typescript": "^0.26.0",
|
||||
"jsdom": "^16.0.1",
|
||||
"rxjs": "^6.4.0",
|
||||
"tempy": "^0.4.0",
|
||||
"ts-node": "^8.3.0",
|
||||
"typescript": "~3.8.2",
|
||||
"xo": "^0.26.1",
|
||||
"zen-observable": "^0.8.8"
|
||||
},
|
||||
"types": "dist/index.d.ts",
|
||||
"sideEffects": false,
|
||||
"ava": {
|
||||
"extensions": [
|
||||
"ts"
|
||||
],
|
||||
"require": [
|
||||
"ts-node/register"
|
||||
]
|
||||
},
|
||||
"xo": {
|
||||
"extends": "xo-typescript",
|
||||
"extensions": [
|
||||
"ts"
|
||||
],
|
||||
"parserOptions": {
|
||||
"project": "./tsconfig.xo.json"
|
||||
},
|
||||
"globals": [
|
||||
"BigInt",
|
||||
"BigInt64Array",
|
||||
"BigUint64Array"
|
||||
],
|
||||
"rules": {
|
||||
"@typescript-eslint/promise-function-async": "off",
|
||||
"@typescript-eslint/no-empty-function": "off",
|
||||
"@typescript-eslint/explicit-function-return-type": "off"
|
||||
}
|
||||
}
|
||||
}
|
||||
-669
@@ -1,669 +0,0 @@
|
||||
# is
|
||||
|
||||
> Type check values
|
||||
|
||||
For example, `is.string('🦄') //=> true`
|
||||
|
||||
<img src="header.gif" width="182" align="right">
|
||||
|
||||
## Highlights
|
||||
|
||||
- Written in TypeScript
|
||||
- [Extensive use of type guards](#type-guards)
|
||||
- [Supports type assertions](#type-assertions)
|
||||
- [Aware of generic type parameters](#generic-type-parameters) (use with caution)
|
||||
- Actively maintained
|
||||
- 
|
||||
|
||||
## Install
|
||||
|
||||
```sh
|
||||
npm install @sindresorhus/is
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
const is = require('@sindresorhus/is');
|
||||
|
||||
is('🦄');
|
||||
//=> 'string'
|
||||
|
||||
is(new Map());
|
||||
//=> 'Map'
|
||||
|
||||
is.number(6);
|
||||
//=> true
|
||||
```
|
||||
|
||||
[Assertions](#type-assertions) perform the same type checks, but throw an error if the type does not match.
|
||||
|
||||
```js
|
||||
const {assert} = require('@sindresorhus/is');
|
||||
|
||||
assert.string(2);
|
||||
//=> Error: Expected value which is `string`, received value of type `number`.
|
||||
```
|
||||
|
||||
And with TypeScript:
|
||||
|
||||
```ts
|
||||
import {assert} from '@sindresorhus/is';
|
||||
|
||||
assert.string(foo);
|
||||
// `foo` is now typed as a `string`.
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
### is(value)
|
||||
|
||||
Returns the type of `value`.
|
||||
|
||||
Primitives are lowercase and object types are camelcase.
|
||||
|
||||
Example:
|
||||
|
||||
- `'undefined'`
|
||||
- `'null'`
|
||||
- `'string'`
|
||||
- `'symbol'`
|
||||
- `'Array'`
|
||||
- `'Function'`
|
||||
- `'Object'`
|
||||
|
||||
Note: It will throw an error if you try to feed it object-wrapped primitives, as that's a bad practice. For example `new String('foo')`.
|
||||
|
||||
### is.{method}
|
||||
|
||||
All the below methods accept a value and returns a boolean for whether the value is of the desired type.
|
||||
|
||||
#### Primitives
|
||||
|
||||
##### .undefined(value)
|
||||
##### .null(value)
|
||||
|
||||
**Note:** TypeScript users must use `.null_()` because of a TypeScript naming limitation.
|
||||
|
||||
##### .string(value)
|
||||
##### .number(value)
|
||||
|
||||
Note: `is.number(NaN)` returns `false`. This intentionally deviates from `typeof` behavior to increase user-friendliness of `is` type checks.
|
||||
|
||||
##### .boolean(value)
|
||||
##### .symbol(value)
|
||||
##### .bigint(value)
|
||||
|
||||
#### Built-in types
|
||||
|
||||
##### .array(value, assertion?)
|
||||
|
||||
Returns true if `value` is an array and all of its items match the assertion (if provided).
|
||||
|
||||
```js
|
||||
is.array(value); // Validate `value` is an array.
|
||||
is.array(value, is.number); // Validate `value` is an array and all of its items are numbers.
|
||||
```
|
||||
|
||||
##### .function(value)
|
||||
|
||||
**Note:** TypeScript users must use `.function_()` because of a TypeScript naming limitation.
|
||||
|
||||
##### .buffer(value)
|
||||
##### .blob(value)
|
||||
##### .object(value)
|
||||
|
||||
Keep in mind that [functions are objects too](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions).
|
||||
|
||||
##### .numericString(value)
|
||||
|
||||
Returns `true` for a string that represents a number satisfying `is.number`, for example, `'42'` and `'-8.3'`.
|
||||
|
||||
Note: `'NaN'` returns `false`, but `'Infinity'` and `'-Infinity'` return `true`.
|
||||
|
||||
##### .regExp(value)
|
||||
##### .date(value)
|
||||
##### .error(value)
|
||||
##### .nativePromise(value)
|
||||
##### .promise(value)
|
||||
|
||||
Returns `true` for any object with a `.then()` and `.catch()` method. Prefer this one over `.nativePromise()` as you usually want to allow userland promise implementations too.
|
||||
|
||||
##### .generator(value)
|
||||
|
||||
Returns `true` for any object that implements its own `.next()` and `.throw()` methods and has a function definition for `Symbol.iterator`.
|
||||
|
||||
##### .generatorFunction(value)
|
||||
|
||||
##### .asyncFunction(value)
|
||||
|
||||
Returns `true` for any `async` function that can be called with the `await` operator.
|
||||
|
||||
```js
|
||||
is.asyncFunction(async () => {});
|
||||
//=> true
|
||||
|
||||
is.asyncFunction(() => {});
|
||||
//=> false
|
||||
```
|
||||
|
||||
##### .asyncGenerator(value)
|
||||
|
||||
```js
|
||||
is.asyncGenerator(
|
||||
(async function * () {
|
||||
yield 4;
|
||||
})()
|
||||
);
|
||||
//=> true
|
||||
|
||||
is.asyncGenerator(
|
||||
(function * () {
|
||||
yield 4;
|
||||
})()
|
||||
);
|
||||
//=> false
|
||||
```
|
||||
|
||||
##### .asyncGeneratorFunction(value)
|
||||
|
||||
```js
|
||||
is.asyncGeneratorFunction(async function * () {
|
||||
yield 4;
|
||||
});
|
||||
//=> true
|
||||
|
||||
is.asyncGeneratorFunction(function * () {
|
||||
yield 4;
|
||||
});
|
||||
//=> false
|
||||
```
|
||||
|
||||
##### .boundFunction(value)
|
||||
|
||||
Returns `true` for any `bound` function.
|
||||
|
||||
```js
|
||||
is.boundFunction(() => {});
|
||||
//=> true
|
||||
|
||||
is.boundFunction(function () {}.bind(null));
|
||||
//=> true
|
||||
|
||||
is.boundFunction(function () {});
|
||||
//=> false
|
||||
```
|
||||
|
||||
##### .map(value)
|
||||
##### .set(value)
|
||||
##### .weakMap(value)
|
||||
##### .weakSet(value)
|
||||
|
||||
#### Typed arrays
|
||||
|
||||
##### .int8Array(value)
|
||||
##### .uint8Array(value)
|
||||
##### .uint8ClampedArray(value)
|
||||
##### .int16Array(value)
|
||||
##### .uint16Array(value)
|
||||
##### .int32Array(value)
|
||||
##### .uint32Array(value)
|
||||
##### .float32Array(value)
|
||||
##### .float64Array(value)
|
||||
##### .bigInt64Array(value)
|
||||
##### .bigUint64Array(value)
|
||||
|
||||
#### Structured data
|
||||
|
||||
##### .arrayBuffer(value)
|
||||
##### .sharedArrayBuffer(value)
|
||||
##### .dataView(value)
|
||||
|
||||
##### .enumCase(value, enum)
|
||||
|
||||
TypeScript-only. Returns `true` if `value` is a member of `enum`.
|
||||
|
||||
```ts
|
||||
enum Direction {
|
||||
Ascending = 'ascending',
|
||||
Descending = 'descending'
|
||||
}
|
||||
|
||||
is.enumCase('ascending', Direction);
|
||||
//=> true
|
||||
|
||||
is.enumCase('other', Direction);
|
||||
//=> false
|
||||
```
|
||||
|
||||
#### Emptiness
|
||||
|
||||
##### .emptyString(value)
|
||||
|
||||
Returns `true` if the value is a `string` and the `.length` is 0.
|
||||
|
||||
##### .emptyStringOrWhitespace(value)
|
||||
|
||||
Returns `true` if `is.emptyString(value)` or if it's a `string` that is all whitespace.
|
||||
|
||||
##### .nonEmptyString(value)
|
||||
|
||||
Returns `true` if the value is a `string` and the `.length` is more than 0.
|
||||
|
||||
##### .nonEmptyStringAndNotWhitespace(value)
|
||||
|
||||
Returns `true` if the value is a `string` that is not empty and not whitespace.
|
||||
|
||||
```js
|
||||
const values = ['property1', '', null, 'property2', ' ', undefined];
|
||||
|
||||
values.filter(is.nonEmptyStringAndNotWhitespace);
|
||||
//=> ['property1', 'property2']
|
||||
```
|
||||
|
||||
##### .emptyArray(value)
|
||||
|
||||
Returns `true` if the value is an `Array` and the `.length` is 0.
|
||||
|
||||
##### .nonEmptyArray(value)
|
||||
|
||||
Returns `true` if the value is an `Array` and the `.length` is more than 0.
|
||||
|
||||
##### .emptyObject(value)
|
||||
|
||||
Returns `true` if the value is an `Object` and `Object.keys(value).length` is 0.
|
||||
|
||||
Please note that `Object.keys` returns only own enumerable properties. Hence something like this can happen:
|
||||
|
||||
```js
|
||||
const object1 = {};
|
||||
|
||||
Object.defineProperty(object1, 'property1', {
|
||||
value: 42,
|
||||
writable: true,
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
|
||||
is.emptyObject(object1);
|
||||
//=> true
|
||||
```
|
||||
|
||||
##### .nonEmptyObject(value)
|
||||
|
||||
Returns `true` if the value is an `Object` and `Object.keys(value).length` is more than 0.
|
||||
|
||||
##### .emptySet(value)
|
||||
|
||||
Returns `true` if the value is a `Set` and the `.size` is 0.
|
||||
|
||||
##### .nonEmptySet(Value)
|
||||
|
||||
Returns `true` if the value is a `Set` and the `.size` is more than 0.
|
||||
|
||||
##### .emptyMap(value)
|
||||
|
||||
Returns `true` if the value is a `Map` and the `.size` is 0.
|
||||
|
||||
##### .nonEmptyMap(value)
|
||||
|
||||
Returns `true` if the value is a `Map` and the `.size` is more than 0.
|
||||
|
||||
#### Miscellaneous
|
||||
|
||||
##### .directInstanceOf(value, class)
|
||||
|
||||
Returns `true` if `value` is a direct instance of `class`.
|
||||
|
||||
```js
|
||||
is.directInstanceOf(new Error(), Error);
|
||||
//=> true
|
||||
|
||||
class UnicornError extends Error {}
|
||||
|
||||
is.directInstanceOf(new UnicornError(), Error);
|
||||
//=> false
|
||||
```
|
||||
|
||||
##### .urlInstance(value)
|
||||
|
||||
Returns `true` if `value` is an instance of the [`URL` class](https://developer.mozilla.org/en-US/docs/Web/API/URL).
|
||||
|
||||
```js
|
||||
const url = new URL('https://example.com');
|
||||
|
||||
is.urlInstance(url);
|
||||
//=> true
|
||||
```
|
||||
|
||||
##### .urlString(value)
|
||||
|
||||
Returns `true` if `value` is a URL string.
|
||||
|
||||
Note: this only does basic checking using the [`URL` class](https://developer.mozilla.org/en-US/docs/Web/API/URL) constructor.
|
||||
|
||||
```js
|
||||
const url = 'https://example.com';
|
||||
|
||||
is.urlString(url);
|
||||
//=> true
|
||||
|
||||
is.urlString(new URL(url));
|
||||
//=> false
|
||||
```
|
||||
|
||||
##### .truthy(value)
|
||||
|
||||
Returns `true` for all values that evaluate to true in a boolean context:
|
||||
|
||||
```js
|
||||
is.truthy('🦄');
|
||||
//=> true
|
||||
|
||||
is.truthy(undefined);
|
||||
//=> false
|
||||
```
|
||||
|
||||
##### .falsy(value)
|
||||
|
||||
Returns `true` if `value` is one of: `false`, `0`, `''`, `null`, `undefined`, `NaN`.
|
||||
|
||||
##### .nan(value)
|
||||
##### .nullOrUndefined(value)
|
||||
##### .primitive(value)
|
||||
|
||||
JavaScript primitives are as follows: `null`, `undefined`, `string`, `number`, `boolean`, `symbol`.
|
||||
|
||||
##### .integer(value)
|
||||
|
||||
##### .safeInteger(value)
|
||||
|
||||
Returns `true` if `value` is a [safe integer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger).
|
||||
|
||||
##### .plainObject(value)
|
||||
|
||||
An object is plain if it's created by either `{}`, `new Object()`, or `Object.create(null)`.
|
||||
|
||||
##### .iterable(value)
|
||||
##### .asyncIterable(value)
|
||||
##### .class(value)
|
||||
|
||||
Returns `true` for instances created by a class.
|
||||
|
||||
**Note:** TypeScript users must use `.class_()` because of a TypeScript naming limitation.
|
||||
|
||||
##### .typedArray(value)
|
||||
|
||||
##### .arrayLike(value)
|
||||
|
||||
A `value` is array-like if it is not a function and has a `value.length` that is a safe integer greater than or equal to 0.
|
||||
|
||||
```js
|
||||
is.arrayLike(document.forms);
|
||||
//=> true
|
||||
|
||||
function foo() {
|
||||
is.arrayLike(arguments);
|
||||
//=> true
|
||||
}
|
||||
foo();
|
||||
```
|
||||
|
||||
##### .inRange(value, range)
|
||||
|
||||
Check if `value` (number) is in the given `range`. The range is an array of two values, lower bound and upper bound, in no specific order.
|
||||
|
||||
```js
|
||||
is.inRange(3, [0, 5]);
|
||||
is.inRange(3, [5, 0]);
|
||||
is.inRange(0, [-2, 2]);
|
||||
```
|
||||
|
||||
##### .inRange(value, upperBound)
|
||||
|
||||
Check if `value` (number) is in the range of `0` to `upperBound`.
|
||||
|
||||
```js
|
||||
is.inRange(3, 10);
|
||||
```
|
||||
|
||||
##### .domElement(value)
|
||||
|
||||
Returns `true` if `value` is a DOM Element.
|
||||
|
||||
##### .nodeStream(value)
|
||||
|
||||
Returns `true` if `value` is a Node.js [stream](https://nodejs.org/api/stream.html).
|
||||
|
||||
```js
|
||||
const fs = require('fs');
|
||||
|
||||
is.nodeStream(fs.createReadStream('unicorn.png'));
|
||||
//=> true
|
||||
```
|
||||
|
||||
##### .observable(value)
|
||||
|
||||
Returns `true` if `value` is an `Observable`.
|
||||
|
||||
```js
|
||||
const {Observable} = require('rxjs');
|
||||
|
||||
is.observable(new Observable());
|
||||
//=> true
|
||||
```
|
||||
|
||||
##### .infinite(value)
|
||||
|
||||
Check if `value` is `Infinity` or `-Infinity`.
|
||||
|
||||
##### .evenInteger(value)
|
||||
|
||||
Returns `true` if `value` is an even integer.
|
||||
|
||||
##### .oddInteger(value)
|
||||
|
||||
Returns `true` if `value` is an odd integer.
|
||||
|
||||
##### .propertyKey(value)
|
||||
|
||||
Returns `true` if `value` can be used as an object property key (either `string`, `number`, or `symbol`).
|
||||
|
||||
##### .formData(value)
|
||||
|
||||
Returns `true` if `value` is an instance of the [`FormData` class](https://developer.mozilla.org/en-US/docs/Web/API/FormData).
|
||||
|
||||
```js
|
||||
const data = new FormData();
|
||||
|
||||
is.formData(data);
|
||||
//=> true
|
||||
```
|
||||
|
||||
##### .urlSearchParams(value)
|
||||
|
||||
Returns `true` if `value` is an instance of the [`URLSearchParams` class](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams).
|
||||
|
||||
```js
|
||||
const searchParams = new URLSearchParams();
|
||||
|
||||
is.urlSearchParams(searchParams);
|
||||
//=> true
|
||||
```
|
||||
|
||||
##### .any(predicate | predicate[], ...values)
|
||||
|
||||
Using a single `predicate` argument, returns `true` if **any** of the input `values` returns true in the `predicate`:
|
||||
|
||||
```js
|
||||
is.any(is.string, {}, true, '🦄');
|
||||
//=> true
|
||||
|
||||
is.any(is.boolean, 'unicorns', [], new Map());
|
||||
//=> false
|
||||
```
|
||||
|
||||
Using an array of `predicate[]`, returns `true` if **any** of the input `values` returns true for **any** of the `predicates` provided in an array:
|
||||
|
||||
```js
|
||||
is.any([is.string, is.number], {}, true, '🦄');
|
||||
//=> true
|
||||
|
||||
is.any([is.boolean, is.number], 'unicorns', [], new Map());
|
||||
//=> false
|
||||
```
|
||||
|
||||
##### .all(predicate, ...values)
|
||||
|
||||
Returns `true` if **all** of the input `values` returns true in the `predicate`:
|
||||
|
||||
```js
|
||||
is.all(is.object, {}, new Map(), new Set());
|
||||
//=> true
|
||||
|
||||
is.all(is.string, '🦄', [], 'unicorns');
|
||||
//=> false
|
||||
```
|
||||
|
||||
## Type guards
|
||||
|
||||
When using `is` together with TypeScript, [type guards](http://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types) are being used extensively to infer the correct type inside if-else statements.
|
||||
|
||||
```ts
|
||||
import is from '@sindresorhus/is';
|
||||
|
||||
const padLeft = (value: string, padding: string | number) => {
|
||||
if (is.number(padding)) {
|
||||
// `padding` is typed as `number`
|
||||
return Array(padding + 1).join(' ') + value;
|
||||
}
|
||||
|
||||
if (is.string(padding)) {
|
||||
// `padding` is typed as `string`
|
||||
return padding + value;
|
||||
}
|
||||
|
||||
throw new TypeError(`Expected 'padding' to be of type 'string' or 'number', got '${is(padding)}'.`);
|
||||
}
|
||||
|
||||
padLeft('🦄', 3);
|
||||
//=> ' 🦄'
|
||||
|
||||
padLeft('🦄', '🌈');
|
||||
//=> '🌈🦄'
|
||||
```
|
||||
|
||||
## Type assertions
|
||||
|
||||
The type guards are also available as [type assertions](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions), which throw an error for unexpected types. It is a convenient one-line version of the often repetitive "if-not-expected-type-throw" pattern.
|
||||
|
||||
```ts
|
||||
import {assert} from '@sindresorhus/is';
|
||||
|
||||
const handleMovieRatingApiResponse = (response: unknown) => {
|
||||
assert.plainObject(response);
|
||||
// `response` is now typed as a plain `object` with `unknown` properties.
|
||||
|
||||
assert.number(response.rating);
|
||||
// `response.rating` is now typed as a `number`.
|
||||
|
||||
assert.string(response.title);
|
||||
// `response.title` is now typed as a `string`.
|
||||
|
||||
return `${response.title} (${response.rating * 10})`;
|
||||
};
|
||||
|
||||
handleMovieRatingApiResponse({rating: 0.87, title: 'The Matrix'});
|
||||
//=> 'The Matrix (8.7)'
|
||||
|
||||
// This throws an error.
|
||||
handleMovieRatingApiResponse({rating: '🦄'});
|
||||
```
|
||||
|
||||
## Generic type parameters
|
||||
|
||||
The type guards and type assertions are aware of [generic type parameters](https://www.typescriptlang.org/docs/handbook/generics.html), such as `Promise<T>` and `Map<Key, Value>`. The default is `unknown` for most cases, since `is` cannot check them at runtime. If the generic type is known at compile-time, either implicitly (inferred) or explicitly (provided), `is` propagates the type so it can be used later.
|
||||
|
||||
Use generic type parameters with caution. They are only checked by the TypeScript compiler, and not checked by `is` at runtime. This can lead to unexpected behavior, where the generic type is _assumed_ at compile-time, but actually is something completely different at runtime. It is best to use `unknown` (default) and type-check the value of the generic type parameter at runtime with `is` or `assert`.
|
||||
|
||||
```ts
|
||||
import {assert} from '@sindresorhus/is';
|
||||
|
||||
async function badNumberAssumption(input: unknown) {
|
||||
// Bad assumption about the generic type parameter fools the compile-time type system.
|
||||
assert.promise<number>(input);
|
||||
// `input` is a `Promise` but only assumed to be `Promise<number>`.
|
||||
|
||||
const resolved = await input;
|
||||
// `resolved` is typed as `number` but was not actually checked at runtime.
|
||||
|
||||
// Multiplication will return NaN if the input promise did not actually contain a number.
|
||||
return 2 * resolved;
|
||||
}
|
||||
|
||||
async function goodNumberAssertion(input: unknown) {
|
||||
assert.promise(input);
|
||||
// `input` is typed as `Promise<unknown>`
|
||||
|
||||
const resolved = await input;
|
||||
// `resolved` is typed as `unknown`
|
||||
|
||||
assert.number(resolved);
|
||||
// `resolved` is typed as `number`
|
||||
|
||||
// Uses runtime checks so only numbers will reach the multiplication.
|
||||
return 2 * resolved;
|
||||
}
|
||||
|
||||
badNumberAssumption(Promise.resolve('An unexpected string'));
|
||||
//=> NaN
|
||||
|
||||
// This correctly throws an error because of the unexpected string value.
|
||||
goodNumberAssertion(Promise.resolve('An unexpected string'));
|
||||
```
|
||||
|
||||
## FAQ
|
||||
|
||||
### Why yet another type checking module?
|
||||
|
||||
There are hundreds of type checking modules on npm, unfortunately, I couldn't find any that fit my needs:
|
||||
|
||||
- Includes both type methods and ability to get the type
|
||||
- Types of primitives returned as lowercase and object types as camelcase
|
||||
- Covers all built-ins
|
||||
- Unsurprising behavior
|
||||
- Well-maintained
|
||||
- Comprehensive test suite
|
||||
|
||||
For the ones I found, pick 3 of these.
|
||||
|
||||
The most common mistakes I noticed in these modules was using `instanceof` for type checking, forgetting that functions are objects, and omitting `symbol` as a primitive.
|
||||
|
||||
### Why not just use `instanceof` instead of this package?
|
||||
|
||||
`instanceof` does not work correctly for all types and it does not work across [realms](https://stackoverflow.com/a/49832343/64949). Examples of realms are iframes, windows, web workers, and the `vm` module in Node.js.
|
||||
|
||||
## For enterprise
|
||||
|
||||
Available as part of the Tidelift Subscription.
|
||||
|
||||
The maintainers of @sindresorhus/is and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-sindresorhus-is?utm_source=npm-sindresorhus-is&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
|
||||
|
||||
## Related
|
||||
|
||||
- [ow](https://github.com/sindresorhus/ow) - Function argument validation for humans
|
||||
- [is-stream](https://github.com/sindresorhus/is-stream) - Check if something is a Node.js stream
|
||||
- [is-observable](https://github.com/sindresorhus/is-observable) - Check if a value is an Observable
|
||||
- [file-type](https://github.com/sindresorhus/file-type) - Detect the file type of a Buffer/Uint8Array
|
||||
- [is-ip](https://github.com/sindresorhus/is-ip) - Check if a string is an IP address
|
||||
- [is-array-sorted](https://github.com/sindresorhus/is-array-sorted) - Check if an Array is sorted
|
||||
- [is-error-constructor](https://github.com/sindresorhus/is-error-constructor) - Check if a value is an error constructor
|
||||
- [is-empty-iterable](https://github.com/sindresorhus/is-empty-iterable) - Check if an Iterable is empty
|
||||
- [is-blob](https://github.com/sindresorhus/is-blob) - Check if a value is a Blob - File-like object of immutable, raw data
|
||||
- [has-emoji](https://github.com/sindresorhus/has-emoji) - Check whether a string has any emoji
|
||||
|
||||
## Maintainers
|
||||
|
||||
- [Sindre Sorhus](https://github.com/sindresorhus)
|
||||
- [Giora Guttsait](https://github.com/gioragutt)
|
||||
- [Brandon Smith](https://github.com/brandon93s)
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2018 Szymon Marczak
|
||||
|
||||
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.
|
||||
-93
@@ -1,93 +0,0 @@
|
||||
# http-timer
|
||||
> Timings for HTTP requests
|
||||
|
||||
[](https://travis-ci.org/szmarczak/http-timer)
|
||||
[](https://coveralls.io/github/szmarczak/http-timer?branch=master)
|
||||
[](https://packagephobia.now.sh/result?p=@szmarczak/http-timer)
|
||||
|
||||
Inspired by the [`request` package](https://github.com/request/request).
|
||||
|
||||
## Installation
|
||||
|
||||
NPM:
|
||||
|
||||
> `npm install @szmarczak/http-timer`
|
||||
|
||||
Yarn:
|
||||
|
||||
> `yarn add @szmarczak/http-timer`
|
||||
|
||||
## Usage
|
||||
**Note:**
|
||||
> - The measured events resemble Node.js events, not the kernel ones.
|
||||
> - Sending a chunk greater than [`highWaterMark`](https://nodejs.org/api/stream.html#stream_new_stream_writable_options) will result in invalid `upload` and `response` timings. You can avoid this by splitting the payload into smaller chunks.
|
||||
|
||||
```js
|
||||
const https = require('https');
|
||||
const timer = require('@szmarczak/http-timer');
|
||||
|
||||
const request = https.get('https://httpbin.org/anything');
|
||||
timer(request);
|
||||
|
||||
request.once('response', response => {
|
||||
response.resume();
|
||||
response.once('end', () => {
|
||||
console.log(response.timings); // You can use `request.timings` as well
|
||||
});
|
||||
});
|
||||
|
||||
// {
|
||||
// start: 1572712180361,
|
||||
// socket: 1572712180362,
|
||||
// lookup: 1572712180415,
|
||||
// connect: 1572712180571,
|
||||
// upload: 1572712180884,
|
||||
// response: 1572712181037,
|
||||
// end: 1572712181039,
|
||||
// error: undefined,
|
||||
// abort: undefined,
|
||||
// phases: {
|
||||
// wait: 1,
|
||||
// dns: 53,
|
||||
// tcp: 156,
|
||||
// request: 313,
|
||||
// firstByte: 153,
|
||||
// download: 2,
|
||||
// total: 678
|
||||
// }
|
||||
// }
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
### timer(request)
|
||||
|
||||
Returns: `Object`
|
||||
|
||||
**Note**: The time is a `number` representing the milliseconds elapsed since the UNIX epoch.
|
||||
|
||||
- `start` - Time when the request started.
|
||||
- `socket` - Time when a socket was assigned to the request.
|
||||
- `lookup` - Time when the DNS lookup finished.
|
||||
- `connect` - Time when the socket successfully connected.
|
||||
- `secureConnect` - Time when the socket securely connected.
|
||||
- `upload` - Time when the request finished uploading.
|
||||
- `response` - Time when the request fired `response` event.
|
||||
- `end` - Time when the response fired `end` event.
|
||||
- `error` - Time when the request fired `error` event.
|
||||
- `abort` - Time when the request fired `abort` event.
|
||||
- `phases`
|
||||
- `wait` - `timings.socket - timings.start`
|
||||
- `dns` - `timings.lookup - timings.socket`
|
||||
- `tcp` - `timings.connect - timings.lookup`
|
||||
- `tls` - `timings.secureConnect - timings.connect`
|
||||
- `request` - `timings.upload - (timings.secureConnect || timings.connect)`
|
||||
- `firstByte` - `timings.response - timings.upload`
|
||||
- `download` - `timings.end - timings.response`
|
||||
- `total` - `(timings.end || timings.error || timings.abort) - timings.start`
|
||||
|
||||
If something has not been measured yet, it will be `undefined`.
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
/// <reference types="node" />
|
||||
import { ClientRequest, IncomingMessage } from 'http';
|
||||
export interface Timings {
|
||||
start: number;
|
||||
socket?: number;
|
||||
lookup?: number;
|
||||
connect?: number;
|
||||
secureConnect?: number;
|
||||
upload?: number;
|
||||
response?: number;
|
||||
end?: number;
|
||||
error?: number;
|
||||
abort?: number;
|
||||
phases: {
|
||||
wait?: number;
|
||||
dns?: number;
|
||||
tcp?: number;
|
||||
tls?: number;
|
||||
request?: number;
|
||||
firstByte?: number;
|
||||
download?: number;
|
||||
total?: number;
|
||||
};
|
||||
}
|
||||
export interface ClientRequestWithTimings extends ClientRequest {
|
||||
timings?: Timings;
|
||||
}
|
||||
export interface IncomingMessageWithTimings extends IncomingMessage {
|
||||
timings?: Timings;
|
||||
}
|
||||
declare const timer: (request: ClientRequestWithTimings) => Timings;
|
||||
export default timer;
|
||||
-126
@@ -1,126 +0,0 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const defer_to_connect_1 = require("defer-to-connect");
|
||||
const util_1 = require("util");
|
||||
const nodejsMajorVersion = Number(process.versions.node.split('.')[0]);
|
||||
const timer = (request) => {
|
||||
if (request.timings) {
|
||||
return request.timings;
|
||||
}
|
||||
const timings = {
|
||||
start: Date.now(),
|
||||
socket: undefined,
|
||||
lookup: undefined,
|
||||
connect: undefined,
|
||||
secureConnect: undefined,
|
||||
upload: undefined,
|
||||
response: undefined,
|
||||
end: undefined,
|
||||
error: undefined,
|
||||
abort: undefined,
|
||||
phases: {
|
||||
wait: undefined,
|
||||
dns: undefined,
|
||||
tcp: undefined,
|
||||
tls: undefined,
|
||||
request: undefined,
|
||||
firstByte: undefined,
|
||||
download: undefined,
|
||||
total: undefined
|
||||
}
|
||||
};
|
||||
request.timings = timings;
|
||||
const handleError = (origin) => {
|
||||
const emit = origin.emit.bind(origin);
|
||||
origin.emit = (event, ...args) => {
|
||||
// Catches the `error` event
|
||||
if (event === 'error') {
|
||||
timings.error = Date.now();
|
||||
timings.phases.total = timings.error - timings.start;
|
||||
origin.emit = emit;
|
||||
}
|
||||
// Saves the original behavior
|
||||
return emit(event, ...args);
|
||||
};
|
||||
};
|
||||
handleError(request);
|
||||
const onAbort = () => {
|
||||
timings.abort = Date.now();
|
||||
// Let the `end` response event be responsible for setting the total phase,
|
||||
// unless the Node.js major version is >= 13.
|
||||
if (!timings.response || nodejsMajorVersion >= 13) {
|
||||
timings.phases.total = Date.now() - timings.start;
|
||||
}
|
||||
};
|
||||
request.prependOnceListener('abort', onAbort);
|
||||
const onSocket = (socket) => {
|
||||
timings.socket = Date.now();
|
||||
timings.phases.wait = timings.socket - timings.start;
|
||||
if (util_1.types.isProxy(socket)) {
|
||||
return;
|
||||
}
|
||||
const lookupListener = () => {
|
||||
timings.lookup = Date.now();
|
||||
timings.phases.dns = timings.lookup - timings.socket;
|
||||
};
|
||||
socket.prependOnceListener('lookup', lookupListener);
|
||||
defer_to_connect_1.default(socket, {
|
||||
connect: () => {
|
||||
timings.connect = Date.now();
|
||||
if (timings.lookup === undefined) {
|
||||
socket.removeListener('lookup', lookupListener);
|
||||
timings.lookup = timings.connect;
|
||||
timings.phases.dns = timings.lookup - timings.socket;
|
||||
}
|
||||
timings.phases.tcp = timings.connect - timings.lookup;
|
||||
// This callback is called before flushing any data,
|
||||
// so we don't need to set `timings.phases.request` here.
|
||||
},
|
||||
secureConnect: () => {
|
||||
timings.secureConnect = Date.now();
|
||||
timings.phases.tls = timings.secureConnect - timings.connect;
|
||||
}
|
||||
});
|
||||
};
|
||||
if (request.socket) {
|
||||
onSocket(request.socket);
|
||||
}
|
||||
else {
|
||||
request.prependOnceListener('socket', onSocket);
|
||||
}
|
||||
const onUpload = () => {
|
||||
var _a;
|
||||
timings.upload = Date.now();
|
||||
timings.phases.request = timings.upload - ((_a = timings.secureConnect) !== null && _a !== void 0 ? _a : timings.connect);
|
||||
};
|
||||
const writableFinished = () => {
|
||||
if (typeof request.writableFinished === 'boolean') {
|
||||
return request.writableFinished;
|
||||
}
|
||||
// Node.js doesn't have `request.writableFinished` property
|
||||
return request.finished && request.outputSize === 0 && (!request.socket || request.socket.writableLength === 0);
|
||||
};
|
||||
if (writableFinished()) {
|
||||
onUpload();
|
||||
}
|
||||
else {
|
||||
request.prependOnceListener('finish', onUpload);
|
||||
}
|
||||
request.prependOnceListener('response', (response) => {
|
||||
timings.response = Date.now();
|
||||
timings.phases.firstByte = timings.response - timings.upload;
|
||||
response.timings = timings;
|
||||
handleError(response);
|
||||
response.prependOnceListener('end', () => {
|
||||
timings.end = Date.now();
|
||||
timings.phases.download = timings.end - timings.response;
|
||||
timings.phases.total = timings.end - timings.start;
|
||||
});
|
||||
response.prependOnceListener('aborted', onAbort);
|
||||
});
|
||||
return timings;
|
||||
};
|
||||
exports.default = timer;
|
||||
// For CommonJS default export support
|
||||
module.exports = timer;
|
||||
module.exports.default = timer;
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
{
|
||||
"name": "@szmarczak/http-timer",
|
||||
"version": "4.0.6",
|
||||
"description": "Timings for HTTP requests",
|
||||
"main": "dist/source",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "xo && tsc --noEmit && nyc ava",
|
||||
"build": "del-cli dist && tsc",
|
||||
"prepare": "npm run build",
|
||||
"coveralls": "nyc report --reporter=text-lcov | coveralls"
|
||||
},
|
||||
"files": [
|
||||
"dist/source"
|
||||
],
|
||||
"keywords": [
|
||||
"http",
|
||||
"https",
|
||||
"timer",
|
||||
"timings"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/szmarczak/http-timer.git"
|
||||
},
|
||||
"author": "Szymon Marczak",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/szmarczak/http-timer/issues"
|
||||
},
|
||||
"homepage": "https://github.com/szmarczak/http-timer#readme",
|
||||
"dependencies": {
|
||||
"defer-to-connect": "^2.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@ava/typescript": "^2.0.0",
|
||||
"@sindresorhus/tsconfig": "^1.0.2",
|
||||
"@types/node": "^16.3.1",
|
||||
"ava": "^3.15.0",
|
||||
"coveralls": "^3.1.1",
|
||||
"del-cli": "^3.0.1",
|
||||
"http2-wrapper": "^2.0.7",
|
||||
"nyc": "^15.1.0",
|
||||
"p-event": "^4.2.0",
|
||||
"typescript": "^4.3.5",
|
||||
"xo": "^0.39.1"
|
||||
},
|
||||
"types": "dist/source",
|
||||
"nyc": {
|
||||
"extension": [
|
||||
".ts"
|
||||
],
|
||||
"exclude": [
|
||||
"**/tests/**"
|
||||
]
|
||||
},
|
||||
"xo": {
|
||||
"rules": {
|
||||
"@typescript-eslint/no-non-null-assertion": "off"
|
||||
}
|
||||
},
|
||||
"ava": {
|
||||
"typescript": {
|
||||
"compile": false,
|
||||
"rewritePaths": {
|
||||
"tests/": "dist/tests/"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
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
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
# Installation
|
||||
> `npm install --save @types/cacheable-request`
|
||||
|
||||
# Summary
|
||||
This package contains type definitions for cacheable-request (https://github.com/lukechilds/cacheable-request#readme).
|
||||
|
||||
# Details
|
||||
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cacheable-request.
|
||||
|
||||
### Additional Details
|
||||
* Last updated: Wed, 09 Nov 2022 16:32:53 GMT
|
||||
* Dependencies: [@types/http-cache-semantics](https://npmjs.com/package/@types/http-cache-semantics), [@types/keyv](https://npmjs.com/package/@types/keyv), [@types/node](https://npmjs.com/package/@types/node), [@types/responselike](https://npmjs.com/package/@types/responselike)
|
||||
* Global values: none
|
||||
|
||||
# Credits
|
||||
These definitions were written by [BendingBender](https://github.com/BendingBender), and [Paul Melnikow](https://github.com/paulmelnikow).
|
||||
-137
@@ -1,137 +0,0 @@
|
||||
// Type definitions for cacheable-request 6.0
|
||||
// Project: https://github.com/lukechilds/cacheable-request#readme
|
||||
// Definitions by: BendingBender <https://github.com/BendingBender>
|
||||
// Paul Melnikow <https://github.com/paulmelnikow>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.3
|
||||
|
||||
/// <reference types="node" />
|
||||
|
||||
import { request, RequestOptions, ClientRequest, ServerResponse } from 'http';
|
||||
import { URL } from 'url';
|
||||
import { EventEmitter } from 'events';
|
||||
import { Store } from 'keyv';
|
||||
import { Options as CacheSemanticsOptions } from 'http-cache-semantics';
|
||||
import ResponseLike = require('responselike');
|
||||
|
||||
export = CacheableRequest;
|
||||
|
||||
declare const CacheableRequest: CacheableRequest;
|
||||
|
||||
type RequestFn = typeof request;
|
||||
|
||||
interface CacheableRequest {
|
||||
new (requestFn: RequestFn, storageAdapter?: string | CacheableRequest.StorageAdapter): (
|
||||
opts: string | URL | (RequestOptions & CacheSemanticsOptions),
|
||||
cb?: (response: ServerResponse | ResponseLike) => void
|
||||
) => CacheableRequest.Emitter;
|
||||
|
||||
RequestError: typeof RequestErrorCls;
|
||||
CacheError: typeof CacheErrorCls;
|
||||
}
|
||||
|
||||
declare namespace CacheableRequest {
|
||||
type StorageAdapter = Store<any>;
|
||||
|
||||
interface Options {
|
||||
/**
|
||||
* If the cache should be used. Setting this to `false` will completely bypass the cache for the current request.
|
||||
* @default true
|
||||
*/
|
||||
cache?: boolean | undefined;
|
||||
|
||||
/**
|
||||
* If set to `true` once a cached resource has expired it is deleted and will have to be re-requested.
|
||||
*
|
||||
* If set to `false`, after a cached resource's TTL expires it is kept in the cache and will be revalidated
|
||||
* on the next request with `If-None-Match`/`If-Modified-Since` headers.
|
||||
* @default false
|
||||
*/
|
||||
strictTtl?: boolean | undefined;
|
||||
|
||||
/**
|
||||
* Limits TTL. The `number` represents milliseconds.
|
||||
* @default undefined
|
||||
*/
|
||||
maxTtl?: number | undefined;
|
||||
|
||||
/**
|
||||
* When set to `true`, if the DB connection fails we will automatically fallback to a network request.
|
||||
* DB errors will still be emitted to notify you of the problem even though the request callback may succeed.
|
||||
* @default false
|
||||
*/
|
||||
automaticFailover?: boolean | undefined;
|
||||
|
||||
/**
|
||||
* Forces refreshing the cache. If the response could be retrieved from the cache, it will perform a
|
||||
* new request and override the cache instead.
|
||||
* @default false
|
||||
*/
|
||||
forceRefresh?: boolean | undefined;
|
||||
}
|
||||
|
||||
interface Emitter extends EventEmitter {
|
||||
addListener(event: 'request', listener: (request: ClientRequest) => void): this;
|
||||
addListener(
|
||||
event: 'response',
|
||||
listener: (response: ServerResponse | ResponseLike) => void
|
||||
): this;
|
||||
addListener(event: 'error', listener: (error: RequestError | CacheError) => void): this;
|
||||
on(event: 'request', listener: (request: ClientRequest) => void): this;
|
||||
on(event: 'response', listener: (response: ServerResponse | ResponseLike) => void): this;
|
||||
on(event: 'error', listener: (error: RequestError | CacheError) => void): this;
|
||||
once(event: 'request', listener: (request: ClientRequest) => void): this;
|
||||
once(event: 'response', listener: (response: ServerResponse | ResponseLike) => void): this;
|
||||
once(event: 'error', listener: (error: RequestError | CacheError) => void): this;
|
||||
prependListener(event: 'request', listener: (request: ClientRequest) => void): this;
|
||||
prependListener(
|
||||
event: 'response',
|
||||
listener: (response: ServerResponse | ResponseLike) => void
|
||||
): this;
|
||||
prependListener(event: 'error', listener: (error: RequestError | CacheError) => void): this;
|
||||
prependOnceListener(event: 'request', listener: (request: ClientRequest) => void): this;
|
||||
prependOnceListener(
|
||||
event: 'response',
|
||||
listener: (response: ServerResponse | ResponseLike) => void
|
||||
): this;
|
||||
prependOnceListener(
|
||||
event: 'error',
|
||||
listener: (error: RequestError | CacheError) => void
|
||||
): this;
|
||||
removeListener(event: 'request', listener: (request: ClientRequest) => void): this;
|
||||
removeListener(
|
||||
event: 'response',
|
||||
listener: (response: ServerResponse | ResponseLike) => void
|
||||
): this;
|
||||
removeListener(event: 'error', listener: (error: RequestError | CacheError) => void): this;
|
||||
off(event: 'request', listener: (request: ClientRequest) => void): this;
|
||||
off(event: 'response', listener: (response: ServerResponse | ResponseLike) => void): this;
|
||||
off(event: 'error', listener: (error: RequestError | CacheError) => void): this;
|
||||
removeAllListeners(event?: 'request' | 'response' | 'error'): this;
|
||||
listeners(event: 'request'): Array<(request: ClientRequest) => void>;
|
||||
listeners(event: 'response'): Array<(response: ServerResponse | ResponseLike) => void>;
|
||||
listeners(event: 'error'): Array<(error: RequestError | CacheError) => void>;
|
||||
rawListeners(event: 'request'): Array<(request: ClientRequest) => void>;
|
||||
rawListeners(event: 'response'): Array<(response: ServerResponse | ResponseLike) => void>;
|
||||
rawListeners(event: 'error'): Array<(error: RequestError | CacheError) => void>;
|
||||
emit(event: 'request', request: ClientRequest): boolean;
|
||||
emit(event: 'response', response: ServerResponse | ResponseLike): boolean;
|
||||
emit(event: 'error', error: RequestError | CacheError): boolean;
|
||||
eventNames(): Array<'request' | 'response' | 'error'>;
|
||||
listenerCount(type: 'request' | 'response' | 'error'): number;
|
||||
}
|
||||
|
||||
type RequestError = RequestErrorCls;
|
||||
type CacheError = CacheErrorCls;
|
||||
}
|
||||
|
||||
declare class RequestErrorCls extends Error {
|
||||
readonly name: 'RequestError';
|
||||
|
||||
constructor(error: Error);
|
||||
}
|
||||
declare class CacheErrorCls extends Error {
|
||||
readonly name: 'CacheError';
|
||||
|
||||
constructor(error: Error);
|
||||
}
|
||||
-35
@@ -1,35 +0,0 @@
|
||||
{
|
||||
"name": "@types/cacheable-request",
|
||||
"version": "6.0.3",
|
||||
"description": "TypeScript definitions for cacheable-request",
|
||||
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cacheable-request",
|
||||
"license": "MIT",
|
||||
"contributors": [
|
||||
{
|
||||
"name": "BendingBender",
|
||||
"url": "https://github.com/BendingBender",
|
||||
"githubUsername": "BendingBender"
|
||||
},
|
||||
{
|
||||
"name": "Paul Melnikow",
|
||||
"url": "https://github.com/paulmelnikow",
|
||||
"githubUsername": "paulmelnikow"
|
||||
}
|
||||
],
|
||||
"main": "",
|
||||
"types": "index.d.ts",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
|
||||
"directory": "types/cacheable-request"
|
||||
},
|
||||
"scripts": {},
|
||||
"dependencies": {
|
||||
"@types/http-cache-semantics": "*",
|
||||
"@types/keyv": "^3.1.4",
|
||||
"@types/node": "*",
|
||||
"@types/responselike": "^1.0.0"
|
||||
},
|
||||
"typesPublisherContentHash": "9345f1216c9d26f9046880c34f6329b2874405d68cf13d1f1f771fbb4d96549f",
|
||||
"typeScriptVersion": "4.1"
|
||||
}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
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
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
# Installation
|
||||
> `npm install --save @types/debug`
|
||||
|
||||
# Summary
|
||||
This package contains type definitions for debug (https://github.com/debug-js/debug).
|
||||
|
||||
# Details
|
||||
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/debug.
|
||||
## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/debug/index.d.ts)
|
||||
````ts
|
||||
declare var debug: debug.Debug & { debug: debug.Debug; default: debug.Debug };
|
||||
|
||||
export = debug;
|
||||
export as namespace debug;
|
||||
|
||||
declare namespace debug {
|
||||
interface Debug {
|
||||
(namespace: string): Debugger;
|
||||
coerce: (val: any) => any;
|
||||
disable: () => string;
|
||||
enable: (namespaces: string) => void;
|
||||
enabled: (namespaces: string) => boolean;
|
||||
formatArgs: (this: Debugger, args: any[]) => void;
|
||||
log: (...args: any[]) => any;
|
||||
selectColor: (namespace: string) => string | number;
|
||||
humanize: typeof import("ms");
|
||||
|
||||
names: string[];
|
||||
skips: string[];
|
||||
|
||||
formatters: Formatters;
|
||||
|
||||
inspectOpts?: {
|
||||
hideDate?: boolean | number | null;
|
||||
colors?: boolean | number | null;
|
||||
depth?: boolean | number | null;
|
||||
showHidden?: boolean | number | null;
|
||||
};
|
||||
}
|
||||
|
||||
type IDebug = Debug;
|
||||
|
||||
interface Formatters {
|
||||
[formatter: string]: (v: any) => string;
|
||||
}
|
||||
|
||||
type IDebugger = Debugger;
|
||||
|
||||
interface Debugger {
|
||||
(formatter: any, ...args: any[]): void;
|
||||
|
||||
color: string;
|
||||
diff: number;
|
||||
enabled: boolean;
|
||||
log: (...args: any[]) => any;
|
||||
namespace: string;
|
||||
destroy: () => boolean;
|
||||
extend: (namespace: string, delimiter?: string) => Debugger;
|
||||
}
|
||||
}
|
||||
|
||||
````
|
||||
|
||||
### Additional Details
|
||||
* Last updated: Thu, 19 Mar 2026 06:47:22 GMT
|
||||
* Dependencies: [@types/ms](https://npmjs.com/package/@types/ms)
|
||||
|
||||
# Credits
|
||||
These definitions were written by [Seon-Wook Park](https://github.com/swook), [Gal Talmor](https://github.com/galtalmor), [John McLaughlin](https://github.com/zamb3zi), [Brasten Sager](https://github.com/brasten), [Nicolas Penin](https://github.com/npenin), [Kristian Brünn](https://github.com/kristianmitk), and [Caleb Gregory](https://github.com/calebgregory).
|
||||
-50
@@ -1,50 +0,0 @@
|
||||
declare var debug: debug.Debug & { debug: debug.Debug; default: debug.Debug };
|
||||
|
||||
export = debug;
|
||||
export as namespace debug;
|
||||
|
||||
declare namespace debug {
|
||||
interface Debug {
|
||||
(namespace: string): Debugger;
|
||||
coerce: (val: any) => any;
|
||||
disable: () => string;
|
||||
enable: (namespaces: string) => void;
|
||||
enabled: (namespaces: string) => boolean;
|
||||
formatArgs: (this: Debugger, args: any[]) => void;
|
||||
log: (...args: any[]) => any;
|
||||
selectColor: (namespace: string) => string | number;
|
||||
humanize: typeof import("ms");
|
||||
|
||||
names: string[];
|
||||
skips: string[];
|
||||
|
||||
formatters: Formatters;
|
||||
|
||||
inspectOpts?: {
|
||||
hideDate?: boolean | number | null;
|
||||
colors?: boolean | number | null;
|
||||
depth?: boolean | number | null;
|
||||
showHidden?: boolean | number | null;
|
||||
};
|
||||
}
|
||||
|
||||
type IDebug = Debug;
|
||||
|
||||
interface Formatters {
|
||||
[formatter: string]: (v: any) => string;
|
||||
}
|
||||
|
||||
type IDebugger = Debugger;
|
||||
|
||||
interface Debugger {
|
||||
(formatter: any, ...args: any[]): void;
|
||||
|
||||
color: string;
|
||||
diff: number;
|
||||
enabled: boolean;
|
||||
log: (...args: any[]) => any;
|
||||
namespace: string;
|
||||
destroy: () => boolean;
|
||||
extend: (namespace: string, delimiter?: string) => Debugger;
|
||||
}
|
||||
}
|
||||
-58
@@ -1,58 +0,0 @@
|
||||
{
|
||||
"name": "@types/debug",
|
||||
"version": "4.1.13",
|
||||
"description": "TypeScript definitions for debug",
|
||||
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/debug",
|
||||
"license": "MIT",
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Seon-Wook Park",
|
||||
"githubUsername": "swook",
|
||||
"url": "https://github.com/swook"
|
||||
},
|
||||
{
|
||||
"name": "Gal Talmor",
|
||||
"githubUsername": "galtalmor",
|
||||
"url": "https://github.com/galtalmor"
|
||||
},
|
||||
{
|
||||
"name": "John McLaughlin",
|
||||
"githubUsername": "zamb3zi",
|
||||
"url": "https://github.com/zamb3zi"
|
||||
},
|
||||
{
|
||||
"name": "Brasten Sager",
|
||||
"githubUsername": "brasten",
|
||||
"url": "https://github.com/brasten"
|
||||
},
|
||||
{
|
||||
"name": "Nicolas Penin",
|
||||
"githubUsername": "npenin",
|
||||
"url": "https://github.com/npenin"
|
||||
},
|
||||
{
|
||||
"name": "Kristian Brünn",
|
||||
"githubUsername": "kristianmitk",
|
||||
"url": "https://github.com/kristianmitk"
|
||||
},
|
||||
{
|
||||
"name": "Caleb Gregory",
|
||||
"githubUsername": "calebgregory",
|
||||
"url": "https://github.com/calebgregory"
|
||||
}
|
||||
],
|
||||
"main": "",
|
||||
"types": "index.d.ts",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
|
||||
"directory": "types/debug"
|
||||
},
|
||||
"scripts": {},
|
||||
"dependencies": {
|
||||
"@types/ms": "*"
|
||||
},
|
||||
"peerDependencies": {},
|
||||
"typesPublisherContentHash": "1c506e100366b85350ff1c28c9cf4cc09e9a07275546bb050993c241c9821cd9",
|
||||
"typeScriptVersion": "5.2"
|
||||
}
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
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
|
||||
Reference in New Issue
Block a user