parse-tmx
Version:
1,653 lines (1,628 loc) • 1.61 MB
JavaScript
import { InvalidOperationError, Operation, exhaustiveGuard, takeOne } from "@esposter/shared";
import { gunzip, inflate } from "node:zlib";
//#region \0rolldown/runtime.js
var __create = Object.create;
var __defProp$1 = Object.defineProperty;
var __getOwnPropDesc$1 = Object.getOwnPropertyDescriptor;
var __getOwnPropNames$1 = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp$1 = Object.prototype.hasOwnProperty;
var __esmMin$1 = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
var __commonJSMin$1 = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __exportAll$1 = (all, no_symbols) => {
let target = {};
for (var name in all) {
__defProp$1(target, name, {
get: all[name],
enumerable: true
});
}
if (!no_symbols) {
__defProp$1(target, Symbol.toStringTag, { value: "Module" });
}
return target;
};
var __copyProps$1 = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (var keys = __getOwnPropNames$1(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp$1.call(to, key) && key !== except) {
__defProp$1(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc$1(from, key)) || desc.enumerable
});
}
}
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps$1(isNodeMode || !mod || !mod.__esModule ? __defProp$1(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
var __toCommonJS$1 = (mod) => __hasOwnProp$1.call(mod, "module.exports") ? mod["module.exports"] : __copyProps$1(__defProp$1({}, "__esModule", { value: true }), mod);
//#endregion
//#region src/models/tmx/node/TMXNodeType.ts
let TMXNodeType = /* @__PURE__ */ function(TMXNodeType) {
TMXNodeType["Data"] = "data";
TMXNodeType["EditorSettings"] = "editorsettings";
TMXNodeType["Export"] = "export";
TMXNodeType["Group"] = "group";
TMXNodeType["Image"] = "image";
TMXNodeType["ImageLayer"] = "imagelayer";
TMXNodeType["Layer"] = "layer";
TMXNodeType["Object"] = "object";
TMXNodeType["Objectgroup"] = "objectgroup";
TMXNodeType["Properties"] = "properties";
TMXNodeType["Property"] = "property";
TMXNodeType["Tileset"] = "tileset";
return TMXNodeType;
}({});
//#endregion
//#region src/models/tmx/shared/TMXMapShared.ts
var TMXMapShared = class {
height = 0;
infinite = 0;
nextlayerid = 0;
nextobjectid = 0;
orientation = "";
renderorder = "";
tiledversion = "";
tileheight = 0;
tilewidth = 0;
version = 0;
width = 0;
};
//#endregion
//#region src/models/tmx/parsed/TMXMapParsed.ts
var TMXMapParsed = class extends TMXMapShared {
editorsettings = {};
layers = [];
properties = [];
tilesets = [];
constructor(init) {
super();
Object.assign(this, init);
}
};
//#endregion
//#region src/models/tmx/parsed/TMXParsed.ts
var TMXParsed = class {
map = new TMXMapParsed();
constructor(map) {
if (map) this.map = map;
}
};
//#endregion
//#region src/util/parseGroup.ts
const parseGroup = async (node, expectedCount, translateFlips) => {
const { $, $$ } = node;
const group = structuredClone($);
group.type = node["#name"];
group.layers = await Promise.all($$.map((l) => parseNode(l, expectedCount, translateFlips)));
return group;
};
//#endregion
//#region src/models/Flipped.ts
let Flipped = /* @__PURE__ */ function(Flipped) {
Flipped[Flipped["Diagonally"] = 536870912] = "Diagonally";
Flipped[Flipped["Vertically"] = 1073741824] = "Vertically";
Flipped[Flipped["Horizontally"] = 2147483648] = "Horizontally";
return Flipped;
}({});
//#endregion
//#region src/util/parseFlips.ts
const parseFlips = (gid) => ({
Diagonal: Boolean(gid & Flipped.Diagonally),
Horizontal: Boolean(gid & Flipped.Horizontally),
Vertical: Boolean(gid & Flipped.Vertically)
});
//#endregion
//#region src/models/Shape.ts
let Shape = /* @__PURE__ */ function(Shape) {
Shape["Ellipse"] = "ellipse";
Shape["Point"] = "point";
Shape["Polygon"] = "polygon";
Shape["Rectangle"] = "rectangle";
return Shape;
}({});
//#endregion
//#region src/util/parseObjectShape.ts
const parseObjectShape = (node) => {
if ("point" in node) return Shape.Point;
else if ("ellipse" in node) return Shape.Ellipse;
else if ("polygon" in node) return Shape.Polygon;
else return Shape.Rectangle;
};
//#endregion
//#region src/util/parseProperties.ts
const parseProperties = (properties) => properties.map(({ property }) => {
const { $, _ } = takeOne(property);
const { name, value } = $;
return {
name,
value: value ?? _
};
});
//#endregion
//#region src/util/parseTileId.ts
const parseTileId = (gid) => gid &= ~Object.values(Flipped).reduce((acc, curr) => acc | curr, 0);
//#endregion
//#region src/util/parseObject.ts
const parseObject = (node) => {
const { $, polygon, properties, text } = node;
const object = structuredClone($);
object.shape = parseObjectShape(node);
if (properties) object.properties = parseProperties(properties);
if (polygon) object.points = takeOne(polygon).$.points.split(" ").map((point) => {
const points = point.split(",");
const x = takeOne(points);
const y = takeOne(points, 1);
return [parseFloat(x), parseFloat(y)];
});
if (text) {
const textNode = takeOne(text);
object.text = textNode._;
object.properties = Object.assign({}, ...object.properties ?? [], textNode.$);
}
if (object.gid) {
object.flips = parseFlips(object.gid);
object.gid = parseTileId(object.gid);
}
return object;
};
//#endregion
//#region src/util/parseLayer.ts
const parseLayer = (node) => {
const { $, image, object, properties } = node;
const layer = structuredClone($);
layer.type = node["#name"];
layer.visible = 1;
if (image) layer.image = structuredClone(takeOne(image).$);
if (object) layer.objects = object.map((o) => parseObject(o));
if (properties) layer.properties = parseProperties(properties);
return layer;
};
//#endregion
//#region src/models/Compression.ts
let Compression = /* @__PURE__ */ function(Compression) {
Compression["Gzip"] = "gzip";
Compression["Zlib"] = "zlib";
return Compression;
}({});
//#endregion
//#region src/models/Encoding.ts
let Encoding = /* @__PURE__ */ function(Encoding) {
Encoding["Base64"] = "base64";
Encoding["Csv"] = "csv";
return Encoding;
}({});
//#endregion
//#region src/util/isTMXEmbeddedTilesetNode.ts
const isTMXEmbeddedTilesetNode = (node) => "tile" in node;
//#endregion
//#region src/util/unpackTileBytes.ts
const unpackTileBytes = (buffer, expectedCount) => {
const unpackedTiles = [];
if (buffer.length !== expectedCount) throw new Error(`Expected ${expectedCount} bytes of tile data; received ${buffer.length}`);
for (let i = 0; i < expectedCount; i += 4) unpackedTiles.push(buffer.readUInt32LE(i));
return unpackedTiles;
};
//#endregion
//#region src/util/parseTileLayer.ts
const parseTileLayer = async (node, expectedCount, translateFlips) => {
const { data, properties } = node;
if (!data) throw new Error("TMXLayer data corrupted!");
const layer = structuredClone(node.$);
layer.type = node["#name"];
if (properties) layer.properties = parseProperties(properties);
const nodeData = takeOne(data);
if (isTMXEmbeddedTilesetNode(nodeData)) layer.data = nodeData.tile?.map(({ $ }) => $.gid ?? 0) ?? [];
else {
const { $, _ } = nodeData;
const { compression, encoding } = $;
const layerData = _.trim();
switch (encoding) {
case Encoding.Base64: {
const buffer = Buffer.from(layerData, encoding);
switch (compression) {
case Compression.Gzip:
case Compression.Zlib:
{
const decompress = compression === Compression.Gzip ? gunzip : inflate;
layer.data = await new Promise((resolve, reject) => {
decompress(buffer, (err, buf) => {
if (err) {
reject(err);
return;
}
resolve(unpackTileBytes(buf, expectedCount));
});
});
}
break;
case void 0:
layer.data = unpackTileBytes(buffer, expectedCount);
break;
default: exhaustiveGuard(compression);
}
break;
}
case Encoding.Csv:
layer.data = layerData.split(",").map((d) => parseInt(d));
break;
default: exhaustiveGuard(encoding);
}
}
if (translateFlips) {
layer.flips = [];
layer.data ??= [];
for (const gid of layer.data) {
layer.flips.push(parseFlips(gid));
layer.data.push(parseTileId(gid));
}
}
return layer;
};
//#endregion
//#region src/util/parseNode.ts
const parseNode = (node, expectedCount, translateFlips) => {
const tmxNodeType = node["#name"];
switch (tmxNodeType) {
case TMXNodeType.Group: return parseGroup(node, expectedCount, translateFlips);
case TMXNodeType.ImageLayer:
case TMXNodeType.Objectgroup: return Promise.resolve(parseLayer(node));
case TMXNodeType.Layer: return parseTileLayer(node, expectedCount, translateFlips);
default: throw new InvalidOperationError(Operation.Read, parseNode.name, tmxNodeType);
}
};
//#endregion
//#region src/util/isExternalTileset.ts
const isExternalTileset = (tileset) => "source" in tileset;
//#endregion
//#region src/util/parseTile.ts
const parseTile = (node) => {
const { $, animation, objectgroup, properties } = node;
const tile = structuredClone($);
if (animation) tile.animation = { frames: takeOne(takeOne(animation), "frame").map(({ $ }) => structuredClone($)) };
if (objectgroup) tile.objects = takeOne(takeOne(objectgroup), "object").map((o) => parseObject(o));
if (properties) tile.properties = parseProperties(properties);
return tile;
};
//#endregion
//#region src/util/parseTileset.ts
const parseTileset = (node) => {
if (isExternalTileset(node.$)) return structuredClone(node.$);
const { $, $$, tile } = node;
for (const childNode of $$) {
if (childNode["#name"] !== TMXNodeType.Image) continue;
const image = structuredClone(childNode.$);
const tiles = tile?.map((t) => parseTile(t)) ?? [];
return {
...$,
image,
tiles
};
}
throw new InvalidOperationError(Operation.Read, parseTileset.name, $.name);
};
//#endregion
//#region src/util/parseXmlValue.ts
const parseXmlValue = (value) => {
if (value === "true") return true;
if (value === "false") return false;
if (/^[+-]?\d+(\.\d+)?$/g.test(value)) {
const parsedValue = parseFloat(value);
return isNaN(parsedValue) ? value : parsedValue;
}
return value;
};
//#endregion
//#region ../xml2js/dist/index.js
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __esmMin = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __exportAll = (all, no_symbols) => {
let target = {};
for (var name in all) __defProp(target, name, {
get: all[name],
enumerable: true
});
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
return target;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
const DefaultCommonOptions = {
attrkey: "$",
charkey: "_"
};
const DefaultBuilderOptions = {
...DefaultCommonOptions,
cdata: false,
doctype: null,
renderOpts: {
indent: " ",
newline: "\n",
pretty: true
},
rootName: "root",
xmldec: {
encoding: "utf8",
standalone: true,
version: "1.0"
}
};
var require_interfaces$3 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.DefaultXMLBuilderCBOptions = exports.XMLBuilderOptionKeys = exports.DefaultBuilderOptions = void 0;
/**
* Defines default values for builder options.
*/
exports.DefaultBuilderOptions = {
version: "1.0",
encoding: void 0,
standalone: void 0,
keepNullNodes: false,
keepNullAttributes: false,
ignoreConverters: false,
skipWhitespaceOnlyText: true,
convert: {
att: "@",
ins: "?",
text: "#",
cdata: "$",
comment: "!"
},
defaultNamespace: {
ele: void 0,
att: void 0
},
namespaceAlias: {
html: "http://www.w3.org/1999/xhtml",
xml: "http://www.w3.org/XML/1998/namespace",
xmlns: "http://www.w3.org/2000/xmlns/",
mathml: "http://www.w3.org/1998/Math/MathML",
svg: "http://www.w3.org/2000/svg",
xlink: "http://www.w3.org/1999/xlink"
},
invalidCharReplacement: void 0,
parser: void 0
};
/**
* Contains keys of `XMLBuilderOptions`.
*/
exports.XMLBuilderOptionKeys = new Set(Object.keys(exports.DefaultBuilderOptions));
/**
* Defines default values for builder options.
*/
exports.DefaultXMLBuilderCBOptions = {
format: "xml",
wellFormed: false,
prettyPrint: false,
indent: " ",
newline: "\n",
offset: 0,
width: 0,
allowEmptyTags: false,
spaceBeforeSlash: false,
keepNullNodes: false,
keepNullAttributes: false,
ignoreConverters: false,
convert: {
att: "@",
ins: "?",
text: "#",
cdata: "$",
comment: "!"
},
defaultNamespace: {
ele: void 0,
att: void 0
},
namespaceAlias: {
html: "http://www.w3.org/1999/xhtml",
xml: "http://www.w3.org/XML/1998/namespace",
xmlns: "http://www.w3.org/2000/xmlns/",
mathml: "http://www.w3.org/1998/Math/MathML",
svg: "http://www.w3.org/2000/svg",
xlink: "http://www.w3.org/1999/xlink"
}
};
}));
var require_FixedSizeSet = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.FixedSizeSet = void 0;
/**
* Represents a set of objects with a size limit.
*/
var FixedSizeSet = class {
_limit;
_items = /* @__PURE__ */ new Set();
/**
* Initializes a new instance of `FixedSizeSet`.
*
* @param limit - maximum number of items to keep in the set. When the limit
* is exceeded the first item is removed from the set.
*/
constructor(limit = 1e3) {
this._limit = limit;
}
/**
* Adds a new item to the set.
*
* @param item - an item
*/
add(item) {
this._items.add(item);
if (this._items.size > this._limit) {
const it = this._items.values().next();
/* istanbul ignore else */
if (!it.done) this._items.delete(it.value);
}
return this;
}
/**
* Removes an item from the set.
*
* @param item - an item
*/
delete(item) {
return this._items.delete(item);
}
/**
* Determines if an item is in the set.
*
* @param item - an item
*/
has(item) {
return this._items.has(item);
}
/**
* Removes all items from the set.
*/
clear() {
this._items.clear();
}
/**
* Gets the number of items in the set.
*/
get size() {
return this._items.size;
}
/**
* Applies the given callback function to all elements of the set.
*/
forEach(callback, thisArg) {
this._items.forEach((e) => callback.call(thisArg, e, e, this));
}
/**
* Iterates through the items in the set.
*/
*keys() {
yield* this._items.keys();
}
/**
* Iterates through the items in the set.
*/
*values() {
yield* this._items.values();
}
/**
* Iterates through the items in the set.
*/
*entries() {
yield* this._items.entries();
}
/**
* Iterates through the items in the set.
*/
*[Symbol.iterator]() {
yield* this._items;
}
/**
* Returns the string tag of the set.
*/
get [Symbol.toStringTag]() {
return "FixedSizeSet";
}
};
exports.FixedSizeSet = FixedSizeSet;
}));
var require_ObjectCache = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.ObjectCache = void 0;
/**
* Represents a cache of objects with a size limit.
*/
var ObjectCache = class {
_limit;
_items = /* @__PURE__ */ new Map();
/**
* Initializes a new instance of `ObjectCache`.
*
* @param limit - maximum number of items to keep in the cache. When the limit
* is exceeded the first item is removed from the cache.
*/
constructor(limit = 1e3) {
this._limit = limit;
}
/**
* Gets an item from the cache.
*
* @param key - object key
*/
get(key) {
return this._items.get(key);
}
/**
* Adds a new item to the cache.
*
* @param key - object key
* @param value - object value
*/
set(key, value) {
this._items.set(key, value);
if (this._items.size > this._limit) {
const it = this._items.keys().next();
/* istanbul ignore else */
if (!it.done) this._items.delete(it.value);
}
}
/**
* Removes an item from the cache.
*
* @param item - an item
*/
delete(key) {
return this._items.delete(key);
}
/**
* Determines if an item is in the cache.
*
* @param item - an item
*/
has(key) {
return this._items.has(key);
}
/**
* Removes all items from the cache.
*/
clear() {
this._items.clear();
}
/**
* Gets the number of items in the cache.
*/
get size() {
return this._items.size;
}
/**
* Applies the given callback function to all elements of the cache.
*/
forEach(callback, thisArg) {
this._items.forEach((v, k) => callback.call(thisArg, k, v));
}
/**
* Iterates through the items in the set.
*/
*keys() {
yield* this._items.keys();
}
/**
* Iterates through the items in the set.
*/
*values() {
yield* this._items.values();
}
/**
* Iterates through the items in the set.
*/
*entries() {
yield* this._items.entries();
}
/**
* Iterates through the items in the set.
*/
*[Symbol.iterator]() {
yield* this._items;
}
/**
* Returns the string tag of the cache.
*/
get [Symbol.toStringTag]() {
return "ObjectCache";
}
};
exports.ObjectCache = ObjectCache;
}));
var require_CompareCache = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.CompareCache = void 0;
/**
* Represents a cache for storing order between equal objects.
*
* This cache is used when an algorithm compares two objects and finds them to
* be equal but still needs to establish an order between those two objects.
* When two such objects `a` and `b` are passed to the `check` method, a random
* number is generated with `Math.random()`. If the random number is less than
* `0.5` it is assumed that `a < b` otherwise `a > b`. The random number along
* with `a` and `b` is stored in the cache, so that subsequent checks result
* in the same consistent result.
*
* The cache has a size limit which is defined on initialization.
*/
var CompareCache = class {
_limit;
_items = /* @__PURE__ */ new Map();
/**
* Initializes a new instance of `CompareCache`.
*
* @param limit - maximum number of items to keep in the cache. When the limit
* is exceeded the first item is removed from the cache.
*/
constructor(limit = 1e3) {
this._limit = limit;
}
/**
* Compares and caches the given objects. Returns `true` if `objA < objB` and
* `false` otherwise.
*
* @param objA - an item to compare
* @param objB - an item to compare
*/
check(objA, objB) {
if (this._items.get(objA) === objB) return true;
else if (this._items.get(objB) === objA) return false;
const result = Math.random() < .5;
if (result) this._items.set(objA, objB);
else this._items.set(objB, objA);
if (this._items.size > this._limit) {
const it = this._items.keys().next();
/* istanbul ignore else */
if (!it.done) this._items.delete(it.value);
}
return result;
}
};
exports.CompareCache = CompareCache;
}));
var require_Lazy = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.Lazy = void 0;
/**
* Represents an object with lazy initialization.
*/
var Lazy = class {
_initialized = false;
_initFunc;
_value;
/**
* Initializes a new instance of `Lazy`.
*
* @param initFunc - initializer function
*/
constructor(initFunc) {
this._value = void 0;
this._initFunc = initFunc;
}
/**
* Gets the value of the object.
*/
get value() {
if (!this._initialized) {
this._value = this._initFunc();
this._initialized = true;
}
return this._value;
}
};
exports.Lazy = Lazy;
}));
var require_StringWalker = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.StringWalker = void 0;
/**
* Walks through the code points of a string.
*/
var StringWalker = class {
_chars;
_length;
_pointer = 0;
_codePoint;
_c;
_remaining;
_substring;
/**
* Initializes a new `StringWalker`.
*
* @param input - input string
*/
constructor(input) {
this._chars = Array.from(input);
this._length = this._chars.length;
}
/**
* Determines if the current position is beyond the end of string.
*/
get eof() {
return this._pointer >= this._length;
}
/**
* Returns the number of code points in the input string.
*/
get length() {
return this._length;
}
/**
* Returns the current code point. Returns `-1` if the position is beyond
* the end of string.
*/
codePoint() {
if (this._codePoint === void 0) if (this.eof) this._codePoint = -1;
else {
const cp = this._chars[this._pointer].codePointAt(0);
/* istanbul ignore else */
if (cp !== void 0) this._codePoint = cp;
else this._codePoint = -1;
}
return this._codePoint;
}
/**
* Returns the current character. Returns an empty string if the position is
* beyond the end of string.
*/
c() {
if (this._c === void 0) this._c = this.eof ? "" : this._chars[this._pointer];
return this._c;
}
/**
* Returns the remaining string.
*/
remaining() {
if (this._remaining === void 0) this._remaining = this.eof ? "" : this._chars.slice(this._pointer + 1).join("");
return this._remaining;
}
/**
* Returns the substring from the current character to the end of string.
*/
substring() {
if (this._substring === void 0) this._substring = this.eof ? "" : this._chars.slice(this._pointer).join("");
return this._substring;
}
/**
* Gets or sets the current position.
*/
get pointer() {
return this._pointer;
}
set pointer(val) {
if (val === this._pointer) return;
this._pointer = val;
this._codePoint = void 0;
this._c = void 0;
this._remaining = void 0;
this._substring = void 0;
}
};
exports.StringWalker = StringWalker;
}));
var require_lib$3 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.StringWalker = exports.Lazy = exports.CompareCache = exports.ObjectCache = exports.FixedSizeSet = void 0;
exports.applyMixin = applyMixin;
exports.applyDefaults = applyDefaults;
exports.forEachArray = forEachArray;
exports.forEachObject = forEachObject;
exports.arrayLength = arrayLength;
exports.objectLength = objectLength;
exports.getObjectValue = getObjectValue;
exports.removeObjectValue = removeObjectValue;
exports.clone = clone;
exports.isBoolean = isBoolean;
exports.isNumber = isNumber;
exports.isString = isString;
exports.isFunction = isFunction;
exports.isObject = isObject;
exports.isArray = isArray;
exports.isSet = isSet;
exports.isMap = isMap;
exports.isEmpty = isEmpty;
exports.isPlainObject = isPlainObject;
exports.isIterable = isIterable;
exports.getValue = getValue;
exports.utf8Encode = utf8Encode;
exports.utf8Decode = utf8Decode;
var FixedSizeSet_js_1 = require_FixedSizeSet();
Object.defineProperty(exports, "FixedSizeSet", {
enumerable: true,
get: function() {
return FixedSizeSet_js_1.FixedSizeSet;
}
});
var ObjectCache_js_1 = require_ObjectCache();
Object.defineProperty(exports, "ObjectCache", {
enumerable: true,
get: function() {
return ObjectCache_js_1.ObjectCache;
}
});
var CompareCache_js_1 = require_CompareCache();
Object.defineProperty(exports, "CompareCache", {
enumerable: true,
get: function() {
return CompareCache_js_1.CompareCache;
}
});
var Lazy_js_1 = require_Lazy();
Object.defineProperty(exports, "Lazy", {
enumerable: true,
get: function() {
return Lazy_js_1.Lazy;
}
});
var StringWalker_js_1 = require_StringWalker();
Object.defineProperty(exports, "StringWalker", {
enumerable: true,
get: function() {
return StringWalker_js_1.StringWalker;
}
});
/**
* Applies the mixin to a given class.
*
* @param baseClass - class to receive the mixin
* @param mixinClass - mixin class
* @param overrides - an array with names of function overrides. Base class
* functions whose names are in this array will be kept by prepending an
* underscore to their names.
*/
function applyMixin(baseClass, mixinClass, ...overrides) {
Object.getOwnPropertyNames(mixinClass.prototype).forEach((name) => {
if (name !== "constructor") {
if (overrides.indexOf(name) !== -1) {
const orgPropDesc = Object.getOwnPropertyDescriptor(baseClass.prototype, name);
/* istanbul ignore else */
if (orgPropDesc) Object.defineProperty(baseClass.prototype, "_" + name, orgPropDesc);
}
const propDesc = Object.getOwnPropertyDescriptor(mixinClass.prototype, name);
/* istanbul ignore else */
if (propDesc) Object.defineProperty(baseClass.prototype, name, propDesc);
}
});
}
/**
* Applies default values to the given object.
*
* @param obj - an object
* @param defaults - an object with default values
* @param overwrite - if set to `true` defaults object always overwrites object
* values, whether they are `undefined` or not.
*/
function applyDefaults(obj, defaults, overwrite = false) {
const result = clone(obj || {});
forEachObject(defaults, (key, val) => {
if (isPlainObject(val)) result[key] = applyDefaults(result[key], val, overwrite);
else if (overwrite || result[key] === void 0) result[key] = val;
});
return result;
}
/**
* Iterates over items of an array or set.
*
* @param arr - array or set to iterate
* @param callback - a callback function which receives each array item as its
* single argument
* @param thisArg - the value of this inside callback
*/
function forEachArray(arr, callback, thisArg) {
arr.forEach(callback, thisArg);
}
/**
* Iterates over key/value pairs of a map or object.
*
* @param obj - map or object to iterate
* @param callback - a callback function which receives object key as its first
* argument and object value as its second argument
* @param thisArg - the value of this inside callback
*/
function forEachObject(obj, callback, thisArg) {
if (isMap(obj)) obj.forEach((value, key) => callback.call(thisArg, key, value));
else for (const key in obj)
/* istanbul ignore else */
if (obj.hasOwnProperty(key)) callback.call(thisArg, key, obj[key]);
}
/**
* Returns the number of entries in an array or set.
*
* @param arr - array or set
*/
function arrayLength(obj) {
if (isSet(obj)) return obj.size;
else return obj.length;
}
/**
* Returns the number of entries in a map or object.
*
* @param obj - map or object
*/
function objectLength(obj) {
if (isMap(obj)) return obj.size;
else return Object.keys(obj).length;
}
/**
* Gets the value of a key from a map or object.
*
* @param obj - map or object
* @param key - the key to retrieve
*/
function getObjectValue(obj, key) {
if (isMap(obj)) return obj.get(key);
else return obj[key];
}
/**
* Removes a property from a map or object.
*
* @param obj - map or object
* @param key - the key to remove
*/
function removeObjectValue(obj, key) {
if (isMap(obj)) obj.delete(key);
else delete obj[key];
}
/**
* Deep clones the given object.
*
* @param obj - an object
*/
function clone(obj) {
if (isFunction(obj)) return obj;
else if (isArray(obj)) {
const result = [];
for (const item of obj) result.push(clone(item));
return result;
} else if (isPlainObject(obj)) {
const result = {};
for (const key in obj)
/* istanbul ignore next */
if (obj.hasOwnProperty(key)) {
const val = obj[key];
result[key] = clone(val);
}
return result;
} else return obj;
}
/**
* Type guard for boolean types
*
* @param x - a variable to type check
*/
function isBoolean(x) {
return typeof x === "boolean";
}
/**
* Type guard for numeric types
*
* @param x - a variable to type check
*/
function isNumber(x) {
return typeof x === "number";
}
/**
* Type guard for strings
*
* @param x - a variable to type check
*/
function isString(x) {
return typeof x === "string";
}
/**
* Type guard for function objects
*
* @param x - a variable to type check
*/
function isFunction(x) {
return !!x && typeof x === "function";
}
/**
* Type guard for JS objects
*
* _Note:_ Functions are objects too
*
* @param x - a variable to type check
*/
function isObject(x) {
const type = typeof x;
return !!x && (type === "function" || type === "object");
}
/**
* Type guard for arrays
*
* @param x - a variable to type check
*/
function isArray(x) {
return Array.isArray(x);
}
/**
* Type guard for sets.
*
* @param x - a variable to check
*/
function isSet(x) {
return x instanceof Set;
}
/**
* Type guard for maps.
*
* @param x - a variable to check
*/
function isMap(x) {
return x instanceof Map;
}
/**
* Determines if `x` is an empty Array or an Object with no own properties.
*
* @param x - a variable to check
*/
function isEmpty(x) {
if (isArray(x)) return !x.length;
else if (isSet(x)) return !x.size;
else if (isMap(x)) return !x.size;
else if (isObject(x)) {
for (const key in x) if (x.hasOwnProperty(key)) return false;
return true;
}
return false;
}
/**
* Determines if `x` is a plain Object.
*
* @param x - a variable to check
*/
function isPlainObject(x) {
if (isObject(x)) {
const proto = Object.getPrototypeOf(x);
const ctor = proto.constructor;
return proto && ctor && typeof ctor === "function" && ctor instanceof ctor && Function.prototype.toString.call(ctor) === Function.prototype.toString.call(Object);
}
return false;
}
/**
* Determines if `x` is an iterable Object.
*
* @param x - a variable to check
*/
function isIterable(x) {
return x && typeof x[Symbol.iterator] === "function";
}
/**
* Gets the primitive value of an object.
*/
function getValue(obj) {
if (isFunction(obj.valueOf)) return obj.valueOf();
else return obj;
}
/**
* UTF-8 encodes the given string.
*
* @param input - a string
*/
function utf8Encode(input) {
const bytes = new Uint8Array(input.length * 4);
let byteIndex = 0;
for (let i = 0; i < input.length; i++) {
let char = input.charCodeAt(i);
if (char < 128) {
bytes[byteIndex++] = char;
continue;
} else if (char < 2048) bytes[byteIndex++] = char >> 6 | 192;
else {
if (char > 55295 && char < 56320) {
if (++i >= input.length) throw new Error("Incomplete surrogate pair.");
const c2 = input.charCodeAt(i);
if (c2 < 56320 || c2 > 57343) throw new Error("Invalid surrogate character.");
char = 65536 + ((char & 1023) << 10) + (c2 & 1023);
bytes[byteIndex++] = char >> 18 | 240;
bytes[byteIndex++] = char >> 12 & 63 | 128;
} else bytes[byteIndex++] = char >> 12 | 224;
bytes[byteIndex++] = char >> 6 & 63 | 128;
}
bytes[byteIndex++] = char & 63 | 128;
}
return bytes.subarray(0, byteIndex);
}
/**
* UTF-8 decodes the given byte sequence into a string.
*
* @param bytes - a byte sequence
*/
function utf8Decode(bytes) {
let result = "";
let i = 0;
while (i < bytes.length) {
var c = bytes[i++];
if (c > 127) if (c > 191 && c < 224) {
if (i >= bytes.length) throw new Error("Incomplete 2-byte sequence.");
c = (c & 31) << 6 | bytes[i++] & 63;
} else if (c > 223 && c < 240) {
if (i + 1 >= bytes.length) throw new Error("Incomplete 3-byte sequence.");
c = (c & 15) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63;
} else if (c > 239 && c < 248) {
if (i + 2 >= bytes.length) throw new Error("Incomplete 4-byte sequence.");
c = (c & 7) << 18 | (bytes[i++] & 63) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63;
} else throw new Error("Unknown multi-byte start.");
if (c <= 65535) result += String.fromCharCode(c);
else if (c <= 1114111) {
c -= 65536;
result += String.fromCharCode(c >> 10 | 55296);
result += String.fromCharCode(c & 1023 | 56320);
} else throw new Error("Code point exceeds UTF-16 limit.");
}
return result;
}
}));
var require_interfaces$2 = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.HowToCompare = exports.WhatToShow = exports.FilterResult = exports.Position = exports.NodeType = exports.EventPhase = exports.BoundaryPosition = void 0;
/**
* Defines the position of a boundary point relative to another.
*/
var BoundaryPosition;
(function(BoundaryPosition) {
BoundaryPosition[BoundaryPosition["Before"] = 0] = "Before";
BoundaryPosition[BoundaryPosition["Equal"] = 1] = "Equal";
BoundaryPosition[BoundaryPosition["After"] = 2] = "After";
})(BoundaryPosition || (exports.BoundaryPosition = BoundaryPosition = {}));
/**
* Defines the event phase.
*/
var EventPhase;
(function(EventPhase) {
EventPhase[EventPhase["None"] = 0] = "None";
EventPhase[EventPhase["Capturing"] = 1] = "Capturing";
EventPhase[EventPhase["AtTarget"] = 2] = "AtTarget";
EventPhase[EventPhase["Bubbling"] = 3] = "Bubbling";
})(EventPhase || (exports.EventPhase = EventPhase = {}));
/**
* Defines the type of a node object.
*/
var NodeType;
(function(NodeType) {
NodeType[NodeType["Element"] = 1] = "Element";
NodeType[NodeType["Attribute"] = 2] = "Attribute";
NodeType[NodeType["Text"] = 3] = "Text";
NodeType[NodeType["CData"] = 4] = "CData";
NodeType[NodeType["EntityReference"] = 5] = "EntityReference";
NodeType[NodeType["Entity"] = 6] = "Entity";
NodeType[NodeType["ProcessingInstruction"] = 7] = "ProcessingInstruction";
NodeType[NodeType["Comment"] = 8] = "Comment";
NodeType[NodeType["Document"] = 9] = "Document";
NodeType[NodeType["DocumentType"] = 10] = "DocumentType";
NodeType[NodeType["DocumentFragment"] = 11] = "DocumentFragment";
NodeType[NodeType["Notation"] = 12] = "Notation";
})(NodeType || (exports.NodeType = NodeType = {}));
/**
* Defines the position of a node in the document relative to another
* node.
*/
var Position;
(function(Position) {
Position[Position["SameNode"] = 0] = "SameNode";
Position[Position["Disconnected"] = 1] = "Disconnected";
Position[Position["Preceding"] = 2] = "Preceding";
Position[Position["Following"] = 4] = "Following";
Position[Position["Contains"] = 8] = "Contains";
Position[Position["ContainedBy"] = 16] = "ContainedBy";
Position[Position["ImplementationSpecific"] = 32] = "ImplementationSpecific";
})(Position || (exports.Position = Position = {}));
/**
* Defines the return value of a filter callback.
*/
var FilterResult;
(function(FilterResult) {
FilterResult[FilterResult["Accept"] = 1] = "Accept";
FilterResult[FilterResult["Reject"] = 2] = "Reject";
FilterResult[FilterResult["Skip"] = 3] = "Skip";
})(FilterResult || (exports.FilterResult = FilterResult = {}));
/**
* Defines what to show in node filter.
*/
var WhatToShow;
(function(WhatToShow) {
WhatToShow[WhatToShow["All"] = 4294967295] = "All";
WhatToShow[WhatToShow["Element"] = 1] = "Element";
WhatToShow[WhatToShow["Attribute"] = 2] = "Attribute";
WhatToShow[WhatToShow["Text"] = 4] = "Text";
WhatToShow[WhatToShow["CDataSection"] = 8] = "CDataSection";
WhatToShow[WhatToShow["EntityReference"] = 16] = "EntityReference";
WhatToShow[WhatToShow["Entity"] = 32] = "Entity";
WhatToShow[WhatToShow["ProcessingInstruction"] = 64] = "ProcessingInstruction";
WhatToShow[WhatToShow["Comment"] = 128] = "Comment";
WhatToShow[WhatToShow["Document"] = 256] = "Document";
WhatToShow[WhatToShow["DocumentType"] = 512] = "DocumentType";
WhatToShow[WhatToShow["DocumentFragment"] = 1024] = "DocumentFragment";
WhatToShow[WhatToShow["Notation"] = 2048] = "Notation";
})(WhatToShow || (exports.WhatToShow = WhatToShow = {}));
/**
* Defines how boundary points are compared.
*/
var HowToCompare;
(function(HowToCompare) {
HowToCompare[HowToCompare["StartToStart"] = 0] = "StartToStart";
HowToCompare[HowToCompare["StartToEnd"] = 1] = "StartToEnd";
HowToCompare[HowToCompare["EndToEnd"] = 2] = "EndToEnd";
HowToCompare[HowToCompare["EndToStart"] = 3] = "EndToStart";
})(HowToCompare || (exports.HowToCompare = HowToCompare = {}));
}));
var require_LocalNameSet = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.LocalNameSet = void 0;
/**
* Represents a set of unique attribute namespaceURI and localName pairs.
* This set will contain tuples of unique attribute namespaceURI and
* localName pairs, and is populated as each attr is processed. This set is
* used to [optionally] enforce the well-formed constraint that an element
* cannot have two attributes with the same namespaceURI and localName.
* This can occur when two otherwise identical attributes on the same
* element differ only by their prefix values.
*/
var LocalNameSet = class {
_items = {};
_nullItems = {};
/**
* Adds or replaces a tuple.
*
* @param ns - namespace URI
* @param localName - attribute local name
*/
set(ns, localName) {
if (ns === null) this._nullItems[localName] = true;
else if (this._items[ns]) this._items[ns][localName] = true;
else {
this._items[ns] = {};
this._items[ns][localName] = true;
}
}
/**
* Determines if the given tuple exists in the set.
*
* @param ns - namespace URI
* @param localName - attribute local name
*/
has(ns, localName) {
if (ns === null) return this._nullItems[localName] === true;
else if (this._items[ns]) return this._items[ns][localName] === true;
else return false;
}
};
exports.LocalNameSet = LocalNameSet;
}));
var require_NamespacePrefixMap = /* @__PURE__ */ __commonJSMin(((exports) => {
Object.defineProperty(exports, "__esModule", { value: true });
exports.NamespacePrefixMap = void 0;
exports.NamespacePrefixMap = class NamespacePrefixMap {
_items = {};
_nullItems = [];
/**
* Creates a copy of the map.
*/
copy() {
/**
* To copy a namespace prefix map map means to copy the map's keys into a
* new empty namespace prefix map, and to copy each of the values in the
* namespace prefix list associated with each keys' value into a new list
* which should be associated with the respective key in the new map.
*/
const mapCopy = new NamespacePrefixMap();
for (const key in this._items) mapCopy._items[key] = this._items[key].slice(0);
mapCopy._nullItems = this._nullItems.slice(0);
return mapCopy;
}
/**
* Retrieves a preferred prefix string from the namespace prefix map.
*
* @param preferredPrefix - preferred prefix string
* @param ns - namespace
*/
get(preferredPrefix, ns) {
/**
* 1. Let candidates list be the result of retrieving a list from map where
* there exists a key in map that matches the value of ns or if there is no
* such key, then stop running these steps, and return the null value.
*/
const candidatesList = ns === null ? this._nullItems : this._items[ns] || null;
if (candidatesList === null) return null;
/**
* 2. Otherwise, for each prefix value prefix in candidates list, iterating
* from beginning to end:
*
* _Note:_ There will always be at least one prefix value in the list.
*/
let prefix = null;
for (let i = 0; i < candidatesList.length; i++) {
prefix = candidatesList[i];
/**
* 2.1. If prefix matches preferred prefix, then stop running these steps
* and return prefix.
*/
if (prefix === preferredPrefix) return prefix;
}
/**
* 2.2. If prefix is the last item in the candidates list, then stop
* running these steps and return prefix.
*/
return prefix;
}
/**
* Checks if a prefix string is found in the namespace prefix map associated
* with the given namespace.
*
* @param prefix - prefix string
* @param ns - namespace
*/
has(prefix, ns) {
/**
* 1. Let candidates list be the result of retrieving a list from map where
* there exists a key in map that matches the value of ns or if there is
* no such key, then stop running these steps, and return false.
*/
const candidatesList = ns === null ? this._nullItems : this._items[ns] || null;
if (candidatesList === null) return false;
/**
* 2. If the value of prefix occurs at least once in candidates list,
* return true, otherwise return false.
*/
return candidatesList.indexOf(prefix) !== -1;
}
/**
* Checks if a prefix string is found in the namespace prefix map.
*
* @param prefix - prefix string
*/
hasPrefix(prefix) {
if (this._nullItems.indexOf(prefix) !== -1) return true;
for (const key in this._items) if (this._items[key].indexOf(prefix) !== -1) return true;
return false;
}
/**
* Adds a prefix string associated with a namespace to the prefix map.
*
* @param prefix - prefix string
* @param ns - namespace
*/
set(prefix, ns) {
/**
* 1. Let candidates list be the result of retrieving a list from map where
* there exists a key in map that matches the value of ns or if there is
* no such key, then let candidates list be null.
*/
const candidatesList = ns === null ? this._nullItems : this._items[ns] || null;
/**
* 2. If candidates list is null, then create a new list with prefix as the
* only item in the list, and associate that list with a new key ns in map.
* 3. Otherwise, append prefix to the end of candidates list.
*
* _Note:_ The steps in retrieve a preferred prefix string use the list to
* track the most recently used (MRU) prefix associated with a given
* namespace, which will be the prefix at the end of the list. This list
* may contain duplicates of the same prefix value seen earlier
* (and that's OK).
*/
if (ns !== null && candidatesList === null) this._items[ns] = [prefix];
else candidatesList.push(prefix);
}
};
}));
var _polyfill_node_global_default;
var init__polyfill_node_global = __esmMin((() => {
init__polyfill_node_global();
_polyfill_node_global_default = typeof _polyfill_node_global_default !== "undefined" ? _polyfill_node_global_default : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {};
}));
function init() {
inited = true;
var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i];
revLookup[code.charCodeAt(i)] = i;
}
revLookup["-".charCodeAt(0)] = 62;
revLookup["_".charCodeAt(0)] = 63;
}
function toByteArray(b64) {
if (!inited) init();
var i, j, l, tmp, placeHolders, arr;
var len = b64.length;
if (len % 4 > 0) throw new Error("Invalid string. Length must be a multiple of 4");
placeHolders = b64[len - 2] === "=" ? 2 : b64[len - 1] === "=" ? 1 : 0;
arr = new Arr(len * 3 / 4 - placeHolders);
l = placeHolders > 0 ? len - 4 : len;
var L = 0;
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
arr[L++] = tmp >> 16 & 255;
arr[L++] = tmp >> 8 & 255;
arr[L++] = tmp & 255;
}
if (placeHolders === 2) {
tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
arr[L++] = tmp & 255;
} else if (placeHolders === 1) {
tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
arr[L++] = tmp >> 8 & 255;
arr[L++] = tmp & 255;
}
return arr;
}
function tripletToBase64(num) {
return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
}
function encodeChunk(uint8, start, end) {
var tmp;
var output = [];
for (var i = start; i < end; i += 3) {
tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2];
output.push(tripletToBase64(tmp));
}
return output.join("");
}
function fromByteArray(uint8) {
if (!inited) init();
var tmp;
var len = uint8.length;
var extraBytes = len % 3;
var output = "";
var parts = [];
var maxChunkLength = 16383;
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
if (extraBytes === 1) {
tmp = uint8[len - 1];
output += lookup[tmp >> 2];
output += lookup[tmp << 4 & 63];
output += "==";
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1];
output += lookup[tmp >> 10];
output += lookup[tmp >> 4 & 63];
output += lookup[tmp << 2 & 63];
output += "=";
}
parts.push(output);
return parts.join("");
}
function read(buffer, offset, isLE, mLen, nBytes) {
var e, m;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var nBits = -7;
var i = isLE ? nBytes - 1 : 0;
var d = isLE ? -1 : 1;
var s = buffer[offset + i];
i += d;
e = s & (1 << -nBits) - 1;
s >>= -nBits;
nBits += eLen;
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8);
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8);
if (e === 0) e = 1 - eBias;
else if (e === eMax) return m ? NaN : (s ? -1 : 1) * Infinity;
else {
m = m + Math.pow(2, mLen);
e = e - eBias;
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
}
function write(buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c;
var eLen = nBytes * 8 - mLen - 1;
var eMax = (1 << eLen) - 1;
var eBias = eMax >> 1;
var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
var i = isLE ? 0 : nBytes - 1;
var d = isLE ? 1 : -1;
var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
value = Math.abs(value);
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0;
e = eMax;
} else {
e = Math.floor(Math.log(value) / Math.LN2);
if (value * (c = Math.pow(2, -e)) < 1) {
e--;
c *= 2;
}
if (e + eBias >= 1) value += rt / c;
else value += rt * Math.pow(2, 1 - eBias);
if (value * c >= 2) {
e++;
c /= 2;
}
if (e + eBias >= eMax) {
m = 0;
e = eMax;
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen);
e = e + eBias;
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
e = 0;
}
}
for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8);
e = e << mLen | m;
eLen += mLen;
for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8);
buffer[offset + i - d] |= s * 128;
}
function kMaxLength() {
return Buffer$1.TYPED_ARRAY_SUPPORT ? 2147483647 : 1073741823;
}
function createBuffer(that, length) {
if (kMaxLength() < length) throw new RangeError("Invalid typed array length");
if (Buffer$1.TYPED_ARRAY_SUPPORT) {
that = new Uint8Array(length);
that.__proto__ = Buffer$1.prototype;
} else {
if (that === null) that = new Buffer$1(length);
that.length = length;
}
return that;
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer$1(arg, encodingOrOffset, length) {
if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) return new Buffer$1(arg, encodingOrOffset, length);
if (typeof arg === "number") {
if (typeof encodingOrOffset === "string") throw new Error("If encoding is specified then the first argument must be a string");
return allocUnsafe(this, arg);
}
return from(this, arg, encodingOrOffset, length);
}
function from(that, value, encodingOrOffset, length) {
if (typeof value === "number") throw new TypeError("\"value\" argument must not be a number");
if (typeof ArrayBuffer !== "undefined" && value instanceof ArrayBuffer) return fromArrayBuffer(that, value, encodingOrOffset, length);
if (typeof value === "string") return fromString(that, value, encodingOrOffset);
return fromObject(that, value);
}
function assertSize(size) {
if (typeof size !== "number") throw new TypeError("\"size\" argument must be a number");
else if (size < 0) throw new RangeError("\"size\" argument must not be negative");
}
function alloc(that, size, fill, encoding) {
assertSize(size);
if (size <= 0) return createBuffer(that, size);
if (fill !== void 0) return typeof encoding === "string" ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill);
return createBuffer(that, size);
}
function allocUnsafe(that, size) {
assertSize(size);
that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);
if (!Buffer$1.TYPED_ARRAY_SUPPORT) for (var i = 0; i < size; ++i) that[i] = 0;
return that;
}
function fromString(that, string, encoding) {
if (typeof encoding !== "string" || encoding === "") encoding = "utf8";
if (!Buffer$1.isEncoding(encoding)) throw new TypeError("\"encoding\" must be a valid string encoding");
var length = byteLength(string,