diff --git a/badges/coverage.svg b/badges/coverage.svg index 00b08488..8c765a9e 100644 --- a/badges/coverage.svg +++ b/badges/coverage.svg @@ -1 +1 @@ -Coverage: 30.3%Coverage30.3% \ No newline at end of file +Coverage: 22.78%Coverage22.78% \ No newline at end of file diff --git a/dist/index.js b/dist/index.js index 01bba51e..12cf3ccb 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1392,7 +1392,7 @@ var require_util = __commonJS({ } obj[kListeners] = null; } - function errorRequest3(client2, request3, err) { + function errorRequest2(client2, request3, err) { try { request3.onError(err); assert2(request3.aborted); @@ -1443,7 +1443,7 @@ var require_util = __commonJS({ bufferToLowerCasedHeaderName, addListener, removeAllListeners, - errorRequest: errorRequest3, + errorRequest: errorRequest2, parseRawHeaders, parseHeaders, parseKeepAliveTimeout, @@ -9160,14 +9160,14 @@ var require_retry_agent = __commonJS({ this.#options = options; } dispatch(opts, handler2) { - const retry5 = new RetryHandler({ + const retry4 = new RetryHandler({ ...opts, retryOptions: this.#options }, { dispatch: this.#agent.dispatch.bind(this.#agent), handler: handler2 }); - return this.#agent.dispatch(opts, retry5); + return this.#agent.dispatch(opts, retry4); } close() { return this.#agent.close(); @@ -23724,11 +23724,11 @@ var require_light = __commonJS({ return this._onFailure(error2, eventInfo, clearGlobalState, run2, free); } async _onFailure(error2, eventInfo, clearGlobalState, run2, free) { - var retry5, retryAfter; + var retry4, retryAfter; if (clearGlobalState()) { - retry5 = await this.Events.trigger("failed", error2, eventInfo); - if (retry5 != null) { - retryAfter = ~~retry5; + retry4 = await this.Events.trigger("failed", error2, eventInfo); + if (retry4 != null) { + retryAfter = ~~retry4; this.Events.trigger("retry", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo); this.retryCount++; return run2(retryAfter); @@ -24243,7 +24243,7 @@ var require_light = __commonJS({ var Batcher_1 = Batcher; var require$$4$1 = () => console.log("You must import the full version of Bottleneck in order to use this feature."); var require$$8 = getCjsExportFromNamespace(version$2); - var Bottleneck3, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5, splice = [].splice; + var Bottleneck2, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5, splice = [].splice; NUM_PRIORITIES$1 = 10; DEFAULT_PRIORITY$1 = 5; parser$5 = parser2; @@ -24254,8 +24254,8 @@ var require_light = __commonJS({ Events$4 = Events_1; States$1 = States_1; Sync$1 = Sync_1; - Bottleneck3 = (function() { - class Bottleneck4 { + Bottleneck2 = (function() { + class Bottleneck3 { constructor(options = {}, ...invalid) { var storeInstanceOptions, storeOptions; this._addToQueue = this._addToQueue.bind(this); @@ -24277,7 +24277,7 @@ var require_light = __commonJS({ storeInstanceOptions = parser$5.load(options, this.localStoreDefaults, {}); return new LocalDatastore$1(this, storeOptions, storeInstanceOptions); } else { - throw new Bottleneck4.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); + throw new Bottleneck3.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); } }).call(this); this._queues.on("leftzero", () => { @@ -24291,7 +24291,7 @@ var require_light = __commonJS({ } _validateOptions(options, invalid) { if (!(options != null && typeof options === "object" && invalid.length === 0)) { - throw new Bottleneck4.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); + throw new Bottleneck3.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); } } ready() { @@ -24488,10 +24488,10 @@ var require_light = __commonJS({ return waitForExecuting(1); }); this._receive = function(job) { - return job._reject(new Bottleneck4.prototype.BottleneckError(options.enqueueErrorMessage)); + return job._reject(new Bottleneck3.prototype.BottleneckError(options.enqueueErrorMessage)); }; this.stop = () => { - return this.Promise.reject(new Bottleneck4.prototype.BottleneckError("stop() has already been called")); + return this.Promise.reject(new Bottleneck3.prototype.BottleneckError("stop() has already been called")); }; return done; } @@ -24510,11 +24510,11 @@ var require_light = __commonJS({ job.doDrop(); return true; } else if (reachedHWM) { - shifted = strategy === Bottleneck4.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck4.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck4.prototype.strategy.OVERFLOW ? job : void 0; + shifted = strategy === Bottleneck3.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck3.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck3.prototype.strategy.OVERFLOW ? job : void 0; if (shifted != null) { shifted.doDrop(); } - if (shifted == null || strategy === Bottleneck4.prototype.strategy.OVERFLOW) { + if (shifted == null || strategy === Bottleneck3.prototype.strategy.OVERFLOW) { if (shifted == null) { job.doDrop(); } @@ -24528,7 +24528,7 @@ var require_light = __commonJS({ } _receive(job) { if (this._states.jobStatus(job.options.id) != null) { - job._reject(new Bottleneck4.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); + job._reject(new Bottleneck3.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); return false; } else { job.doReceive(); @@ -24598,31 +24598,31 @@ var require_light = __commonJS({ return this._store.__incrementReservoir__(incr); } } - Bottleneck4.default = Bottleneck4; - Bottleneck4.Events = Events$4; - Bottleneck4.version = Bottleneck4.prototype.version = require$$8.version; - Bottleneck4.strategy = Bottleneck4.prototype.strategy = { + Bottleneck3.default = Bottleneck3; + Bottleneck3.Events = Events$4; + Bottleneck3.version = Bottleneck3.prototype.version = require$$8.version; + Bottleneck3.strategy = Bottleneck3.prototype.strategy = { LEAK: 1, OVERFLOW: 2, OVERFLOW_PRIORITY: 4, BLOCK: 3 }; - Bottleneck4.BottleneckError = Bottleneck4.prototype.BottleneckError = BottleneckError_1; - Bottleneck4.Group = Bottleneck4.prototype.Group = Group_1; - Bottleneck4.RedisConnection = Bottleneck4.prototype.RedisConnection = require$$2; - Bottleneck4.IORedisConnection = Bottleneck4.prototype.IORedisConnection = require$$3; - Bottleneck4.Batcher = Bottleneck4.prototype.Batcher = Batcher_1; - Bottleneck4.prototype.jobDefaults = { + Bottleneck3.BottleneckError = Bottleneck3.prototype.BottleneckError = BottleneckError_1; + Bottleneck3.Group = Bottleneck3.prototype.Group = Group_1; + Bottleneck3.RedisConnection = Bottleneck3.prototype.RedisConnection = require$$2; + Bottleneck3.IORedisConnection = Bottleneck3.prototype.IORedisConnection = require$$3; + Bottleneck3.Batcher = Bottleneck3.prototype.Batcher = Batcher_1; + Bottleneck3.prototype.jobDefaults = { priority: DEFAULT_PRIORITY$1, weight: 1, expiration: null, id: "" }; - Bottleneck4.prototype.storeDefaults = { + Bottleneck3.prototype.storeDefaults = { maxConcurrent: null, minTime: 0, highWater: null, - strategy: Bottleneck4.prototype.strategy.LEAK, + strategy: Bottleneck3.prototype.strategy.LEAK, penalty: null, reservoir: null, reservoirRefreshInterval: null, @@ -24631,12 +24631,12 @@ var require_light = __commonJS({ reservoirIncreaseAmount: null, reservoirIncreaseMaximum: null }; - Bottleneck4.prototype.localStoreDefaults = { + Bottleneck3.prototype.localStoreDefaults = { Promise, timeout: null, heartbeatInterval: 250 }; - Bottleneck4.prototype.redisStoreDefaults = { + Bottleneck3.prototype.redisStoreDefaults = { Promise, timeout: null, heartbeatInterval: 5e3, @@ -24647,7 +24647,7 @@ var require_light = __commonJS({ clearDatastore: false, connection: null }; - Bottleneck4.prototype.instanceDefaults = { + Bottleneck3.prototype.instanceDefaults = { datastore: "local", connection: null, id: "", @@ -24655,73 +24655,31 @@ var require_light = __commonJS({ trackDoneStatus: false, Promise }; - Bottleneck4.prototype.stopDefaults = { + Bottleneck3.prototype.stopDefaults = { enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", dropWaitingJobs: true, dropErrorMessage: "This limiter has been stopped." }; - return Bottleneck4; + return Bottleneck3; }).call(commonjsGlobal); - var Bottleneck_1 = Bottleneck3; + var Bottleneck_1 = Bottleneck2; var lib = Bottleneck_1; return lib; })); } }); -// node_modules/@octokit/plugin-retry/node_modules/@octokit/request-error/dist-src/index.js -var RequestError2; -var init_dist_src6 = __esm({ - "node_modules/@octokit/plugin-retry/node_modules/@octokit/request-error/dist-src/index.js"() { - "use strict"; - RequestError2 = class extends Error { - name; - /** - * http status code - */ - status; - /** - * Request options that lead to the error. - */ - request; - /** - * Response object if a response was received - */ - response; - constructor(message, statusCode, options) { - super(message); - this.name = "HttpError"; - this.status = Number.parseInt(statusCode); - if (Number.isNaN(this.status)) { - this.status = 0; - } - if ("response" in options) { - this.response = options.response; - } - const requestCopy = Object.assign({}, options.request); - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace( - /(? VERSION9, retry: () => retry }); +function isRequestError(error2) { + return error2.request !== void 0; +} async function errorRequest(state4, octokit, error2, options) { - if (!error2.request || !error2.request.request) { + if (!isRequestError(error2) || !error2?.request.request) { throw error2; } if (error2.status >= 400 && !state4.doNotRetry.includes(error2.status)) { @@ -24734,8 +24692,8 @@ async function errorRequest(state4, octokit, error2, options) { async function wrapRequest(state4, octokit, request3, options) { const limiter = new import_light.default(); limiter.on("failed", function(error2, info2) { - const maxRetries = ~~error2.request.request.retries; - const after = ~~error2.request.request.retryAfter; + const maxRetries = ~~error2.request.request?.retries; + const after = ~~error2.request.request?.retryAfter; options.request.retryCount = info2.retryCount + 1; if (maxRetries > info2.retryCount) { return after * state4.retryAfterBaseValue; @@ -24747,11 +24705,11 @@ async function wrapRequest(state4, octokit, request3, options) { ); } async function requestWithGraphqlErrorHandling(state4, octokit, request3, options) { - const response = await request3(request3, options); + const response = await request3(options); if (response.data && response.data.errors && response.data.errors.length > 0 && /Something went wrong while executing your query/.test( response.data.errors[0].message )) { - const error2 = new RequestError2(response.data.errors[0].message, 500, { + const error2 = new RequestError(response.data.errors[0].message, 500, { request: options, response }); @@ -24769,11 +24727,7 @@ function retry(octokit, octokitOptions) { }, octokitOptions.retry ); - if (state4.enabled) { - octokit.hook.error("request", errorRequest.bind(null, state4, octokit)); - octokit.hook.wrap("request", wrapRequest.bind(null, state4, octokit)); - } - return { + const retryPlugin = { retry: { retryRequest: (error2, retries, retryAfter) => { error2.request.request = Object.assign({}, error2.request.request, { @@ -24784,13 +24738,18 @@ function retry(octokit, octokitOptions) { } } }; + if (state4.enabled) { + octokit.hook.error("request", errorRequest.bind(null, state4, retryPlugin)); + octokit.hook.wrap("request", wrapRequest.bind(null, state4, retryPlugin)); + } + return retryPlugin; } var import_light, VERSION9; var init_dist_bundle6 = __esm({ "node_modules/@octokit/plugin-retry/dist-bundle/index.js"() { "use strict"; import_light = __toESM(require_light(), 1); - init_dist_src6(); + init_dist_src(); VERSION9 = "0.0.0-development"; retry.VERSION = VERSION9; } @@ -37388,7 +37347,7 @@ var require_graceful_fs = __commonJS({ function enqueue(elem) { debug2("ENQUEUE", elem[0].name, elem[1]); fs16[gracefulQueue].push(elem); - retry5(); + retry4(); } var retryTimer; function resetQueue() { @@ -37399,9 +37358,9 @@ var require_graceful_fs = __commonJS({ fs16[gracefulQueue][i6][4] = now; } } - retry5(); + retry4(); } - function retry5() { + function retry4() { clearTimeout(retryTimer); retryTimer = void 0; if (fs16[gracefulQueue].length === 0) @@ -37432,7 +37391,7 @@ var require_graceful_fs = __commonJS({ } } if (retryTimer === void 0) { - retryTimer = setTimeout(retry5, 0); + retryTimer = setTimeout(retry4, 0); } } } @@ -86266,8 +86225,8 @@ var require_base = __commonJS({ var _logger = require_logger(); var _logger2 = _interopRequireDefault(_logger); var _internalProtoAccess = require_proto_access(); - var VERSION11 = "4.7.9"; - exports2.VERSION = VERSION11; + var VERSION10 = "4.7.9"; + exports2.VERSION = VERSION10; var COMPILER_REVISION = 8; exports2.COMPILER_REVISION = COMPILER_REVISION; var LAST_COMPATIBLE_COMPILER_REVISION = 7; @@ -132772,11 +132731,11 @@ var init_RemoteProviderInit = __esm({ }); // node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/retry.js -var retry4; +var retry3; var init_retry3 = __esm({ "node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/retry.js"() { "use strict"; - retry4 = (toRetry, maxRetries) => { + retry3 = (toRetry, maxRetries) => { let promise = toRetry(); for (let i6 = 0; i6 < maxRetries; i6++) { promise = promise.catch(toRetry); @@ -132802,7 +132761,7 @@ var init_fromContainerMetadata = __esm({ ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; fromContainerMetadata = (init = {}) => { const { timeout: timeout2, maxRetries } = providerConfigFromInit(init); - return () => retry4(async () => { + return () => retry3(async () => { const requestOptions = await getCmdsUri({ logger: init.logger }); const credsResponse = JSON.parse(await requestFromEcsImds(timeout2, requestOptions)); if (!isImdsCredentials(credsResponse)) { @@ -133081,7 +133040,7 @@ var init_fromInstanceMetadata = __esm({ throw new InstanceMetadataV1FallbackError(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join(", ")}].`); } } - const imdsProfile = (await retry4(async () => { + const imdsProfile = (await retry3(async () => { let profile2; try { profile2 = await getProfile(options); @@ -133093,7 +133052,7 @@ var init_fromInstanceMetadata = __esm({ } return profile2; }, maxRetries2)).trim(); - return retry4(async () => { + return retry3(async () => { let creds; try { creds = await getCredentialsFromProfile(imdsProfile, options, init); @@ -145780,8 +145739,8 @@ var COMMUNITY_REPORTS_PATH = "community-reports"; // src/client/github/client.ts async function createGitHubClient() { const { Octokit: Octokit3 } = await Promise.resolve().then(() => (init_dist_src5(), dist_src_exports)); - const { retry: retry5 } = await Promise.resolve().then(() => (init_dist_bundle6(), dist_bundle_exports)); - const OctokitWithRetry = Octokit3.plugin(retry5); + const { retry: retry4 } = await Promise.resolve().then(() => (init_dist_bundle6(), dist_bundle_exports)); + const OctokitWithRetry = Octokit3.plugin(retry4); if (!GITHUB_TOKEN) { throw new Error("GitHub token is required to authenticate Octokit"); } @@ -178287,83 +178246,10 @@ function getRetryOptions(defaultOptions4, retries = defaultMaxRetryNumber, exemp // node_modules/@actions/artifact/lib/internal/delete/delete-artifact.js init_dist_src4(); - -// node_modules/@actions/artifact/node_modules/@octokit/plugin-retry/dist-bundle/index.js -var import_light2 = __toESM(require_light(), 1); -init_dist_src(); -var VERSION10 = "0.0.0-development"; -function isRequestError(error2) { - return error2.request !== void 0; -} -async function errorRequest2(state4, octokit, error2, options) { - if (!isRequestError(error2) || !error2?.request.request) { - throw error2; - } - if (error2.status >= 400 && !state4.doNotRetry.includes(error2.status)) { - const retries = options.request.retries != null ? options.request.retries : state4.retries; - const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2); - throw octokit.retry.retryRequest(error2, retries, retryAfter); - } - throw error2; -} -async function wrapRequest2(state4, octokit, request3, options) { - const limiter = new import_light2.default(); - limiter.on("failed", function(error2, info2) { - const maxRetries = ~~error2.request.request?.retries; - const after = ~~error2.request.request?.retryAfter; - options.request.retryCount = info2.retryCount + 1; - if (maxRetries > info2.retryCount) { - return after * state4.retryAfterBaseValue; - } - }); - return limiter.schedule( - requestWithGraphqlErrorHandling2.bind(null, state4, octokit, request3), - options - ); -} -async function requestWithGraphqlErrorHandling2(state4, octokit, request3, options) { - const response = await request3(options); - if (response.data && response.data.errors && response.data.errors.length > 0 && /Something went wrong while executing your query/.test( - response.data.errors[0].message - )) { - const error2 = new RequestError(response.data.errors[0].message, 500, { - request: options, - response - }); - return errorRequest2(state4, octokit, error2, options); - } - return response; -} -function retry3(octokit, octokitOptions) { - const state4 = Object.assign( - { - enabled: true, - retryAfterBaseValue: 1e3, - doNotRetry: [400, 401, 403, 404, 410, 422, 451], - retries: 3 - }, - octokitOptions.retry - ); - const retryPlugin = { - retry: { - retryRequest: (error2, retries, retryAfter) => { - error2.request.request = Object.assign({}, error2.request.request, { - retries, - retryAfter - }); - return error2; - } - } - }; - if (state4.enabled) { - octokit.hook.error("request", errorRequest2.bind(null, state4, retryPlugin)); - octokit.hook.wrap("request", wrapRequest2.bind(null, state4, retryPlugin)); - } - return retryPlugin; -} -retry3.VERSION = VERSION10; +init_dist_bundle6(); // node_modules/@actions/artifact/lib/internal/find/get-artifact.js +init_dist_bundle6(); init_dist_src4(); var __awaiter11 = function(thisArg, _arguments, P2, generator) { function adopt(value) { @@ -178403,7 +178289,7 @@ function getArtifactPublic(artifactName, workflowRunId, repositoryOwner, reposit retry: retryOpts, request: requestOpts }; - const github = getOctokit(token, opts, retry3, requestLog); + const github = getOctokit(token, opts, retry, requestLog); const getArtifactResp = yield github.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts{?name}", { owner: repositoryOwner, repo: repositoryName, @@ -178506,7 +178392,7 @@ function deleteArtifactPublic(artifactName, workflowRunId, repositoryOwner, repo retry: retryOpts, request: requestOpts }; - const github = getOctokit(token, opts, retry3, requestLog); + const github = getOctokit(token, opts, retry, requestLog); const getArtifactResp = yield getArtifactPublic(artifactName, workflowRunId, repositoryOwner, repositoryName, token); const deleteArtifactResp = yield github.rest.actions.deleteArtifact({ owner: repositoryOwner, @@ -178554,6 +178440,7 @@ function deleteArtifactInternal(artifactName) { // node_modules/@actions/artifact/lib/internal/find/list-artifacts.js init_dist_src4(); +init_dist_bundle6(); var __awaiter13 = function(thisArg, _arguments, P2, generator) { function adopt(value) { return value instanceof P2 ? value : new P2(function(resolve4) { @@ -178596,7 +178483,7 @@ function listArtifactsPublic(workflowRunId_1, repositoryOwner_1, repositoryName_ retry: retryOpts, request: requestOpts }; - const github = getOctokit(token, opts, retry3, requestLog); + const github = getOctokit(token, opts, retry, requestLog); let currentPageNumber = 1; const { data: listArtifactResponse } = yield github.request("GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", { owner: repositoryOwner, diff --git a/dist/index.js.map b/dist/index.js.map index 71ec8c87..d3322f06 100644 --- a/dist/index.js.map +++ b/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../node_modules/tunnel/lib/tunnel.js","../node_modules/tunnel/index.js","../node_modules/undici/lib/core/symbols.js","../node_modules/undici/lib/core/errors.js","../node_modules/undici/lib/core/constants.js","../node_modules/undici/lib/core/tree.js","../node_modules/undici/lib/core/util.js","../node_modules/undici/lib/core/diagnostics.js","../node_modules/undici/lib/core/request.js","../node_modules/undici/lib/dispatcher/dispatcher.js","../node_modules/undici/lib/dispatcher/dispatcher-base.js","../node_modules/undici/lib/util/timers.js","../node_modules/undici/lib/core/connect.js","../node_modules/undici/lib/llhttp/utils.js","../node_modules/undici/lib/llhttp/constants.js","../node_modules/undici/lib/llhttp/llhttp-wasm.js","../node_modules/undici/lib/llhttp/llhttp_simd-wasm.js","../node_modules/undici/lib/web/fetch/constants.js","../node_modules/undici/lib/web/fetch/global.js","../node_modules/undici/lib/web/fetch/data-url.js","../node_modules/undici/lib/web/fetch/webidl.js","../node_modules/undici/lib/web/fetch/util.js","../node_modules/undici/lib/web/fetch/symbols.js","../node_modules/undici/lib/web/fetch/file.js","../node_modules/undici/lib/web/fetch/formdata.js","../node_modules/undici/lib/web/fetch/formdata-parser.js","../node_modules/undici/lib/web/fetch/body.js","../node_modules/undici/lib/dispatcher/client-h1.js","../node_modules/undici/lib/dispatcher/client-h2.js","../node_modules/undici/lib/handler/redirect-handler.js","../node_modules/undici/lib/interceptor/redirect-interceptor.js","../node_modules/undici/lib/dispatcher/client.js","../node_modules/undici/lib/dispatcher/fixed-queue.js","../node_modules/undici/lib/dispatcher/pool-stats.js","../node_modules/undici/lib/dispatcher/pool-base.js","../node_modules/undici/lib/dispatcher/pool.js","../node_modules/undici/lib/dispatcher/balanced-pool.js","../node_modules/undici/lib/dispatcher/agent.js","../node_modules/undici/lib/dispatcher/proxy-agent.js","../node_modules/undici/lib/dispatcher/env-http-proxy-agent.js","../node_modules/undici/lib/handler/retry-handler.js","../node_modules/undici/lib/dispatcher/retry-agent.js","../node_modules/undici/lib/api/readable.js","../node_modules/undici/lib/api/util.js","../node_modules/undici/lib/api/api-request.js","../node_modules/undici/lib/api/abort-signal.js","../node_modules/undici/lib/api/api-stream.js","../node_modules/undici/lib/api/api-pipeline.js","../node_modules/undici/lib/api/api-upgrade.js","../node_modules/undici/lib/api/api-connect.js","../node_modules/undici/lib/api/index.js","../node_modules/undici/lib/mock/mock-errors.js","../node_modules/undici/lib/mock/mock-symbols.js","../node_modules/undici/lib/mock/mock-utils.js","../node_modules/undici/lib/mock/mock-interceptor.js","../node_modules/undici/lib/mock/mock-client.js","../node_modules/undici/lib/mock/mock-pool.js","../node_modules/undici/lib/mock/pluralizer.js","../node_modules/undici/lib/mock/pending-interceptors-formatter.js","../node_modules/undici/lib/mock/mock-agent.js","../node_modules/undici/lib/global.js","../node_modules/undici/lib/handler/decorator-handler.js","../node_modules/undici/lib/interceptor/redirect.js","../node_modules/undici/lib/interceptor/retry.js","../node_modules/undici/lib/interceptor/dump.js","../node_modules/undici/lib/interceptor/dns.js","../node_modules/undici/lib/web/fetch/headers.js","../node_modules/undici/lib/web/fetch/response.js","../node_modules/undici/lib/web/fetch/dispatcher-weakref.js","../node_modules/undici/lib/web/fetch/request.js","../node_modules/undici/lib/web/fetch/index.js","../node_modules/undici/lib/web/fileapi/symbols.js","../node_modules/undici/lib/web/fileapi/progressevent.js","../node_modules/undici/lib/web/fileapi/encoding.js","../node_modules/undici/lib/web/fileapi/util.js","../node_modules/undici/lib/web/fileapi/filereader.js","../node_modules/undici/lib/web/cache/symbols.js","../node_modules/undici/lib/web/cache/util.js","../node_modules/undici/lib/web/cache/cache.js","../node_modules/undici/lib/web/cache/cachestorage.js","../node_modules/undici/lib/web/cookies/constants.js","../node_modules/undici/lib/web/cookies/util.js","../node_modules/undici/lib/web/cookies/parse.js","../node_modules/undici/lib/web/cookies/index.js","../node_modules/undici/lib/web/websocket/events.js","../node_modules/undici/lib/web/websocket/constants.js","../node_modules/undici/lib/web/websocket/symbols.js","../node_modules/undici/lib/web/websocket/util.js","../node_modules/undici/lib/web/websocket/frame.js","../node_modules/undici/lib/web/websocket/connection.js","../node_modules/undici/lib/web/websocket/permessage-deflate.js","../node_modules/undici/lib/web/websocket/receiver.js","../node_modules/undici/lib/web/websocket/sender.js","../node_modules/undici/lib/web/websocket/websocket.js","../node_modules/undici/lib/web/eventsource/util.js","../node_modules/undici/lib/web/eventsource/eventsource-stream.js","../node_modules/undici/lib/web/eventsource/eventsource.js","../node_modules/undici/index.js","../node_modules/@actions/github/node_modules/@actions/http-client/src/proxy.ts","../node_modules/@actions/github/node_modules/@actions/http-client/src/index.ts","../node_modules/@octokit/core/node_modules/universal-user-agent/index.js","../node_modules/@octokit/core/node_modules/before-after-hook/lib/register.js","../node_modules/@octokit/core/node_modules/before-after-hook/lib/add.js","../node_modules/@octokit/core/node_modules/before-after-hook/lib/remove.js","../node_modules/@octokit/core/node_modules/before-after-hook/index.js","../node_modules/@octokit/endpoint/node_modules/universal-user-agent/index.js","../node_modules/@octokit/endpoint/dist-bundle/index.js","../node_modules/@octokit/request/node_modules/universal-user-agent/index.js","../node_modules/fast-content-type-parse/index.js","../node_modules/json-with-bigint/json-with-bigint.js","../node_modules/@octokit/request-error/dist-src/index.js","../node_modules/@octokit/request/dist-bundle/index.js","../node_modules/@octokit/graphql/node_modules/universal-user-agent/index.js","../node_modules/@octokit/graphql/dist-bundle/index.js","../node_modules/@octokit/auth-token/dist-bundle/index.js","../node_modules/@octokit/core/dist-src/version.js","../node_modules/@octokit/core/dist-src/index.js","../node_modules/@octokit/src/version.ts","../node_modules/@octokit/src/generated/endpoints.ts","../node_modules/@octokit/src/endpoints-to-methods.ts","../node_modules/@octokit/src/index.ts","../node_modules/@octokit/plugin-paginate-rest/dist-bundle/index.js","../node_modules/@octokit/plugin-request-log/dist-src/version.js","../node_modules/@octokit/plugin-request-log/dist-src/index.js","../node_modules/@octokit/rest/dist-src/version.js","../node_modules/@octokit/rest/dist-src/index.js","../node_modules/bottleneck/light.js","../node_modules/@octokit/plugin-retry/node_modules/@octokit/request-error/dist-src/index.js","../node_modules/@octokit/plugin-retry/dist-bundle/index.js","../node_modules/adm-zip/util/constants.js","../node_modules/adm-zip/util/errors.js","../node_modules/adm-zip/util/utils.js","../node_modules/adm-zip/util/fattr.js","../node_modules/adm-zip/util/decoder.js","../node_modules/adm-zip/util/index.js","../node_modules/adm-zip/headers/entryHeader.js","../node_modules/adm-zip/headers/mainHeader.js","../node_modules/adm-zip/headers/index.js","../node_modules/adm-zip/methods/deflater.js","../node_modules/adm-zip/methods/inflater.js","../node_modules/adm-zip/methods/zipcrypto.js","../node_modules/adm-zip/methods/index.js","../node_modules/adm-zip/zipEntry.js","../node_modules/adm-zip/zipFile.js","../node_modules/adm-zip/adm-zip.js","../node_modules/@actions/artifact/package.json","../node_modules/@actions/artifact/lib/internal/shared/package-version.cjs","../node_modules/ms/index.js","../node_modules/debug/src/common.js","../node_modules/debug/src/browser.js","../node_modules/has-flag/index.js","../node_modules/supports-color/index.js","../node_modules/debug/src/node.js","../node_modules/debug/src/index.js","../node_modules/agent-base/src/helpers.ts","../node_modules/agent-base/src/index.ts","../node_modules/https-proxy-agent/src/parse-proxy-response.ts","../node_modules/https-proxy-agent/src/index.ts","../node_modules/http-proxy-agent/src/index.ts","../node_modules/@azure/core-tracing/src/state-cjs.cts","../node_modules/@azure/core-client/src/state-cjs.cts","../node_modules/fast-xml-parser/src/util.js","../node_modules/fast-xml-parser/src/validator.js","../node_modules/@nodable/entities/src/entities.js","../node_modules/@nodable/entities/src/EntityDecoder.js","../node_modules/@nodable/entities/src/index.js","../node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js","../node_modules/fast-xml-parser/src/xmlparser/xmlNode.js","../node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js","../node_modules/strnum/strnum.js","../node_modules/fast-xml-parser/src/ignoreAttributes.js","../node_modules/path-expression-matcher/src/Expression.js","../node_modules/path-expression-matcher/src/ExpressionSet.js","../node_modules/path-expression-matcher/src/Matcher.js","../node_modules/path-expression-matcher/src/index.js","../node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js","../node_modules/fast-xml-parser/src/xmlparser/node2json.js","../node_modules/fast-xml-parser/src/xmlparser/XMLParser.js","../node_modules/fast-xml-builder/src/orderedJs2Xml.js","../node_modules/fast-xml-builder/src/ignoreAttributes.js","../node_modules/fast-xml-builder/src/fxb.js","../node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js","../node_modules/fast-xml-parser/src/fxp.js","../node_modules/readdir-glob/node_modules/minimatch/lib/path.js","../node_modules/balanced-match/index.js","../node_modules/brace-expansion/index.js","../node_modules/readdir-glob/node_modules/minimatch/minimatch.js","../node_modules/readdir-glob/index.js","../node_modules/async/dist/async.mjs","../node_modules/graceful-fs/polyfills.js","../node_modules/graceful-fs/legacy-streams.js","../node_modules/graceful-fs/clone.js","../node_modules/graceful-fs/graceful-fs.js","../node_modules/is-stream/index.js","../node_modules/process-nextick-args/index.js","../node_modules/lazystream/node_modules/isarray/index.js","../node_modules/lazystream/node_modules/readable-stream/lib/internal/streams/stream.js","../node_modules/safe-buffer/index.js","../node_modules/core-util-is/lib/util.js","../node_modules/inherits/inherits_browser.js","../node_modules/inherits/inherits.js","../node_modules/lazystream/node_modules/readable-stream/lib/internal/streams/BufferList.js","../node_modules/lazystream/node_modules/readable-stream/lib/internal/streams/destroy.js","../node_modules/util-deprecate/node.js","../node_modules/lazystream/node_modules/readable-stream/lib/_stream_writable.js","../node_modules/lazystream/node_modules/readable-stream/lib/_stream_duplex.js","../node_modules/lazystream/node_modules/string_decoder/lib/string_decoder.js","../node_modules/lazystream/node_modules/readable-stream/lib/_stream_readable.js","../node_modules/lazystream/node_modules/readable-stream/lib/_stream_transform.js","../node_modules/lazystream/node_modules/readable-stream/lib/_stream_passthrough.js","../node_modules/lazystream/node_modules/readable-stream/readable.js","../node_modules/lazystream/node_modules/readable-stream/passthrough.js","../node_modules/lazystream/lib/lazystream.js","../node_modules/normalize-path/index.js","../node_modules/lodash/identity.js","../node_modules/lodash/_apply.js","../node_modules/lodash/_overRest.js","../node_modules/lodash/constant.js","../node_modules/lodash/_freeGlobal.js","../node_modules/lodash/_root.js","../node_modules/lodash/_Symbol.js","../node_modules/lodash/_getRawTag.js","../node_modules/lodash/_objectToString.js","../node_modules/lodash/_baseGetTag.js","../node_modules/lodash/isObject.js","../node_modules/lodash/isFunction.js","../node_modules/lodash/_coreJsData.js","../node_modules/lodash/_isMasked.js","../node_modules/lodash/_toSource.js","../node_modules/lodash/_baseIsNative.js","../node_modules/lodash/_getValue.js","../node_modules/lodash/_getNative.js","../node_modules/lodash/_defineProperty.js","../node_modules/lodash/_baseSetToString.js","../node_modules/lodash/_shortOut.js","../node_modules/lodash/_setToString.js","../node_modules/lodash/_baseRest.js","../node_modules/lodash/eq.js","../node_modules/lodash/isLength.js","../node_modules/lodash/isArrayLike.js","../node_modules/lodash/_isIndex.js","../node_modules/lodash/_isIterateeCall.js","../node_modules/lodash/_baseTimes.js","../node_modules/lodash/isObjectLike.js","../node_modules/lodash/_baseIsArguments.js","../node_modules/lodash/isArguments.js","../node_modules/lodash/isArray.js","../node_modules/lodash/stubFalse.js","../node_modules/lodash/isBuffer.js","../node_modules/lodash/_baseIsTypedArray.js","../node_modules/lodash/_baseUnary.js","../node_modules/lodash/_nodeUtil.js","../node_modules/lodash/isTypedArray.js","../node_modules/lodash/_arrayLikeKeys.js","../node_modules/lodash/_isPrototype.js","../node_modules/lodash/_nativeKeysIn.js","../node_modules/lodash/_baseKeysIn.js","../node_modules/lodash/keysIn.js","../node_modules/lodash/defaults.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/ours/primordials.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/ours/util/inspect.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/ours/errors.js","../node_modules/event-target-shim/src/event.mjs","../node_modules/event-target-shim/src/event-target.mjs","../node_modules/abort-controller/src/abort-signal.ts","../node_modules/abort-controller/src/abort-controller.ts","../node_modules/archiver-utils/node_modules/readable-stream/lib/ours/util.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/internal/validators.js","../node_modules/process/index.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/internal/streams/utils.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/internal/streams/end-of-stream.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/internal/streams/destroy.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/internal/streams/legacy.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/internal/streams/add-abort-signal.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/internal/streams/buffer_list.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/internal/streams/state.js","../node_modules/archiver-utils/node_modules/safe-buffer/index.js","../node_modules/archiver-utils/node_modules/string_decoder/lib/string_decoder.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/internal/streams/from.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/internal/streams/readable.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/internal/streams/writable.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/internal/streams/duplexify.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/internal/streams/duplex.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/internal/streams/transform.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/internal/streams/passthrough.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/internal/streams/pipeline.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/internal/streams/compose.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/internal/streams/operators.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/stream/promises.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/stream.js","../node_modules/archiver-utils/node_modules/readable-stream/lib/ours/index.js","../node_modules/lodash/_arrayPush.js","../node_modules/lodash/_isFlattenable.js","../node_modules/lodash/_baseFlatten.js","../node_modules/lodash/flatten.js","../node_modules/lodash/_nativeCreate.js","../node_modules/lodash/_hashClear.js","../node_modules/lodash/_hashDelete.js","../node_modules/lodash/_hashGet.js","../node_modules/lodash/_hashHas.js","../node_modules/lodash/_hashSet.js","../node_modules/lodash/_Hash.js","../node_modules/lodash/_listCacheClear.js","../node_modules/lodash/_assocIndexOf.js","../node_modules/lodash/_listCacheDelete.js","../node_modules/lodash/_listCacheGet.js","../node_modules/lodash/_listCacheHas.js","../node_modules/lodash/_listCacheSet.js","../node_modules/lodash/_ListCache.js","../node_modules/lodash/_Map.js","../node_modules/lodash/_mapCacheClear.js","../node_modules/lodash/_isKeyable.js","../node_modules/lodash/_getMapData.js","../node_modules/lodash/_mapCacheDelete.js","../node_modules/lodash/_mapCacheGet.js","../node_modules/lodash/_mapCacheHas.js","../node_modules/lodash/_mapCacheSet.js","../node_modules/lodash/_MapCache.js","../node_modules/lodash/_setCacheAdd.js","../node_modules/lodash/_setCacheHas.js","../node_modules/lodash/_SetCache.js","../node_modules/lodash/_baseFindIndex.js","../node_modules/lodash/_baseIsNaN.js","../node_modules/lodash/_strictIndexOf.js","../node_modules/lodash/_baseIndexOf.js","../node_modules/lodash/_arrayIncludes.js","../node_modules/lodash/_arrayIncludesWith.js","../node_modules/lodash/_arrayMap.js","../node_modules/lodash/_cacheHas.js","../node_modules/lodash/_baseDifference.js","../node_modules/lodash/isArrayLikeObject.js","../node_modules/lodash/difference.js","../node_modules/lodash/_Set.js","../node_modules/lodash/noop.js","../node_modules/lodash/_setToArray.js","../node_modules/lodash/_createSet.js","../node_modules/lodash/_baseUniq.js","../node_modules/lodash/union.js","../node_modules/lodash/_overArg.js","../node_modules/lodash/_getPrototype.js","../node_modules/lodash/isPlainObject.js","../node_modules/minimatch/src/assert-valid-pattern.ts","../node_modules/minimatch/src/brace-expressions.ts","../node_modules/minimatch/src/unescape.ts","../node_modules/minimatch/src/ast.ts","../node_modules/minimatch/src/escape.ts","../node_modules/minimatch/src/index.ts","../node_modules/archiver-utils/node_modules/lru-cache/src/index.ts","../node_modules/minipass/src/index.ts","../node_modules/archiver-utils/node_modules/path-scurry/src/index.ts","../node_modules/archiver-utils/node_modules/glob/src/pattern.ts","../node_modules/archiver-utils/node_modules/glob/src/ignore.ts","../node_modules/archiver-utils/node_modules/glob/src/processor.ts","../node_modules/archiver-utils/node_modules/glob/src/walker.ts","../node_modules/archiver-utils/node_modules/glob/src/glob.ts","../node_modules/archiver-utils/node_modules/glob/src/has-magic.ts","../node_modules/archiver-utils/node_modules/glob/src/index.ts","../node_modules/archiver-utils/file.js","../node_modules/archiver-utils/index.js","../node_modules/archiver/lib/error.js","../node_modules/archiver/node_modules/readable-stream/lib/ours/primordials.js","../node_modules/archiver/node_modules/readable-stream/lib/ours/util/inspect.js","../node_modules/archiver/node_modules/readable-stream/lib/ours/errors.js","../node_modules/archiver/node_modules/readable-stream/lib/ours/util.js","../node_modules/archiver/node_modules/readable-stream/lib/internal/validators.js","../node_modules/archiver/node_modules/readable-stream/lib/internal/streams/utils.js","../node_modules/archiver/node_modules/readable-stream/lib/internal/streams/end-of-stream.js","../node_modules/archiver/node_modules/readable-stream/lib/internal/streams/destroy.js","../node_modules/archiver/node_modules/readable-stream/lib/internal/streams/legacy.js","../node_modules/archiver/node_modules/readable-stream/lib/internal/streams/add-abort-signal.js","../node_modules/archiver/node_modules/readable-stream/lib/internal/streams/buffer_list.js","../node_modules/archiver/node_modules/readable-stream/lib/internal/streams/state.js","../node_modules/archiver/node_modules/safe-buffer/index.js","../node_modules/archiver/node_modules/string_decoder/lib/string_decoder.js","../node_modules/archiver/node_modules/readable-stream/lib/internal/streams/from.js","../node_modules/archiver/node_modules/readable-stream/lib/internal/streams/readable.js","../node_modules/archiver/node_modules/readable-stream/lib/internal/streams/writable.js","../node_modules/archiver/node_modules/readable-stream/lib/internal/streams/duplexify.js","../node_modules/archiver/node_modules/readable-stream/lib/internal/streams/duplex.js","../node_modules/archiver/node_modules/readable-stream/lib/internal/streams/transform.js","../node_modules/archiver/node_modules/readable-stream/lib/internal/streams/passthrough.js","../node_modules/archiver/node_modules/readable-stream/lib/internal/streams/pipeline.js","../node_modules/archiver/node_modules/readable-stream/lib/internal/streams/compose.js","../node_modules/archiver/node_modules/readable-stream/lib/internal/streams/operators.js","../node_modules/archiver/node_modules/readable-stream/lib/stream/promises.js","../node_modules/archiver/node_modules/readable-stream/lib/stream.js","../node_modules/archiver/node_modules/readable-stream/lib/ours/index.js","../node_modules/archiver/lib/core.js","../node_modules/compress-commons/lib/archivers/archive-entry.js","../node_modules/compress-commons/lib/archivers/zip/util.js","../node_modules/compress-commons/lib/archivers/zip/general-purpose-bit.js","../node_modules/compress-commons/lib/archivers/zip/unix-stat.js","../node_modules/compress-commons/lib/archivers/zip/constants.js","../node_modules/compress-commons/lib/archivers/zip/zip-archive-entry.js","../node_modules/compress-commons/node_modules/readable-stream/lib/ours/primordials.js","../node_modules/compress-commons/node_modules/readable-stream/lib/ours/util/inspect.js","../node_modules/compress-commons/node_modules/readable-stream/lib/ours/errors.js","../node_modules/compress-commons/node_modules/readable-stream/lib/ours/util.js","../node_modules/compress-commons/node_modules/readable-stream/lib/internal/validators.js","../node_modules/compress-commons/node_modules/readable-stream/lib/internal/streams/utils.js","../node_modules/compress-commons/node_modules/readable-stream/lib/internal/streams/end-of-stream.js","../node_modules/compress-commons/node_modules/readable-stream/lib/internal/streams/destroy.js","../node_modules/compress-commons/node_modules/readable-stream/lib/internal/streams/legacy.js","../node_modules/compress-commons/node_modules/readable-stream/lib/internal/streams/add-abort-signal.js","../node_modules/compress-commons/node_modules/readable-stream/lib/internal/streams/buffer_list.js","../node_modules/compress-commons/node_modules/readable-stream/lib/internal/streams/state.js","../node_modules/compress-commons/node_modules/safe-buffer/index.js","../node_modules/compress-commons/node_modules/string_decoder/lib/string_decoder.js","../node_modules/compress-commons/node_modules/readable-stream/lib/internal/streams/from.js","../node_modules/compress-commons/node_modules/readable-stream/lib/internal/streams/readable.js","../node_modules/compress-commons/node_modules/readable-stream/lib/internal/streams/writable.js","../node_modules/compress-commons/node_modules/readable-stream/lib/internal/streams/duplexify.js","../node_modules/compress-commons/node_modules/readable-stream/lib/internal/streams/duplex.js","../node_modules/compress-commons/node_modules/readable-stream/lib/internal/streams/transform.js","../node_modules/compress-commons/node_modules/readable-stream/lib/internal/streams/passthrough.js","../node_modules/compress-commons/node_modules/readable-stream/lib/internal/streams/pipeline.js","../node_modules/compress-commons/node_modules/readable-stream/lib/internal/streams/compose.js","../node_modules/compress-commons/node_modules/readable-stream/lib/internal/streams/operators.js","../node_modules/compress-commons/node_modules/readable-stream/lib/stream/promises.js","../node_modules/compress-commons/node_modules/readable-stream/lib/stream.js","../node_modules/compress-commons/node_modules/readable-stream/lib/ours/index.js","../node_modules/compress-commons/lib/util/index.js","../node_modules/compress-commons/lib/archivers/archive-output-stream.js","../node_modules/crc-32/crc32.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/ours/primordials.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/ours/util/inspect.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/ours/errors.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/ours/util.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/internal/validators.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/internal/streams/utils.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/internal/streams/end-of-stream.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/internal/streams/destroy.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/internal/streams/legacy.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/internal/streams/add-abort-signal.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/internal/streams/buffer_list.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/internal/streams/state.js","../node_modules/crc32-stream/node_modules/safe-buffer/index.js","../node_modules/crc32-stream/node_modules/string_decoder/lib/string_decoder.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/internal/streams/from.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/internal/streams/readable.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/internal/streams/writable.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/internal/streams/duplexify.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/internal/streams/duplex.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/internal/streams/transform.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/internal/streams/passthrough.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/internal/streams/pipeline.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/internal/streams/compose.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/internal/streams/operators.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/stream/promises.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/stream.js","../node_modules/crc32-stream/node_modules/readable-stream/lib/ours/index.js","../node_modules/crc32-stream/lib/crc32-stream.js","../node_modules/crc32-stream/lib/deflate-crc32-stream.js","../node_modules/crc32-stream/lib/index.js","../node_modules/compress-commons/lib/archivers/zip/zip-archive-output-stream.js","../node_modules/compress-commons/lib/compress-commons.js","../node_modules/zip-stream/index.js","../node_modules/archiver/lib/plugins/zip.js","../node_modules/fast-fifo/fixed-size.js","../node_modules/fast-fifo/index.js","../node_modules/b4a/index.js","../node_modules/text-decoder/lib/pass-through-decoder.js","../node_modules/text-decoder/lib/utf8-decoder.js","../node_modules/text-decoder/index.js","../node_modules/streamx/index.js","../node_modules/tar-stream/headers.js","../node_modules/tar-stream/extract.js","../node_modules/tar-stream/constants.js","../node_modules/tar-stream/pack.js","../node_modules/tar-stream/index.js","../node_modules/archiver/lib/plugins/tar.js","../node_modules/buffer-crc32/dist/index.cjs","../node_modules/archiver/lib/plugins/json.js","../node_modules/archiver/index.js","../node_modules/traverse/index.js","../node_modules/chainsaw/index.js","../node_modules/buffers/index.js","../node_modules/binary/lib/vars.js","../node_modules/binary/index.js","../node_modules/unzip-stream/lib/matcher-stream.js","../node_modules/unzip-stream/lib/entry.js","../node_modules/unzip-stream/lib/unzip-stream.js","../node_modules/unzip-stream/lib/parser-stream.js","../node_modules/unzip-stream/node_modules/mkdirp/index.js","../node_modules/unzip-stream/lib/extract.js","../node_modules/unzip-stream/unzip.js","../node_modules/universalify/index.js","../node_modules/fs-extra/lib/fs/index.js","../node_modules/fs-extra/lib/mkdirs/utils.js","../node_modules/fs-extra/lib/mkdirs/make-dir.js","../node_modules/fs-extra/lib/mkdirs/index.js","../node_modules/fs-extra/lib/path-exists/index.js","../node_modules/fs-extra/lib/util/utimes.js","../node_modules/fs-extra/lib/util/stat.js","../node_modules/fs-extra/lib/copy/copy.js","../node_modules/fs-extra/lib/copy/copy-sync.js","../node_modules/fs-extra/lib/copy/index.js","../node_modules/fs-extra/lib/remove/index.js","../node_modules/fs-extra/lib/empty/index.js","../node_modules/fs-extra/lib/ensure/file.js","../node_modules/fs-extra/lib/ensure/link.js","../node_modules/fs-extra/lib/ensure/symlink-paths.js","../node_modules/fs-extra/lib/ensure/symlink-type.js","../node_modules/fs-extra/lib/ensure/symlink.js","../node_modules/fs-extra/lib/ensure/index.js","../node_modules/jsonfile/utils.js","../node_modules/jsonfile/index.js","../node_modules/fs-extra/lib/json/jsonfile.js","../node_modules/fs-extra/lib/output-file/index.js","../node_modules/fs-extra/lib/json/output-json.js","../node_modules/fs-extra/lib/json/output-json-sync.js","../node_modules/fs-extra/lib/json/index.js","../node_modules/fs-extra/lib/move/move.js","../node_modules/fs-extra/lib/move/move-sync.js","../node_modules/fs-extra/lib/move/index.js","../node_modules/fs-extra/lib/index.js","../node_modules/xml2js/lib/defaults.js","../node_modules/xmlbuilder/lib/Utility.js","../node_modules/xmlbuilder/lib/XMLDOMImplementation.js","../node_modules/xmlbuilder/lib/XMLDOMErrorHandler.js","../node_modules/xmlbuilder/lib/XMLDOMStringList.js","../node_modules/xmlbuilder/lib/XMLDOMConfiguration.js","../node_modules/xmlbuilder/lib/NodeType.js","../node_modules/xmlbuilder/lib/XMLAttribute.js","../node_modules/xmlbuilder/lib/XMLNamedNodeMap.js","../node_modules/xmlbuilder/lib/XMLElement.js","../node_modules/xmlbuilder/lib/XMLCharacterData.js","../node_modules/xmlbuilder/lib/XMLCData.js","../node_modules/xmlbuilder/lib/XMLComment.js","../node_modules/xmlbuilder/lib/XMLDeclaration.js","../node_modules/xmlbuilder/lib/XMLDTDAttList.js","../node_modules/xmlbuilder/lib/XMLDTDEntity.js","../node_modules/xmlbuilder/lib/XMLDTDElement.js","../node_modules/xmlbuilder/lib/XMLDTDNotation.js","../node_modules/xmlbuilder/lib/XMLDocType.js","../node_modules/xmlbuilder/lib/XMLRaw.js","../node_modules/xmlbuilder/lib/XMLText.js","../node_modules/xmlbuilder/lib/XMLProcessingInstruction.js","../node_modules/xmlbuilder/lib/XMLDummy.js","../node_modules/xmlbuilder/lib/XMLNodeList.js","../node_modules/xmlbuilder/lib/DocumentPosition.js","../node_modules/xmlbuilder/lib/XMLNode.js","../node_modules/xmlbuilder/lib/XMLStringifier.js","../node_modules/xmlbuilder/lib/WriterState.js","../node_modules/xmlbuilder/lib/XMLWriterBase.js","../node_modules/xmlbuilder/lib/XMLStringWriter.js","../node_modules/xmlbuilder/lib/XMLDocument.js","../node_modules/xmlbuilder/lib/XMLDocumentCB.js","../node_modules/xmlbuilder/lib/XMLStreamWriter.js","../node_modules/xmlbuilder/lib/index.js","../node_modules/xml2js/lib/builder.js","../node_modules/sax/lib/sax.js","../node_modules/xml2js/lib/bom.js","../node_modules/xml2js/lib/processors.js","../node_modules/xml2js/lib/parser.js","../node_modules/xml2js/lib/xml2js.js","../node_modules/handlebars/lib/handlebars/utils.js","../node_modules/handlebars/lib/handlebars/exception.js","../node_modules/handlebars/lib/handlebars/helpers/block-helper-missing.js","../node_modules/handlebars/lib/handlebars/helpers/each.js","../node_modules/handlebars/lib/handlebars/helpers/helper-missing.js","../node_modules/handlebars/lib/handlebars/helpers/if.js","../node_modules/handlebars/lib/handlebars/helpers/log.js","../node_modules/handlebars/lib/handlebars/helpers/lookup.js","../node_modules/handlebars/lib/handlebars/helpers/with.js","../node_modules/handlebars/lib/handlebars/helpers.js","../node_modules/handlebars/lib/handlebars/decorators/inline.js","../node_modules/handlebars/lib/handlebars/decorators.js","../node_modules/handlebars/lib/handlebars/logger.js","../node_modules/handlebars/lib/handlebars/internal/proto-access.js","../node_modules/handlebars/lib/handlebars/base.js","../node_modules/handlebars/lib/handlebars/safe-string.js","../node_modules/handlebars/lib/handlebars/internal/wrapHelper.js","../node_modules/handlebars/lib/handlebars/runtime.js","../node_modules/handlebars/lib/handlebars/no-conflict.js","../node_modules/handlebars/lib/handlebars.runtime.js","../node_modules/handlebars/lib/handlebars/compiler/ast.js","../node_modules/handlebars/lib/handlebars/compiler/parser.js","../node_modules/handlebars/lib/handlebars/compiler/visitor.js","../node_modules/handlebars/lib/handlebars/compiler/whitespace-control.js","../node_modules/handlebars/lib/handlebars/compiler/helpers.js","../node_modules/handlebars/lib/handlebars/compiler/base.js","../node_modules/handlebars/lib/handlebars/compiler/compiler.js","../node_modules/source-map/lib/base64.js","../node_modules/source-map/lib/base64-vlq.js","../node_modules/source-map/lib/util.js","../node_modules/source-map/lib/array-set.js","../node_modules/source-map/lib/mapping-list.js","../node_modules/source-map/lib/source-map-generator.js","../node_modules/source-map/lib/binary-search.js","../node_modules/source-map/lib/quick-sort.js","../node_modules/source-map/lib/source-map-consumer.js","../node_modules/source-map/lib/source-node.js","../node_modules/source-map/source-map.js","../node_modules/handlebars/lib/handlebars/compiler/code-gen.js","../node_modules/handlebars/lib/handlebars/compiler/javascript-compiler.js","../node_modules/handlebars/lib/handlebars.js","../node_modules/handlebars/lib/handlebars/compiler/printer.js","../node_modules/handlebars/lib/index.js","../node_modules/entities/lib/maps/entities.json","../node_modules/entities/lib/maps/legacy.json","../node_modules/entities/lib/maps/xml.json","../node_modules/entities/lib/maps/decode.json","../node_modules/entities/lib/decode_codepoint.js","../node_modules/entities/lib/decode.js","../node_modules/entities/lib/encode.js","../node_modules/entities/lib/index.js","../node_modules/ansi-to-html/src/ansi_to_html.js","../node_modules/slack-ctrf/dist/message-formatter.js","../node_modules/slack-ctrf/dist/slack-notify.js","../node_modules/slack-ctrf/dist/utils/common.js","../node_modules/slack-ctrf/dist/slack-reporter.js","../node_modules/slack-ctrf/dist/index.js","../node_modules/teams-ctrf/dist/message-formatter.js","../node_modules/teams-ctrf/dist/teams-notify.js","../node_modules/teams-ctrf/dist/teams-reporter.js","../node_modules/teams-ctrf/dist/index.js","../node_modules/y18n/build/index.cjs","../node_modules/yargs-parser/build/index.cjs","../node_modules/ansi-regex/index.js","../node_modules/strip-ansi/index.js","../node_modules/is-fullwidth-code-point/index.js","../node_modules/emoji-regex/index.js","../node_modules/string-width/index.js","../node_modules/color-name/index.js","../node_modules/color-convert/conversions.js","../node_modules/color-convert/route.js","../node_modules/color-convert/index.js","../node_modules/ansi-styles/index.js","../node_modules/wrap-ansi/index.js","../node_modules/ai-ctrf/node_modules/cliui/build/index.cjs","../node_modules/escalade/sync/index.js","../node_modules/get-caller-file/index.ts","../node_modules/require-directory/index.js","../node_modules/ai-ctrf/node_modules/yargs/build/index.cjs","../node_modules/ai-ctrf/node_modules/yargs/yargs","../node_modules/ai-ctrf/node_modules/yargs/helpers/index.js","../node_modules/ai-ctrf/dist/assess.js","../node_modules/ai-ctrf/dist/common.js","../node_modules/ai-ctrf/dist/constants.js","../node_modules/openai/src/internal/qs/formats.ts","../node_modules/openai/src/internal/qs/utils.ts","../node_modules/openai/src/internal/qs/stringify.ts","../node_modules/openai/src/internal/qs/index.ts","../node_modules/openai/src/version.ts","../node_modules/openai/src/_shims/registry.ts","../node_modules/webidl-conversions/lib/index.js","../node_modules/whatwg-url/lib/utils.js","../node_modules/tr46/lib/mappingTable.json","../node_modules/tr46/index.js","../node_modules/whatwg-url/lib/url-state-machine.js","../node_modules/whatwg-url/lib/URL-impl.js","../node_modules/whatwg-url/lib/URL.js","../node_modules/whatwg-url/lib/public-api.js","../node_modules/node-fetch/lib/index.mjs","../node_modules/web-streams-polyfill/dist/ponyfill.js","../node_modules/formdata-node/lib/cjs/isFunction.js","../node_modules/formdata-node/lib/cjs/blobHelpers.js","../node_modules/formdata-node/lib/cjs/Blob.js","../node_modules/formdata-node/lib/cjs/File.js","../node_modules/formdata-node/lib/cjs/isFile.js","../node_modules/formdata-node/lib/cjs/isBlob.js","../node_modules/formdata-node/lib/cjs/deprecateConstructorEntries.js","../node_modules/formdata-node/lib/cjs/FormData.js","../node_modules/formdata-node/lib/cjs/index.js","../node_modules/humanize-ms/index.js","../node_modules/agentkeepalive/lib/constants.js","../node_modules/agentkeepalive/lib/agent.js","../node_modules/agentkeepalive/lib/https_agent.js","../node_modules/agentkeepalive/index.js","../node_modules/form-data-encoder/lib/cjs/util/createBoundary.js","../node_modules/form-data-encoder/lib/cjs/util/isPlainObject.js","../node_modules/form-data-encoder/lib/cjs/util/normalizeValue.js","../node_modules/form-data-encoder/lib/cjs/util/escapeName.js","../node_modules/form-data-encoder/lib/cjs/util/isFunction.js","../node_modules/form-data-encoder/lib/cjs/util/isFileLike.js","../node_modules/form-data-encoder/lib/cjs/util/isFormData.js","../node_modules/form-data-encoder/lib/cjs/FormDataEncoder.js","../node_modules/form-data-encoder/lib/cjs/FileLike.js","../node_modules/form-data-encoder/lib/cjs/FormDataLike.js","../node_modules/form-data-encoder/lib/cjs/index.js","../node_modules/openai/src/_shims/MultipartBody.ts","../node_modules/node-domexception/index.js","../node_modules/formdata-node/lib/cjs/isPlainObject.js","../node_modules/formdata-node/lib/cjs/fileFromPath.js","../node_modules/openai/src/_shims/node-runtime.ts","../node_modules/openai/src/_shims/auto/runtime-node.ts","../node_modules/openai/_shims/index.js","../node_modules/openai/src/error.ts","../node_modules/openai/src/internal/decoders/line.ts","../node_modules/openai/src/internal/stream-utils.ts","../node_modules/openai/src/streaming.ts","../node_modules/openai/src/uploads.ts","../node_modules/openai/src/core.ts","../node_modules/openai/src/pagination.ts","../node_modules/openai/src/resource.ts","../node_modules/openai/src/resources/chat/completions/messages.ts","../node_modules/openai/src/resources/chat/completions/completions.ts","../node_modules/openai/src/resources/chat/chat.ts","../node_modules/openai/src/resources/chat/completions/index.ts","../node_modules/openai/src/resources/chat/index.ts","../node_modules/openai/src/resources/audio/speech.ts","../node_modules/openai/src/resources/audio/transcriptions.ts","../node_modules/openai/src/resources/audio/translations.ts","../node_modules/openai/src/resources/audio/audio.ts","../node_modules/openai/src/resources/batches.ts","../node_modules/openai/src/lib/EventStream.ts","../node_modules/openai/src/lib/AssistantStream.ts","../node_modules/openai/src/resources/beta/assistants.ts","../node_modules/openai/src/lib/RunnableFunction.ts","../node_modules/openai/src/lib/chatCompletionUtils.ts","../node_modules/openai/src/lib/parser.ts","../node_modules/openai/src/lib/AbstractChatCompletionRunner.ts","../node_modules/openai/src/lib/ChatCompletionRunner.ts","../node_modules/openai/src/_vendor/partial-json-parser/parser.ts","../node_modules/openai/src/lib/ChatCompletionStream.ts","../node_modules/openai/src/lib/ChatCompletionStreamingRunner.ts","../node_modules/openai/src/resources/beta/chat/completions.ts","../node_modules/openai/src/resources/beta/chat/chat.ts","../node_modules/openai/src/resources/beta/realtime/sessions.ts","../node_modules/openai/src/resources/beta/realtime/transcription-sessions.ts","../node_modules/openai/src/resources/beta/realtime/realtime.ts","../node_modules/openai/src/resources/beta/threads/messages.ts","../node_modules/openai/src/resources/beta/threads/runs/steps.ts","../node_modules/openai/src/resources/beta/threads/runs/runs.ts","../node_modules/openai/src/resources/beta/threads/threads.ts","../node_modules/openai/src/resources/beta/beta.ts","../node_modules/openai/src/resources/completions.ts","../node_modules/openai/src/resources/containers/files/content.ts","../node_modules/openai/src/resources/containers/files/files.ts","../node_modules/openai/src/resources/containers/containers.ts","../node_modules/openai/src/resources/embeddings.ts","../node_modules/openai/src/resources/evals/runs/output-items.ts","../node_modules/openai/src/resources/evals/runs/runs.ts","../node_modules/openai/src/resources/evals/evals.ts","../node_modules/openai/src/resources/files.ts","../node_modules/openai/src/resources/fine-tuning/methods.ts","../node_modules/openai/src/resources/fine-tuning/alpha/graders.ts","../node_modules/openai/src/resources/fine-tuning/alpha/alpha.ts","../node_modules/openai/src/resources/fine-tuning/checkpoints/permissions.ts","../node_modules/openai/src/resources/fine-tuning/checkpoints/checkpoints.ts","../node_modules/openai/src/resources/fine-tuning/jobs/checkpoints.ts","../node_modules/openai/src/resources/fine-tuning/jobs/jobs.ts","../node_modules/openai/src/resources/fine-tuning/fine-tuning.ts","../node_modules/openai/src/resources/graders/grader-models.ts","../node_modules/openai/src/resources/graders/graders.ts","../node_modules/openai/src/resources/images.ts","../node_modules/openai/src/resources/models.ts","../node_modules/openai/src/resources/moderations.ts","../node_modules/openai/src/lib/ResponsesParser.ts","../node_modules/openai/src/resources/responses/input-items.ts","../node_modules/openai/src/lib/responses/ResponseStream.ts","../node_modules/openai/src/resources/responses/responses.ts","../node_modules/openai/src/resources/uploads/parts.ts","../node_modules/openai/src/resources/uploads/uploads.ts","../node_modules/openai/src/lib/Util.ts","../node_modules/openai/src/resources/vector-stores/files.ts","../node_modules/openai/src/resources/vector-stores/file-batches.ts","../node_modules/openai/src/resources/vector-stores/vector-stores.ts","../node_modules/openai/src/resources/index.ts","../node_modules/openai/src/index.ts","../node_modules/@anthropic-ai/sdk/src/version.ts","../node_modules/@anthropic-ai/sdk/src/_shims/registry.ts","../node_modules/@anthropic-ai/sdk/src/_shims/MultipartBody.ts","../node_modules/@anthropic-ai/sdk/src/_shims/node-runtime.ts","../node_modules/@anthropic-ai/sdk/src/_shims/auto/runtime-node.ts","../node_modules/@anthropic-ai/sdk/_shims/index.js","../node_modules/@anthropic-ai/sdk/src/streaming.ts","../node_modules/@anthropic-ai/sdk/src/uploads.ts","../node_modules/@anthropic-ai/sdk/src/core.ts","../node_modules/@anthropic-ai/sdk/src/error.ts","../node_modules/@anthropic-ai/sdk/src/resource.ts","../node_modules/@anthropic-ai/sdk/src/_vendor/partial-json-parser/parser.ts","../node_modules/@anthropic-ai/sdk/src/lib/PromptCachingBetaMessageStream.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/prompt-caching/messages.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/prompt-caching/prompt-caching.ts","../node_modules/@anthropic-ai/sdk/src/resources/beta/beta.ts","../node_modules/@anthropic-ai/sdk/src/resources/completions.ts","../node_modules/@anthropic-ai/sdk/src/lib/MessageStream.ts","../node_modules/@anthropic-ai/sdk/src/resources/messages.ts","../node_modules/@anthropic-ai/sdk/src/resources/index.ts","../node_modules/@anthropic-ai/sdk/src/index.ts","../node_modules/ai-ctrf/dist/models/claude.js","../node_modules/ai-ctrf/dist/models/azure-openai.js","../node_modules/ai-ctrf/dist/models/grok.js","../node_modules/ai-ctrf/dist/models/deepseek.js","../node_modules/@google/generative-ai/dist/index.js","../node_modules/ai-ctrf/dist/models/gemini.js","../node_modules/ai-ctrf/dist/models/perplexity.js","../node_modules/ai-ctrf/dist/models/openrouter.js","../node_modules/@aws-sdk/middleware-eventstream/dist-es/eventStreamConfiguration.js","../node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js","../node_modules/@smithy/protocol-http/dist-es/extensions/index.js","../node_modules/@smithy/types/dist-es/abort.js","../node_modules/@smithy/types/dist-es/auth/auth.js","../node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js","../node_modules/@smithy/types/dist-es/auth/HttpAuthScheme.js","../node_modules/@smithy/types/dist-es/auth/HttpAuthSchemeProvider.js","../node_modules/@smithy/types/dist-es/auth/HttpSigner.js","../node_modules/@smithy/types/dist-es/auth/IdentityProviderConfig.js","../node_modules/@smithy/types/dist-es/auth/index.js","../node_modules/@smithy/types/dist-es/blob/blob-payload-input-types.js","../node_modules/@smithy/types/dist-es/checksum.js","../node_modules/@smithy/types/dist-es/client.js","../node_modules/@smithy/types/dist-es/command.js","../node_modules/@smithy/types/dist-es/connection/config.js","../node_modules/@smithy/types/dist-es/connection/manager.js","../node_modules/@smithy/types/dist-es/connection/pool.js","../node_modules/@smithy/types/dist-es/connection/index.js","../node_modules/@smithy/types/dist-es/crypto.js","../node_modules/@smithy/types/dist-es/encode.js","../node_modules/@smithy/types/dist-es/endpoint.js","../node_modules/@smithy/types/dist-es/endpoints/EndpointRuleObject.js","../node_modules/@smithy/types/dist-es/endpoints/ErrorRuleObject.js","../node_modules/@smithy/types/dist-es/endpoints/RuleSetObject.js","../node_modules/@smithy/types/dist-es/endpoints/shared.js","../node_modules/@smithy/types/dist-es/endpoints/TreeRuleObject.js","../node_modules/@smithy/types/dist-es/endpoints/index.js","../node_modules/@smithy/types/dist-es/eventStream.js","../node_modules/@smithy/types/dist-es/extensions/checksum.js","../node_modules/@smithy/types/dist-es/extensions/defaultClientConfiguration.js","../node_modules/@smithy/types/dist-es/extensions/defaultExtensionConfiguration.js","../node_modules/@smithy/types/dist-es/extensions/index.js","../node_modules/@smithy/types/dist-es/feature-ids.js","../node_modules/@smithy/types/dist-es/http.js","../node_modules/@smithy/types/dist-es/http/httpHandlerInitialization.js","../node_modules/@smithy/types/dist-es/identity/apiKeyIdentity.js","../node_modules/@smithy/types/dist-es/identity/awsCredentialIdentity.js","../node_modules/@smithy/types/dist-es/identity/identity.js","../node_modules/@smithy/types/dist-es/identity/tokenIdentity.js","../node_modules/@smithy/types/dist-es/identity/index.js","../node_modules/@smithy/types/dist-es/logger.js","../node_modules/@smithy/types/dist-es/middleware.js","../node_modules/@smithy/types/dist-es/pagination.js","../node_modules/@smithy/types/dist-es/profile.js","../node_modules/@smithy/types/dist-es/response.js","../node_modules/@smithy/types/dist-es/retry.js","../node_modules/@smithy/types/dist-es/schema/schema.js","../node_modules/@smithy/types/dist-es/schema/traits.js","../node_modules/@smithy/types/dist-es/schema/schema-deprecated.js","../node_modules/@smithy/types/dist-es/schema/sentinels.js","../node_modules/@smithy/types/dist-es/schema/static-schemas.js","../node_modules/@smithy/types/dist-es/serde.js","../node_modules/@smithy/types/dist-es/shapes.js","../node_modules/@smithy/types/dist-es/signature.js","../node_modules/@smithy/types/dist-es/stream.js","../node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-common-types.js","../node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-input-types.js","../node_modules/@smithy/types/dist-es/streaming-payload/streaming-blob-payload-output-types.js","../node_modules/@smithy/types/dist-es/transfer.js","../node_modules/@smithy/types/dist-es/transform/client-payload-blob-type-narrow.js","../node_modules/@smithy/types/dist-es/transform/mutable.js","../node_modules/@smithy/types/dist-es/transform/no-undefined.js","../node_modules/@smithy/types/dist-es/transform/type-transform.js","../node_modules/@smithy/types/dist-es/uri.js","../node_modules/@smithy/types/dist-es/util.js","../node_modules/@smithy/types/dist-es/waiter.js","../node_modules/@smithy/types/dist-es/index.js","../node_modules/@smithy/protocol-http/dist-es/Field.js","../node_modules/@smithy/protocol-http/dist-es/Fields.js","../node_modules/@smithy/protocol-http/dist-es/httpHandler.js","../node_modules/@smithy/protocol-http/dist-es/httpRequest.js","../node_modules/@smithy/protocol-http/dist-es/httpResponse.js","../node_modules/@smithy/protocol-http/dist-es/isValidHostname.js","../node_modules/@smithy/protocol-http/dist-es/types.js","../node_modules/@smithy/protocol-http/dist-es/index.js","../node_modules/@aws-sdk/middleware-eventstream/dist-es/eventStreamHandlingMiddleware.js","../node_modules/@aws-sdk/middleware-eventstream/dist-es/eventStreamHeaderMiddleware.js","../node_modules/@aws-sdk/middleware-eventstream/dist-es/getEventStreamPlugin.js","../node_modules/@aws-sdk/middleware-eventstream/dist-es/index.js","../node_modules/@aws-sdk/middleware-host-header/dist-es/index.js","../node_modules/@aws-sdk/middleware-logger/dist-es/loggerMiddleware.js","../node_modules/@aws-sdk/middleware-logger/dist-es/index.js","../node_modules/@aws-sdk/middleware-recursion-detection/dist-es/configuration.js","../node_modules/@aws/lambda-invoke-store/dist-es/invoke-store.js","../node_modules/@aws-sdk/middleware-recursion-detection/dist-es/recursionDetectionMiddleware.js","../node_modules/@aws-sdk/middleware-recursion-detection/dist-es/getRecursionDetectionPlugin.js","../node_modules/@aws-sdk/middleware-recursion-detection/dist-es/index.js","../node_modules/@smithy/core/dist-es/getSmithyContext.js","../node_modules/@smithy/util-middleware/dist-es/getSmithyContext.js","../node_modules/@smithy/util-middleware/dist-es/normalizeProvider.js","../node_modules/@smithy/util-middleware/dist-es/index.js","../node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/resolveAuthOptions.js","../node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js","../node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js","../node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js","../node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/index.js","../node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js","../node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js","../node_modules/@smithy/core/dist-es/middleware-http-signing/index.js","../node_modules/@smithy/core/dist-es/normalizeProvider.js","../node_modules/@smithy/core/dist-es/pagination/createPaginator.js","../node_modules/@smithy/is-array-buffer/dist-es/index.js","../node_modules/@smithy/util-buffer-from/dist-es/index.js","../node_modules/@smithy/util-base64/dist-es/fromBase64.js","../node_modules/@smithy/util-utf8/dist-es/fromUtf8.js","../node_modules/@smithy/util-utf8/dist-es/toUint8Array.js","../node_modules/@smithy/util-utf8/dist-es/toUtf8.js","../node_modules/@smithy/util-utf8/dist-es/index.js","../node_modules/@smithy/util-base64/dist-es/toBase64.js","../node_modules/@smithy/util-base64/dist-es/index.js","../node_modules/@smithy/util-stream/dist-es/blob/Uint8ArrayBlobAdapter.js","../node_modules/@smithy/util-stream/dist-es/checksum/ChecksumStream.js","../node_modules/@smithy/util-stream/dist-es/stream-type-check.js","../node_modules/@smithy/util-stream/dist-es/checksum/createChecksumStream.js","../node_modules/@smithy/util-stream/dist-es/createBufferedReadable.js","../node_modules/@smithy/util-stream/dist-es/getAwsChunkedEncodingStream.js","../node_modules/@smithy/util-stream/dist-es/headStream.js","../node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js","../node_modules/@smithy/util-uri-escape/dist-es/escape-uri-path.js","../node_modules/@smithy/util-uri-escape/dist-es/index.js","../node_modules/@smithy/querystring-builder/dist-es/index.js","../node_modules/@smithy/node-http-handler/dist-es/build-abort-error.js","../node_modules/@smithy/node-http-handler/dist-es/constants.js","../node_modules/@smithy/node-http-handler/dist-es/get-transformed-headers.js","../node_modules/@smithy/node-http-handler/dist-es/timing.js","../node_modules/@smithy/node-http-handler/dist-es/set-connection-timeout.js","../node_modules/@smithy/node-http-handler/dist-es/set-request-timeout.js","../node_modules/@smithy/node-http-handler/dist-es/set-socket-keep-alive.js","../node_modules/@smithy/node-http-handler/dist-es/set-socket-timeout.js","../node_modules/@smithy/node-http-handler/dist-es/write-request-body.js","../node_modules/@smithy/node-http-handler/dist-es/node-http-handler.js","../node_modules/@smithy/node-http-handler/dist-es/node-http2-connection-pool.js","../node_modules/@smithy/node-http-handler/dist-es/node-http2-connection-manager.js","../node_modules/@smithy/node-http-handler/dist-es/node-http2-handler.js","../node_modules/@smithy/node-http-handler/dist-es/stream-collector/collector.js","../node_modules/@smithy/node-http-handler/dist-es/stream-collector/index.js","../node_modules/@smithy/node-http-handler/dist-es/index.js","../node_modules/@smithy/fetch-http-handler/dist-es/fetch-http-handler.js","../node_modules/@smithy/fetch-http-handler/dist-es/stream-collector.js","../node_modules/@smithy/fetch-http-handler/dist-es/index.js","../node_modules/@smithy/util-hex-encoding/dist-es/index.js","../node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.browser.js","../node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.js","../node_modules/@smithy/util-stream/dist-es/splitStream.js","../node_modules/@smithy/util-stream/dist-es/index.js","../node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js","../node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js","../node_modules/@smithy/core/dist-es/submodules/schema/deref.js","../node_modules/@smithy/core/dist-es/submodules/schema/schemas/operation.js","../node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaDeserializationMiddleware.js","../node_modules/@smithy/querystring-parser/dist-es/index.js","../node_modules/@smithy/url-parser/dist-es/index.js","../node_modules/@smithy/core/dist-es/submodules/endpoints/toEndpointV1.js","../node_modules/@smithy/core/dist-es/submodules/endpoints/index.js","../node_modules/@smithy/core/dist-es/submodules/schema/middleware/schemaSerializationMiddleware.js","../node_modules/@smithy/core/dist-es/submodules/schema/middleware/getSchemaSerdePlugin.js","../node_modules/@smithy/core/dist-es/submodules/schema/schemas/Schema.js","../node_modules/@smithy/core/dist-es/submodules/schema/schemas/ListSchema.js","../node_modules/@smithy/core/dist-es/submodules/schema/schemas/MapSchema.js","../node_modules/@smithy/core/dist-es/submodules/schema/schemas/OperationSchema.js","../node_modules/@smithy/core/dist-es/submodules/schema/schemas/StructureSchema.js","../node_modules/@smithy/core/dist-es/submodules/schema/schemas/ErrorSchema.js","../node_modules/@smithy/core/dist-es/submodules/schema/schemas/translateTraits.js","../node_modules/@smithy/core/dist-es/submodules/schema/schemas/NormalizedSchema.js","../node_modules/@smithy/core/dist-es/submodules/schema/schemas/SimpleSchema.js","../node_modules/@smithy/core/dist-es/submodules/schema/schemas/sentinels.js","../node_modules/@smithy/core/dist-es/submodules/schema/TypeRegistry.js","../node_modules/@smithy/core/dist-es/submodules/schema/index.js","../node_modules/@smithy/core/dist-es/submodules/serde/copyDocumentWithTransform.js","../node_modules/@smithy/core/dist-es/submodules/serde/parse-utils.js","../node_modules/@smithy/core/dist-es/submodules/serde/date-utils.js","../node_modules/@smithy/uuid/dist-es/randomUUID.js","../node_modules/@smithy/uuid/dist-es/v4.js","../node_modules/@smithy/uuid/dist-es/index.js","../node_modules/@smithy/core/dist-es/submodules/serde/generateIdempotencyToken.js","../node_modules/@smithy/core/dist-es/submodules/serde/lazy-json.js","../node_modules/@smithy/core/dist-es/submodules/serde/quote-header.js","../node_modules/@smithy/core/dist-es/submodules/serde/schema-serde-lib/schema-date-utils.js","../node_modules/@smithy/core/dist-es/submodules/serde/split-every.js","../node_modules/@smithy/core/dist-es/submodules/serde/split-header.js","../node_modules/@smithy/core/dist-es/submodules/serde/value/NumericValue.js","../node_modules/@smithy/core/dist-es/submodules/serde/index.js","../node_modules/@smithy/core/dist-es/submodules/protocols/SerdeContext.js","../node_modules/@smithy/core/dist-es/submodules/event-streams/EventStreamSerde.js","../node_modules/@smithy/core/dist-es/submodules/event-streams/index.js","../node_modules/@smithy/core/dist-es/submodules/protocols/HttpProtocol.js","../node_modules/@smithy/core/dist-es/submodules/protocols/HttpBindingProtocol.js","../node_modules/@smithy/core/dist-es/submodules/protocols/RpcProtocol.js","../node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js","../node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js","../node_modules/@smithy/core/dist-es/submodules/protocols/serde/determineTimestampFormat.js","../node_modules/@smithy/core/dist-es/submodules/protocols/serde/FromStringShapeDeserializer.js","../node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeDeserializer.js","../node_modules/@smithy/core/dist-es/submodules/protocols/serde/ToStringShapeSerializer.js","../node_modules/@smithy/core/dist-es/submodules/protocols/serde/HttpInterceptingShapeSerializer.js","../node_modules/@smithy/core/dist-es/submodules/protocols/index.js","../node_modules/@smithy/core/dist-es/request-builder/requestBuilder.js","../node_modules/@smithy/core/dist-es/setFeature.js","../node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js","../node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpApiKeyAuth.js","../node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/httpBearerAuth.js","../node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/noAuth.js","../node_modules/@smithy/core/dist-es/util-identity-and-auth/httpAuthSchemes/index.js","../node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js","../node_modules/@smithy/core/dist-es/util-identity-and-auth/index.js","../node_modules/@smithy/core/dist-es/index.js","../node_modules/@aws-sdk/middleware-user-agent/dist-es/configurations.js","../node_modules/@smithy/util-endpoints/dist-es/cache/EndpointCache.js","../node_modules/@smithy/util-endpoints/dist-es/lib/isIpAddress.js","../node_modules/@smithy/util-endpoints/dist-es/lib/isValidHostLabel.js","../node_modules/@smithy/util-endpoints/dist-es/utils/customEndpointFunctions.js","../node_modules/@smithy/util-endpoints/dist-es/debug/debugId.js","../node_modules/@smithy/util-endpoints/dist-es/debug/toDebugString.js","../node_modules/@smithy/util-endpoints/dist-es/debug/index.js","../node_modules/@smithy/util-endpoints/dist-es/types/EndpointError.js","../node_modules/@smithy/util-endpoints/dist-es/types/EndpointFunctions.js","../node_modules/@smithy/util-endpoints/dist-es/types/EndpointRuleObject.js","../node_modules/@smithy/util-endpoints/dist-es/types/ErrorRuleObject.js","../node_modules/@smithy/util-endpoints/dist-es/types/RuleSetObject.js","../node_modules/@smithy/util-endpoints/dist-es/types/TreeRuleObject.js","../node_modules/@smithy/util-endpoints/dist-es/types/shared.js","../node_modules/@smithy/util-endpoints/dist-es/types/index.js","../node_modules/@smithy/util-endpoints/dist-es/lib/booleanEquals.js","../node_modules/@smithy/util-endpoints/dist-es/lib/getAttrPathList.js","../node_modules/@smithy/util-endpoints/dist-es/lib/getAttr.js","../node_modules/@smithy/util-endpoints/dist-es/lib/isSet.js","../node_modules/@smithy/util-endpoints/dist-es/lib/not.js","../node_modules/@smithy/util-endpoints/dist-es/lib/parseURL.js","../node_modules/@smithy/util-endpoints/dist-es/lib/stringEquals.js","../node_modules/@smithy/util-endpoints/dist-es/lib/substring.js","../node_modules/@smithy/util-endpoints/dist-es/lib/uriEncode.js","../node_modules/@smithy/util-endpoints/dist-es/lib/index.js","../node_modules/@smithy/util-endpoints/dist-es/utils/endpointFunctions.js","../node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTemplate.js","../node_modules/@smithy/util-endpoints/dist-es/utils/getReferenceValue.js","../node_modules/@smithy/util-endpoints/dist-es/utils/evaluateExpression.js","../node_modules/@smithy/util-endpoints/dist-es/utils/callFunction.js","../node_modules/@smithy/util-endpoints/dist-es/utils/evaluateCondition.js","../node_modules/@smithy/util-endpoints/dist-es/utils/evaluateConditions.js","../node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointHeaders.js","../node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperties.js","../node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointUrl.js","../node_modules/@smithy/util-endpoints/dist-es/utils/evaluateEndpointRule.js","../node_modules/@smithy/util-endpoints/dist-es/utils/evaluateErrorRule.js","../node_modules/@smithy/util-endpoints/dist-es/utils/evaluateRules.js","../node_modules/@smithy/util-endpoints/dist-es/utils/index.js","../node_modules/@smithy/util-endpoints/dist-es/resolveEndpoint.js","../node_modules/@smithy/util-endpoints/dist-es/index.js","../node_modules/@aws-sdk/util-endpoints/dist-es/lib/isIpAddress.js","../node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js","../node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js","../node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partitions.json","../node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js","../node_modules/@aws-sdk/util-endpoints/dist-es/aws.js","../node_modules/@aws-sdk/util-endpoints/dist-es/resolveDefaultAwsRegionalEndpointsConfig.js","../node_modules/@aws-sdk/util-endpoints/dist-es/resolveEndpoint.js","../node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointError.js","../node_modules/@aws-sdk/util-endpoints/dist-es/types/EndpointRuleObject.js","../node_modules/@aws-sdk/util-endpoints/dist-es/types/ErrorRuleObject.js","../node_modules/@aws-sdk/util-endpoints/dist-es/types/RuleSetObject.js","../node_modules/@aws-sdk/util-endpoints/dist-es/types/TreeRuleObject.js","../node_modules/@aws-sdk/util-endpoints/dist-es/types/shared.js","../node_modules/@aws-sdk/util-endpoints/dist-es/types/index.js","../node_modules/@aws-sdk/util-endpoints/dist-es/index.js","../node_modules/@aws-sdk/core/dist-es/submodules/client/emitWarningIfUnsupportedVersion.js","../node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js","../node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js","../node_modules/@aws-sdk/core/dist-es/submodules/client/setTokenFeature.js","../node_modules/@aws-sdk/core/dist-es/submodules/client/index.js","../node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js","../node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js","../node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js","../node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js","../node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/index.js","../node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js","../node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getArrayForCommaSeparatedString.js","../node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getBearerTokenEnvKey.js","../node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/NODE_AUTH_SCHEME_PREFERENCE_OPTIONS.js","../node_modules/@smithy/property-provider/dist-es/ProviderError.js","../node_modules/@smithy/property-provider/dist-es/CredentialsProviderError.js","../node_modules/@smithy/property-provider/dist-es/TokenProviderError.js","../node_modules/@smithy/property-provider/dist-es/chain.js","../node_modules/@smithy/property-provider/dist-es/fromStatic.js","../node_modules/@smithy/property-provider/dist-es/memoize.js","../node_modules/@smithy/property-provider/dist-es/index.js","../node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js","../node_modules/@smithy/signature-v4/dist-es/constants.js","../node_modules/@smithy/signature-v4/dist-es/credentialDerivation.js","../node_modules/@smithy/signature-v4/dist-es/getCanonicalHeaders.js","../node_modules/@smithy/signature-v4/dist-es/getPayloadHash.js","../node_modules/@smithy/signature-v4/dist-es/HeaderFormatter.js","../node_modules/@smithy/signature-v4/dist-es/headerUtil.js","../node_modules/@smithy/signature-v4/dist-es/moveHeadersToQuery.js","../node_modules/@smithy/signature-v4/dist-es/prepareRequest.js","../node_modules/@smithy/signature-v4/dist-es/getCanonicalQuery.js","../node_modules/@smithy/signature-v4/dist-es/utilDate.js","../node_modules/@smithy/signature-v4/dist-es/SignatureV4Base.js","../node_modules/@smithy/signature-v4/dist-es/SignatureV4.js","../node_modules/@smithy/signature-v4/dist-es/signature-v4a-container.js","../node_modules/@smithy/signature-v4/dist-es/index.js","../node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js","../node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/index.js","../node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/index.js","../node_modules/@smithy/middleware-stack/dist-es/MiddlewareStack.js","../node_modules/@smithy/middleware-stack/dist-es/index.js","../node_modules/@smithy/smithy-client/dist-es/client.js","../node_modules/@smithy/smithy-client/dist-es/collect-stream-body.js","../node_modules/@smithy/smithy-client/dist-es/schemaLogFilter.js","../node_modules/@smithy/smithy-client/dist-es/command.js","../node_modules/@smithy/smithy-client/dist-es/constants.js","../node_modules/@smithy/smithy-client/dist-es/create-aggregated-client.js","../node_modules/@smithy/smithy-client/dist-es/exceptions.js","../node_modules/@smithy/smithy-client/dist-es/default-error-handler.js","../node_modules/@smithy/smithy-client/dist-es/defaults-mode.js","../node_modules/@smithy/smithy-client/dist-es/emitWarningIfUnsupportedVersion.js","../node_modules/@smithy/smithy-client/dist-es/extended-encode-uri-component.js","../node_modules/@smithy/smithy-client/dist-es/extensions/checksum.js","../node_modules/@smithy/smithy-client/dist-es/extensions/retry.js","../node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js","../node_modules/@smithy/smithy-client/dist-es/extensions/index.js","../node_modules/@smithy/smithy-client/dist-es/get-array-if-single-item.js","../node_modules/@smithy/smithy-client/dist-es/get-value-from-text-node.js","../node_modules/@smithy/smithy-client/dist-es/is-serializable-header-value.js","../node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js","../node_modules/@smithy/smithy-client/dist-es/object-mapping.js","../node_modules/@smithy/smithy-client/dist-es/resolve-path.js","../node_modules/@smithy/smithy-client/dist-es/ser-utils.js","../node_modules/@smithy/smithy-client/dist-es/serde-json.js","../node_modules/@smithy/smithy-client/dist-es/index.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/ProtocolLib.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/cbor/AwsSmithyRpcV2CborProtocol.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/coercing-serializers.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/ConfigurableSerdeContext.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/UnionSerde.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/jsonReviver.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/parseJsonBody.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonShapeDeserializer.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/jsonReplacer.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonShapeSerializer.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/JsonCodec.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJsonRpcProtocol.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJson1_0Protocol.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsJson1_1Protocol.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/AwsRestJsonProtocol.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/json/awsExpectUnion.js","../node_modules/@aws-sdk/xml-builder/dist-es/XmlText.js","../node_modules/@aws-sdk/xml-builder/dist-es/XmlNode.js","../node_modules/@aws-sdk/xml-builder/dist-es/xml-external/nodable_entities.js","../node_modules/@aws-sdk/xml-builder/dist-es/xml-parser.js","../node_modules/@aws-sdk/xml-builder/dist-es/index.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlShapeDeserializer.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/QueryShapeSerializer.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/AwsQueryProtocol.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/AwsEc2QueryProtocol.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/query/QuerySerializerSettings.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlShapeSerializer.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/XmlCodec.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/AwsRestXmlProtocol.js","../node_modules/@aws-sdk/core/dist-es/submodules/protocols/index.js","../node_modules/@aws-sdk/core/dist-es/index.js","../node_modules/@smithy/util-retry/dist-es/config.js","../node_modules/@smithy/service-error-classification/dist-es/constants.js","../node_modules/@smithy/service-error-classification/dist-es/index.js","../node_modules/@smithy/util-retry/dist-es/DefaultRateLimiter.js","../node_modules/@smithy/util-retry/dist-es/constants.js","../node_modules/@smithy/util-retry/dist-es/defaultRetryBackoffStrategy.js","../node_modules/@smithy/util-retry/dist-es/defaultRetryToken.js","../node_modules/@smithy/util-retry/dist-es/StandardRetryStrategy.js","../node_modules/@smithy/util-retry/dist-es/AdaptiveRetryStrategy.js","../node_modules/@smithy/util-retry/dist-es/ConfiguredRetryStrategy.js","../node_modules/@smithy/util-retry/dist-es/types.js","../node_modules/@smithy/util-retry/dist-es/index.js","../node_modules/@aws-sdk/middleware-user-agent/dist-es/check-features.js","../node_modules/@aws-sdk/middleware-user-agent/dist-es/constants.js","../node_modules/@aws-sdk/middleware-user-agent/dist-es/encode-features.js","../node_modules/@aws-sdk/middleware-user-agent/dist-es/user-agent-middleware.js","../node_modules/@aws-sdk/middleware-user-agent/dist-es/index.js","../node_modules/tslib/tslib.es6.mjs","../node_modules/@aws-crypto/util/node_modules/@smithy/is-array-buffer/dist-es/index.js","../node_modules/@aws-crypto/util/node_modules/@smithy/util-buffer-from/dist-es/index.js","../node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/fromUtf8.js","../node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js","../node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/toUtf8.js","../node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-es/index.js","../node_modules/@aws-crypto/util/src/convertToBuffer.ts","../node_modules/@aws-crypto/util/src/isEmptyData.ts","../node_modules/@aws-crypto/util/src/numToUint8.ts","../node_modules/@aws-crypto/util/src/uint32ArrayFrom.ts","../node_modules/@aws-crypto/util/src/index.ts","../node_modules/@aws-crypto/crc32/src/aws_crc32.ts","../node_modules/@aws-crypto/crc32/src/index.ts","../node_modules/@smithy/eventstream-codec/dist-es/Int64.js","../node_modules/@smithy/eventstream-codec/dist-es/HeaderMarshaller.js","../node_modules/@smithy/eventstream-codec/dist-es/splitMessage.js","../node_modules/@smithy/eventstream-codec/dist-es/EventStreamCodec.js","../node_modules/@smithy/eventstream-codec/dist-es/Message.js","../node_modules/@smithy/eventstream-codec/dist-es/MessageDecoderStream.js","../node_modules/@smithy/eventstream-codec/dist-es/MessageEncoderStream.js","../node_modules/@smithy/eventstream-codec/dist-es/SmithyMessageDecoderStream.js","../node_modules/@smithy/eventstream-codec/dist-es/SmithyMessageEncoderStream.js","../node_modules/@smithy/eventstream-codec/dist-es/index.js","../node_modules/@smithy/eventstream-serde-universal/dist-es/getChunkedStream.js","../node_modules/@smithy/eventstream-serde-universal/dist-es/getUnmarshalledStream.js","../node_modules/@smithy/eventstream-serde-universal/dist-es/EventStreamMarshaller.js","../node_modules/@smithy/eventstream-serde-universal/dist-es/provider.js","../node_modules/@smithy/eventstream-serde-universal/dist-es/index.js","../node_modules/@aws-sdk/middleware-websocket/dist-es/utils.js","../node_modules/@aws-sdk/middleware-websocket/dist-es/WebSocketFetchHandler.js","../node_modules/@aws-sdk/middleware-websocket/dist-es/middlewares/websocketEndpointMiddleware.js","../node_modules/@aws-sdk/middleware-websocket/dist-es/middlewares/websocketInjectSessionIdMiddleware.js","../node_modules/@aws-sdk/middleware-websocket/dist-es/getWebSocketPlugin.js","../node_modules/@aws-sdk/middleware-websocket/dist-es/WebsocketSignatureV4.js","../node_modules/@aws-sdk/middleware-websocket/dist-es/resolveWebSocketConfig.js","../node_modules/@aws-sdk/middleware-websocket/dist-es/ws-eventstream/eventStreamPayloadHandlerProvider.js","../node_modules/@aws-sdk/middleware-websocket/dist-es/index.js","../node_modules/@smithy/util-config-provider/dist-es/booleanSelector.js","../node_modules/@smithy/util-config-provider/dist-es/numberSelector.js","../node_modules/@smithy/util-config-provider/dist-es/types.js","../node_modules/@smithy/util-config-provider/dist-es/index.js","../node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseDualstackEndpointConfigOptions.js","../node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseFipsEndpointConfigOptions.js","../node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveCustomEndpointsConfig.js","../node_modules/@smithy/config-resolver/dist-es/endpointsConfig/resolveEndpointsConfig.js","../node_modules/@smithy/config-resolver/dist-es/endpointsConfig/index.js","../node_modules/@smithy/config-resolver/dist-es/regionConfig/config.js","../node_modules/@smithy/config-resolver/dist-es/regionConfig/checkRegion.js","../node_modules/@smithy/config-resolver/dist-es/regionConfig/isFipsRegion.js","../node_modules/@smithy/config-resolver/dist-es/regionConfig/getRealRegion.js","../node_modules/@smithy/config-resolver/dist-es/regionConfig/resolveRegionConfig.js","../node_modules/@smithy/config-resolver/dist-es/regionConfig/index.js","../node_modules/@smithy/config-resolver/dist-es/regionInfo/PartitionHash.js","../node_modules/@smithy/config-resolver/dist-es/regionInfo/RegionHash.js","../node_modules/@smithy/config-resolver/dist-es/regionInfo/getRegionInfo.js","../node_modules/@smithy/config-resolver/dist-es/regionInfo/index.js","../node_modules/@smithy/config-resolver/dist-es/index.js","../node_modules/@smithy/eventstream-serde-config-resolver/dist-es/EventStreamSerdeConfig.js","../node_modules/@smithy/eventstream-serde-config-resolver/dist-es/index.js","../node_modules/@smithy/middleware-content-length/dist-es/index.js","../node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/s3.js","../node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/index.js","../node_modules/@smithy/middleware-endpoint/dist-es/adaptors/createConfigValueProvider.js","../node_modules/@smithy/node-config-provider/dist-es/getSelectorName.js","../node_modules/@smithy/node-config-provider/dist-es/fromEnv.js","../node_modules/@smithy/shared-ini-file-loader/dist-es/getHomeDir.js","../node_modules/@smithy/shared-ini-file-loader/dist-es/getProfileName.js","../node_modules/@smithy/shared-ini-file-loader/dist-es/getSSOTokenFilepath.js","../node_modules/@smithy/shared-ini-file-loader/dist-es/getSSOTokenFromFile.js","../node_modules/@smithy/shared-ini-file-loader/dist-es/constants.js","../node_modules/@smithy/shared-ini-file-loader/dist-es/getConfigData.js","../node_modules/@smithy/shared-ini-file-loader/dist-es/getConfigFilepath.js","../node_modules/@smithy/shared-ini-file-loader/dist-es/getCredentialsFilepath.js","../node_modules/@smithy/shared-ini-file-loader/dist-es/parseIni.js","../node_modules/@smithy/shared-ini-file-loader/dist-es/readFile.js","../node_modules/@smithy/shared-ini-file-loader/dist-es/loadSharedConfigFiles.js","../node_modules/@smithy/shared-ini-file-loader/dist-es/getSsoSessionData.js","../node_modules/@smithy/shared-ini-file-loader/dist-es/loadSsoSessionData.js","../node_modules/@smithy/shared-ini-file-loader/dist-es/mergeConfigFiles.js","../node_modules/@smithy/shared-ini-file-loader/dist-es/parseKnownFiles.js","../node_modules/@smithy/shared-ini-file-loader/dist-es/externalDataInterceptor.js","../node_modules/@smithy/shared-ini-file-loader/dist-es/types.js","../node_modules/@smithy/shared-ini-file-loader/dist-es/index.js","../node_modules/@smithy/node-config-provider/dist-es/fromSharedConfigFiles.js","../node_modules/@smithy/node-config-provider/dist-es/fromStatic.js","../node_modules/@smithy/node-config-provider/dist-es/configLoader.js","../node_modules/@smithy/node-config-provider/dist-es/index.js","../node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointUrlConfig.js","../node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromConfig.js","../node_modules/@smithy/middleware-endpoint/dist-es/adaptors/toEndpointV1.js","../node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromInstructions.js","../node_modules/@smithy/middleware-endpoint/dist-es/adaptors/index.js","../node_modules/@smithy/middleware-endpoint/dist-es/endpointMiddleware.js","../node_modules/@smithy/middleware-serde/dist-es/deserializerMiddleware.js","../node_modules/@smithy/middleware-serde/dist-es/serializerMiddleware.js","../node_modules/@smithy/middleware-serde/dist-es/serdePlugin.js","../node_modules/@smithy/middleware-serde/dist-es/index.js","../node_modules/@smithy/middleware-endpoint/dist-es/getEndpointPlugin.js","../node_modules/@smithy/middleware-endpoint/dist-es/resolveEndpointConfig.js","../node_modules/@smithy/middleware-endpoint/dist-es/resolveEndpointRequiredConfig.js","../node_modules/@smithy/middleware-endpoint/dist-es/types.js","../node_modules/@smithy/middleware-endpoint/dist-es/index.js","../node_modules/@smithy/middleware-retry/dist-es/delayDecider.js","../node_modules/@smithy/middleware-retry/dist-es/retryDecider.js","../node_modules/@smithy/middleware-retry/dist-es/util.js","../node_modules/@smithy/middleware-retry/dist-es/StandardRetryStrategy.js","../node_modules/@smithy/middleware-retry/dist-es/AdaptiveRetryStrategy.js","../node_modules/@smithy/middleware-retry/dist-es/configurations.js","../node_modules/@smithy/middleware-retry/dist-es/omitRetryHeadersMiddleware.js","../node_modules/@smithy/middleware-retry/dist-es/isStreamingPayload/isStreamingPayload.js","../node_modules/@smithy/middleware-retry/dist-es/retryMiddleware.js","../node_modules/@smithy/middleware-retry/dist-es/index.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/auth/httpAuthSchemeProvider.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/endpoint/EndpointParameters.js","../node_modules/@aws-sdk/client-bedrock-runtime/package.json","../node_modules/@aws-sdk/credential-provider-env/dist-es/fromEnv.js","../node_modules/@aws-sdk/credential-provider-env/dist-es/index.js","../node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/httpRequest.js","../node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/ImdsCredentials.js","../node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/RemoteProviderInit.js","../node_modules/@smithy/credential-provider-imds/dist-es/remoteProvider/retry.js","../node_modules/@smithy/credential-provider-imds/dist-es/fromContainerMetadata.js","../node_modules/@smithy/credential-provider-imds/dist-es/error/InstanceMetadataV1FallbackError.js","../node_modules/@smithy/credential-provider-imds/dist-es/config/Endpoint.js","../node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointConfigOptions.js","../node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointMode.js","../node_modules/@smithy/credential-provider-imds/dist-es/config/EndpointModeConfigOptions.js","../node_modules/@smithy/credential-provider-imds/dist-es/utils/getInstanceMetadataEndpoint.js","../node_modules/@smithy/credential-provider-imds/dist-es/utils/getExtendedInstanceMetadataCredentials.js","../node_modules/@smithy/credential-provider-imds/dist-es/utils/staticStabilityProvider.js","../node_modules/@smithy/credential-provider-imds/dist-es/fromInstanceMetadata.js","../node_modules/@smithy/credential-provider-imds/dist-es/types.js","../node_modules/@smithy/credential-provider-imds/dist-es/index.js","../node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/checkUrl.js","../node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/requestHelpers.js","../node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/retry-wrapper.js","../node_modules/@aws-sdk/credential-provider-http/dist-es/fromHttp/fromHttp.js","../node_modules/@aws-sdk/credential-provider-http/dist-es/index.js","../node_modules/@aws-sdk/credential-provider-node/dist-es/remoteProvider.js","../node_modules/@aws-sdk/credential-provider-node/dist-es/runtime/memoize-chain.js","../node_modules/@aws-sdk/credential-provider-sso/dist-es/isSsoProfile.js","../node_modules/@aws-sdk/token-providers/dist-es/fromEnvSigningName.js","../node_modules/@aws-sdk/token-providers/dist-es/constants.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthSchemeProvider.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/EndpointParameters.js","../node_modules/@aws-sdk/nested-clients/package.json","../node_modules/@aws-sdk/util-user-agent-node/dist-es/getRuntimeUserAgentPair.js","../node_modules/@aws-sdk/util-user-agent-node/dist-es/getNodeModulesParentDirs.js","../node_modules/@aws-sdk/util-user-agent-node/dist-es/getSanitizedTypeScriptVersion.js","../node_modules/@aws-sdk/util-user-agent-node/dist-es/getSanitizedDevTypeScriptVersion.js","../node_modules/@aws-sdk/util-user-agent-node/dist-es/getTypeScriptUserAgentPair.js","../node_modules/@aws-sdk/util-user-agent-node/dist-es/crt-availability.js","../node_modules/@aws-sdk/util-user-agent-node/dist-es/is-crt-available.js","../node_modules/@aws-sdk/util-user-agent-node/dist-es/defaultUserAgent.js","../node_modules/@aws-sdk/util-user-agent-node/dist-es/nodeAppIdConfigOptions.js","../node_modules/@aws-sdk/util-user-agent-node/dist-es/index.js","../node_modules/@smithy/hash-node/dist-es/index.js","../node_modules/@smithy/util-body-length-node/dist-es/calculateBodyLength.js","../node_modules/@smithy/util-body-length-node/dist-es/index.js","../node_modules/@smithy/util-defaults-mode-node/dist-es/constants.js","../node_modules/@smithy/util-defaults-mode-node/dist-es/defaultsModeConfig.js","../node_modules/@smithy/util-defaults-mode-node/dist-es/resolveDefaultsModeConfig.js","../node_modules/@smithy/util-defaults-mode-node/dist-es/index.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/ruleset.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/endpoint/endpointResolver.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/SSOOIDCServiceException.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/errors.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/schemas/schemas_0.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.shared.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeConfig.js","../node_modules/@aws-sdk/region-config-resolver/dist-es/extensions/index.js","../node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/awsRegionConfig.js","../node_modules/@aws-sdk/region-config-resolver/dist-es/regionConfig/stsRegionDefaultResolver.js","../node_modules/@aws-sdk/region-config-resolver/dist-es/index.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/auth/httpAuthExtensionConfiguration.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/runtimeExtensions.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDCClient.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/CreateTokenCommand.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/SSOOIDC.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/commands/index.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/enums.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/models/models_0.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso-oidc/index.js","../node_modules/@aws-sdk/token-providers/dist-es/getSsoOidcClient.js","../node_modules/@aws-sdk/token-providers/dist-es/getNewSsoOidcToken.js","../node_modules/@aws-sdk/token-providers/dist-es/validateTokenExpiry.js","../node_modules/@aws-sdk/token-providers/dist-es/validateTokenKey.js","../node_modules/@aws-sdk/token-providers/dist-es/writeSSOTokenToFile.js","../node_modules/@aws-sdk/token-providers/dist-es/fromSso.js","../node_modules/@aws-sdk/token-providers/dist-es/fromStatic.js","../node_modules/@aws-sdk/token-providers/dist-es/nodeProvider.js","../node_modules/@aws-sdk/token-providers/dist-es/index.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/auth/httpAuthSchemeProvider.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/endpoint/EndpointParameters.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/endpoint/ruleset.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/endpoint/endpointResolver.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/models/SSOServiceException.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/models/errors.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/schemas/schemas_0.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/runtimeConfig.shared.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/runtimeConfig.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/auth/httpAuthExtensionConfiguration.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/runtimeExtensions.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/SSOClient.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/commands/GetRoleCredentialsCommand.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/SSO.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/commands/index.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/models/models_0.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sso/index.js","../node_modules/@aws-sdk/credential-provider-sso/dist-es/loadSso.js","../node_modules/@aws-sdk/credential-provider-sso/dist-es/resolveSSOCredentials.js","../node_modules/@aws-sdk/credential-provider-sso/dist-es/validateSsoProfile.js","../node_modules/@aws-sdk/credential-provider-sso/dist-es/fromSSO.js","../node_modules/@aws-sdk/credential-provider-sso/dist-es/types.js","../node_modules/@aws-sdk/credential-provider-sso/dist-es/index.js","../node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveCredentialSource.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthSchemeProvider.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/EndpointParameters.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/ruleset.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/endpoint/endpointResolver.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/STSServiceException.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/errors.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/schemas/schemas_0.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.shared.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeConfig.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/auth/httpAuthExtensionConfiguration.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/runtimeExtensions.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STSClient.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleCommand.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/AssumeRoleWithWebIdentityCommand.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/STS.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/commands/index.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/models/models_0.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultStsRoleAssumers.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/defaultRoleAssumers.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/sts/index.js","../node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveAssumeRoleCredentials.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/auth/httpAuthSchemeProvider.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/endpoint/EndpointParameters.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/endpoint/ruleset.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/endpoint/endpointResolver.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/SigninServiceException.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/errors.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/schemas/schemas_0.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/runtimeConfig.shared.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/runtimeConfig.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/auth/httpAuthExtensionConfiguration.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/runtimeExtensions.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/SigninClient.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/commands/CreateOAuth2TokenCommand.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/Signin.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/commands/index.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/enums.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/models/models_0.js","../node_modules/@aws-sdk/nested-clients/dist-es/submodules/signin/index.js","../node_modules/@aws-sdk/credential-provider-login/dist-es/LoginCredentialsFetcher.js","../node_modules/@aws-sdk/credential-provider-login/dist-es/fromLoginCredentials.js","../node_modules/@aws-sdk/credential-provider-login/dist-es/types.js","../node_modules/@aws-sdk/credential-provider-login/dist-es/index.js","../node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveLoginCredentials.js","../node_modules/@aws-sdk/credential-provider-process/dist-es/getValidatedProcessCredentials.js","../node_modules/@aws-sdk/credential-provider-process/dist-es/resolveProcessCredentials.js","../node_modules/@aws-sdk/credential-provider-process/dist-es/fromProcess.js","../node_modules/@aws-sdk/credential-provider-process/dist-es/index.js","../node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProcessCredentials.js","../node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveSsoCredentials.js","../node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveStaticCredentials.js","../node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromWebToken.js","../node_modules/@aws-sdk/credential-provider-web-identity/dist-es/fromTokenFile.js","../node_modules/@aws-sdk/credential-provider-web-identity/dist-es/index.js","../node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveWebIdentityCredentials.js","../node_modules/@aws-sdk/credential-provider-ini/dist-es/resolveProfileData.js","../node_modules/@aws-sdk/credential-provider-ini/dist-es/fromIni.js","../node_modules/@aws-sdk/credential-provider-ini/dist-es/index.js","../node_modules/@aws-sdk/credential-provider-node/dist-es/defaultProvider.js","../node_modules/@aws-sdk/credential-provider-node/dist-es/index.js","../node_modules/@aws-sdk/eventstream-handler-node/dist-es/EventSigningTransformStream.js","../node_modules/@aws-sdk/eventstream-handler-node/dist-es/EventStreamPayloadHandler.js","../node_modules/@aws-sdk/eventstream-handler-node/dist-es/eventStreamPayloadHandlerProvider.js","../node_modules/@aws-sdk/eventstream-handler-node/dist-es/index.js","../node_modules/@smithy/eventstream-serde-node/dist-es/utils.js","../node_modules/@smithy/eventstream-serde-node/dist-es/EventStreamMarshaller.js","../node_modules/@smithy/eventstream-serde-node/dist-es/provider.js","../node_modules/@smithy/eventstream-serde-node/dist-es/index.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/endpoint/ruleset.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/endpoint/endpointResolver.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/models/BedrockRuntimeServiceException.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/models/errors.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/schemas/schemas_0.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/runtimeConfig.shared.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/runtimeConfig.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/auth/httpAuthExtensionConfiguration.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/runtimeExtensions.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/BedrockRuntimeClient.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/ApplyGuardrailCommand.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/ConverseCommand.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/ConverseStreamCommand.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/CountTokensCommand.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/GetAsyncInvokeCommand.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/InvokeModelCommand.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/InvokeModelWithBidirectionalStreamCommand.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/InvokeModelWithResponseStreamCommand.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/ListAsyncInvokesCommand.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/StartAsyncInvokeCommand.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/pagination/ListAsyncInvokesPaginator.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/BedrockRuntime.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/commands/index.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/pagination/Interfaces.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/pagination/index.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/models/enums.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/models/models_0.js","../node_modules/@aws-sdk/client-bedrock-runtime/dist-es/index.js","../node_modules/ai-ctrf/dist/models/bedrock.js","../node_modules/ai-ctrf/dist/models/custom.js","../node_modules/ai-ctrf/dist/consolidated-summary.js","../node_modules/ai-ctrf/dist/models/openai.js","../node_modules/ai-ctrf/dist/json-summary.js","../node_modules/ai-ctrf/dist/report-insights.js","../node_modules/ai-ctrf/dist/models/mistral.js","../node_modules/ai-ctrf/dist/models/ollama.js","../node_modules/ai-ctrf/dist/index.js","../node_modules/@actions/core/src/command.ts","../node_modules/@actions/core/src/utils.ts","../node_modules/@actions/core/src/file-command.ts","../node_modules/@actions/core/src/core.ts","../node_modules/@actions/http-client/src/index.ts","../node_modules/@actions/http-client/src/proxy.ts","../node_modules/@actions/http-client/src/auth.ts","../node_modules/@actions/core/src/summary.ts","../node_modules/@actions/core/src/platform.ts","../node_modules/@actions/io/src/io-util.ts","../node_modules/@actions/exec/src/toolrunner.ts","../src/ctrf/enrichers.ts","../src/ctrf/helpers.ts","../node_modules/@actions/github/src/context.ts","../node_modules/@actions/github/src/internal/utils.ts","../node_modules/@actions/github/src/utils.ts","../node_modules/@actions/github/src/github.ts","../src/config/index.ts","../src/client/github/client.ts","../src/client/github/issues.ts","../src/client/github/workflows.ts","../src/client/github/artifacts.ts","../node_modules/@actions/artifact/src/internal/shared/config.ts","../node_modules/@actions/artifact/src/internal/upload/upload-artifact.ts","../node_modules/@protobuf-ts/runtime/build/es2015/json-typings.js","../node_modules/@protobuf-ts/runtime/build/es2015/base64.js","../node_modules/@protobuf-ts/runtime/build/es2015/binary-format-contract.js","../node_modules/@protobuf-ts/runtime/build/es2015/goog-varint.js","../node_modules/@protobuf-ts/runtime/build/es2015/pb-long.js","../node_modules/@protobuf-ts/runtime/build/es2015/binary-reader.js","../node_modules/@protobuf-ts/runtime/build/es2015/assert.js","../node_modules/@protobuf-ts/runtime/build/es2015/binary-writer.js","../node_modules/@protobuf-ts/runtime/build/es2015/json-format-contract.js","../node_modules/@protobuf-ts/runtime/build/es2015/message-type-contract.js","../node_modules/@protobuf-ts/runtime/build/es2015/lower-camel-case.js","../node_modules/@protobuf-ts/runtime/build/es2015/reflection-info.js","../node_modules/@protobuf-ts/runtime/build/es2015/oneof.js","../node_modules/@protobuf-ts/runtime/build/es2015/reflection-type-check.js","../node_modules/@protobuf-ts/runtime/build/es2015/reflection-long-convert.js","../node_modules/@protobuf-ts/runtime/build/es2015/reflection-json-reader.js","../node_modules/@protobuf-ts/runtime/build/es2015/reflection-json-writer.js","../node_modules/@protobuf-ts/runtime/build/es2015/reflection-scalar-default.js","../node_modules/@protobuf-ts/runtime/build/es2015/reflection-binary-reader.js","../node_modules/@protobuf-ts/runtime/build/es2015/reflection-binary-writer.js","../node_modules/@protobuf-ts/runtime/build/es2015/reflection-create.js","../node_modules/@protobuf-ts/runtime/build/es2015/reflection-merge-partial.js","../node_modules/@protobuf-ts/runtime/build/es2015/reflection-equals.js","../node_modules/@protobuf-ts/runtime/build/es2015/message-type.js","../node_modules/@actions/artifact/src/generated/google/protobuf/timestamp.ts","../node_modules/@actions/artifact/src/generated/google/protobuf/wrappers.ts","../node_modules/@protobuf-ts/runtime-rpc/build/es2015/reflection-info.js","../node_modules/@protobuf-ts/runtime-rpc/build/es2015/service-type.js","../node_modules/@actions/artifact/src/generated/results/api/v1/artifact.ts","../node_modules/@actions/artifact/src/generated/results/api/v1/artifact.twirp-client.ts","../node_modules/@actions/artifact/src/internal/upload/retention.ts","../node_modules/@actions/artifact/src/internal/upload/path-and-artifact-name-validation.ts","../node_modules/@actions/artifact/src/internal/shared/user-agent.ts","../node_modules/@actions/artifact/src/internal/shared/errors.ts","../node_modules/jwt-decode/build/esm/index.js","../node_modules/@actions/artifact/src/internal/shared/util.ts","../node_modules/@actions/artifact/src/internal/shared/artifact-twirp-client.ts","../node_modules/@actions/artifact/src/internal/upload/upload-zip-specification.ts","../node_modules/@typespec/ts-http-runtime/src/abort-controller/AbortError.ts","../node_modules/@typespec/ts-http-runtime/src/logger/log.ts","../node_modules/@typespec/ts-http-runtime/src/logger/debug.ts","../node_modules/@typespec/ts-http-runtime/src/logger/logger.ts","../node_modules/@typespec/ts-http-runtime/src/httpHeaders.ts","../node_modules/@typespec/ts-http-runtime/src/util/uuidUtils.ts","../node_modules/@typespec/ts-http-runtime/src/pipelineRequest.ts","../node_modules/@typespec/ts-http-runtime/src/pipeline.ts","../node_modules/@typespec/ts-http-runtime/src/util/object.ts","../node_modules/@typespec/ts-http-runtime/src/util/error.ts","../node_modules/@typespec/ts-http-runtime/src/util/inspect.ts","../node_modules/@typespec/ts-http-runtime/src/util/sanitizer.ts","../node_modules/@typespec/ts-http-runtime/src/restError.ts","../node_modules/@typespec/ts-http-runtime/src/util/bytesEncoding.ts","../node_modules/@typespec/ts-http-runtime/src/nodeHttpClient.ts","../node_modules/@typespec/ts-http-runtime/src/log.ts","../node_modules/@typespec/ts-http-runtime/src/defaultHttpClient.ts","../node_modules/@typespec/ts-http-runtime/src/policies/logPolicy.ts","../node_modules/@typespec/ts-http-runtime/src/policies/redirectPolicy.ts","../node_modules/@typespec/ts-http-runtime/src/util/userAgentPlatform.ts","../node_modules/@typespec/ts-http-runtime/src/constants.ts","../node_modules/@typespec/ts-http-runtime/src/util/userAgent.ts","../node_modules/@typespec/ts-http-runtime/src/policies/userAgentPolicy.ts","../node_modules/@typespec/ts-http-runtime/src/policies/decompressResponsePolicy.ts","../node_modules/@typespec/ts-http-runtime/src/util/random.ts","../node_modules/@typespec/ts-http-runtime/src/util/delay.ts","../node_modules/@typespec/ts-http-runtime/src/util/helpers.ts","../node_modules/@typespec/ts-http-runtime/src/retryStrategies/throttlingRetryStrategy.ts","../node_modules/@typespec/ts-http-runtime/src/retryStrategies/exponentialRetryStrategy.ts","../node_modules/@typespec/ts-http-runtime/src/policies/retryPolicy.ts","../node_modules/@typespec/ts-http-runtime/src/policies/defaultRetryPolicy.ts","../node_modules/@typespec/ts-http-runtime/src/util/checkEnvironment.ts","../node_modules/@typespec/ts-http-runtime/src/policies/formDataPolicy.ts","../node_modules/@typespec/ts-http-runtime/src/policies/proxyPolicy.ts","../node_modules/@typespec/ts-http-runtime/src/policies/agentPolicy.ts","../node_modules/@typespec/ts-http-runtime/src/policies/tlsPolicy.ts","../node_modules/@typespec/ts-http-runtime/src/util/typeGuards.ts","../node_modules/@typespec/ts-http-runtime/src/util/concat.ts","../node_modules/@typespec/ts-http-runtime/src/policies/multipartPolicy.ts","../node_modules/@azure/core-rest-pipeline/src/pipeline.ts","../node_modules/@azure/logger/src/index.ts","../node_modules/@azure/core-rest-pipeline/src/log.ts","../node_modules/@azure/core-rest-pipeline/src/policies/logPolicy.ts","../node_modules/@azure/core-rest-pipeline/src/policies/redirectPolicy.ts","../node_modules/@azure/core-rest-pipeline/src/util/userAgentPlatform.ts","../node_modules/@azure/core-rest-pipeline/src/constants.ts","../node_modules/@azure/core-rest-pipeline/src/util/userAgent.ts","../node_modules/@azure/core-rest-pipeline/src/policies/userAgentPolicy.ts","../node_modules/@typespec/ts-http-runtime/src/util/sha256.ts","../node_modules/@azure/abort-controller/src/AbortError.ts","../node_modules/@azure/core-util/src/createAbortablePromise.ts","../node_modules/@azure/core-util/src/delay.ts","../node_modules/@azure/core-util/src/error.ts","../node_modules/@azure/core-util/src/index.ts","../node_modules/@azure/core-rest-pipeline/src/util/file.ts","../node_modules/@azure/core-rest-pipeline/src/policies/multipartPolicy.ts","../node_modules/@azure/core-rest-pipeline/src/policies/decompressResponsePolicy.ts","../node_modules/@azure/core-rest-pipeline/src/policies/defaultRetryPolicy.ts","../node_modules/@azure/core-rest-pipeline/src/policies/formDataPolicy.ts","../node_modules/@azure/core-rest-pipeline/src/policies/proxyPolicy.ts","../node_modules/@azure/core-rest-pipeline/src/policies/setClientRequestIdPolicy.ts","../node_modules/@azure/core-rest-pipeline/src/policies/agentPolicy.ts","../node_modules/@azure/core-rest-pipeline/src/policies/tlsPolicy.ts","../node_modules/@azure/core-tracing/src/tracingContext.ts","../node_modules/@azure/core-tracing/src/state.ts","../node_modules/@azure/core-tracing/src/instrumenter.ts","../node_modules/@azure/core-tracing/src/tracingClient.ts","../node_modules/@azure/core-rest-pipeline/src/restError.ts","../node_modules/@azure/core-rest-pipeline/src/policies/tracingPolicy.ts","../node_modules/@azure/core-rest-pipeline/src/util/wrapAbortSignal.ts","../node_modules/@azure/core-rest-pipeline/src/policies/wrapAbortSignalLikePolicy.ts","../node_modules/@azure/core-rest-pipeline/src/createPipelineFromOptions.ts","../node_modules/@azure/core-rest-pipeline/src/defaultHttpClient.ts","../node_modules/@azure/core-rest-pipeline/src/httpHeaders.ts","../node_modules/@azure/core-rest-pipeline/src/pipelineRequest.ts","../node_modules/@azure/core-rest-pipeline/src/policies/retryPolicy.ts","../node_modules/@azure/core-rest-pipeline/src/util/tokenCycler.ts","../node_modules/@azure/core-rest-pipeline/src/policies/bearerTokenAuthenticationPolicy.ts","../node_modules/@azure/core-auth/src/tokenCredential.ts","../node_modules/@azure/core-http-compat/src/policies/disableKeepAlivePolicy.ts","../node_modules/@azure/core-client/src/base64.ts","../node_modules/@azure/core-client/src/interfaces.ts","../node_modules/@azure/core-client/src/utils.ts","../node_modules/@azure/core-client/src/serializer.ts","../node_modules/@azure/core-client/src/state.ts","../node_modules/@azure/core-client/src/operationHelpers.ts","../node_modules/@azure/core-client/src/deserializationPolicy.ts","../node_modules/@azure/core-client/src/interfaceHelpers.ts","../node_modules/@azure/core-client/src/serializationPolicy.ts","../node_modules/@azure/core-client/src/pipeline.ts","../node_modules/@azure/core-client/src/httpClientCache.ts","../node_modules/@azure/core-client/src/urlHelpers.ts","../node_modules/@azure/core-client/src/log.ts","../node_modules/@azure/core-client/src/serviceClient.ts","../node_modules/@azure/core-client/src/authorizeRequestOnTenantChallenge.ts","../node_modules/@azure/core-http-compat/src/util.ts","../node_modules/@azure/core-http-compat/src/response.ts","../node_modules/@azure/core-http-compat/src/extendedClient.ts","../node_modules/@azure/core-http-compat/src/policies/requestPolicyFactoryPolicy.ts","../node_modules/@azure/core-http-compat/src/httpClientAdapter.ts","../node_modules/@azure/core-xml/src/xml.ts","../node_modules/@azure/core-xml/src/xml.common.ts","../node_modules/@azure/storage-blob/src/log.ts","../node_modules/@azure/storage-common/src/BufferScheduler.ts","../node_modules/@azure/storage-common/src/BuffersStream.ts","../node_modules/@azure/storage-common/src/PooledBuffer.ts","../node_modules/@azure/storage-common/src/cache.ts","../node_modules/@azure/storage-common/src/policies/RequestPolicy.ts","../node_modules/@azure/storage-common/src/utils/constants.ts","../node_modules/@azure/storage-common/src/utils/utils.common.ts","../node_modules/@azure/storage-common/src/policies/StorageBrowserPolicy.ts","../node_modules/@azure/storage-common/src/StorageBrowserPolicyFactory.ts","../node_modules/@azure/storage-common/src/policies/CredentialPolicy.ts","../node_modules/@azure/storage-common/src/policies/AnonymousCredentialPolicy.ts","../node_modules/@azure/storage-common/src/credentials/Credential.ts","../node_modules/@azure/storage-common/src/credentials/AnonymousCredential.ts","../node_modules/@azure/storage-common/src/credentials/StorageSharedKeyCredential.ts","../node_modules/@azure/storage-common/src/utils/SharedKeyComparator.ts","../node_modules/@azure/storage-common/src/policies/StorageSharedKeyCredentialPolicy.ts","../node_modules/@azure/storage-common/src/log.ts","../node_modules/@azure/storage-common/src/policies/StorageRetryPolicyType.ts","../node_modules/@azure/storage-common/src/policies/StorageRetryPolicy.ts","../node_modules/@azure/storage-common/src/StorageRetryPolicyFactory.ts","../node_modules/@azure/storage-common/src/policies/StorageBrowserPolicyV2.ts","../node_modules/@azure/storage-common/src/policies/StorageCorrectContentLengthPolicy.ts","../node_modules/@azure/storage-common/src/policies/StorageRetryPolicyV2.ts","../node_modules/@azure/storage-common/src/policies/StorageSharedKeyCredentialPolicyV2.ts","../node_modules/@azure/storage-common/src/policies/StorageRequestFailureDetailsParserPolicy.ts","../node_modules/@azure/storage-common/src/credentials/UserDelegationKeyCredential.ts","../node_modules/@azure/storage-blob/src/utils/constants.ts","../node_modules/@azure/storage-blob/src/Pipeline.ts","../node_modules/@azure/storage-blob/src/generated/src/models/index.ts","../node_modules/@azure/storage-blob/src/generated/src/models/mappers.ts","../node_modules/@azure/storage-blob/src/generated/src/models/parameters.ts","../node_modules/@azure/storage-blob/src/generated/src/operations/service.ts","../node_modules/@azure/storage-blob/src/generated/src/operations/container.ts","../node_modules/@azure/storage-blob/src/generated/src/operations/blob.ts","../node_modules/@azure/storage-blob/src/generated/src/operations/pageBlob.ts","../node_modules/@azure/storage-blob/src/generated/src/operations/appendBlob.ts","../node_modules/@azure/storage-blob/src/generated/src/operations/blockBlob.ts","../node_modules/@azure/storage-blob/src/generated/src/storageClient.ts","../node_modules/@azure/storage-blob/src/StorageContextClient.ts","../node_modules/@azure/storage-blob/src/utils/utils.common.ts","../node_modules/@azure/storage-blob/src/StorageClient.ts","../node_modules/@azure/storage-blob/src/utils/tracing.ts","../node_modules/@azure/storage-blob/src/sas/BlobSASPermissions.ts","../node_modules/@azure/storage-blob/src/sas/ContainerSASPermissions.ts","../node_modules/@azure/storage-blob/src/sas/SasIPRange.ts","../node_modules/@azure/storage-blob/src/sas/SASQueryParameters.ts","../node_modules/@azure/storage-blob/src/sas/BlobSASSignatureValues.ts","../node_modules/@azure/storage-blob/src/BlobLeaseClient.ts","../node_modules/@azure/storage-blob/src/utils/RetriableReadableStream.ts","../node_modules/@azure/storage-blob/src/BlobDownloadResponse.ts","../node_modules/@azure/storage-blob/src/utils/BlobQuickQueryStream.ts","../node_modules/@azure/storage-blob/src/internal-avro/AvroConstants.ts","../node_modules/@azure/storage-blob/src/internal-avro/AvroParser.ts","../node_modules/@azure/storage-blob/src/internal-avro/utils/utils.common.ts","../node_modules/@azure/storage-blob/src/internal-avro/AvroReader.ts","../node_modules/@azure/storage-blob/src/internal-avro/AvroReadable.ts","../node_modules/@azure/storage-blob/src/internal-avro/AvroReadableFromStream.ts","../node_modules/@azure/storage-blob/src/BlobQueryResponse.ts","../node_modules/@azure/storage-blob/src/models.ts","../node_modules/@azure/storage-blob/src/PageBlobRangeResponse.ts","../node_modules/@azure/core-lro/src/logger.ts","../node_modules/@azure/core-lro/src/legacy/poller.ts","../node_modules/@azure/storage-blob/src/pollers/BlobStartCopyFromUrlPoller.ts","../node_modules/@azure/storage-blob/src/Range.ts","../node_modules/@azure/storage-blob/src/utils/Batch.ts","../node_modules/@azure/storage-blob/src/utils/utils.ts","../node_modules/@azure/storage-blob/src/Clients.ts","../node_modules/@azure/storage-blob/src/utils/Mutex.ts","../node_modules/@azure/storage-blob/src/generatedModels.ts","../node_modules/@actions/artifact/src/internal/upload/blob-upload.ts","../node_modules/@actions/artifact/src/internal/upload/zip.ts","../node_modules/@actions/artifact/src/internal/upload/stream.ts","../node_modules/@actions/artifact/src/internal/upload/types.ts","../node_modules/@actions/artifact/src/internal/download/download-artifact.ts","../node_modules/@actions/artifact/src/internal/find/retry-options.ts","../node_modules/@actions/artifact/src/internal/delete/delete-artifact.ts","../node_modules/@actions/artifact/node_modules/@octokit/plugin-retry/dist-bundle/index.js","../node_modules/@actions/artifact/src/internal/find/get-artifact.ts","../node_modules/@actions/artifact/src/internal/find/list-artifacts.ts","../node_modules/@actions/artifact/src/internal/client.ts","../node_modules/@actions/artifact/src/artifact.ts","../src/ctrf/core/src/methods/utilities/sort-reports.ts","../src/ctrf/core/src/methods/run-insights.ts","../src/ctrf/previous-results.ts","../src/ctrf/slowest-tests.ts","../src/ctrf/average-test-duration.ts","../src/ctrf/core/src/methods/read-reports.ts","../node_modules/glob/node_modules/balanced-match/src/index.ts","../node_modules/glob/node_modules/brace-expansion/src/index.ts","../node_modules/glob/node_modules/minimatch/src/assert-valid-pattern.ts","../node_modules/glob/node_modules/minimatch/src/brace-expressions.ts","../node_modules/glob/node_modules/minimatch/src/unescape.ts","../node_modules/glob/node_modules/minimatch/src/ast.ts","../node_modules/glob/node_modules/minimatch/src/escape.ts","../node_modules/glob/node_modules/minimatch/src/index.ts","../node_modules/glob/src/glob.ts","../node_modules/glob/node_modules/lru-cache/src/index.ts","../node_modules/glob/node_modules/path-scurry/src/index.ts","../node_modules/glob/node_modules/minipass/src/index.ts","../node_modules/glob/src/pattern.ts","../node_modules/glob/src/ignore.ts","../node_modules/glob/src/processor.ts","../node_modules/glob/src/walker.ts","../node_modules/glob/src/has-magic.ts","../node_modules/glob/src/index.ts","../src/ctrf/handle-baseline.ts","../src/ctrf/summary-insights.ts","../src/ctrf/metrics.ts","../src/utils/file-system.ts","../src/ctrf/core/src/constants.ts","../src/ctrf/core/src/methods/merge-reports.ts","../src/utils/report-utils.ts","../node_modules/junit-to-ctrf/dist/convert.js","../node_modules/junit-to-ctrf/dist/read.js","../node_modules/junit-to-ctrf/node_modules/balanced-match/src/index.ts","../node_modules/junit-to-ctrf/node_modules/brace-expansion/src/index.ts","../node_modules/junit-to-ctrf/node_modules/minimatch/src/assert-valid-pattern.ts","../node_modules/junit-to-ctrf/node_modules/minimatch/src/brace-expressions.ts","../node_modules/junit-to-ctrf/node_modules/minimatch/src/unescape.ts","../node_modules/junit-to-ctrf/node_modules/minimatch/src/ast.ts","../node_modules/junit-to-ctrf/node_modules/minimatch/src/escape.ts","../node_modules/junit-to-ctrf/node_modules/minimatch/src/index.ts","../node_modules/junit-to-ctrf/node_modules/glob/src/glob.ts","../node_modules/path-scurry/node_modules/lru-cache/src/index.ts","../node_modules/path-scurry/src/index.ts","../node_modules/minipass/src/index.ts","../node_modules/junit-to-ctrf/node_modules/glob/src/pattern.ts","../node_modules/junit-to-ctrf/node_modules/glob/src/ignore.ts","../node_modules/junit-to-ctrf/node_modules/glob/src/processor.ts","../node_modules/junit-to-ctrf/node_modules/glob/src/walker.ts","../node_modules/junit-to-ctrf/node_modules/glob/src/has-magic.ts","../node_modules/junit-to-ctrf/node_modules/glob/src/index.ts","../src/ctrf/report-conditionals.ts","../src/ctrf/prefix-test-names-with-suite.ts","../src/ctrf/group-test-results.ts","../src/ctrf/report-preparation.ts","../src/handlebars/core.ts","../src/handlebars/helpers/string.ts","../src/handlebars/helpers/ctrf.ts","../src/handlebars/helpers/ansi.ts","../src/handlebars/helpers/array.ts","../src/handlebars/helpers/math.ts","../src/handlebars/helpers/index.ts","../src/github/context.ts","../node_modules/handlebars-helpers-ctrf/dist/index.js","../node_modules/handlebars-helpers-ctrf/dist/helper-registry.js","../node_modules/handlebars-helpers-ctrf/dist/helpers/array.js","../node_modules/handlebars-helpers-ctrf/dist/helpers/collections.js","../node_modules/handlebars-helpers-ctrf/dist/helpers/comparison.js","../node_modules/handlebars-helpers-ctrf/dist/helpers/ctrf.js","../node_modules/handlebars-helpers-ctrf/dist/helpers/date.js","../node_modules/handlebars-helpers-ctrf/dist/helpers/fs.js","../node_modules/handlebars-helpers-ctrf/dist/helpers/github.js","../node_modules/handlebars-helpers-ctrf/dist/helpers/inflection.js","../node_modules/handlebars-helpers-ctrf/node_modules/balanced-match/src/index.ts","../node_modules/handlebars-helpers-ctrf/node_modules/brace-expansion/src/index.ts","../node_modules/handlebars-helpers-ctrf/node_modules/minimatch/src/assert-valid-pattern.ts","../node_modules/handlebars-helpers-ctrf/node_modules/minimatch/src/brace-expressions.ts","../node_modules/handlebars-helpers-ctrf/node_modules/minimatch/src/unescape.ts","../node_modules/handlebars-helpers-ctrf/node_modules/minimatch/src/ast.ts","../node_modules/handlebars-helpers-ctrf/node_modules/minimatch/src/escape.ts","../node_modules/handlebars-helpers-ctrf/node_modules/minimatch/src/index.ts","../node_modules/handlebars-helpers-ctrf/dist/helpers/match.js","../node_modules/handlebars-helpers-ctrf/dist/helpers/math.js","../node_modules/handlebars-helpers-ctrf/dist/helpers/misc.js","../node_modules/handlebars-helpers-ctrf/dist/helpers/number.js","../node_modules/handlebars-helpers-ctrf/dist/helpers/object.js","../node_modules/handlebars-helpers-ctrf/dist/helpers/path.js","../node_modules/handlebars-helpers-ctrf/dist/helpers/regex.js","../node_modules/handlebars-helpers-ctrf/dist/helpers/string.js","../node_modules/handlebars-helpers-ctrf/dist/helpers/timestamp.js","../node_modules/handlebars-helpers-ctrf/dist/helpers/url.js","../src/reports/core.ts","../src/reports/constants.ts","../src/github/core.ts","../src/github/helpers.ts","../src/core/inputs.ts","../src/client/github/checks.ts","../src/github/handler.ts","../src/integrations/slack.ts","../src/integrations/teams.ts","../src/integrations/ai.ts","../src/integrations/handler.ts","../src/core/action-handler.ts","../src/index.ts"],"sourcesContent":["'use strict';\n\nvar net = require('net');\nvar tls = require('tls');\nvar http = require('http');\nvar https = require('https');\nvar events = require('events');\nvar assert = require('assert');\nvar util = require('util');\n\n\nexports.httpOverHttp = httpOverHttp;\nexports.httpsOverHttp = httpsOverHttp;\nexports.httpOverHttps = httpOverHttps;\nexports.httpsOverHttps = httpsOverHttps;\n\n\nfunction httpOverHttp(options) {\n var agent = new TunnelingAgent(options);\n agent.request = http.request;\n return agent;\n}\n\nfunction httpsOverHttp(options) {\n var agent = new TunnelingAgent(options);\n agent.request = http.request;\n agent.createSocket = createSecureSocket;\n agent.defaultPort = 443;\n return agent;\n}\n\nfunction httpOverHttps(options) {\n var agent = new TunnelingAgent(options);\n agent.request = https.request;\n return agent;\n}\n\nfunction httpsOverHttps(options) {\n var agent = new TunnelingAgent(options);\n agent.request = https.request;\n agent.createSocket = createSecureSocket;\n agent.defaultPort = 443;\n return agent;\n}\n\n\nfunction TunnelingAgent(options) {\n var self = this;\n self.options = options || {};\n self.proxyOptions = self.options.proxy || {};\n self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;\n self.requests = [];\n self.sockets = [];\n\n self.on('free', function onFree(socket, host, port, localAddress) {\n var options = toOptions(host, port, localAddress);\n for (var i = 0, len = self.requests.length; i < len; ++i) {\n var pending = self.requests[i];\n if (pending.host === options.host && pending.port === options.port) {\n // Detect the request to connect same origin server,\n // reuse the connection.\n self.requests.splice(i, 1);\n pending.request.onSocket(socket);\n return;\n }\n }\n socket.destroy();\n self.removeSocket(socket);\n });\n}\nutil.inherits(TunnelingAgent, events.EventEmitter);\n\nTunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {\n var self = this;\n var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));\n\n if (self.sockets.length >= this.maxSockets) {\n // We are over limit so we'll add it to the queue.\n self.requests.push(options);\n return;\n }\n\n // If we are under maxSockets create a new one.\n self.createSocket(options, function(socket) {\n socket.on('free', onFree);\n socket.on('close', onCloseOrRemove);\n socket.on('agentRemove', onCloseOrRemove);\n req.onSocket(socket);\n\n function onFree() {\n self.emit('free', socket, options);\n }\n\n function onCloseOrRemove(err) {\n self.removeSocket(socket);\n socket.removeListener('free', onFree);\n socket.removeListener('close', onCloseOrRemove);\n socket.removeListener('agentRemove', onCloseOrRemove);\n }\n });\n};\n\nTunnelingAgent.prototype.createSocket = function createSocket(options, cb) {\n var self = this;\n var placeholder = {};\n self.sockets.push(placeholder);\n\n var connectOptions = mergeOptions({}, self.proxyOptions, {\n method: 'CONNECT',\n path: options.host + ':' + options.port,\n agent: false,\n headers: {\n host: options.host + ':' + options.port\n }\n });\n if (options.localAddress) {\n connectOptions.localAddress = options.localAddress;\n }\n if (connectOptions.proxyAuth) {\n connectOptions.headers = connectOptions.headers || {};\n connectOptions.headers['Proxy-Authorization'] = 'Basic ' +\n new Buffer(connectOptions.proxyAuth).toString('base64');\n }\n\n debug('making CONNECT request');\n var connectReq = self.request(connectOptions);\n connectReq.useChunkedEncodingByDefault = false; // for v0.6\n connectReq.once('response', onResponse); // for v0.6\n connectReq.once('upgrade', onUpgrade); // for v0.6\n connectReq.once('connect', onConnect); // for v0.7 or later\n connectReq.once('error', onError);\n connectReq.end();\n\n function onResponse(res) {\n // Very hacky. This is necessary to avoid http-parser leaks.\n res.upgrade = true;\n }\n\n function onUpgrade(res, socket, head) {\n // Hacky.\n process.nextTick(function() {\n onConnect(res, socket, head);\n });\n }\n\n function onConnect(res, socket, head) {\n connectReq.removeAllListeners();\n socket.removeAllListeners();\n\n if (res.statusCode !== 200) {\n debug('tunneling socket could not be established, statusCode=%d',\n res.statusCode);\n socket.destroy();\n var error = new Error('tunneling socket could not be established, ' +\n 'statusCode=' + res.statusCode);\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n return;\n }\n if (head.length > 0) {\n debug('got illegal response body from proxy');\n socket.destroy();\n var error = new Error('got illegal response body from proxy');\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n return;\n }\n debug('tunneling connection has established');\n self.sockets[self.sockets.indexOf(placeholder)] = socket;\n return cb(socket);\n }\n\n function onError(cause) {\n connectReq.removeAllListeners();\n\n debug('tunneling socket could not be established, cause=%s\\n',\n cause.message, cause.stack);\n var error = new Error('tunneling socket could not be established, ' +\n 'cause=' + cause.message);\n error.code = 'ECONNRESET';\n options.request.emit('error', error);\n self.removeSocket(placeholder);\n }\n};\n\nTunnelingAgent.prototype.removeSocket = function removeSocket(socket) {\n var pos = this.sockets.indexOf(socket)\n if (pos === -1) {\n return;\n }\n this.sockets.splice(pos, 1);\n\n var pending = this.requests.shift();\n if (pending) {\n // If we have pending requests and a socket gets closed a new one\n // needs to be created to take over in the pool for the one that closed.\n this.createSocket(pending, function(socket) {\n pending.request.onSocket(socket);\n });\n }\n};\n\nfunction createSecureSocket(options, cb) {\n var self = this;\n TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {\n var hostHeader = options.request.getHeader('host');\n var tlsOptions = mergeOptions({}, self.options, {\n socket: socket,\n servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host\n });\n\n // 0 is dummy port for v0.6\n var secureSocket = tls.connect(0, tlsOptions);\n self.sockets[self.sockets.indexOf(socket)] = secureSocket;\n cb(secureSocket);\n });\n}\n\n\nfunction toOptions(host, port, localAddress) {\n if (typeof host === 'string') { // since v0.10\n return {\n host: host,\n port: port,\n localAddress: localAddress\n };\n }\n return host; // for v0.11 or later\n}\n\nfunction mergeOptions(target) {\n for (var i = 1, len = arguments.length; i < len; ++i) {\n var overrides = arguments[i];\n if (typeof overrides === 'object') {\n var keys = Object.keys(overrides);\n for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {\n var k = keys[j];\n if (overrides[k] !== undefined) {\n target[k] = overrides[k];\n }\n }\n }\n }\n return target;\n}\n\n\nvar debug;\nif (process.env.NODE_DEBUG && /\\btunnel\\b/.test(process.env.NODE_DEBUG)) {\n debug = function() {\n var args = Array.prototype.slice.call(arguments);\n if (typeof args[0] === 'string') {\n args[0] = 'TUNNEL: ' + args[0];\n } else {\n args.unshift('TUNNEL:');\n }\n console.error.apply(console, args);\n }\n} else {\n debug = function() {};\n}\nexports.debug = debug; // for test\n","module.exports = require('./lib/tunnel');\n","module.exports = {\n kClose: Symbol('close'),\n kDestroy: Symbol('destroy'),\n kDispatch: Symbol('dispatch'),\n kUrl: Symbol('url'),\n kWriting: Symbol('writing'),\n kResuming: Symbol('resuming'),\n kQueue: Symbol('queue'),\n kConnect: Symbol('connect'),\n kConnecting: Symbol('connecting'),\n kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'),\n kKeepAliveMaxTimeout: Symbol('max keep alive timeout'),\n kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'),\n kKeepAliveTimeoutValue: Symbol('keep alive timeout'),\n kKeepAlive: Symbol('keep alive'),\n kHeadersTimeout: Symbol('headers timeout'),\n kBodyTimeout: Symbol('body timeout'),\n kServerName: Symbol('server name'),\n kLocalAddress: Symbol('local address'),\n kHost: Symbol('host'),\n kNoRef: Symbol('no ref'),\n kBodyUsed: Symbol('used'),\n kBody: Symbol('abstracted request body'),\n kRunning: Symbol('running'),\n kBlocking: Symbol('blocking'),\n kPending: Symbol('pending'),\n kSize: Symbol('size'),\n kBusy: Symbol('busy'),\n kQueued: Symbol('queued'),\n kFree: Symbol('free'),\n kConnected: Symbol('connected'),\n kClosed: Symbol('closed'),\n kNeedDrain: Symbol('need drain'),\n kReset: Symbol('reset'),\n kDestroyed: Symbol.for('nodejs.stream.destroyed'),\n kResume: Symbol('resume'),\n kOnError: Symbol('on error'),\n kMaxHeadersSize: Symbol('max headers size'),\n kRunningIdx: Symbol('running index'),\n kPendingIdx: Symbol('pending index'),\n kError: Symbol('error'),\n kClients: Symbol('clients'),\n kClient: Symbol('client'),\n kParser: Symbol('parser'),\n kOnDestroyed: Symbol('destroy callbacks'),\n kPipelining: Symbol('pipelining'),\n kSocket: Symbol('socket'),\n kHostHeader: Symbol('host header'),\n kConnector: Symbol('connector'),\n kStrictContentLength: Symbol('strict content length'),\n kMaxRedirections: Symbol('maxRedirections'),\n kMaxRequests: Symbol('maxRequestsPerClient'),\n kProxy: Symbol('proxy agent options'),\n kCounter: Symbol('socket request counter'),\n kInterceptors: Symbol('dispatch interceptors'),\n kMaxResponseSize: Symbol('max response size'),\n kHTTP2Session: Symbol('http2Session'),\n kHTTP2SessionState: Symbol('http2Session state'),\n kRetryHandlerDefaultRetry: Symbol('retry agent default retry'),\n kConstruct: Symbol('constructable'),\n kListeners: Symbol('listeners'),\n kHTTPContext: Symbol('http context'),\n kMaxConcurrentStreams: Symbol('max concurrent streams'),\n kNoProxyAgent: Symbol('no proxy agent'),\n kHttpProxyAgent: Symbol('http proxy agent'),\n kHttpsProxyAgent: Symbol('https proxy agent')\n}\n","'use strict'\n\nconst kUndiciError = Symbol.for('undici.error.UND_ERR')\nclass UndiciError extends Error {\n constructor (message) {\n super(message)\n this.name = 'UndiciError'\n this.code = 'UND_ERR'\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kUndiciError] === true\n }\n\n [kUndiciError] = true\n}\n\nconst kConnectTimeoutError = Symbol.for('undici.error.UND_ERR_CONNECT_TIMEOUT')\nclass ConnectTimeoutError extends UndiciError {\n constructor (message) {\n super(message)\n this.name = 'ConnectTimeoutError'\n this.message = message || 'Connect Timeout Error'\n this.code = 'UND_ERR_CONNECT_TIMEOUT'\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kConnectTimeoutError] === true\n }\n\n [kConnectTimeoutError] = true\n}\n\nconst kHeadersTimeoutError = Symbol.for('undici.error.UND_ERR_HEADERS_TIMEOUT')\nclass HeadersTimeoutError extends UndiciError {\n constructor (message) {\n super(message)\n this.name = 'HeadersTimeoutError'\n this.message = message || 'Headers Timeout Error'\n this.code = 'UND_ERR_HEADERS_TIMEOUT'\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kHeadersTimeoutError] === true\n }\n\n [kHeadersTimeoutError] = true\n}\n\nconst kHeadersOverflowError = Symbol.for('undici.error.UND_ERR_HEADERS_OVERFLOW')\nclass HeadersOverflowError extends UndiciError {\n constructor (message) {\n super(message)\n this.name = 'HeadersOverflowError'\n this.message = message || 'Headers Overflow Error'\n this.code = 'UND_ERR_HEADERS_OVERFLOW'\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kHeadersOverflowError] === true\n }\n\n [kHeadersOverflowError] = true\n}\n\nconst kBodyTimeoutError = Symbol.for('undici.error.UND_ERR_BODY_TIMEOUT')\nclass BodyTimeoutError extends UndiciError {\n constructor (message) {\n super(message)\n this.name = 'BodyTimeoutError'\n this.message = message || 'Body Timeout Error'\n this.code = 'UND_ERR_BODY_TIMEOUT'\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kBodyTimeoutError] === true\n }\n\n [kBodyTimeoutError] = true\n}\n\nconst kResponseStatusCodeError = Symbol.for('undici.error.UND_ERR_RESPONSE_STATUS_CODE')\nclass ResponseStatusCodeError extends UndiciError {\n constructor (message, statusCode, headers, body) {\n super(message)\n this.name = 'ResponseStatusCodeError'\n this.message = message || 'Response Status Code Error'\n this.code = 'UND_ERR_RESPONSE_STATUS_CODE'\n this.body = body\n this.status = statusCode\n this.statusCode = statusCode\n this.headers = headers\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kResponseStatusCodeError] === true\n }\n\n [kResponseStatusCodeError] = true\n}\n\nconst kInvalidArgumentError = Symbol.for('undici.error.UND_ERR_INVALID_ARG')\nclass InvalidArgumentError extends UndiciError {\n constructor (message) {\n super(message)\n this.name = 'InvalidArgumentError'\n this.message = message || 'Invalid Argument Error'\n this.code = 'UND_ERR_INVALID_ARG'\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kInvalidArgumentError] === true\n }\n\n [kInvalidArgumentError] = true\n}\n\nconst kInvalidReturnValueError = Symbol.for('undici.error.UND_ERR_INVALID_RETURN_VALUE')\nclass InvalidReturnValueError extends UndiciError {\n constructor (message) {\n super(message)\n this.name = 'InvalidReturnValueError'\n this.message = message || 'Invalid Return Value Error'\n this.code = 'UND_ERR_INVALID_RETURN_VALUE'\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kInvalidReturnValueError] === true\n }\n\n [kInvalidReturnValueError] = true\n}\n\nconst kAbortError = Symbol.for('undici.error.UND_ERR_ABORT')\nclass AbortError extends UndiciError {\n constructor (message) {\n super(message)\n this.name = 'AbortError'\n this.message = message || 'The operation was aborted'\n this.code = 'UND_ERR_ABORT'\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kAbortError] === true\n }\n\n [kAbortError] = true\n}\n\nconst kRequestAbortedError = Symbol.for('undici.error.UND_ERR_ABORTED')\nclass RequestAbortedError extends AbortError {\n constructor (message) {\n super(message)\n this.name = 'AbortError'\n this.message = message || 'Request aborted'\n this.code = 'UND_ERR_ABORTED'\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kRequestAbortedError] === true\n }\n\n [kRequestAbortedError] = true\n}\n\nconst kInformationalError = Symbol.for('undici.error.UND_ERR_INFO')\nclass InformationalError extends UndiciError {\n constructor (message) {\n super(message)\n this.name = 'InformationalError'\n this.message = message || 'Request information'\n this.code = 'UND_ERR_INFO'\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kInformationalError] === true\n }\n\n [kInformationalError] = true\n}\n\nconst kRequestContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_REQ_CONTENT_LENGTH_MISMATCH')\nclass RequestContentLengthMismatchError extends UndiciError {\n constructor (message) {\n super(message)\n this.name = 'RequestContentLengthMismatchError'\n this.message = message || 'Request body length does not match content-length header'\n this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kRequestContentLengthMismatchError] === true\n }\n\n [kRequestContentLengthMismatchError] = true\n}\n\nconst kResponseContentLengthMismatchError = Symbol.for('undici.error.UND_ERR_RES_CONTENT_LENGTH_MISMATCH')\nclass ResponseContentLengthMismatchError extends UndiciError {\n constructor (message) {\n super(message)\n this.name = 'ResponseContentLengthMismatchError'\n this.message = message || 'Response body length does not match content-length header'\n this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kResponseContentLengthMismatchError] === true\n }\n\n [kResponseContentLengthMismatchError] = true\n}\n\nconst kClientDestroyedError = Symbol.for('undici.error.UND_ERR_DESTROYED')\nclass ClientDestroyedError extends UndiciError {\n constructor (message) {\n super(message)\n this.name = 'ClientDestroyedError'\n this.message = message || 'The client is destroyed'\n this.code = 'UND_ERR_DESTROYED'\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kClientDestroyedError] === true\n }\n\n [kClientDestroyedError] = true\n}\n\nconst kClientClosedError = Symbol.for('undici.error.UND_ERR_CLOSED')\nclass ClientClosedError extends UndiciError {\n constructor (message) {\n super(message)\n this.name = 'ClientClosedError'\n this.message = message || 'The client is closed'\n this.code = 'UND_ERR_CLOSED'\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kClientClosedError] === true\n }\n\n [kClientClosedError] = true\n}\n\nconst kSocketError = Symbol.for('undici.error.UND_ERR_SOCKET')\nclass SocketError extends UndiciError {\n constructor (message, socket) {\n super(message)\n this.name = 'SocketError'\n this.message = message || 'Socket error'\n this.code = 'UND_ERR_SOCKET'\n this.socket = socket\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kSocketError] === true\n }\n\n [kSocketError] = true\n}\n\nconst kNotSupportedError = Symbol.for('undici.error.UND_ERR_NOT_SUPPORTED')\nclass NotSupportedError extends UndiciError {\n constructor (message) {\n super(message)\n this.name = 'NotSupportedError'\n this.message = message || 'Not supported error'\n this.code = 'UND_ERR_NOT_SUPPORTED'\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kNotSupportedError] === true\n }\n\n [kNotSupportedError] = true\n}\n\nconst kBalancedPoolMissingUpstreamError = Symbol.for('undici.error.UND_ERR_BPL_MISSING_UPSTREAM')\nclass BalancedPoolMissingUpstreamError extends UndiciError {\n constructor (message) {\n super(message)\n this.name = 'MissingUpstreamError'\n this.message = message || 'No upstream has been added to the BalancedPool'\n this.code = 'UND_ERR_BPL_MISSING_UPSTREAM'\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kBalancedPoolMissingUpstreamError] === true\n }\n\n [kBalancedPoolMissingUpstreamError] = true\n}\n\nconst kHTTPParserError = Symbol.for('undici.error.UND_ERR_HTTP_PARSER')\nclass HTTPParserError extends Error {\n constructor (message, code, data) {\n super(message)\n this.name = 'HTTPParserError'\n this.code = code ? `HPE_${code}` : undefined\n this.data = data ? data.toString() : undefined\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kHTTPParserError] === true\n }\n\n [kHTTPParserError] = true\n}\n\nconst kResponseExceededMaxSizeError = Symbol.for('undici.error.UND_ERR_RES_EXCEEDED_MAX_SIZE')\nclass ResponseExceededMaxSizeError extends UndiciError {\n constructor (message) {\n super(message)\n this.name = 'ResponseExceededMaxSizeError'\n this.message = message || 'Response content exceeded max size'\n this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE'\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kResponseExceededMaxSizeError] === true\n }\n\n [kResponseExceededMaxSizeError] = true\n}\n\nconst kRequestRetryError = Symbol.for('undici.error.UND_ERR_REQ_RETRY')\nclass RequestRetryError extends UndiciError {\n constructor (message, code, { headers, data }) {\n super(message)\n this.name = 'RequestRetryError'\n this.message = message || 'Request retry error'\n this.code = 'UND_ERR_REQ_RETRY'\n this.statusCode = code\n this.data = data\n this.headers = headers\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kRequestRetryError] === true\n }\n\n [kRequestRetryError] = true\n}\n\nconst kResponseError = Symbol.for('undici.error.UND_ERR_RESPONSE')\nclass ResponseError extends UndiciError {\n constructor (message, code, { headers, data }) {\n super(message)\n this.name = 'ResponseError'\n this.message = message || 'Response error'\n this.code = 'UND_ERR_RESPONSE'\n this.statusCode = code\n this.data = data\n this.headers = headers\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kResponseError] === true\n }\n\n [kResponseError] = true\n}\n\nconst kSecureProxyConnectionError = Symbol.for('undici.error.UND_ERR_PRX_TLS')\nclass SecureProxyConnectionError extends UndiciError {\n constructor (cause, message, options) {\n super(message, { cause, ...(options ?? {}) })\n this.name = 'SecureProxyConnectionError'\n this.message = message || 'Secure Proxy Connection failed'\n this.code = 'UND_ERR_PRX_TLS'\n this.cause = cause\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kSecureProxyConnectionError] === true\n }\n\n [kSecureProxyConnectionError] = true\n}\n\nconst kMessageSizeExceededError = Symbol.for('undici.error.UND_ERR_WS_MESSAGE_SIZE_EXCEEDED')\nclass MessageSizeExceededError extends UndiciError {\n constructor (message) {\n super(message)\n this.name = 'MessageSizeExceededError'\n this.message = message || 'Max decompressed message size exceeded'\n this.code = 'UND_ERR_WS_MESSAGE_SIZE_EXCEEDED'\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kMessageSizeExceededError] === true\n }\n\n get [kMessageSizeExceededError] () {\n return true\n }\n}\n\nmodule.exports = {\n AbortError,\n HTTPParserError,\n UndiciError,\n HeadersTimeoutError,\n HeadersOverflowError,\n BodyTimeoutError,\n RequestContentLengthMismatchError,\n ConnectTimeoutError,\n ResponseStatusCodeError,\n InvalidArgumentError,\n InvalidReturnValueError,\n RequestAbortedError,\n ClientDestroyedError,\n ClientClosedError,\n InformationalError,\n SocketError,\n NotSupportedError,\n ResponseContentLengthMismatchError,\n BalancedPoolMissingUpstreamError,\n ResponseExceededMaxSizeError,\n RequestRetryError,\n ResponseError,\n SecureProxyConnectionError,\n MessageSizeExceededError\n}\n","'use strict'\n\n/** @type {Record} */\nconst headerNameLowerCasedRecord = {}\n\n// https://developer.mozilla.org/docs/Web/HTTP/Headers\nconst wellknownHeaderNames = [\n 'Accept',\n 'Accept-Encoding',\n 'Accept-Language',\n 'Accept-Ranges',\n 'Access-Control-Allow-Credentials',\n 'Access-Control-Allow-Headers',\n 'Access-Control-Allow-Methods',\n 'Access-Control-Allow-Origin',\n 'Access-Control-Expose-Headers',\n 'Access-Control-Max-Age',\n 'Access-Control-Request-Headers',\n 'Access-Control-Request-Method',\n 'Age',\n 'Allow',\n 'Alt-Svc',\n 'Alt-Used',\n 'Authorization',\n 'Cache-Control',\n 'Clear-Site-Data',\n 'Connection',\n 'Content-Disposition',\n 'Content-Encoding',\n 'Content-Language',\n 'Content-Length',\n 'Content-Location',\n 'Content-Range',\n 'Content-Security-Policy',\n 'Content-Security-Policy-Report-Only',\n 'Content-Type',\n 'Cookie',\n 'Cross-Origin-Embedder-Policy',\n 'Cross-Origin-Opener-Policy',\n 'Cross-Origin-Resource-Policy',\n 'Date',\n 'Device-Memory',\n 'Downlink',\n 'ECT',\n 'ETag',\n 'Expect',\n 'Expect-CT',\n 'Expires',\n 'Forwarded',\n 'From',\n 'Host',\n 'If-Match',\n 'If-Modified-Since',\n 'If-None-Match',\n 'If-Range',\n 'If-Unmodified-Since',\n 'Keep-Alive',\n 'Last-Modified',\n 'Link',\n 'Location',\n 'Max-Forwards',\n 'Origin',\n 'Permissions-Policy',\n 'Pragma',\n 'Proxy-Authenticate',\n 'Proxy-Authorization',\n 'RTT',\n 'Range',\n 'Referer',\n 'Referrer-Policy',\n 'Refresh',\n 'Retry-After',\n 'Sec-WebSocket-Accept',\n 'Sec-WebSocket-Extensions',\n 'Sec-WebSocket-Key',\n 'Sec-WebSocket-Protocol',\n 'Sec-WebSocket-Version',\n 'Server',\n 'Server-Timing',\n 'Service-Worker-Allowed',\n 'Service-Worker-Navigation-Preload',\n 'Set-Cookie',\n 'SourceMap',\n 'Strict-Transport-Security',\n 'Supports-Loading-Mode',\n 'TE',\n 'Timing-Allow-Origin',\n 'Trailer',\n 'Transfer-Encoding',\n 'Upgrade',\n 'Upgrade-Insecure-Requests',\n 'User-Agent',\n 'Vary',\n 'Via',\n 'WWW-Authenticate',\n 'X-Content-Type-Options',\n 'X-DNS-Prefetch-Control',\n 'X-Frame-Options',\n 'X-Permitted-Cross-Domain-Policies',\n 'X-Powered-By',\n 'X-Requested-With',\n 'X-XSS-Protection'\n]\n\nfor (let i = 0; i < wellknownHeaderNames.length; ++i) {\n const key = wellknownHeaderNames[i]\n const lowerCasedKey = key.toLowerCase()\n headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] =\n lowerCasedKey\n}\n\n// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.\nObject.setPrototypeOf(headerNameLowerCasedRecord, null)\n\nmodule.exports = {\n wellknownHeaderNames,\n headerNameLowerCasedRecord\n}\n","'use strict'\n\nconst {\n wellknownHeaderNames,\n headerNameLowerCasedRecord\n} = require('./constants')\n\nclass TstNode {\n /** @type {any} */\n value = null\n /** @type {null | TstNode} */\n left = null\n /** @type {null | TstNode} */\n middle = null\n /** @type {null | TstNode} */\n right = null\n /** @type {number} */\n code\n /**\n * @param {string} key\n * @param {any} value\n * @param {number} index\n */\n constructor (key, value, index) {\n if (index === undefined || index >= key.length) {\n throw new TypeError('Unreachable')\n }\n const code = this.code = key.charCodeAt(index)\n // check code is ascii string\n if (code > 0x7F) {\n throw new TypeError('key must be ascii string')\n }\n if (key.length !== ++index) {\n this.middle = new TstNode(key, value, index)\n } else {\n this.value = value\n }\n }\n\n /**\n * @param {string} key\n * @param {any} value\n */\n add (key, value) {\n const length = key.length\n if (length === 0) {\n throw new TypeError('Unreachable')\n }\n let index = 0\n let node = this\n while (true) {\n const code = key.charCodeAt(index)\n // check code is ascii string\n if (code > 0x7F) {\n throw new TypeError('key must be ascii string')\n }\n if (node.code === code) {\n if (length === ++index) {\n node.value = value\n break\n } else if (node.middle !== null) {\n node = node.middle\n } else {\n node.middle = new TstNode(key, value, index)\n break\n }\n } else if (node.code < code) {\n if (node.left !== null) {\n node = node.left\n } else {\n node.left = new TstNode(key, value, index)\n break\n }\n } else if (node.right !== null) {\n node = node.right\n } else {\n node.right = new TstNode(key, value, index)\n break\n }\n }\n }\n\n /**\n * @param {Uint8Array} key\n * @return {TstNode | null}\n */\n search (key) {\n const keylength = key.length\n let index = 0\n let node = this\n while (node !== null && index < keylength) {\n let code = key[index]\n // A-Z\n // First check if it is bigger than 0x5a.\n // Lowercase letters have higher char codes than uppercase ones.\n // Also we assume that headers will mostly contain lowercase characters.\n if (code <= 0x5a && code >= 0x41) {\n // Lowercase for uppercase.\n code |= 32\n }\n while (node !== null) {\n if (code === node.code) {\n if (keylength === ++index) {\n // Returns Node since it is the last key.\n return node\n }\n node = node.middle\n break\n }\n node = node.code < code ? node.left : node.right\n }\n }\n return null\n }\n}\n\nclass TernarySearchTree {\n /** @type {TstNode | null} */\n node = null\n\n /**\n * @param {string} key\n * @param {any} value\n * */\n insert (key, value) {\n if (this.node === null) {\n this.node = new TstNode(key, value, 0)\n } else {\n this.node.add(key, value)\n }\n }\n\n /**\n * @param {Uint8Array} key\n * @return {any}\n */\n lookup (key) {\n return this.node?.search(key)?.value ?? null\n }\n}\n\nconst tree = new TernarySearchTree()\n\nfor (let i = 0; i < wellknownHeaderNames.length; ++i) {\n const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]]\n tree.insert(key, key)\n}\n\nmodule.exports = {\n TernarySearchTree,\n tree\n}\n","'use strict'\n\nconst assert = require('node:assert')\nconst { kDestroyed, kBodyUsed, kListeners, kBody } = require('./symbols')\nconst { IncomingMessage } = require('node:http')\nconst stream = require('node:stream')\nconst net = require('node:net')\nconst { Blob } = require('node:buffer')\nconst nodeUtil = require('node:util')\nconst { stringify } = require('node:querystring')\nconst { EventEmitter: EE } = require('node:events')\nconst { InvalidArgumentError } = require('./errors')\nconst { headerNameLowerCasedRecord } = require('./constants')\nconst { tree } = require('./tree')\n\nconst [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v))\n\nclass BodyAsyncIterable {\n constructor (body) {\n this[kBody] = body\n this[kBodyUsed] = false\n }\n\n async * [Symbol.asyncIterator] () {\n assert(!this[kBodyUsed], 'disturbed')\n this[kBodyUsed] = true\n yield * this[kBody]\n }\n}\n\nfunction wrapRequestBody (body) {\n if (isStream(body)) {\n // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp\n // so that it can be dispatched again?\n // TODO (fix): Do we need 100-expect support to provide a way to do this properly?\n if (bodyLength(body) === 0) {\n body\n .on('data', function () {\n assert(false)\n })\n }\n\n if (typeof body.readableDidRead !== 'boolean') {\n body[kBodyUsed] = false\n EE.prototype.on.call(body, 'data', function () {\n this[kBodyUsed] = true\n })\n }\n\n return body\n } else if (body && typeof body.pipeTo === 'function') {\n // TODO (fix): We can't access ReadableStream internal state\n // to determine whether or not it has been disturbed. This is just\n // a workaround.\n return new BodyAsyncIterable(body)\n } else if (\n body &&\n typeof body !== 'string' &&\n !ArrayBuffer.isView(body) &&\n isIterable(body)\n ) {\n // TODO: Should we allow re-using iterable if !this.opts.idempotent\n // or through some other flag?\n return new BodyAsyncIterable(body)\n } else {\n return body\n }\n}\n\nfunction nop () {}\n\nfunction isStream (obj) {\n return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function'\n}\n\n// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License)\nfunction isBlobLike (object) {\n if (object === null) {\n return false\n } else if (object instanceof Blob) {\n return true\n } else if (typeof object !== 'object') {\n return false\n } else {\n const sTag = object[Symbol.toStringTag]\n\n return (sTag === 'Blob' || sTag === 'File') && (\n ('stream' in object && typeof object.stream === 'function') ||\n ('arrayBuffer' in object && typeof object.arrayBuffer === 'function')\n )\n }\n}\n\nfunction buildURL (url, queryParams) {\n if (url.includes('?') || url.includes('#')) {\n throw new Error('Query params cannot be passed when url already contains \"?\" or \"#\".')\n }\n\n const stringified = stringify(queryParams)\n\n if (stringified) {\n url += '?' + stringified\n }\n\n return url\n}\n\nfunction isValidPort (port) {\n const value = parseInt(port, 10)\n return (\n value === Number(port) &&\n value >= 0 &&\n value <= 65535\n )\n}\n\nfunction isHttpOrHttpsPrefixed (value) {\n return (\n value != null &&\n value[0] === 'h' &&\n value[1] === 't' &&\n value[2] === 't' &&\n value[3] === 'p' &&\n (\n value[4] === ':' ||\n (\n value[4] === 's' &&\n value[5] === ':'\n )\n )\n )\n}\n\nfunction parseURL (url) {\n if (typeof url === 'string') {\n url = new URL(url)\n\n if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {\n throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')\n }\n\n return url\n }\n\n if (!url || typeof url !== 'object') {\n throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')\n }\n\n if (!(url instanceof URL)) {\n if (url.port != null && url.port !== '' && isValidPort(url.port) === false) {\n throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')\n }\n\n if (url.path != null && typeof url.path !== 'string') {\n throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.')\n }\n\n if (url.pathname != null && typeof url.pathname !== 'string') {\n throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.')\n }\n\n if (url.hostname != null && typeof url.hostname !== 'string') {\n throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.')\n }\n\n if (url.origin != null && typeof url.origin !== 'string') {\n throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.')\n }\n\n if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {\n throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')\n }\n\n const port = url.port != null\n ? url.port\n : (url.protocol === 'https:' ? 443 : 80)\n let origin = url.origin != null\n ? url.origin\n : `${url.protocol || ''}//${url.hostname || ''}:${port}`\n let path = url.path != null\n ? url.path\n : `${url.pathname || ''}${url.search || ''}`\n\n if (origin[origin.length - 1] === '/') {\n origin = origin.slice(0, origin.length - 1)\n }\n\n if (path && path[0] !== '/') {\n path = `/${path}`\n }\n // new URL(path, origin) is unsafe when `path` contains an absolute URL\n // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL:\n // If first parameter is a relative URL, second param is required, and will be used as the base URL.\n // If first parameter is an absolute URL, a given second param will be ignored.\n return new URL(`${origin}${path}`)\n }\n\n if (!isHttpOrHttpsPrefixed(url.origin || url.protocol)) {\n throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')\n }\n\n return url\n}\n\nfunction parseOrigin (url) {\n url = parseURL(url)\n\n if (url.pathname !== '/' || url.search || url.hash) {\n throw new InvalidArgumentError('invalid url')\n }\n\n return url\n}\n\nfunction getHostname (host) {\n if (host[0] === '[') {\n const idx = host.indexOf(']')\n\n assert(idx !== -1)\n return host.substring(1, idx)\n }\n\n const idx = host.indexOf(':')\n if (idx === -1) return host\n\n return host.substring(0, idx)\n}\n\n// IP addresses are not valid server names per RFC6066\n// > Currently, the only server names supported are DNS hostnames\nfunction getServerName (host) {\n if (!host) {\n return null\n }\n\n assert(typeof host === 'string')\n\n const servername = getHostname(host)\n if (net.isIP(servername)) {\n return ''\n }\n\n return servername\n}\n\nfunction deepClone (obj) {\n return JSON.parse(JSON.stringify(obj))\n}\n\nfunction isAsyncIterable (obj) {\n return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function')\n}\n\nfunction isIterable (obj) {\n return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function'))\n}\n\nfunction bodyLength (body) {\n if (body == null) {\n return 0\n } else if (isStream(body)) {\n const state = body._readableState\n return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length)\n ? state.length\n : null\n } else if (isBlobLike(body)) {\n return body.size != null ? body.size : null\n } else if (isBuffer(body)) {\n return body.byteLength\n }\n\n return null\n}\n\nfunction isDestroyed (body) {\n return body && !!(body.destroyed || body[kDestroyed] || (stream.isDestroyed?.(body)))\n}\n\nfunction destroy (stream, err) {\n if (stream == null || !isStream(stream) || isDestroyed(stream)) {\n return\n }\n\n if (typeof stream.destroy === 'function') {\n if (Object.getPrototypeOf(stream).constructor === IncomingMessage) {\n // See: https://github.com/nodejs/node/pull/38505/files\n stream.socket = null\n }\n\n stream.destroy(err)\n } else if (err) {\n queueMicrotask(() => {\n stream.emit('error', err)\n })\n }\n\n if (stream.destroyed !== true) {\n stream[kDestroyed] = true\n }\n}\n\nconst KEEPALIVE_TIMEOUT_EXPR = /timeout=(\\d+)/\nfunction parseKeepAliveTimeout (val) {\n const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR)\n return m ? parseInt(m[1], 10) * 1000 : null\n}\n\n/**\n * Retrieves a header name and returns its lowercase value.\n * @param {string | Buffer} value Header name\n * @returns {string}\n */\nfunction headerNameToString (value) {\n return typeof value === 'string'\n ? headerNameLowerCasedRecord[value] ?? value.toLowerCase()\n : tree.lookup(value) ?? value.toString('latin1').toLowerCase()\n}\n\n/**\n * Receive the buffer as a string and return its lowercase value.\n * @param {Buffer} value Header name\n * @returns {string}\n */\nfunction bufferToLowerCasedHeaderName (value) {\n return tree.lookup(value) ?? value.toString('latin1').toLowerCase()\n}\n\n/**\n * @param {Record | (Buffer | string | (Buffer | string)[])[]} headers\n * @param {Record} [obj]\n * @returns {Record}\n */\nfunction parseHeaders (headers, obj) {\n if (obj === undefined) obj = {}\n for (let i = 0; i < headers.length; i += 2) {\n const key = headerNameToString(headers[i])\n let val = obj[key]\n\n if (val) {\n if (typeof val === 'string') {\n val = [val]\n obj[key] = val\n }\n val.push(headers[i + 1].toString('utf8'))\n } else {\n const headersValue = headers[i + 1]\n if (typeof headersValue === 'string') {\n obj[key] = headersValue\n } else {\n obj[key] = Array.isArray(headersValue) ? headersValue.map(x => x.toString('utf8')) : headersValue.toString('utf8')\n }\n }\n }\n\n // See https://github.com/nodejs/node/pull/46528\n if ('content-length' in obj && 'content-disposition' in obj) {\n obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1')\n }\n\n return obj\n}\n\nfunction parseRawHeaders (headers) {\n const len = headers.length\n const ret = new Array(len)\n\n let hasContentLength = false\n let contentDispositionIdx = -1\n let key\n let val\n let kLen = 0\n\n for (let n = 0; n < headers.length; n += 2) {\n key = headers[n]\n val = headers[n + 1]\n\n typeof key !== 'string' && (key = key.toString())\n typeof val !== 'string' && (val = val.toString('utf8'))\n\n kLen = key.length\n if (kLen === 14 && key[7] === '-' && (key === 'content-length' || key.toLowerCase() === 'content-length')) {\n hasContentLength = true\n } else if (kLen === 19 && key[7] === '-' && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) {\n contentDispositionIdx = n + 1\n }\n ret[n] = key\n ret[n + 1] = val\n }\n\n // See https://github.com/nodejs/node/pull/46528\n if (hasContentLength && contentDispositionIdx !== -1) {\n ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1')\n }\n\n return ret\n}\n\nfunction isBuffer (buffer) {\n // See, https://github.com/mcollina/undici/pull/319\n return buffer instanceof Uint8Array || Buffer.isBuffer(buffer)\n}\n\nfunction validateHandler (handler, method, upgrade) {\n if (!handler || typeof handler !== 'object') {\n throw new InvalidArgumentError('handler must be an object')\n }\n\n if (typeof handler.onConnect !== 'function') {\n throw new InvalidArgumentError('invalid onConnect method')\n }\n\n if (typeof handler.onError !== 'function') {\n throw new InvalidArgumentError('invalid onError method')\n }\n\n if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) {\n throw new InvalidArgumentError('invalid onBodySent method')\n }\n\n if (upgrade || method === 'CONNECT') {\n if (typeof handler.onUpgrade !== 'function') {\n throw new InvalidArgumentError('invalid onUpgrade method')\n }\n } else {\n if (typeof handler.onHeaders !== 'function') {\n throw new InvalidArgumentError('invalid onHeaders method')\n }\n\n if (typeof handler.onData !== 'function') {\n throw new InvalidArgumentError('invalid onData method')\n }\n\n if (typeof handler.onComplete !== 'function') {\n throw new InvalidArgumentError('invalid onComplete method')\n }\n }\n}\n\n// A body is disturbed if it has been read from and it cannot\n// be re-used without losing state or data.\nfunction isDisturbed (body) {\n // TODO (fix): Why is body[kBodyUsed] needed?\n return !!(body && (stream.isDisturbed(body) || body[kBodyUsed]))\n}\n\nfunction isErrored (body) {\n return !!(body && stream.isErrored(body))\n}\n\nfunction isReadable (body) {\n return !!(body && stream.isReadable(body))\n}\n\nfunction getSocketInfo (socket) {\n return {\n localAddress: socket.localAddress,\n localPort: socket.localPort,\n remoteAddress: socket.remoteAddress,\n remotePort: socket.remotePort,\n remoteFamily: socket.remoteFamily,\n timeout: socket.timeout,\n bytesWritten: socket.bytesWritten,\n bytesRead: socket.bytesRead\n }\n}\n\n/** @type {globalThis['ReadableStream']} */\nfunction ReadableStreamFrom (iterable) {\n // We cannot use ReadableStream.from here because it does not return a byte stream.\n\n let iterator\n return new ReadableStream(\n {\n async start () {\n iterator = iterable[Symbol.asyncIterator]()\n },\n async pull (controller) {\n const { done, value } = await iterator.next()\n if (done) {\n queueMicrotask(() => {\n controller.close()\n controller.byobRequest?.respond(0)\n })\n } else {\n const buf = Buffer.isBuffer(value) ? value : Buffer.from(value)\n if (buf.byteLength) {\n controller.enqueue(new Uint8Array(buf))\n }\n }\n return controller.desiredSize > 0\n },\n async cancel (reason) {\n await iterator.return()\n },\n type: 'bytes'\n }\n )\n}\n\n// The chunk should be a FormData instance and contains\n// all the required methods.\nfunction isFormDataLike (object) {\n return (\n object &&\n typeof object === 'object' &&\n typeof object.append === 'function' &&\n typeof object.delete === 'function' &&\n typeof object.get === 'function' &&\n typeof object.getAll === 'function' &&\n typeof object.has === 'function' &&\n typeof object.set === 'function' &&\n object[Symbol.toStringTag] === 'FormData'\n )\n}\n\nfunction addAbortListener (signal, listener) {\n if ('addEventListener' in signal) {\n signal.addEventListener('abort', listener, { once: true })\n return () => signal.removeEventListener('abort', listener)\n }\n signal.addListener('abort', listener)\n return () => signal.removeListener('abort', listener)\n}\n\nconst hasToWellFormed = typeof String.prototype.toWellFormed === 'function'\nconst hasIsWellFormed = typeof String.prototype.isWellFormed === 'function'\n\n/**\n * @param {string} val\n */\nfunction toUSVString (val) {\n return hasToWellFormed ? `${val}`.toWellFormed() : nodeUtil.toUSVString(val)\n}\n\n/**\n * @param {string} val\n */\n// TODO: move this to webidl\nfunction isUSVString (val) {\n return hasIsWellFormed ? `${val}`.isWellFormed() : toUSVString(val) === `${val}`\n}\n\n/**\n * @see https://tools.ietf.org/html/rfc7230#section-3.2.6\n * @param {number} c\n */\nfunction isTokenCharCode (c) {\n switch (c) {\n case 0x22:\n case 0x28:\n case 0x29:\n case 0x2c:\n case 0x2f:\n case 0x3a:\n case 0x3b:\n case 0x3c:\n case 0x3d:\n case 0x3e:\n case 0x3f:\n case 0x40:\n case 0x5b:\n case 0x5c:\n case 0x5d:\n case 0x7b:\n case 0x7d:\n // DQUOTE and \"(),/:;<=>?@[\\]{}\"\n return false\n default:\n // VCHAR %x21-7E\n return c >= 0x21 && c <= 0x7e\n }\n}\n\n/**\n * @param {string} characters\n */\nfunction isValidHTTPToken (characters) {\n if (characters.length === 0) {\n return false\n }\n for (let i = 0; i < characters.length; ++i) {\n if (!isTokenCharCode(characters.charCodeAt(i))) {\n return false\n }\n }\n return true\n}\n\n// headerCharRegex have been lifted from\n// https://github.com/nodejs/node/blob/main/lib/_http_common.js\n\n/**\n * Matches if val contains an invalid field-vchar\n * field-value = *( field-content / obs-fold )\n * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]\n * field-vchar = VCHAR / obs-text\n */\nconst headerCharRegex = /[^\\t\\x20-\\x7e\\x80-\\xff]/\n\n/**\n * @param {string} characters\n */\nfunction isValidHeaderValue (characters) {\n return !headerCharRegex.test(characters)\n}\n\n// Parsed accordingly to RFC 9110\n// https://www.rfc-editor.org/rfc/rfc9110#field.content-range\nfunction parseRangeHeader (range) {\n if (range == null || range === '') return { start: 0, end: null, size: null }\n\n const m = range ? range.match(/^bytes (\\d+)-(\\d+)\\/(\\d+)?$/) : null\n return m\n ? {\n start: parseInt(m[1]),\n end: m[2] ? parseInt(m[2]) : null,\n size: m[3] ? parseInt(m[3]) : null\n }\n : null\n}\n\nfunction addListener (obj, name, listener) {\n const listeners = (obj[kListeners] ??= [])\n listeners.push([name, listener])\n obj.on(name, listener)\n return obj\n}\n\nfunction removeAllListeners (obj) {\n for (const [name, listener] of obj[kListeners] ?? []) {\n obj.removeListener(name, listener)\n }\n obj[kListeners] = null\n}\n\nfunction errorRequest (client, request, err) {\n try {\n request.onError(err)\n assert(request.aborted)\n } catch (err) {\n client.emit('error', err)\n }\n}\n\nconst kEnumerableProperty = Object.create(null)\nkEnumerableProperty.enumerable = true\n\nconst normalizedMethodRecordsBase = {\n delete: 'DELETE',\n DELETE: 'DELETE',\n get: 'GET',\n GET: 'GET',\n head: 'HEAD',\n HEAD: 'HEAD',\n options: 'OPTIONS',\n OPTIONS: 'OPTIONS',\n post: 'POST',\n POST: 'POST',\n put: 'PUT',\n PUT: 'PUT'\n}\n\nconst normalizedMethodRecords = {\n ...normalizedMethodRecordsBase,\n patch: 'patch',\n PATCH: 'PATCH'\n}\n\n// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.\nObject.setPrototypeOf(normalizedMethodRecordsBase, null)\nObject.setPrototypeOf(normalizedMethodRecords, null)\n\nmodule.exports = {\n kEnumerableProperty,\n nop,\n isDisturbed,\n isErrored,\n isReadable,\n toUSVString,\n isUSVString,\n isBlobLike,\n parseOrigin,\n parseURL,\n getServerName,\n isStream,\n isIterable,\n isAsyncIterable,\n isDestroyed,\n headerNameToString,\n bufferToLowerCasedHeaderName,\n addListener,\n removeAllListeners,\n errorRequest,\n parseRawHeaders,\n parseHeaders,\n parseKeepAliveTimeout,\n destroy,\n bodyLength,\n deepClone,\n ReadableStreamFrom,\n isBuffer,\n validateHandler,\n getSocketInfo,\n isFormDataLike,\n buildURL,\n addAbortListener,\n isValidHTTPToken,\n isValidHeaderValue,\n isTokenCharCode,\n parseRangeHeader,\n normalizedMethodRecordsBase,\n normalizedMethodRecords,\n isValidPort,\n isHttpOrHttpsPrefixed,\n nodeMajor,\n nodeMinor,\n safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE'],\n wrapRequestBody\n}\n","'use strict'\nconst diagnosticsChannel = require('node:diagnostics_channel')\nconst util = require('node:util')\n\nconst undiciDebugLog = util.debuglog('undici')\nconst fetchDebuglog = util.debuglog('fetch')\nconst websocketDebuglog = util.debuglog('websocket')\nlet isClientSet = false\nconst channels = {\n // Client\n beforeConnect: diagnosticsChannel.channel('undici:client:beforeConnect'),\n connected: diagnosticsChannel.channel('undici:client:connected'),\n connectError: diagnosticsChannel.channel('undici:client:connectError'),\n sendHeaders: diagnosticsChannel.channel('undici:client:sendHeaders'),\n // Request\n create: diagnosticsChannel.channel('undici:request:create'),\n bodySent: diagnosticsChannel.channel('undici:request:bodySent'),\n headers: diagnosticsChannel.channel('undici:request:headers'),\n trailers: diagnosticsChannel.channel('undici:request:trailers'),\n error: diagnosticsChannel.channel('undici:request:error'),\n // WebSocket\n open: diagnosticsChannel.channel('undici:websocket:open'),\n close: diagnosticsChannel.channel('undici:websocket:close'),\n socketError: diagnosticsChannel.channel('undici:websocket:socket_error'),\n ping: diagnosticsChannel.channel('undici:websocket:ping'),\n pong: diagnosticsChannel.channel('undici:websocket:pong')\n}\n\nif (undiciDebugLog.enabled || fetchDebuglog.enabled) {\n const debuglog = fetchDebuglog.enabled ? fetchDebuglog : undiciDebugLog\n\n // Track all Client events\n diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(evt => {\n const {\n connectParams: { version, protocol, port, host }\n } = evt\n debuglog(\n 'connecting to %s using %s%s',\n `${host}${port ? `:${port}` : ''}`,\n protocol,\n version\n )\n })\n\n diagnosticsChannel.channel('undici:client:connected').subscribe(evt => {\n const {\n connectParams: { version, protocol, port, host }\n } = evt\n debuglog(\n 'connected to %s using %s%s',\n `${host}${port ? `:${port}` : ''}`,\n protocol,\n version\n )\n })\n\n diagnosticsChannel.channel('undici:client:connectError').subscribe(evt => {\n const {\n connectParams: { version, protocol, port, host },\n error\n } = evt\n debuglog(\n 'connection to %s using %s%s errored - %s',\n `${host}${port ? `:${port}` : ''}`,\n protocol,\n version,\n error.message\n )\n })\n\n diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(evt => {\n const {\n request: { method, path, origin }\n } = evt\n debuglog('sending request to %s %s/%s', method, origin, path)\n })\n\n // Track Request events\n diagnosticsChannel.channel('undici:request:headers').subscribe(evt => {\n const {\n request: { method, path, origin },\n response: { statusCode }\n } = evt\n debuglog(\n 'received response to %s %s/%s - HTTP %d',\n method,\n origin,\n path,\n statusCode\n )\n })\n\n diagnosticsChannel.channel('undici:request:trailers').subscribe(evt => {\n const {\n request: { method, path, origin }\n } = evt\n debuglog('trailers received from %s %s/%s', method, origin, path)\n })\n\n diagnosticsChannel.channel('undici:request:error').subscribe(evt => {\n const {\n request: { method, path, origin },\n error\n } = evt\n debuglog(\n 'request to %s %s/%s errored - %s',\n method,\n origin,\n path,\n error.message\n )\n })\n\n isClientSet = true\n}\n\nif (websocketDebuglog.enabled) {\n if (!isClientSet) {\n const debuglog = undiciDebugLog.enabled ? undiciDebugLog : websocketDebuglog\n diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(evt => {\n const {\n connectParams: { version, protocol, port, host }\n } = evt\n debuglog(\n 'connecting to %s%s using %s%s',\n host,\n port ? `:${port}` : '',\n protocol,\n version\n )\n })\n\n diagnosticsChannel.channel('undici:client:connected').subscribe(evt => {\n const {\n connectParams: { version, protocol, port, host }\n } = evt\n debuglog(\n 'connected to %s%s using %s%s',\n host,\n port ? `:${port}` : '',\n protocol,\n version\n )\n })\n\n diagnosticsChannel.channel('undici:client:connectError').subscribe(evt => {\n const {\n connectParams: { version, protocol, port, host },\n error\n } = evt\n debuglog(\n 'connection to %s%s using %s%s errored - %s',\n host,\n port ? `:${port}` : '',\n protocol,\n version,\n error.message\n )\n })\n\n diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(evt => {\n const {\n request: { method, path, origin }\n } = evt\n debuglog('sending request to %s %s/%s', method, origin, path)\n })\n }\n\n // Track all WebSocket events\n diagnosticsChannel.channel('undici:websocket:open').subscribe(evt => {\n const {\n address: { address, port }\n } = evt\n websocketDebuglog('connection opened %s%s', address, port ? `:${port}` : '')\n })\n\n diagnosticsChannel.channel('undici:websocket:close').subscribe(evt => {\n const { websocket, code, reason } = evt\n websocketDebuglog(\n 'closed connection to %s - %s %s',\n websocket.url,\n code,\n reason\n )\n })\n\n diagnosticsChannel.channel('undici:websocket:socket_error').subscribe(err => {\n websocketDebuglog('connection errored - %s', err.message)\n })\n\n diagnosticsChannel.channel('undici:websocket:ping').subscribe(evt => {\n websocketDebuglog('ping received')\n })\n\n diagnosticsChannel.channel('undici:websocket:pong').subscribe(evt => {\n websocketDebuglog('pong received')\n })\n}\n\nmodule.exports = {\n channels\n}\n","'use strict'\n\nconst {\n InvalidArgumentError,\n NotSupportedError\n} = require('./errors')\nconst assert = require('node:assert')\nconst {\n isValidHTTPToken,\n isValidHeaderValue,\n isStream,\n destroy,\n isBuffer,\n isFormDataLike,\n isIterable,\n isBlobLike,\n buildURL,\n validateHandler,\n getServerName,\n normalizedMethodRecords\n} = require('./util')\nconst { channels } = require('./diagnostics.js')\nconst { headerNameLowerCasedRecord } = require('./constants')\n\n// Verifies that a given path is valid does not contain control chars \\x00 to \\x20\nconst invalidPathRegex = /[^\\u0021-\\u00ff]/\n\nconst kHandler = Symbol('handler')\n\nclass Request {\n constructor (origin, {\n path,\n method,\n body,\n headers,\n query,\n idempotent,\n blocking,\n upgrade,\n headersTimeout,\n bodyTimeout,\n reset,\n throwOnError,\n expectContinue,\n servername\n }, handler) {\n if (typeof path !== 'string') {\n throw new InvalidArgumentError('path must be a string')\n } else if (\n path[0] !== '/' &&\n !(path.startsWith('http://') || path.startsWith('https://')) &&\n method !== 'CONNECT'\n ) {\n throw new InvalidArgumentError('path must be an absolute URL or start with a slash')\n } else if (invalidPathRegex.test(path)) {\n throw new InvalidArgumentError('invalid request path')\n }\n\n if (typeof method !== 'string') {\n throw new InvalidArgumentError('method must be a string')\n } else if (normalizedMethodRecords[method] === undefined && !isValidHTTPToken(method)) {\n throw new InvalidArgumentError('invalid request method')\n }\n\n if (upgrade && typeof upgrade !== 'string') {\n throw new InvalidArgumentError('upgrade must be a string')\n }\n\n if (upgrade && !isValidHeaderValue(upgrade)) {\n throw new InvalidArgumentError('invalid upgrade header')\n }\n\n if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {\n throw new InvalidArgumentError('invalid headersTimeout')\n }\n\n if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {\n throw new InvalidArgumentError('invalid bodyTimeout')\n }\n\n if (reset != null && typeof reset !== 'boolean') {\n throw new InvalidArgumentError('invalid reset')\n }\n\n if (expectContinue != null && typeof expectContinue !== 'boolean') {\n throw new InvalidArgumentError('invalid expectContinue')\n }\n\n this.headersTimeout = headersTimeout\n\n this.bodyTimeout = bodyTimeout\n\n this.throwOnError = throwOnError === true\n\n this.method = method\n\n this.abort = null\n\n if (body == null) {\n this.body = null\n } else if (isStream(body)) {\n this.body = body\n\n const rState = this.body._readableState\n if (!rState || !rState.autoDestroy) {\n this.endHandler = function autoDestroy () {\n destroy(this)\n }\n this.body.on('end', this.endHandler)\n }\n\n this.errorHandler = err => {\n if (this.abort) {\n this.abort(err)\n } else {\n this.error = err\n }\n }\n this.body.on('error', this.errorHandler)\n } else if (isBuffer(body)) {\n this.body = body.byteLength ? body : null\n } else if (ArrayBuffer.isView(body)) {\n this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null\n } else if (body instanceof ArrayBuffer) {\n this.body = body.byteLength ? Buffer.from(body) : null\n } else if (typeof body === 'string') {\n this.body = body.length ? Buffer.from(body) : null\n } else if (isFormDataLike(body) || isIterable(body) || isBlobLike(body)) {\n this.body = body\n } else {\n throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable')\n }\n\n this.completed = false\n\n this.aborted = false\n\n this.upgrade = upgrade || null\n\n this.path = query ? buildURL(path, query) : path\n\n this.origin = origin\n\n this.idempotent = idempotent == null\n ? method === 'HEAD' || method === 'GET'\n : idempotent\n\n this.blocking = blocking == null ? false : blocking\n\n this.reset = reset == null ? null : reset\n\n this.host = null\n\n this.contentLength = null\n\n this.contentType = null\n\n this.headers = []\n\n // Only for H2\n this.expectContinue = expectContinue != null ? expectContinue : false\n\n if (Array.isArray(headers)) {\n if (headers.length % 2 !== 0) {\n throw new InvalidArgumentError('headers array must be even')\n }\n for (let i = 0; i < headers.length; i += 2) {\n processHeader(this, headers[i], headers[i + 1])\n }\n } else if (headers && typeof headers === 'object') {\n if (headers[Symbol.iterator]) {\n for (const header of headers) {\n if (!Array.isArray(header) || header.length !== 2) {\n throw new InvalidArgumentError('headers must be in key-value pair format')\n }\n processHeader(this, header[0], header[1])\n }\n } else {\n const keys = Object.keys(headers)\n for (let i = 0; i < keys.length; ++i) {\n processHeader(this, keys[i], headers[keys[i]])\n }\n }\n } else if (headers != null) {\n throw new InvalidArgumentError('headers must be an object or an array')\n }\n\n validateHandler(handler, method, upgrade)\n\n this.servername = servername || getServerName(this.host)\n\n this[kHandler] = handler\n\n if (channels.create.hasSubscribers) {\n channels.create.publish({ request: this })\n }\n }\n\n onBodySent (chunk) {\n if (this[kHandler].onBodySent) {\n try {\n return this[kHandler].onBodySent(chunk)\n } catch (err) {\n this.abort(err)\n }\n }\n }\n\n onRequestSent () {\n if (channels.bodySent.hasSubscribers) {\n channels.bodySent.publish({ request: this })\n }\n\n if (this[kHandler].onRequestSent) {\n try {\n return this[kHandler].onRequestSent()\n } catch (err) {\n this.abort(err)\n }\n }\n }\n\n onConnect (abort) {\n assert(!this.aborted)\n assert(!this.completed)\n\n if (this.error) {\n abort(this.error)\n } else {\n this.abort = abort\n return this[kHandler].onConnect(abort)\n }\n }\n\n onResponseStarted () {\n return this[kHandler].onResponseStarted?.()\n }\n\n onHeaders (statusCode, headers, resume, statusText) {\n assert(!this.aborted)\n assert(!this.completed)\n\n if (channels.headers.hasSubscribers) {\n channels.headers.publish({ request: this, response: { statusCode, headers, statusText } })\n }\n\n try {\n return this[kHandler].onHeaders(statusCode, headers, resume, statusText)\n } catch (err) {\n this.abort(err)\n }\n }\n\n onData (chunk) {\n assert(!this.aborted)\n assert(!this.completed)\n\n try {\n return this[kHandler].onData(chunk)\n } catch (err) {\n this.abort(err)\n return false\n }\n }\n\n onUpgrade (statusCode, headers, socket) {\n assert(!this.aborted)\n assert(!this.completed)\n\n return this[kHandler].onUpgrade(statusCode, headers, socket)\n }\n\n onComplete (trailers) {\n this.onFinally()\n\n assert(!this.aborted)\n\n this.completed = true\n if (channels.trailers.hasSubscribers) {\n channels.trailers.publish({ request: this, trailers })\n }\n\n try {\n return this[kHandler].onComplete(trailers)\n } catch (err) {\n // TODO (fix): This might be a bad idea?\n this.onError(err)\n }\n }\n\n onError (error) {\n this.onFinally()\n\n if (channels.error.hasSubscribers) {\n channels.error.publish({ request: this, error })\n }\n\n if (this.aborted) {\n return\n }\n this.aborted = true\n\n return this[kHandler].onError(error)\n }\n\n onFinally () {\n if (this.errorHandler) {\n this.body.off('error', this.errorHandler)\n this.errorHandler = null\n }\n\n if (this.endHandler) {\n this.body.off('end', this.endHandler)\n this.endHandler = null\n }\n }\n\n addHeader (key, value) {\n processHeader(this, key, value)\n return this\n }\n}\n\nfunction processHeader (request, key, val) {\n if (val && (typeof val === 'object' && !Array.isArray(val))) {\n throw new InvalidArgumentError(`invalid ${key} header`)\n } else if (val === undefined) {\n return\n }\n\n let headerName = headerNameLowerCasedRecord[key]\n\n if (headerName === undefined) {\n headerName = key.toLowerCase()\n if (headerNameLowerCasedRecord[headerName] === undefined && !isValidHTTPToken(headerName)) {\n throw new InvalidArgumentError('invalid header key')\n }\n }\n\n if (Array.isArray(val)) {\n const arr = []\n for (let i = 0; i < val.length; i++) {\n if (typeof val[i] === 'string') {\n if (!isValidHeaderValue(val[i])) {\n throw new InvalidArgumentError(`invalid ${key} header`)\n }\n arr.push(val[i])\n } else if (val[i] === null) {\n arr.push('')\n } else if (typeof val[i] === 'object') {\n throw new InvalidArgumentError(`invalid ${key} header`)\n } else {\n arr.push(`${val[i]}`)\n }\n }\n val = arr\n } else if (typeof val === 'string') {\n if (!isValidHeaderValue(val)) {\n throw new InvalidArgumentError(`invalid ${key} header`)\n }\n } else if (val === null) {\n val = ''\n } else {\n val = `${val}`\n }\n\n if (headerName === 'host') {\n if (request.host !== null) {\n throw new InvalidArgumentError('duplicate host header')\n }\n if (typeof val !== 'string') {\n throw new InvalidArgumentError('invalid host header')\n }\n // Consumed by Client\n request.host = val\n } else if (headerName === 'content-length') {\n if (request.contentLength !== null) {\n throw new InvalidArgumentError('duplicate content-length header')\n }\n request.contentLength = parseInt(val, 10)\n if (!Number.isFinite(request.contentLength)) {\n throw new InvalidArgumentError('invalid content-length header')\n }\n } else if (request.contentType === null && headerName === 'content-type') {\n request.contentType = val\n request.headers.push(key, val)\n } else if (headerName === 'transfer-encoding' || headerName === 'keep-alive' || headerName === 'upgrade') {\n throw new InvalidArgumentError(`invalid ${headerName} header`)\n } else if (headerName === 'connection') {\n const value = typeof val === 'string' ? val.toLowerCase() : null\n if (value !== 'close' && value !== 'keep-alive') {\n throw new InvalidArgumentError('invalid connection header')\n }\n\n if (value === 'close') {\n request.reset = true\n }\n } else if (headerName === 'expect') {\n throw new NotSupportedError('expect header not supported')\n } else {\n request.headers.push(key, val)\n }\n}\n\nmodule.exports = Request\n","'use strict'\nconst EventEmitter = require('node:events')\n\nclass Dispatcher extends EventEmitter {\n dispatch () {\n throw new Error('not implemented')\n }\n\n close () {\n throw new Error('not implemented')\n }\n\n destroy () {\n throw new Error('not implemented')\n }\n\n compose (...args) {\n // So we handle [interceptor1, interceptor2] or interceptor1, interceptor2, ...\n const interceptors = Array.isArray(args[0]) ? args[0] : args\n let dispatch = this.dispatch.bind(this)\n\n for (const interceptor of interceptors) {\n if (interceptor == null) {\n continue\n }\n\n if (typeof interceptor !== 'function') {\n throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`)\n }\n\n dispatch = interceptor(dispatch)\n\n if (dispatch == null || typeof dispatch !== 'function' || dispatch.length !== 2) {\n throw new TypeError('invalid interceptor')\n }\n }\n\n return new ComposedDispatcher(this, dispatch)\n }\n}\n\nclass ComposedDispatcher extends Dispatcher {\n #dispatcher = null\n #dispatch = null\n\n constructor (dispatcher, dispatch) {\n super()\n this.#dispatcher = dispatcher\n this.#dispatch = dispatch\n }\n\n dispatch (...args) {\n this.#dispatch(...args)\n }\n\n close (...args) {\n return this.#dispatcher.close(...args)\n }\n\n destroy (...args) {\n return this.#dispatcher.destroy(...args)\n }\n}\n\nmodule.exports = Dispatcher\n","'use strict'\n\nconst Dispatcher = require('./dispatcher')\nconst {\n ClientDestroyedError,\n ClientClosedError,\n InvalidArgumentError\n} = require('../core/errors')\nconst { kDestroy, kClose, kClosed, kDestroyed, kDispatch, kInterceptors } = require('../core/symbols')\n\nconst kOnDestroyed = Symbol('onDestroyed')\nconst kOnClosed = Symbol('onClosed')\nconst kInterceptedDispatch = Symbol('Intercepted Dispatch')\nconst kWebSocketOptions = Symbol('webSocketOptions')\n\nclass DispatcherBase extends Dispatcher {\n constructor (opts) {\n super()\n\n this[kDestroyed] = false\n this[kOnDestroyed] = null\n this[kClosed] = false\n this[kOnClosed] = []\n this[kWebSocketOptions] = opts?.webSocket ?? {}\n }\n\n get webSocketOptions () {\n return {\n maxPayloadSize: this[kWebSocketOptions].maxPayloadSize ?? 128 * 1024 * 1024\n }\n }\n\n get destroyed () {\n return this[kDestroyed]\n }\n\n get closed () {\n return this[kClosed]\n }\n\n get interceptors () {\n return this[kInterceptors]\n }\n\n set interceptors (newInterceptors) {\n if (newInterceptors) {\n for (let i = newInterceptors.length - 1; i >= 0; i--) {\n const interceptor = this[kInterceptors][i]\n if (typeof interceptor !== 'function') {\n throw new InvalidArgumentError('interceptor must be an function')\n }\n }\n }\n\n this[kInterceptors] = newInterceptors\n }\n\n close (callback) {\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n this.close((err, data) => {\n return err ? reject(err) : resolve(data)\n })\n })\n }\n\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n if (this[kDestroyed]) {\n queueMicrotask(() => callback(new ClientDestroyedError(), null))\n return\n }\n\n if (this[kClosed]) {\n if (this[kOnClosed]) {\n this[kOnClosed].push(callback)\n } else {\n queueMicrotask(() => callback(null, null))\n }\n return\n }\n\n this[kClosed] = true\n this[kOnClosed].push(callback)\n\n const onClosed = () => {\n const callbacks = this[kOnClosed]\n this[kOnClosed] = null\n for (let i = 0; i < callbacks.length; i++) {\n callbacks[i](null, null)\n }\n }\n\n // Should not error.\n this[kClose]()\n .then(() => this.destroy())\n .then(() => {\n queueMicrotask(onClosed)\n })\n }\n\n destroy (err, callback) {\n if (typeof err === 'function') {\n callback = err\n err = null\n }\n\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n this.destroy(err, (err, data) => {\n return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data)\n })\n })\n }\n\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n if (this[kDestroyed]) {\n if (this[kOnDestroyed]) {\n this[kOnDestroyed].push(callback)\n } else {\n queueMicrotask(() => callback(null, null))\n }\n return\n }\n\n if (!err) {\n err = new ClientDestroyedError()\n }\n\n this[kDestroyed] = true\n this[kOnDestroyed] = this[kOnDestroyed] || []\n this[kOnDestroyed].push(callback)\n\n const onDestroyed = () => {\n const callbacks = this[kOnDestroyed]\n this[kOnDestroyed] = null\n for (let i = 0; i < callbacks.length; i++) {\n callbacks[i](null, null)\n }\n }\n\n // Should not error.\n this[kDestroy](err).then(() => {\n queueMicrotask(onDestroyed)\n })\n }\n\n [kInterceptedDispatch] (opts, handler) {\n if (!this[kInterceptors] || this[kInterceptors].length === 0) {\n this[kInterceptedDispatch] = this[kDispatch]\n return this[kDispatch](opts, handler)\n }\n\n let dispatch = this[kDispatch].bind(this)\n for (let i = this[kInterceptors].length - 1; i >= 0; i--) {\n dispatch = this[kInterceptors][i](dispatch)\n }\n this[kInterceptedDispatch] = dispatch\n return dispatch(opts, handler)\n }\n\n dispatch (opts, handler) {\n if (!handler || typeof handler !== 'object') {\n throw new InvalidArgumentError('handler must be an object')\n }\n\n try {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('opts must be an object.')\n }\n\n if (this[kDestroyed] || this[kOnDestroyed]) {\n throw new ClientDestroyedError()\n }\n\n if (this[kClosed]) {\n throw new ClientClosedError()\n }\n\n return this[kInterceptedDispatch](opts, handler)\n } catch (err) {\n if (typeof handler.onError !== 'function') {\n throw new InvalidArgumentError('invalid onError method')\n }\n\n handler.onError(err)\n\n return false\n }\n }\n}\n\nmodule.exports = DispatcherBase\n","'use strict'\n\n/**\n * This module offers an optimized timer implementation designed for scenarios\n * where high precision is not critical.\n *\n * The timer achieves faster performance by using a low-resolution approach,\n * with an accuracy target of within 500ms. This makes it particularly useful\n * for timers with delays of 1 second or more, where exact timing is less\n * crucial.\n *\n * It's important to note that Node.js timers are inherently imprecise, as\n * delays can occur due to the event loop being blocked by other operations.\n * Consequently, timers may trigger later than their scheduled time.\n */\n\n/**\n * The fastNow variable contains the internal fast timer clock value.\n *\n * @type {number}\n */\nlet fastNow = 0\n\n/**\n * RESOLUTION_MS represents the target resolution time in milliseconds.\n *\n * @type {number}\n * @default 1000\n */\nconst RESOLUTION_MS = 1e3\n\n/**\n * TICK_MS defines the desired interval in milliseconds between each tick.\n * The target value is set to half the resolution time, minus 1 ms, to account\n * for potential event loop overhead.\n *\n * @type {number}\n * @default 499\n */\nconst TICK_MS = (RESOLUTION_MS >> 1) - 1\n\n/**\n * fastNowTimeout is a Node.js timer used to manage and process\n * the FastTimers stored in the `fastTimers` array.\n *\n * @type {NodeJS.Timeout}\n */\nlet fastNowTimeout\n\n/**\n * The kFastTimer symbol is used to identify FastTimer instances.\n *\n * @type {Symbol}\n */\nconst kFastTimer = Symbol('kFastTimer')\n\n/**\n * The fastTimers array contains all active FastTimers.\n *\n * @type {FastTimer[]}\n */\nconst fastTimers = []\n\n/**\n * These constants represent the various states of a FastTimer.\n */\n\n/**\n * The `NOT_IN_LIST` constant indicates that the FastTimer is not included\n * in the `fastTimers` array. Timers with this status will not be processed\n * during the next tick by the `onTick` function.\n *\n * A FastTimer can be re-added to the `fastTimers` array by invoking the\n * `refresh` method on the FastTimer instance.\n *\n * @type {-2}\n */\nconst NOT_IN_LIST = -2\n\n/**\n * The `TO_BE_CLEARED` constant indicates that the FastTimer is scheduled\n * for removal from the `fastTimers` array. A FastTimer in this state will\n * be removed in the next tick by the `onTick` function and will no longer\n * be processed.\n *\n * This status is also set when the `clear` method is called on the FastTimer instance.\n *\n * @type {-1}\n */\nconst TO_BE_CLEARED = -1\n\n/**\n * The `PENDING` constant signifies that the FastTimer is awaiting processing\n * in the next tick by the `onTick` function. Timers with this status will have\n * their `_idleStart` value set and their status updated to `ACTIVE` in the next tick.\n *\n * @type {0}\n */\nconst PENDING = 0\n\n/**\n * The `ACTIVE` constant indicates that the FastTimer is active and waiting\n * for its timer to expire. During the next tick, the `onTick` function will\n * check if the timer has expired, and if so, it will execute the associated callback.\n *\n * @type {1}\n */\nconst ACTIVE = 1\n\n/**\n * The onTick function processes the fastTimers array.\n *\n * @returns {void}\n */\nfunction onTick () {\n /**\n * Increment the fastNow value by the TICK_MS value, despite the actual time\n * that has passed since the last tick. This approach ensures independence\n * from the system clock and delays caused by a blocked event loop.\n *\n * @type {number}\n */\n fastNow += TICK_MS\n\n /**\n * The `idx` variable is used to iterate over the `fastTimers` array.\n * Expired timers are removed by replacing them with the last element in the array.\n * Consequently, `idx` is only incremented when the current element is not removed.\n *\n * @type {number}\n */\n let idx = 0\n\n /**\n * The len variable will contain the length of the fastTimers array\n * and will be decremented when a FastTimer should be removed from the\n * fastTimers array.\n *\n * @type {number}\n */\n let len = fastTimers.length\n\n while (idx < len) {\n /**\n * @type {FastTimer}\n */\n const timer = fastTimers[idx]\n\n // If the timer is in the ACTIVE state and the timer has expired, it will\n // be processed in the next tick.\n if (timer._state === PENDING) {\n // Set the _idleStart value to the fastNow value minus the TICK_MS value\n // to account for the time the timer was in the PENDING state.\n timer._idleStart = fastNow - TICK_MS\n timer._state = ACTIVE\n } else if (\n timer._state === ACTIVE &&\n fastNow >= timer._idleStart + timer._idleTimeout\n ) {\n timer._state = TO_BE_CLEARED\n timer._idleStart = -1\n timer._onTimeout(timer._timerArg)\n }\n\n if (timer._state === TO_BE_CLEARED) {\n timer._state = NOT_IN_LIST\n\n // Move the last element to the current index and decrement len if it is\n // not the only element in the array.\n if (--len !== 0) {\n fastTimers[idx] = fastTimers[len]\n }\n } else {\n ++idx\n }\n }\n\n // Set the length of the fastTimers array to the new length and thus\n // removing the excess FastTimers elements from the array.\n fastTimers.length = len\n\n // If there are still active FastTimers in the array, refresh the Timer.\n // If there are no active FastTimers, the timer will be refreshed again\n // when a new FastTimer is instantiated.\n if (fastTimers.length !== 0) {\n refreshTimeout()\n }\n}\n\nfunction refreshTimeout () {\n // If the fastNowTimeout is already set, refresh it.\n if (fastNowTimeout) {\n fastNowTimeout.refresh()\n // fastNowTimeout is not instantiated yet, create a new Timer.\n } else {\n clearTimeout(fastNowTimeout)\n fastNowTimeout = setTimeout(onTick, TICK_MS)\n\n // If the Timer has an unref method, call it to allow the process to exit if\n // there are no other active handles.\n if (fastNowTimeout.unref) {\n fastNowTimeout.unref()\n }\n }\n}\n\n/**\n * The `FastTimer` class is a data structure designed to store and manage\n * timer information.\n */\nclass FastTimer {\n [kFastTimer] = true\n\n /**\n * The state of the timer, which can be one of the following:\n * - NOT_IN_LIST (-2)\n * - TO_BE_CLEARED (-1)\n * - PENDING (0)\n * - ACTIVE (1)\n *\n * @type {-2|-1|0|1}\n * @private\n */\n _state = NOT_IN_LIST\n\n /**\n * The number of milliseconds to wait before calling the callback.\n *\n * @type {number}\n * @private\n */\n _idleTimeout = -1\n\n /**\n * The time in milliseconds when the timer was started. This value is used to\n * calculate when the timer should expire.\n *\n * @type {number}\n * @default -1\n * @private\n */\n _idleStart = -1\n\n /**\n * The function to be executed when the timer expires.\n * @type {Function}\n * @private\n */\n _onTimeout\n\n /**\n * The argument to be passed to the callback when the timer expires.\n *\n * @type {*}\n * @private\n */\n _timerArg\n\n /**\n * @constructor\n * @param {Function} callback A function to be executed after the timer\n * expires.\n * @param {number} delay The time, in milliseconds that the timer should wait\n * before the specified function or code is executed.\n * @param {*} arg\n */\n constructor (callback, delay, arg) {\n this._onTimeout = callback\n this._idleTimeout = delay\n this._timerArg = arg\n\n this.refresh()\n }\n\n /**\n * Sets the timer's start time to the current time, and reschedules the timer\n * to call its callback at the previously specified duration adjusted to the\n * current time.\n * Using this on a timer that has already called its callback will reactivate\n * the timer.\n *\n * @returns {void}\n */\n refresh () {\n // In the special case that the timer is not in the list of active timers,\n // add it back to the array to be processed in the next tick by the onTick\n // function.\n if (this._state === NOT_IN_LIST) {\n fastTimers.push(this)\n }\n\n // If the timer is the only active timer, refresh the fastNowTimeout for\n // better resolution.\n if (!fastNowTimeout || fastTimers.length === 1) {\n refreshTimeout()\n }\n\n // Setting the state to PENDING will cause the timer to be reset in the\n // next tick by the onTick function.\n this._state = PENDING\n }\n\n /**\n * The `clear` method cancels the timer, preventing it from executing.\n *\n * @returns {void}\n * @private\n */\n clear () {\n // Set the state to TO_BE_CLEARED to mark the timer for removal in the next\n // tick by the onTick function.\n this._state = TO_BE_CLEARED\n\n // Reset the _idleStart value to -1 to indicate that the timer is no longer\n // active.\n this._idleStart = -1\n }\n}\n\n/**\n * This module exports a setTimeout and clearTimeout function that can be\n * used as a drop-in replacement for the native functions.\n */\nmodule.exports = {\n /**\n * The setTimeout() method sets a timer which executes a function once the\n * timer expires.\n * @param {Function} callback A function to be executed after the timer\n * expires.\n * @param {number} delay The time, in milliseconds that the timer should\n * wait before the specified function or code is executed.\n * @param {*} [arg] An optional argument to be passed to the callback function\n * when the timer expires.\n * @returns {NodeJS.Timeout|FastTimer}\n */\n setTimeout (callback, delay, arg) {\n // If the delay is less than or equal to the RESOLUTION_MS value return a\n // native Node.js Timer instance.\n return delay <= RESOLUTION_MS\n ? setTimeout(callback, delay, arg)\n : new FastTimer(callback, delay, arg)\n },\n /**\n * The clearTimeout method cancels an instantiated Timer previously created\n * by calling setTimeout.\n *\n * @param {NodeJS.Timeout|FastTimer} timeout\n */\n clearTimeout (timeout) {\n // If the timeout is a FastTimer, call its own clear method.\n if (timeout[kFastTimer]) {\n /**\n * @type {FastTimer}\n */\n timeout.clear()\n // Otherwise it is an instance of a native NodeJS.Timeout, so call the\n // Node.js native clearTimeout function.\n } else {\n clearTimeout(timeout)\n }\n },\n /**\n * The setFastTimeout() method sets a fastTimer which executes a function once\n * the timer expires.\n * @param {Function} callback A function to be executed after the timer\n * expires.\n * @param {number} delay The time, in milliseconds that the timer should\n * wait before the specified function or code is executed.\n * @param {*} [arg] An optional argument to be passed to the callback function\n * when the timer expires.\n * @returns {FastTimer}\n */\n setFastTimeout (callback, delay, arg) {\n return new FastTimer(callback, delay, arg)\n },\n /**\n * The clearTimeout method cancels an instantiated FastTimer previously\n * created by calling setFastTimeout.\n *\n * @param {FastTimer} timeout\n */\n clearFastTimeout (timeout) {\n timeout.clear()\n },\n /**\n * The now method returns the value of the internal fast timer clock.\n *\n * @returns {number}\n */\n now () {\n return fastNow\n },\n /**\n * Trigger the onTick function to process the fastTimers array.\n * Exported for testing purposes only.\n * Marking as deprecated to discourage any use outside of testing.\n * @deprecated\n * @param {number} [delay=0] The delay in milliseconds to add to the now value.\n */\n tick (delay = 0) {\n fastNow += delay - RESOLUTION_MS + 1\n onTick()\n onTick()\n },\n /**\n * Reset FastTimers.\n * Exported for testing purposes only.\n * Marking as deprecated to discourage any use outside of testing.\n * @deprecated\n */\n reset () {\n fastNow = 0\n fastTimers.length = 0\n clearTimeout(fastNowTimeout)\n fastNowTimeout = null\n },\n /**\n * Exporting for testing purposes only.\n * Marking as deprecated to discourage any use outside of testing.\n * @deprecated\n */\n kFastTimer\n}\n","'use strict'\n\nconst net = require('node:net')\nconst assert = require('node:assert')\nconst util = require('./util')\nconst { InvalidArgumentError, ConnectTimeoutError } = require('./errors')\nconst timers = require('../util/timers')\n\nfunction noop () {}\n\nlet tls // include tls conditionally since it is not always available\n\n// TODO: session re-use does not wait for the first\n// connection to resolve the session and might therefore\n// resolve the same servername multiple times even when\n// re-use is enabled.\n\nlet SessionCache\n// FIXME: remove workaround when the Node bug is fixed\n// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308\nif (global.FinalizationRegistry && !(process.env.NODE_V8_COVERAGE || process.env.UNDICI_NO_FG)) {\n SessionCache = class WeakSessionCache {\n constructor (maxCachedSessions) {\n this._maxCachedSessions = maxCachedSessions\n this._sessionCache = new Map()\n this._sessionRegistry = new global.FinalizationRegistry((key) => {\n if (this._sessionCache.size < this._maxCachedSessions) {\n return\n }\n\n const ref = this._sessionCache.get(key)\n if (ref !== undefined && ref.deref() === undefined) {\n this._sessionCache.delete(key)\n }\n })\n }\n\n get (sessionKey) {\n const ref = this._sessionCache.get(sessionKey)\n return ref ? ref.deref() : null\n }\n\n set (sessionKey, session) {\n if (this._maxCachedSessions === 0) {\n return\n }\n\n this._sessionCache.set(sessionKey, new WeakRef(session))\n this._sessionRegistry.register(session, sessionKey)\n }\n }\n} else {\n SessionCache = class SimpleSessionCache {\n constructor (maxCachedSessions) {\n this._maxCachedSessions = maxCachedSessions\n this._sessionCache = new Map()\n }\n\n get (sessionKey) {\n return this._sessionCache.get(sessionKey)\n }\n\n set (sessionKey, session) {\n if (this._maxCachedSessions === 0) {\n return\n }\n\n if (this._sessionCache.size >= this._maxCachedSessions) {\n // remove the oldest session\n const { value: oldestKey } = this._sessionCache.keys().next()\n this._sessionCache.delete(oldestKey)\n }\n\n this._sessionCache.set(sessionKey, session)\n }\n }\n}\n\nfunction buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, session: customSession, ...opts }) {\n if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {\n throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero')\n }\n\n const options = { path: socketPath, ...opts }\n const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions)\n timeout = timeout == null ? 10e3 : timeout\n allowH2 = allowH2 != null ? allowH2 : false\n return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) {\n let socket\n if (protocol === 'https:') {\n if (!tls) {\n tls = require('node:tls')\n }\n servername = servername || options.servername || util.getServerName(host) || null\n\n const sessionKey = servername || hostname\n assert(sessionKey)\n\n const session = customSession || sessionCache.get(sessionKey) || null\n\n port = port || 443\n\n socket = tls.connect({\n highWaterMark: 16384, // TLS in node can't have bigger HWM anyway...\n ...options,\n servername,\n session,\n localAddress,\n // TODO(HTTP/2): Add support for h2c\n ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'],\n socket: httpSocket, // upgrade socket connection\n port,\n host: hostname\n })\n\n socket\n .on('session', function (session) {\n // TODO (fix): Can a session become invalid once established? Don't think so?\n sessionCache.set(sessionKey, session)\n })\n } else {\n assert(!httpSocket, 'httpSocket can only be sent on TLS update')\n\n port = port || 80\n\n socket = net.connect({\n highWaterMark: 64 * 1024, // Same as nodejs fs streams.\n ...options,\n localAddress,\n port,\n host: hostname\n })\n }\n\n // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket\n if (options.keepAlive == null || options.keepAlive) {\n const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay\n socket.setKeepAlive(true, keepAliveInitialDelay)\n }\n\n const clearConnectTimeout = setupConnectTimeout(new WeakRef(socket), { timeout, hostname, port })\n\n socket\n .setNoDelay(true)\n .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () {\n queueMicrotask(clearConnectTimeout)\n\n if (callback) {\n const cb = callback\n callback = null\n cb(null, this)\n }\n })\n .on('error', function (err) {\n queueMicrotask(clearConnectTimeout)\n\n if (callback) {\n const cb = callback\n callback = null\n cb(err)\n }\n })\n\n return socket\n }\n}\n\n/**\n * @param {WeakRef} socketWeakRef\n * @param {object} opts\n * @param {number} opts.timeout\n * @param {string} opts.hostname\n * @param {number} opts.port\n * @returns {() => void}\n */\nconst setupConnectTimeout = process.platform === 'win32'\n ? (socketWeakRef, opts) => {\n if (!opts.timeout) {\n return noop\n }\n\n let s1 = null\n let s2 = null\n const fastTimer = timers.setFastTimeout(() => {\n // setImmediate is added to make sure that we prioritize socket error events over timeouts\n s1 = setImmediate(() => {\n // Windows needs an extra setImmediate probably due to implementation differences in the socket logic\n s2 = setImmediate(() => onConnectTimeout(socketWeakRef.deref(), opts))\n })\n }, opts.timeout)\n return () => {\n timers.clearFastTimeout(fastTimer)\n clearImmediate(s1)\n clearImmediate(s2)\n }\n }\n : (socketWeakRef, opts) => {\n if (!opts.timeout) {\n return noop\n }\n\n let s1 = null\n const fastTimer = timers.setFastTimeout(() => {\n // setImmediate is added to make sure that we prioritize socket error events over timeouts\n s1 = setImmediate(() => {\n onConnectTimeout(socketWeakRef.deref(), opts)\n })\n }, opts.timeout)\n return () => {\n timers.clearFastTimeout(fastTimer)\n clearImmediate(s1)\n }\n }\n\n/**\n * @param {net.Socket} socket\n * @param {object} opts\n * @param {number} opts.timeout\n * @param {string} opts.hostname\n * @param {number} opts.port\n */\nfunction onConnectTimeout (socket, opts) {\n // The socket could be already garbage collected\n if (socket == null) {\n return\n }\n\n let message = 'Connect Timeout Error'\n if (Array.isArray(socket.autoSelectFamilyAttemptedAddresses)) {\n message += ` (attempted addresses: ${socket.autoSelectFamilyAttemptedAddresses.join(', ')},`\n } else {\n message += ` (attempted address: ${opts.hostname}:${opts.port},`\n }\n\n message += ` timeout: ${opts.timeout}ms)`\n\n util.destroy(socket, new ConnectTimeoutError(message))\n}\n\nmodule.exports = buildConnector\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.enumToMap = void 0;\nfunction enumToMap(obj) {\n const res = {};\n Object.keys(obj).forEach((key) => {\n const value = obj[key];\n if (typeof value === 'number') {\n res[key] = value;\n }\n });\n return res;\n}\nexports.enumToMap = enumToMap;\n//# sourceMappingURL=utils.js.map","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0;\nconst utils_1 = require(\"./utils\");\n// C headers\nvar ERROR;\n(function (ERROR) {\n ERROR[ERROR[\"OK\"] = 0] = \"OK\";\n ERROR[ERROR[\"INTERNAL\"] = 1] = \"INTERNAL\";\n ERROR[ERROR[\"STRICT\"] = 2] = \"STRICT\";\n ERROR[ERROR[\"LF_EXPECTED\"] = 3] = \"LF_EXPECTED\";\n ERROR[ERROR[\"UNEXPECTED_CONTENT_LENGTH\"] = 4] = \"UNEXPECTED_CONTENT_LENGTH\";\n ERROR[ERROR[\"CLOSED_CONNECTION\"] = 5] = \"CLOSED_CONNECTION\";\n ERROR[ERROR[\"INVALID_METHOD\"] = 6] = \"INVALID_METHOD\";\n ERROR[ERROR[\"INVALID_URL\"] = 7] = \"INVALID_URL\";\n ERROR[ERROR[\"INVALID_CONSTANT\"] = 8] = \"INVALID_CONSTANT\";\n ERROR[ERROR[\"INVALID_VERSION\"] = 9] = \"INVALID_VERSION\";\n ERROR[ERROR[\"INVALID_HEADER_TOKEN\"] = 10] = \"INVALID_HEADER_TOKEN\";\n ERROR[ERROR[\"INVALID_CONTENT_LENGTH\"] = 11] = \"INVALID_CONTENT_LENGTH\";\n ERROR[ERROR[\"INVALID_CHUNK_SIZE\"] = 12] = \"INVALID_CHUNK_SIZE\";\n ERROR[ERROR[\"INVALID_STATUS\"] = 13] = \"INVALID_STATUS\";\n ERROR[ERROR[\"INVALID_EOF_STATE\"] = 14] = \"INVALID_EOF_STATE\";\n ERROR[ERROR[\"INVALID_TRANSFER_ENCODING\"] = 15] = \"INVALID_TRANSFER_ENCODING\";\n ERROR[ERROR[\"CB_MESSAGE_BEGIN\"] = 16] = \"CB_MESSAGE_BEGIN\";\n ERROR[ERROR[\"CB_HEADERS_COMPLETE\"] = 17] = \"CB_HEADERS_COMPLETE\";\n ERROR[ERROR[\"CB_MESSAGE_COMPLETE\"] = 18] = \"CB_MESSAGE_COMPLETE\";\n ERROR[ERROR[\"CB_CHUNK_HEADER\"] = 19] = \"CB_CHUNK_HEADER\";\n ERROR[ERROR[\"CB_CHUNK_COMPLETE\"] = 20] = \"CB_CHUNK_COMPLETE\";\n ERROR[ERROR[\"PAUSED\"] = 21] = \"PAUSED\";\n ERROR[ERROR[\"PAUSED_UPGRADE\"] = 22] = \"PAUSED_UPGRADE\";\n ERROR[ERROR[\"PAUSED_H2_UPGRADE\"] = 23] = \"PAUSED_H2_UPGRADE\";\n ERROR[ERROR[\"USER\"] = 24] = \"USER\";\n})(ERROR = exports.ERROR || (exports.ERROR = {}));\nvar TYPE;\n(function (TYPE) {\n TYPE[TYPE[\"BOTH\"] = 0] = \"BOTH\";\n TYPE[TYPE[\"REQUEST\"] = 1] = \"REQUEST\";\n TYPE[TYPE[\"RESPONSE\"] = 2] = \"RESPONSE\";\n})(TYPE = exports.TYPE || (exports.TYPE = {}));\nvar FLAGS;\n(function (FLAGS) {\n FLAGS[FLAGS[\"CONNECTION_KEEP_ALIVE\"] = 1] = \"CONNECTION_KEEP_ALIVE\";\n FLAGS[FLAGS[\"CONNECTION_CLOSE\"] = 2] = \"CONNECTION_CLOSE\";\n FLAGS[FLAGS[\"CONNECTION_UPGRADE\"] = 4] = \"CONNECTION_UPGRADE\";\n FLAGS[FLAGS[\"CHUNKED\"] = 8] = \"CHUNKED\";\n FLAGS[FLAGS[\"UPGRADE\"] = 16] = \"UPGRADE\";\n FLAGS[FLAGS[\"CONTENT_LENGTH\"] = 32] = \"CONTENT_LENGTH\";\n FLAGS[FLAGS[\"SKIPBODY\"] = 64] = \"SKIPBODY\";\n FLAGS[FLAGS[\"TRAILING\"] = 128] = \"TRAILING\";\n // 1 << 8 is unused\n FLAGS[FLAGS[\"TRANSFER_ENCODING\"] = 512] = \"TRANSFER_ENCODING\";\n})(FLAGS = exports.FLAGS || (exports.FLAGS = {}));\nvar LENIENT_FLAGS;\n(function (LENIENT_FLAGS) {\n LENIENT_FLAGS[LENIENT_FLAGS[\"HEADERS\"] = 1] = \"HEADERS\";\n LENIENT_FLAGS[LENIENT_FLAGS[\"CHUNKED_LENGTH\"] = 2] = \"CHUNKED_LENGTH\";\n LENIENT_FLAGS[LENIENT_FLAGS[\"KEEP_ALIVE\"] = 4] = \"KEEP_ALIVE\";\n})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {}));\nvar METHODS;\n(function (METHODS) {\n METHODS[METHODS[\"DELETE\"] = 0] = \"DELETE\";\n METHODS[METHODS[\"GET\"] = 1] = \"GET\";\n METHODS[METHODS[\"HEAD\"] = 2] = \"HEAD\";\n METHODS[METHODS[\"POST\"] = 3] = \"POST\";\n METHODS[METHODS[\"PUT\"] = 4] = \"PUT\";\n /* pathological */\n METHODS[METHODS[\"CONNECT\"] = 5] = \"CONNECT\";\n METHODS[METHODS[\"OPTIONS\"] = 6] = \"OPTIONS\";\n METHODS[METHODS[\"TRACE\"] = 7] = \"TRACE\";\n /* WebDAV */\n METHODS[METHODS[\"COPY\"] = 8] = \"COPY\";\n METHODS[METHODS[\"LOCK\"] = 9] = \"LOCK\";\n METHODS[METHODS[\"MKCOL\"] = 10] = \"MKCOL\";\n METHODS[METHODS[\"MOVE\"] = 11] = \"MOVE\";\n METHODS[METHODS[\"PROPFIND\"] = 12] = \"PROPFIND\";\n METHODS[METHODS[\"PROPPATCH\"] = 13] = \"PROPPATCH\";\n METHODS[METHODS[\"SEARCH\"] = 14] = \"SEARCH\";\n METHODS[METHODS[\"UNLOCK\"] = 15] = \"UNLOCK\";\n METHODS[METHODS[\"BIND\"] = 16] = \"BIND\";\n METHODS[METHODS[\"REBIND\"] = 17] = \"REBIND\";\n METHODS[METHODS[\"UNBIND\"] = 18] = \"UNBIND\";\n METHODS[METHODS[\"ACL\"] = 19] = \"ACL\";\n /* subversion */\n METHODS[METHODS[\"REPORT\"] = 20] = \"REPORT\";\n METHODS[METHODS[\"MKACTIVITY\"] = 21] = \"MKACTIVITY\";\n METHODS[METHODS[\"CHECKOUT\"] = 22] = \"CHECKOUT\";\n METHODS[METHODS[\"MERGE\"] = 23] = \"MERGE\";\n /* upnp */\n METHODS[METHODS[\"M-SEARCH\"] = 24] = \"M-SEARCH\";\n METHODS[METHODS[\"NOTIFY\"] = 25] = \"NOTIFY\";\n METHODS[METHODS[\"SUBSCRIBE\"] = 26] = \"SUBSCRIBE\";\n METHODS[METHODS[\"UNSUBSCRIBE\"] = 27] = \"UNSUBSCRIBE\";\n /* RFC-5789 */\n METHODS[METHODS[\"PATCH\"] = 28] = \"PATCH\";\n METHODS[METHODS[\"PURGE\"] = 29] = \"PURGE\";\n /* CalDAV */\n METHODS[METHODS[\"MKCALENDAR\"] = 30] = \"MKCALENDAR\";\n /* RFC-2068, section 19.6.1.2 */\n METHODS[METHODS[\"LINK\"] = 31] = \"LINK\";\n METHODS[METHODS[\"UNLINK\"] = 32] = \"UNLINK\";\n /* icecast */\n METHODS[METHODS[\"SOURCE\"] = 33] = \"SOURCE\";\n /* RFC-7540, section 11.6 */\n METHODS[METHODS[\"PRI\"] = 34] = \"PRI\";\n /* RFC-2326 RTSP */\n METHODS[METHODS[\"DESCRIBE\"] = 35] = \"DESCRIBE\";\n METHODS[METHODS[\"ANNOUNCE\"] = 36] = \"ANNOUNCE\";\n METHODS[METHODS[\"SETUP\"] = 37] = \"SETUP\";\n METHODS[METHODS[\"PLAY\"] = 38] = \"PLAY\";\n METHODS[METHODS[\"PAUSE\"] = 39] = \"PAUSE\";\n METHODS[METHODS[\"TEARDOWN\"] = 40] = \"TEARDOWN\";\n METHODS[METHODS[\"GET_PARAMETER\"] = 41] = \"GET_PARAMETER\";\n METHODS[METHODS[\"SET_PARAMETER\"] = 42] = \"SET_PARAMETER\";\n METHODS[METHODS[\"REDIRECT\"] = 43] = \"REDIRECT\";\n METHODS[METHODS[\"RECORD\"] = 44] = \"RECORD\";\n /* RAOP */\n METHODS[METHODS[\"FLUSH\"] = 45] = \"FLUSH\";\n})(METHODS = exports.METHODS || (exports.METHODS = {}));\nexports.METHODS_HTTP = [\n METHODS.DELETE,\n METHODS.GET,\n METHODS.HEAD,\n METHODS.POST,\n METHODS.PUT,\n METHODS.CONNECT,\n METHODS.OPTIONS,\n METHODS.TRACE,\n METHODS.COPY,\n METHODS.LOCK,\n METHODS.MKCOL,\n METHODS.MOVE,\n METHODS.PROPFIND,\n METHODS.PROPPATCH,\n METHODS.SEARCH,\n METHODS.UNLOCK,\n METHODS.BIND,\n METHODS.REBIND,\n METHODS.UNBIND,\n METHODS.ACL,\n METHODS.REPORT,\n METHODS.MKACTIVITY,\n METHODS.CHECKOUT,\n METHODS.MERGE,\n METHODS['M-SEARCH'],\n METHODS.NOTIFY,\n METHODS.SUBSCRIBE,\n METHODS.UNSUBSCRIBE,\n METHODS.PATCH,\n METHODS.PURGE,\n METHODS.MKCALENDAR,\n METHODS.LINK,\n METHODS.UNLINK,\n METHODS.PRI,\n // TODO(indutny): should we allow it with HTTP?\n METHODS.SOURCE,\n];\nexports.METHODS_ICE = [\n METHODS.SOURCE,\n];\nexports.METHODS_RTSP = [\n METHODS.OPTIONS,\n METHODS.DESCRIBE,\n METHODS.ANNOUNCE,\n METHODS.SETUP,\n METHODS.PLAY,\n METHODS.PAUSE,\n METHODS.TEARDOWN,\n METHODS.GET_PARAMETER,\n METHODS.SET_PARAMETER,\n METHODS.REDIRECT,\n METHODS.RECORD,\n METHODS.FLUSH,\n // For AirPlay\n METHODS.GET,\n METHODS.POST,\n];\nexports.METHOD_MAP = utils_1.enumToMap(METHODS);\nexports.H_METHOD_MAP = {};\nObject.keys(exports.METHOD_MAP).forEach((key) => {\n if (/^H/.test(key)) {\n exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key];\n }\n});\nvar FINISH;\n(function (FINISH) {\n FINISH[FINISH[\"SAFE\"] = 0] = \"SAFE\";\n FINISH[FINISH[\"SAFE_WITH_CB\"] = 1] = \"SAFE_WITH_CB\";\n FINISH[FINISH[\"UNSAFE\"] = 2] = \"UNSAFE\";\n})(FINISH = exports.FINISH || (exports.FINISH = {}));\nexports.ALPHA = [];\nfor (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) {\n // Upper case\n exports.ALPHA.push(String.fromCharCode(i));\n // Lower case\n exports.ALPHA.push(String.fromCharCode(i + 0x20));\n}\nexports.NUM_MAP = {\n 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,\n 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,\n};\nexports.HEX_MAP = {\n 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,\n 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,\n A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF,\n a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf,\n};\nexports.NUM = [\n '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n];\nexports.ALPHANUM = exports.ALPHA.concat(exports.NUM);\nexports.MARK = ['-', '_', '.', '!', '~', '*', '\\'', '(', ')'];\nexports.USERINFO_CHARS = exports.ALPHANUM\n .concat(exports.MARK)\n .concat(['%', ';', ':', '&', '=', '+', '$', ',']);\n// TODO(indutny): use RFC\nexports.STRICT_URL_CHAR = [\n '!', '\"', '$', '%', '&', '\\'',\n '(', ')', '*', '+', ',', '-', '.', '/',\n ':', ';', '<', '=', '>',\n '@', '[', '\\\\', ']', '^', '_',\n '`',\n '{', '|', '}', '~',\n].concat(exports.ALPHANUM);\nexports.URL_CHAR = exports.STRICT_URL_CHAR\n .concat(['\\t', '\\f']);\n// All characters with 0x80 bit set to 1\nfor (let i = 0x80; i <= 0xff; i++) {\n exports.URL_CHAR.push(i);\n}\nexports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']);\n/* Tokens as defined by rfc 2616. Also lowercases them.\n * token = 1*\n * separators = \"(\" | \")\" | \"<\" | \">\" | \"@\"\n * | \",\" | \";\" | \":\" | \"\\\" | <\">\n * | \"/\" | \"[\" | \"]\" | \"?\" | \"=\"\n * | \"{\" | \"}\" | SP | HT\n */\nexports.STRICT_TOKEN = [\n '!', '#', '$', '%', '&', '\\'',\n '*', '+', '-', '.',\n '^', '_', '`',\n '|', '~',\n].concat(exports.ALPHANUM);\nexports.TOKEN = exports.STRICT_TOKEN.concat([' ']);\n/*\n * Verify that a char is a valid visible (printable) US-ASCII\n * character or %x80-FF\n */\nexports.HEADER_CHARS = ['\\t'];\nfor (let i = 32; i <= 255; i++) {\n if (i !== 127) {\n exports.HEADER_CHARS.push(i);\n }\n}\n// ',' = \\x44\nexports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44);\nexports.MAJOR = exports.NUM_MAP;\nexports.MINOR = exports.MAJOR;\nvar HEADER_STATE;\n(function (HEADER_STATE) {\n HEADER_STATE[HEADER_STATE[\"GENERAL\"] = 0] = \"GENERAL\";\n HEADER_STATE[HEADER_STATE[\"CONNECTION\"] = 1] = \"CONNECTION\";\n HEADER_STATE[HEADER_STATE[\"CONTENT_LENGTH\"] = 2] = \"CONTENT_LENGTH\";\n HEADER_STATE[HEADER_STATE[\"TRANSFER_ENCODING\"] = 3] = \"TRANSFER_ENCODING\";\n HEADER_STATE[HEADER_STATE[\"UPGRADE\"] = 4] = \"UPGRADE\";\n HEADER_STATE[HEADER_STATE[\"CONNECTION_KEEP_ALIVE\"] = 5] = \"CONNECTION_KEEP_ALIVE\";\n HEADER_STATE[HEADER_STATE[\"CONNECTION_CLOSE\"] = 6] = \"CONNECTION_CLOSE\";\n HEADER_STATE[HEADER_STATE[\"CONNECTION_UPGRADE\"] = 7] = \"CONNECTION_UPGRADE\";\n HEADER_STATE[HEADER_STATE[\"TRANSFER_ENCODING_CHUNKED\"] = 8] = \"TRANSFER_ENCODING_CHUNKED\";\n})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {}));\nexports.SPECIAL_HEADERS = {\n 'connection': HEADER_STATE.CONNECTION,\n 'content-length': HEADER_STATE.CONTENT_LENGTH,\n 'proxy-connection': HEADER_STATE.CONNECTION,\n 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING,\n 'upgrade': HEADER_STATE.UPGRADE,\n};\n//# sourceMappingURL=constants.js.map","'use strict'\n\nconst { Buffer } = require('node:buffer')\n\nmodule.exports = Buffer.from('AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAX8AYAJ/fwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAy0sBQYAAAIAAAAAAAACAQIAAgICAAADAAAAAAMDAwMBAQEBAQEBAQEAAAIAAAAEBQFwARISBQMBAAIGCAF/AUGA1AQLB9EFIgZtZW1vcnkCAAtfaW5pdGlhbGl6ZQAIGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAtsbGh0dHBfaW5pdAAJGGxsaHR0cF9zaG91bGRfa2VlcF9hbGl2ZQAvDGxsaHR0cF9hbGxvYwALBm1hbGxvYwAxC2xsaHR0cF9mcmVlAAwEZnJlZQAMD2xsaHR0cF9nZXRfdHlwZQANFWxsaHR0cF9nZXRfaHR0cF9tYWpvcgAOFWxsaHR0cF9nZXRfaHR0cF9taW5vcgAPEWxsaHR0cF9nZXRfbWV0aG9kABAWbGxodHRwX2dldF9zdGF0dXNfY29kZQAREmxsaHR0cF9nZXRfdXBncmFkZQASDGxsaHR0cF9yZXNldAATDmxsaHR0cF9leGVjdXRlABQUbGxodHRwX3NldHRpbmdzX2luaXQAFQ1sbGh0dHBfZmluaXNoABYMbGxodHRwX3BhdXNlABcNbGxodHRwX3Jlc3VtZQAYG2xsaHR0cF9yZXN1bWVfYWZ0ZXJfdXBncmFkZQAZEGxsaHR0cF9nZXRfZXJybm8AGhdsbGh0dHBfZ2V0X2Vycm9yX3JlYXNvbgAbF2xsaHR0cF9zZXRfZXJyb3JfcmVhc29uABwUbGxodHRwX2dldF9lcnJvcl9wb3MAHRFsbGh0dHBfZXJybm9fbmFtZQAeEmxsaHR0cF9tZXRob2RfbmFtZQAfEmxsaHR0cF9zdGF0dXNfbmFtZQAgGmxsaHR0cF9zZXRfbGVuaWVudF9oZWFkZXJzACEhbGxodHRwX3NldF9sZW5pZW50X2NodW5rZWRfbGVuZ3RoACIdbGxodHRwX3NldF9sZW5pZW50X2tlZXBfYWxpdmUAIyRsbGh0dHBfc2V0X2xlbmllbnRfdHJhbnNmZXJfZW5jb2RpbmcAJBhsbGh0dHBfbWVzc2FnZV9uZWVkc19lb2YALgkXAQBBAQsRAQIDBAUKBgcrLSwqKSglJyYK07MCLBYAQYjQACgCAARAAAtBiNAAQQE2AgALFAAgABAwIAAgAjYCOCAAIAE6ACgLFAAgACAALwEyIAAtAC4gABAvEAALHgEBf0HAABAyIgEQMCABQYAINgI4IAEgADoAKCABC48MAQd/AkAgAEUNACAAQQhrIgEgAEEEaygCACIAQXhxIgRqIQUCQCAAQQFxDQAgAEEDcUUNASABIAEoAgAiAGsiAUGc0AAoAgBJDQEgACAEaiEEAkACQEGg0AAoAgAgAUcEQCAAQf8BTQRAIABBA3YhAyABKAIIIgAgASgCDCICRgRAQYzQAEGM0AAoAgBBfiADd3E2AgAMBQsgAiAANgIIIAAgAjYCDAwECyABKAIYIQYgASABKAIMIgBHBEAgACABKAIIIgI2AgggAiAANgIMDAMLIAFBFGoiAygCACICRQRAIAEoAhAiAkUNAiABQRBqIQMLA0AgAyEHIAIiAEEUaiIDKAIAIgINACAAQRBqIQMgACgCECICDQALIAdBADYCAAwCCyAFKAIEIgBBA3FBA0cNAiAFIABBfnE2AgRBlNAAIAQ2AgAgBSAENgIAIAEgBEEBcjYCBAwDC0EAIQALIAZFDQACQCABKAIcIgJBAnRBvNIAaiIDKAIAIAFGBEAgAyAANgIAIAANAUGQ0ABBkNAAKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgAUYbaiAANgIAIABFDQELIAAgBjYCGCABKAIQIgIEQCAAIAI2AhAgAiAANgIYCyABQRRqKAIAIgJFDQAgAEEUaiACNgIAIAIgADYCGAsgASAFTw0AIAUoAgQiAEEBcUUNAAJAAkACQAJAIABBAnFFBEBBpNAAKAIAIAVGBEBBpNAAIAE2AgBBmNAAQZjQACgCACAEaiIANgIAIAEgAEEBcjYCBCABQaDQACgCAEcNBkGU0ABBADYCAEGg0ABBADYCAAwGC0Gg0AAoAgAgBUYEQEGg0AAgATYCAEGU0ABBlNAAKAIAIARqIgA2AgAgASAAQQFyNgIEIAAgAWogADYCAAwGCyAAQXhxIARqIQQgAEH/AU0EQCAAQQN2IQMgBSgCCCIAIAUoAgwiAkYEQEGM0ABBjNAAKAIAQX4gA3dxNgIADAULIAIgADYCCCAAIAI2AgwMBAsgBSgCGCEGIAUgBSgCDCIARwRAQZzQACgCABogACAFKAIIIgI2AgggAiAANgIMDAMLIAVBFGoiAygCACICRQRAIAUoAhAiAkUNAiAFQRBqIQMLA0AgAyEHIAIiAEEUaiIDKAIAIgINACAAQRBqIQMgACgCECICDQALIAdBADYCAAwCCyAFIABBfnE2AgQgASAEaiAENgIAIAEgBEEBcjYCBAwDC0EAIQALIAZFDQACQCAFKAIcIgJBAnRBvNIAaiIDKAIAIAVGBEAgAyAANgIAIAANAUGQ0ABBkNAAKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiAANgIAIABFDQELIAAgBjYCGCAFKAIQIgIEQCAAIAI2AhAgAiAANgIYCyAFQRRqKAIAIgJFDQAgAEEUaiACNgIAIAIgADYCGAsgASAEaiAENgIAIAEgBEEBcjYCBCABQaDQACgCAEcNAEGU0AAgBDYCAAwBCyAEQf8BTQRAIARBeHFBtNAAaiEAAn9BjNAAKAIAIgJBASAEQQN2dCIDcUUEQEGM0AAgAiADcjYCACAADAELIAAoAggLIgIgATYCDCAAIAE2AgggASAANgIMIAEgAjYCCAwBC0EfIQIgBEH///8HTQRAIARBJiAEQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAgsgASACNgIcIAFCADcCECACQQJ0QbzSAGohAAJAQZDQACgCACIDQQEgAnQiB3FFBEAgACABNgIAQZDQACADIAdyNgIAIAEgADYCGCABIAE2AgggASABNgIMDAELIARBGSACQQF2a0EAIAJBH0cbdCECIAAoAgAhAAJAA0AgACIDKAIEQXhxIARGDQEgAkEddiEAIAJBAXQhAiADIABBBHFqQRBqIgcoAgAiAA0ACyAHIAE2AgAgASADNgIYIAEgATYCDCABIAE2AggMAQsgAygCCCIAIAE2AgwgAyABNgIIIAFBADYCGCABIAM2AgwgASAANgIIC0Gs0ABBrNAAKAIAQQFrIgBBfyAAGzYCAAsLBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LQAEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABAwIAAgBDYCOCAAIAM6ACggACACOgAtIAAgATYCGAu74gECB38DfiABIAJqIQQCQCAAIgIoAgwiAA0AIAIoAgQEQCACIAE2AgQLIwBBEGsiCCQAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAIoAhwiA0EBaw7dAdoBAdkBAgMEBQYHCAkKCwwNDtgBDxDXARES1gETFBUWFxgZGhvgAd8BHB0e1QEfICEiIyQl1AEmJygpKiss0wHSAS0u0QHQAS8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRtsBR0hJSs8BzgFLzQFMzAFNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AAYEBggGDAYQBhQGGAYcBiAGJAYoBiwGMAY0BjgGPAZABkQGSAZMBlAGVAZYBlwGYAZkBmgGbAZwBnQGeAZ8BoAGhAaIBowGkAaUBpgGnAagBqQGqAasBrAGtAa4BrwGwAbEBsgGzAbQBtQG2AbcBywHKAbgByQG5AcgBugG7AbwBvQG+Ab8BwAHBAcIBwwHEAcUBxgEA3AELQQAMxgELQQ4MxQELQQ0MxAELQQ8MwwELQRAMwgELQRMMwQELQRQMwAELQRUMvwELQRYMvgELQRgMvQELQRkMvAELQRoMuwELQRsMugELQRwMuQELQR0MuAELQQgMtwELQR4MtgELQSAMtQELQR8MtAELQQcMswELQSEMsgELQSIMsQELQSMMsAELQSQMrwELQRIMrgELQREMrQELQSUMrAELQSYMqwELQScMqgELQSgMqQELQcMBDKgBC0EqDKcBC0ErDKYBC0EsDKUBC0EtDKQBC0EuDKMBC0EvDKIBC0HEAQyhAQtBMAygAQtBNAyfAQtBDAyeAQtBMQydAQtBMgycAQtBMwybAQtBOQyaAQtBNQyZAQtBxQEMmAELQQsMlwELQToMlgELQTYMlQELQQoMlAELQTcMkwELQTgMkgELQTwMkQELQTsMkAELQT0MjwELQQkMjgELQSkMjQELQT4MjAELQT8MiwELQcAADIoBC0HBAAyJAQtBwgAMiAELQcMADIcBC0HEAAyGAQtBxQAMhQELQcYADIQBC0EXDIMBC0HHAAyCAQtByAAMgQELQckADIABC0HKAAx/C0HLAAx+C0HNAAx9C0HMAAx8C0HOAAx7C0HPAAx6C0HQAAx5C0HRAAx4C0HSAAx3C0HTAAx2C0HUAAx1C0HWAAx0C0HVAAxzC0EGDHILQdcADHELQQUMcAtB2AAMbwtBBAxuC0HZAAxtC0HaAAxsC0HbAAxrC0HcAAxqC0EDDGkLQd0ADGgLQd4ADGcLQd8ADGYLQeEADGULQeAADGQLQeIADGMLQeMADGILQQIMYQtB5AAMYAtB5QAMXwtB5gAMXgtB5wAMXQtB6AAMXAtB6QAMWwtB6gAMWgtB6wAMWQtB7AAMWAtB7QAMVwtB7gAMVgtB7wAMVQtB8AAMVAtB8QAMUwtB8gAMUgtB8wAMUQtB9AAMUAtB9QAMTwtB9gAMTgtB9wAMTQtB+AAMTAtB+QAMSwtB+gAMSgtB+wAMSQtB/AAMSAtB/QAMRwtB/gAMRgtB/wAMRQtBgAEMRAtBgQEMQwtBggEMQgtBgwEMQQtBhAEMQAtBhQEMPwtBhgEMPgtBhwEMPQtBiAEMPAtBiQEMOwtBigEMOgtBiwEMOQtBjAEMOAtBjQEMNwtBjgEMNgtBjwEMNQtBkAEMNAtBkQEMMwtBkgEMMgtBkwEMMQtBlAEMMAtBlQEMLwtBlgEMLgtBlwEMLQtBmAEMLAtBmQEMKwtBmgEMKgtBmwEMKQtBnAEMKAtBnQEMJwtBngEMJgtBnwEMJQtBoAEMJAtBoQEMIwtBogEMIgtBowEMIQtBpAEMIAtBpQEMHwtBpgEMHgtBpwEMHQtBqAEMHAtBqQEMGwtBqgEMGgtBqwEMGQtBrAEMGAtBrQEMFwtBrgEMFgtBAQwVC0GvAQwUC0GwAQwTC0GxAQwSC0GzAQwRC0GyAQwQC0G0AQwPC0G1AQwOC0G2AQwNC0G3AQwMC0G4AQwLC0G5AQwKC0G6AQwJC0G7AQwIC0HGAQwHC0G8AQwGC0G9AQwFC0G+AQwEC0G/AQwDC0HAAQwCC0HCAQwBC0HBAQshAwNAAkACQAJAAkACQAJAAkACQAJAIAICfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAgJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCADDsYBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHyAhIyUmKCorLC8wMTIzNDU2Nzk6Ozw9lANAQkRFRklLTk9QUVJTVFVWWFpbXF1eX2BhYmNkZWZnaGpsb3Bxc3V2eHl6e3x/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEBkgGTAZQBlQGWAZcBmAGZAZoBmwGcAZ0BngGfAaABoQGiAaMBpAGlAaYBpwGoAakBqgGrAawBrQGuAa8BsAGxAbIBswG0AbUBtgG3AbgBuQG6AbsBvAG9Ab4BvwHAAcEBwgHDAcQBxQHGAccByAHJAcsBzAHNAc4BzwGKA4kDiAOHA4QDgwOAA/sC+gL5AvgC9wL0AvMC8gLLAsECsALZAQsgASAERw3wAkHdASEDDLMDCyABIARHDcgBQcMBIQMMsgMLIAEgBEcNe0H3ACEDDLEDCyABIARHDXBB7wAhAwywAwsgASAERw1pQeoAIQMMrwMLIAEgBEcNZUHoACEDDK4DCyABIARHDWJB5gAhAwytAwsgASAERw0aQRghAwysAwsgASAERw0VQRIhAwyrAwsgASAERw1CQcUAIQMMqgMLIAEgBEcNNEE/IQMMqQMLIAEgBEcNMkE8IQMMqAMLIAEgBEcNK0ExIQMMpwMLIAItAC5BAUYNnwMMwQILQQAhAAJAAkACQCACLQAqRQ0AIAItACtFDQAgAi8BMCIDQQJxRQ0BDAILIAIvATAiA0EBcUUNAQtBASEAIAItAChBAUYNACACLwEyIgVB5ABrQeQASQ0AIAVBzAFGDQAgBUGwAkYNACADQcAAcQ0AQQAhACADQYgEcUGABEYNACADQShxQQBHIQALIAJBADsBMCACQQA6AC8gAEUN3wIgAkIANwMgDOACC0EAIQACQCACKAI4IgNFDQAgAygCLCIDRQ0AIAIgAxEAACEACyAARQ3MASAAQRVHDd0CIAJBBDYCHCACIAE2AhQgAkGwGDYCECACQRU2AgxBACEDDKQDCyABIARGBEBBBiEDDKQDCyABQQFqIQFBACEAAkAgAigCOCIDRQ0AIAMoAlQiA0UNACACIAMRAAAhAAsgAA3ZAgwcCyACQgA3AyBBEiEDDIkDCyABIARHDRZBHSEDDKEDCyABIARHBEAgAUEBaiEBQRAhAwyIAwtBByEDDKADCyACIAIpAyAiCiAEIAFrrSILfSIMQgAgCiAMWhs3AyAgCiALWA3UAkEIIQMMnwMLIAEgBEcEQCACQQk2AgggAiABNgIEQRQhAwyGAwtBCSEDDJ4DCyACKQMgQgBSDccBIAIgAi8BMEGAAXI7ATAMQgsgASAERw0/QdAAIQMMnAMLIAEgBEYEQEELIQMMnAMLIAFBAWohAUEAIQACQCACKAI4IgNFDQAgAygCUCIDRQ0AIAIgAxEAACEACyAADc8CDMYBC0EAIQACQCACKAI4IgNFDQAgAygCSCIDRQ0AIAIgAxEAACEACyAARQ3GASAAQRVHDc0CIAJBCzYCHCACIAE2AhQgAkGCGTYCECACQRU2AgxBACEDDJoDC0EAIQACQCACKAI4IgNFDQAgAygCSCIDRQ0AIAIgAxEAACEACyAARQ0MIABBFUcNygIgAkEaNgIcIAIgATYCFCACQYIZNgIQIAJBFTYCDEEAIQMMmQMLQQAhAAJAIAIoAjgiA0UNACADKAJMIgNFDQAgAiADEQAAIQALIABFDcQBIABBFUcNxwIgAkELNgIcIAIgATYCFCACQZEXNgIQIAJBFTYCDEEAIQMMmAMLIAEgBEYEQEEPIQMMmAMLIAEtAAAiAEE7Rg0HIABBDUcNxAIgAUEBaiEBDMMBC0EAIQACQCACKAI4IgNFDQAgAygCTCIDRQ0AIAIgAxEAACEACyAARQ3DASAAQRVHDcICIAJBDzYCHCACIAE2AhQgAkGRFzYCECACQRU2AgxBACEDDJYDCwNAIAEtAABB8DVqLQAAIgBBAUcEQCAAQQJHDcECIAIoAgQhAEEAIQMgAkEANgIEIAIgACABQQFqIgEQLSIADcICDMUBCyAEIAFBAWoiAUcNAAtBEiEDDJUDC0EAIQACQCACKAI4IgNFDQAgAygCTCIDRQ0AIAIgAxEAACEACyAARQ3FASAAQRVHDb0CIAJBGzYCHCACIAE2AhQgAkGRFzYCECACQRU2AgxBACEDDJQDCyABIARGBEBBFiEDDJQDCyACQQo2AgggAiABNgIEQQAhAAJAIAIoAjgiA0UNACADKAJIIgNFDQAgAiADEQAAIQALIABFDcIBIABBFUcNuQIgAkEVNgIcIAIgATYCFCACQYIZNgIQIAJBFTYCDEEAIQMMkwMLIAEgBEcEQANAIAEtAABB8DdqLQAAIgBBAkcEQAJAIABBAWsOBMQCvQIAvgK9AgsgAUEBaiEBQQghAwz8AgsgBCABQQFqIgFHDQALQRUhAwyTAwtBFSEDDJIDCwNAIAEtAABB8DlqLQAAIgBBAkcEQCAAQQFrDgTFArcCwwK4ArcCCyAEIAFBAWoiAUcNAAtBGCEDDJEDCyABIARHBEAgAkELNgIIIAIgATYCBEEHIQMM+AILQRkhAwyQAwsgAUEBaiEBDAILIAEgBEYEQEEaIQMMjwMLAkAgAS0AAEENaw4UtQG/Ab8BvwG/Ab8BvwG/Ab8BvwG/Ab8BvwG/Ab8BvwG/Ab8BvwEAvwELQQAhAyACQQA2AhwgAkGvCzYCECACQQI2AgwgAiABQQFqNgIUDI4DCyABIARGBEBBGyEDDI4DCyABLQAAIgBBO0cEQCAAQQ1HDbECIAFBAWohAQy6AQsgAUEBaiEBC0EiIQMM8wILIAEgBEYEQEEcIQMMjAMLQgAhCgJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAS0AAEEwaw43wQLAAgABAgMEBQYH0AHQAdAB0AHQAdAB0AEICQoLDA3QAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdABDg8QERIT0AELQgIhCgzAAgtCAyEKDL8CC0IEIQoMvgILQgUhCgy9AgtCBiEKDLwCC0IHIQoMuwILQgghCgy6AgtCCSEKDLkCC0IKIQoMuAILQgshCgy3AgtCDCEKDLYCC0INIQoMtQILQg4hCgy0AgtCDyEKDLMCC0IKIQoMsgILQgshCgyxAgtCDCEKDLACC0INIQoMrwILQg4hCgyuAgtCDyEKDK0CC0IAIQoCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAEtAABBMGsON8ACvwIAAQIDBAUGB74CvgK+Ar4CvgK+Ar4CCAkKCwwNvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ag4PEBESE74CC0ICIQoMvwILQgMhCgy+AgtCBCEKDL0CC0IFIQoMvAILQgYhCgy7AgtCByEKDLoCC0IIIQoMuQILQgkhCgy4AgtCCiEKDLcCC0ILIQoMtgILQgwhCgy1AgtCDSEKDLQCC0IOIQoMswILQg8hCgyyAgtCCiEKDLECC0ILIQoMsAILQgwhCgyvAgtCDSEKDK4CC0IOIQoMrQILQg8hCgysAgsgAiACKQMgIgogBCABa60iC30iDEIAIAogDFobNwMgIAogC1gNpwJBHyEDDIkDCyABIARHBEAgAkEJNgIIIAIgATYCBEElIQMM8AILQSAhAwyIAwtBASEFIAIvATAiA0EIcUUEQCACKQMgQgBSIQULAkAgAi0ALgRAQQEhACACLQApQQVGDQEgA0HAAHFFIAVxRQ0BC0EAIQAgA0HAAHENAEECIQAgA0EIcQ0AIANBgARxBEACQCACLQAoQQFHDQAgAi0ALUEKcQ0AQQUhAAwCC0EEIQAMAQsgA0EgcUUEQAJAIAItAChBAUYNACACLwEyIgBB5ABrQeQASQ0AIABBzAFGDQAgAEGwAkYNAEEEIQAgA0EocUUNAiADQYgEcUGABEYNAgtBACEADAELQQBBAyACKQMgUBshAAsgAEEBaw4FvgIAsAEBpAKhAgtBESEDDO0CCyACQQE6AC8MhAMLIAEgBEcNnQJBJCEDDIQDCyABIARHDRxBxgAhAwyDAwtBACEAAkAgAigCOCIDRQ0AIAMoAkQiA0UNACACIAMRAAAhAAsgAEUNJyAAQRVHDZgCIAJB0AA2AhwgAiABNgIUIAJBkRg2AhAgAkEVNgIMQQAhAwyCAwsgASAERgRAQSghAwyCAwtBACEDIAJBADYCBCACQQw2AgggAiABIAEQKiIARQ2UAiACQSc2AhwgAiABNgIUIAIgADYCDAyBAwsgASAERgRAQSkhAwyBAwsgAS0AACIAQSBGDRMgAEEJRw2VAiABQQFqIQEMFAsgASAERwRAIAFBAWohAQwWC0EqIQMM/wILIAEgBEYEQEErIQMM/wILIAEtAAAiAEEJRyAAQSBHcQ2QAiACLQAsQQhHDd0CIAJBADoALAzdAgsgASAERgRAQSwhAwz+AgsgAS0AAEEKRw2OAiABQQFqIQEMsAELIAEgBEcNigJBLyEDDPwCCwNAIAEtAAAiAEEgRwRAIABBCmsOBIQCiAKIAoQChgILIAQgAUEBaiIBRw0AC0ExIQMM+wILQTIhAyABIARGDfoCIAIoAgAiACAEIAFraiEHIAEgAGtBA2ohBgJAA0AgAEHwO2otAAAgAS0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQEgAEEDRgRAQQYhAQziAgsgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAc2AgAM+wILIAJBADYCAAyGAgtBMyEDIAQgASIARg35AiAEIAFrIAIoAgAiAWohByAAIAFrQQhqIQYCQANAIAFB9DtqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBCEYEQEEFIQEM4QILIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADPoCCyACQQA2AgAgACEBDIUCC0E0IQMgBCABIgBGDfgCIAQgAWsgAigCACIBaiEHIAAgAWtBBWohBgJAA0AgAUHQwgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBBUYEQEEHIQEM4AILIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADPkCCyACQQA2AgAgACEBDIQCCyABIARHBEADQCABLQAAQYA+ai0AACIAQQFHBEAgAEECRg0JDIECCyAEIAFBAWoiAUcNAAtBMCEDDPgCC0EwIQMM9wILIAEgBEcEQANAIAEtAAAiAEEgRwRAIABBCmsOBP8B/gH+Af8B/gELIAQgAUEBaiIBRw0AC0E4IQMM9wILQTghAwz2AgsDQCABLQAAIgBBIEcgAEEJR3EN9gEgBCABQQFqIgFHDQALQTwhAwz1AgsDQCABLQAAIgBBIEcEQAJAIABBCmsOBPkBBAT5AQALIABBLEYN9QEMAwsgBCABQQFqIgFHDQALQT8hAwz0AgtBwAAhAyABIARGDfMCIAIoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAEGAQGstAAAgAS0AAEEgckcNASAAQQZGDdsCIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADPQCCyACQQA2AgALQTYhAwzZAgsgASAERgRAQcEAIQMM8gILIAJBDDYCCCACIAE2AgQgAi0ALEEBaw4E+wHuAewB6wHUAgsgAUEBaiEBDPoBCyABIARHBEADQAJAIAEtAAAiAEEgciAAIABBwQBrQf8BcUEaSRtB/wFxIgBBCUYNACAAQSBGDQACQAJAAkACQCAAQeMAaw4TAAMDAwMDAwMBAwMDAwMDAwMDAgMLIAFBAWohAUExIQMM3AILIAFBAWohAUEyIQMM2wILIAFBAWohAUEzIQMM2gILDP4BCyAEIAFBAWoiAUcNAAtBNSEDDPACC0E1IQMM7wILIAEgBEcEQANAIAEtAABBgDxqLQAAQQFHDfcBIAQgAUEBaiIBRw0AC0E9IQMM7wILQT0hAwzuAgtBACEAAkAgAigCOCIDRQ0AIAMoAkAiA0UNACACIAMRAAAhAAsgAEUNASAAQRVHDeYBIAJBwgA2AhwgAiABNgIUIAJB4xg2AhAgAkEVNgIMQQAhAwztAgsgAUEBaiEBC0E8IQMM0gILIAEgBEYEQEHCACEDDOsCCwJAA0ACQCABLQAAQQlrDhgAAswCzALRAswCzALMAswCzALMAswCzALMAswCzALMAswCzALMAswCzALMAgDMAgsgBCABQQFqIgFHDQALQcIAIQMM6wILIAFBAWohASACLQAtQQFxRQ3+AQtBLCEDDNACCyABIARHDd4BQcQAIQMM6AILA0AgAS0AAEGQwABqLQAAQQFHDZwBIAQgAUEBaiIBRw0AC0HFACEDDOcCCyABLQAAIgBBIEYN/gEgAEE6Rw3AAiACKAIEIQBBACEDIAJBADYCBCACIAAgARApIgAN3gEM3QELQccAIQMgBCABIgBGDeUCIAQgAWsgAigCACIBaiEHIAAgAWtBBWohBgNAIAFBkMIAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNvwIgAUEFRg3CAiABQQFqIQEgBCAAQQFqIgBHDQALIAIgBzYCAAzlAgtByAAhAyAEIAEiAEYN5AIgBCABayACKAIAIgFqIQcgACABa0EJaiEGA0AgAUGWwgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw2+AkECIAFBCUYNwgIaIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADOQCCyABIARGBEBByQAhAwzkAgsCQAJAIAEtAAAiAEEgciAAIABBwQBrQf8BcUEaSRtB/wFxQe4Aaw4HAL8CvwK/Ar8CvwIBvwILIAFBAWohAUE+IQMMywILIAFBAWohAUE/IQMMygILQcoAIQMgBCABIgBGDeICIAQgAWsgAigCACIBaiEGIAAgAWtBAWohBwNAIAFBoMIAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNvAIgAUEBRg2+AiABQQFqIQEgBCAAQQFqIgBHDQALIAIgBjYCAAziAgtBywAhAyAEIAEiAEYN4QIgBCABayACKAIAIgFqIQcgACABa0EOaiEGA0AgAUGiwgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw27AiABQQ5GDb4CIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADOECC0HMACEDIAQgASIARg3gAiAEIAFrIAIoAgAiAWohByAAIAFrQQ9qIQYDQCABQcDCAGotAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDboCQQMgAUEPRg2+AhogAUEBaiEBIAQgAEEBaiIARw0ACyACIAc2AgAM4AILQc0AIQMgBCABIgBGDd8CIAQgAWsgAigCACIBaiEHIAAgAWtBBWohBgNAIAFB0MIAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNuQJBBCABQQVGDb0CGiABQQFqIQEgBCAAQQFqIgBHDQALIAIgBzYCAAzfAgsgASAERgRAQc4AIQMM3wILAkACQAJAAkAgAS0AACIAQSByIAAgAEHBAGtB/wFxQRpJG0H/AXFB4wBrDhMAvAK8ArwCvAK8ArwCvAK8ArwCvAK8ArwCAbwCvAK8AgIDvAILIAFBAWohAUHBACEDDMgCCyABQQFqIQFBwgAhAwzHAgsgAUEBaiEBQcMAIQMMxgILIAFBAWohAUHEACEDDMUCCyABIARHBEAgAkENNgIIIAIgATYCBEHFACEDDMUCC0HPACEDDN0CCwJAAkAgAS0AAEEKaw4EAZABkAEAkAELIAFBAWohAQtBKCEDDMMCCyABIARGBEBB0QAhAwzcAgsgAS0AAEEgRw0AIAFBAWohASACLQAtQQFxRQ3QAQtBFyEDDMECCyABIARHDcsBQdIAIQMM2QILQdMAIQMgASAERg3YAiACKAIAIgAgBCABa2ohBiABIABrQQFqIQUDQCABLQAAIABB1sIAai0AAEcNxwEgAEEBRg3KASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBjYCAAzYAgsgASAERgRAQdUAIQMM2AILIAEtAABBCkcNwgEgAUEBaiEBDMoBCyABIARGBEBB1gAhAwzXAgsCQAJAIAEtAABBCmsOBADDAcMBAcMBCyABQQFqIQEMygELIAFBAWohAUHKACEDDL0CC0EAIQACQCACKAI4IgNFDQAgAygCPCIDRQ0AIAIgAxEAACEACyAADb8BQc0AIQMMvAILIAItAClBIkYNzwIMiQELIAQgASIFRgRAQdsAIQMM1AILQQAhAEEBIQFBASEGQQAhAwJAAn8CQAJAAkACQAJAAkACQCAFLQAAQTBrDgrFAcQBAAECAwQFBgjDAQtBAgwGC0EDDAULQQQMBAtBBQwDC0EGDAILQQcMAQtBCAshA0EAIQFBACEGDL0BC0EJIQNBASEAQQAhAUEAIQYMvAELIAEgBEYEQEHdACEDDNMCCyABLQAAQS5HDbgBIAFBAWohAQyIAQsgASAERw22AUHfACEDDNECCyABIARHBEAgAkEONgIIIAIgATYCBEHQACEDDLgCC0HgACEDDNACC0HhACEDIAEgBEYNzwIgAigCACIAIAQgAWtqIQUgASAAa0EDaiEGA0AgAS0AACAAQeLCAGotAABHDbEBIABBA0YNswEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMzwILQeIAIQMgASAERg3OAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYDQCABLQAAIABB5sIAai0AAEcNsAEgAEECRg2vASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAzOAgtB4wAhAyABIARGDc0CIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgNAIAEtAAAgAEHpwgBqLQAARw2vASAAQQNGDa0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADM0CCyABIARGBEBB5QAhAwzNAgsgAUEBaiEBQQAhAAJAIAIoAjgiA0UNACADKAIwIgNFDQAgAiADEQAAIQALIAANqgFB1gAhAwyzAgsgASAERwRAA0AgAS0AACIAQSBHBEACQAJAAkAgAEHIAGsOCwABswGzAbMBswGzAbMBswGzAQKzAQsgAUEBaiEBQdIAIQMMtwILIAFBAWohAUHTACEDDLYCCyABQQFqIQFB1AAhAwy1AgsgBCABQQFqIgFHDQALQeQAIQMMzAILQeQAIQMMywILA0AgAS0AAEHwwgBqLQAAIgBBAUcEQCAAQQJrDgOnAaYBpQGkAQsgBCABQQFqIgFHDQALQeYAIQMMygILIAFBAWogASAERw0CGkHnACEDDMkCCwNAIAEtAABB8MQAai0AACIAQQFHBEACQCAAQQJrDgSiAaEBoAEAnwELQdcAIQMMsQILIAQgAUEBaiIBRw0AC0HoACEDDMgCCyABIARGBEBB6QAhAwzIAgsCQCABLQAAIgBBCmsOGrcBmwGbAbQBmwGbAZsBmwGbAZsBmwGbAZsBmwGbAZsBmwGbAZsBmwGbAZsBpAGbAZsBAJkBCyABQQFqCyEBQQYhAwytAgsDQCABLQAAQfDGAGotAABBAUcNfSAEIAFBAWoiAUcNAAtB6gAhAwzFAgsgAUEBaiABIARHDQIaQesAIQMMxAILIAEgBEYEQEHsACEDDMQCCyABQQFqDAELIAEgBEYEQEHtACEDDMMCCyABQQFqCyEBQQQhAwyoAgsgASAERgRAQe4AIQMMwQILAkACQAJAIAEtAABB8MgAai0AAEEBaw4HkAGPAY4BAHwBAo0BCyABQQFqIQEMCwsgAUEBagyTAQtBACEDIAJBADYCHCACQZsSNgIQIAJBBzYCDCACIAFBAWo2AhQMwAILAkADQCABLQAAQfDIAGotAAAiAEEERwRAAkACQCAAQQFrDgeUAZMBkgGNAQAEAY0BC0HaACEDDKoCCyABQQFqIQFB3AAhAwypAgsgBCABQQFqIgFHDQALQe8AIQMMwAILIAFBAWoMkQELIAQgASIARgRAQfAAIQMMvwILIAAtAABBL0cNASAAQQFqIQEMBwsgBCABIgBGBEBB8QAhAwy+AgsgAC0AACIBQS9GBEAgAEEBaiEBQd0AIQMMpQILIAFBCmsiA0EWSw0AIAAhAUEBIAN0QYmAgAJxDfkBC0EAIQMgAkEANgIcIAIgADYCFCACQYwcNgIQIAJBBzYCDAy8AgsgASAERwRAIAFBAWohAUHeACEDDKMCC0HyACEDDLsCCyABIARGBEBB9AAhAwy7AgsCQCABLQAAQfDMAGotAABBAWsOA/cBcwCCAQtB4QAhAwyhAgsgASAERwRAA0AgAS0AAEHwygBqLQAAIgBBA0cEQAJAIABBAWsOAvkBAIUBC0HfACEDDKMCCyAEIAFBAWoiAUcNAAtB8wAhAwy6AgtB8wAhAwy5AgsgASAERwRAIAJBDzYCCCACIAE2AgRB4AAhAwygAgtB9QAhAwy4AgsgASAERgRAQfYAIQMMuAILIAJBDzYCCCACIAE2AgQLQQMhAwydAgsDQCABLQAAQSBHDY4CIAQgAUEBaiIBRw0AC0H3ACEDDLUCCyABIARGBEBB+AAhAwy1AgsgAS0AAEEgRw16IAFBAWohAQxbC0EAIQACQCACKAI4IgNFDQAgAygCOCIDRQ0AIAIgAxEAACEACyAADXgMgAILIAEgBEYEQEH6ACEDDLMCCyABLQAAQcwARw10IAFBAWohAUETDHYLQfsAIQMgASAERg2xAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYDQCABLQAAIABB8M4Aai0AAEcNcyAAQQVGDXUgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMsQILIAEgBEYEQEH8ACEDDLECCwJAAkAgAS0AAEHDAGsODAB0dHR0dHR0dHR0AXQLIAFBAWohAUHmACEDDJgCCyABQQFqIQFB5wAhAwyXAgtB/QAhAyABIARGDa8CIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQe3PAGotAABHDXIgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADLACCyACQQA2AgAgBkEBaiEBQRAMcwtB/gAhAyABIARGDa4CIAIoAgAiACAEIAFraiEFIAEgAGtBBWohBgJAA0AgAS0AACAAQfbOAGotAABHDXEgAEEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADK8CCyACQQA2AgAgBkEBaiEBQRYMcgtB/wAhAyABIARGDa0CIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQfzOAGotAABHDXAgAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADK4CCyACQQA2AgAgBkEBaiEBQQUMcQsgASAERgRAQYABIQMMrQILIAEtAABB2QBHDW4gAUEBaiEBQQgMcAsgASAERgRAQYEBIQMMrAILAkACQCABLQAAQc4Aaw4DAG8BbwsgAUEBaiEBQesAIQMMkwILIAFBAWohAUHsACEDDJICCyABIARGBEBBggEhAwyrAgsCQAJAIAEtAABByABrDggAbm5ubm5uAW4LIAFBAWohAUHqACEDDJICCyABQQFqIQFB7QAhAwyRAgtBgwEhAyABIARGDakCIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQYDPAGotAABHDWwgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADKoCCyACQQA2AgAgBkEBaiEBQQAMbQtBhAEhAyABIARGDagCIAIoAgAiACAEIAFraiEFIAEgAGtBBGohBgJAA0AgAS0AACAAQYPPAGotAABHDWsgAEEERg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADKkCCyACQQA2AgAgBkEBaiEBQSMMbAsgASAERgRAQYUBIQMMqAILAkACQCABLQAAQcwAaw4IAGtra2trawFrCyABQQFqIQFB7wAhAwyPAgsgAUEBaiEBQfAAIQMMjgILIAEgBEYEQEGGASEDDKcCCyABLQAAQcUARw1oIAFBAWohAQxgC0GHASEDIAEgBEYNpQIgAigCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABBiM8Aai0AAEcNaCAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMpgILIAJBADYCACAGQQFqIQFBLQxpC0GIASEDIAEgBEYNpAIgAigCACIAIAQgAWtqIQUgASAAa0EIaiEGAkADQCABLQAAIABB0M8Aai0AAEcNZyAAQQhGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMpQILIAJBADYCACAGQQFqIQFBKQxoCyABIARGBEBBiQEhAwykAgtBASABLQAAQd8ARw1nGiABQQFqIQEMXgtBigEhAyABIARGDaICIAIoAgAiACAEIAFraiEFIAEgAGtBAWohBgNAIAEtAAAgAEGMzwBqLQAARw1kIABBAUYN+gEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMogILQYsBIQMgASAERg2hAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGOzwBqLQAARw1kIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyiAgsgAkEANgIAIAZBAWohAUECDGULQYwBIQMgASAERg2gAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHwzwBqLQAARw1jIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyhAgsgAkEANgIAIAZBAWohAUEfDGQLQY0BIQMgASAERg2fAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHyzwBqLQAARw1iIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAygAgsgAkEANgIAIAZBAWohAUEJDGMLIAEgBEYEQEGOASEDDJ8CCwJAAkAgAS0AAEHJAGsOBwBiYmJiYgFiCyABQQFqIQFB+AAhAwyGAgsgAUEBaiEBQfkAIQMMhQILQY8BIQMgASAERg2dAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGRzwBqLQAARw1gIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyeAgsgAkEANgIAIAZBAWohAUEYDGELQZABIQMgASAERg2cAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGXzwBqLQAARw1fIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAydAgsgAkEANgIAIAZBAWohAUEXDGALQZEBIQMgASAERg2bAiACKAIAIgAgBCABa2ohBSABIABrQQZqIQYCQANAIAEtAAAgAEGazwBqLQAARw1eIABBBkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAycAgsgAkEANgIAIAZBAWohAUEVDF8LQZIBIQMgASAERg2aAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGhzwBqLQAARw1dIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAybAgsgAkEANgIAIAZBAWohAUEeDF4LIAEgBEYEQEGTASEDDJoCCyABLQAAQcwARw1bIAFBAWohAUEKDF0LIAEgBEYEQEGUASEDDJkCCwJAAkAgAS0AAEHBAGsODwBcXFxcXFxcXFxcXFxcAVwLIAFBAWohAUH+ACEDDIACCyABQQFqIQFB/wAhAwz/AQsgASAERgRAQZUBIQMMmAILAkACQCABLQAAQcEAaw4DAFsBWwsgAUEBaiEBQf0AIQMM/wELIAFBAWohAUGAASEDDP4BC0GWASEDIAEgBEYNlgIgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBp88Aai0AAEcNWSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMlwILIAJBADYCACAGQQFqIQFBCwxaCyABIARGBEBBlwEhAwyWAgsCQAJAAkACQCABLQAAQS1rDiMAW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1sBW1tbW1sCW1tbA1sLIAFBAWohAUH7ACEDDP8BCyABQQFqIQFB/AAhAwz+AQsgAUEBaiEBQYEBIQMM/QELIAFBAWohAUGCASEDDPwBC0GYASEDIAEgBEYNlAIgAigCACIAIAQgAWtqIQUgASAAa0EEaiEGAkADQCABLQAAIABBqc8Aai0AAEcNVyAAQQRGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMlQILIAJBADYCACAGQQFqIQFBGQxYC0GZASEDIAEgBEYNkwIgAigCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBrs8Aai0AAEcNViAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMlAILIAJBADYCACAGQQFqIQFBBgxXC0GaASEDIAEgBEYNkgIgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBtM8Aai0AAEcNVSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMkwILIAJBADYCACAGQQFqIQFBHAxWC0GbASEDIAEgBEYNkQIgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBts8Aai0AAEcNVCAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMkgILIAJBADYCACAGQQFqIQFBJwxVCyABIARGBEBBnAEhAwyRAgsCQAJAIAEtAABB1ABrDgIAAVQLIAFBAWohAUGGASEDDPgBCyABQQFqIQFBhwEhAwz3AQtBnQEhAyABIARGDY8CIAIoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQbjPAGotAABHDVIgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADJACCyACQQA2AgAgBkEBaiEBQSYMUwtBngEhAyABIARGDY4CIAIoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQbrPAGotAABHDVEgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADI8CCyACQQA2AgAgBkEBaiEBQQMMUgtBnwEhAyABIARGDY0CIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQe3PAGotAABHDVAgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADI4CCyACQQA2AgAgBkEBaiEBQQwMUQtBoAEhAyABIARGDYwCIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQbzPAGotAABHDU8gAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADI0CCyACQQA2AgAgBkEBaiEBQQ0MUAsgASAERgRAQaEBIQMMjAILAkACQCABLQAAQcYAaw4LAE9PT09PT09PTwFPCyABQQFqIQFBiwEhAwzzAQsgAUEBaiEBQYwBIQMM8gELIAEgBEYEQEGiASEDDIsCCyABLQAAQdAARw1MIAFBAWohAQxGCyABIARGBEBBowEhAwyKAgsCQAJAIAEtAABByQBrDgcBTU1NTU0ATQsgAUEBaiEBQY4BIQMM8QELIAFBAWohAUEiDE0LQaQBIQMgASAERg2IAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHAzwBqLQAARw1LIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyJAgsgAkEANgIAIAZBAWohAUEdDEwLIAEgBEYEQEGlASEDDIgCCwJAAkAgAS0AAEHSAGsOAwBLAUsLIAFBAWohAUGQASEDDO8BCyABQQFqIQFBBAxLCyABIARGBEBBpgEhAwyHAgsCQAJAAkACQAJAIAEtAABBwQBrDhUATU1NTU1NTU1NTQFNTQJNTQNNTQRNCyABQQFqIQFBiAEhAwzxAQsgAUEBaiEBQYkBIQMM8AELIAFBAWohAUGKASEDDO8BCyABQQFqIQFBjwEhAwzuAQsgAUEBaiEBQZEBIQMM7QELQacBIQMgASAERg2FAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHtzwBqLQAARw1IIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyGAgsgAkEANgIAIAZBAWohAUERDEkLQagBIQMgASAERg2EAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHCzwBqLQAARw1HIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyFAgsgAkEANgIAIAZBAWohAUEsDEgLQakBIQMgASAERg2DAiACKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEHFzwBqLQAARw1GIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyEAgsgAkEANgIAIAZBAWohAUErDEcLQaoBIQMgASAERg2CAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHKzwBqLQAARw1FIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyDAgsgAkEANgIAIAZBAWohAUEUDEYLIAEgBEYEQEGrASEDDIICCwJAAkACQAJAIAEtAABBwgBrDg8AAQJHR0dHR0dHR0dHRwNHCyABQQFqIQFBkwEhAwzrAQsgAUEBaiEBQZQBIQMM6gELIAFBAWohAUGVASEDDOkBCyABQQFqIQFBlgEhAwzoAQsgASAERgRAQawBIQMMgQILIAEtAABBxQBHDUIgAUEBaiEBDD0LQa0BIQMgASAERg3/ASACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHNzwBqLQAARw1CIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyAAgsgAkEANgIAIAZBAWohAUEODEMLIAEgBEYEQEGuASEDDP8BCyABLQAAQdAARw1AIAFBAWohAUElDEILQa8BIQMgASAERg39ASACKAIAIgAgBCABa2ohBSABIABrQQhqIQYCQANAIAEtAAAgAEHQzwBqLQAARw1AIABBCEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAz+AQsgAkEANgIAIAZBAWohAUEqDEELIAEgBEYEQEGwASEDDP0BCwJAAkAgAS0AAEHVAGsOCwBAQEBAQEBAQEABQAsgAUEBaiEBQZoBIQMM5AELIAFBAWohAUGbASEDDOMBCyABIARGBEBBsQEhAwz8AQsCQAJAIAEtAABBwQBrDhQAPz8/Pz8/Pz8/Pz8/Pz8/Pz8/AT8LIAFBAWohAUGZASEDDOMBCyABQQFqIQFBnAEhAwziAQtBsgEhAyABIARGDfoBIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQdnPAGotAABHDT0gAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADPsBCyACQQA2AgAgBkEBaiEBQSEMPgtBswEhAyABIARGDfkBIAIoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAS0AACAAQd3PAGotAABHDTwgAEEGRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADPoBCyACQQA2AgAgBkEBaiEBQRoMPQsgASAERgRAQbQBIQMM+QELAkACQAJAIAEtAABBxQBrDhEAPT09PT09PT09AT09PT09Aj0LIAFBAWohAUGdASEDDOEBCyABQQFqIQFBngEhAwzgAQsgAUEBaiEBQZ8BIQMM3wELQbUBIQMgASAERg33ASACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHkzwBqLQAARw06IABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAz4AQsgAkEANgIAIAZBAWohAUEoDDsLQbYBIQMgASAERg32ASACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHqzwBqLQAARw05IABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAz3AQsgAkEANgIAIAZBAWohAUEHDDoLIAEgBEYEQEG3ASEDDPYBCwJAAkAgAS0AAEHFAGsODgA5OTk5OTk5OTk5OTkBOQsgAUEBaiEBQaEBIQMM3QELIAFBAWohAUGiASEDDNwBC0G4ASEDIAEgBEYN9AEgAigCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB7c8Aai0AAEcNNyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM9QELIAJBADYCACAGQQFqIQFBEgw4C0G5ASEDIAEgBEYN8wEgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB8M8Aai0AAEcNNiAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM9AELIAJBADYCACAGQQFqIQFBIAw3C0G6ASEDIAEgBEYN8gEgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB8s8Aai0AAEcNNSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM8wELIAJBADYCACAGQQFqIQFBDww2CyABIARGBEBBuwEhAwzyAQsCQAJAIAEtAABByQBrDgcANTU1NTUBNQsgAUEBaiEBQaUBIQMM2QELIAFBAWohAUGmASEDDNgBC0G8ASEDIAEgBEYN8AEgAigCACIAIAQgAWtqIQUgASAAa0EHaiEGAkADQCABLQAAIABB9M8Aai0AAEcNMyAAQQdGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM8QELIAJBADYCACAGQQFqIQFBGww0CyABIARGBEBBvQEhAwzwAQsCQAJAAkAgAS0AAEHCAGsOEgA0NDQ0NDQ0NDQBNDQ0NDQ0AjQLIAFBAWohAUGkASEDDNgBCyABQQFqIQFBpwEhAwzXAQsgAUEBaiEBQagBIQMM1gELIAEgBEYEQEG+ASEDDO8BCyABLQAAQc4ARw0wIAFBAWohAQwsCyABIARGBEBBvwEhAwzuAQsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCABLQAAQcEAaw4VAAECAz8EBQY/Pz8HCAkKCz8MDQ4PPwsgAUEBaiEBQegAIQMM4wELIAFBAWohAUHpACEDDOIBCyABQQFqIQFB7gAhAwzhAQsgAUEBaiEBQfIAIQMM4AELIAFBAWohAUHzACEDDN8BCyABQQFqIQFB9gAhAwzeAQsgAUEBaiEBQfcAIQMM3QELIAFBAWohAUH6ACEDDNwBCyABQQFqIQFBgwEhAwzbAQsgAUEBaiEBQYQBIQMM2gELIAFBAWohAUGFASEDDNkBCyABQQFqIQFBkgEhAwzYAQsgAUEBaiEBQZgBIQMM1wELIAFBAWohAUGgASEDDNYBCyABQQFqIQFBowEhAwzVAQsgAUEBaiEBQaoBIQMM1AELIAEgBEcEQCACQRA2AgggAiABNgIEQasBIQMM1AELQcABIQMM7AELQQAhAAJAIAIoAjgiA0UNACADKAI0IgNFDQAgAiADEQAAIQALIABFDV4gAEEVRw0HIAJB0QA2AhwgAiABNgIUIAJBsBc2AhAgAkEVNgIMQQAhAwzrAQsgAUEBaiABIARHDQgaQcIBIQMM6gELA0ACQCABLQAAQQprDgQIAAALAAsgBCABQQFqIgFHDQALQcMBIQMM6QELIAEgBEcEQCACQRE2AgggAiABNgIEQQEhAwzQAQtBxAEhAwzoAQsgASAERgRAQcUBIQMM6AELAkACQCABLQAAQQprDgQBKCgAKAsgAUEBagwJCyABQQFqDAULIAEgBEYEQEHGASEDDOcBCwJAAkAgAS0AAEEKaw4XAQsLAQsLCwsLCwsLCwsLCwsLCwsLCwALCyABQQFqIQELQbABIQMMzQELIAEgBEYEQEHIASEDDOYBCyABLQAAQSBHDQkgAkEAOwEyIAFBAWohAUGzASEDDMwBCwNAIAEhAAJAIAEgBEcEQCABLQAAQTBrQf8BcSIDQQpJDQEMJwtBxwEhAwzmAQsCQCACLwEyIgFBmTNLDQAgAiABQQpsIgU7ATIgBUH+/wNxIANB//8Dc0sNACAAQQFqIQEgAiADIAVqIgM7ATIgA0H//wNxQegHSQ0BCwtBACEDIAJBADYCHCACQcEJNgIQIAJBDTYCDCACIABBAWo2AhQM5AELIAJBADYCHCACIAE2AhQgAkHwDDYCECACQRs2AgxBACEDDOMBCyACKAIEIQAgAkEANgIEIAIgACABECYiAA0BIAFBAWoLIQFBrQEhAwzIAQsgAkHBATYCHCACIAA2AgwgAiABQQFqNgIUQQAhAwzgAQsgAigCBCEAIAJBADYCBCACIAAgARAmIgANASABQQFqCyEBQa4BIQMMxQELIAJBwgE2AhwgAiAANgIMIAIgAUEBajYCFEEAIQMM3QELIAJBADYCHCACIAE2AhQgAkGXCzYCECACQQ02AgxBACEDDNwBCyACQQA2AhwgAiABNgIUIAJB4xA2AhAgAkEJNgIMQQAhAwzbAQsgAkECOgAoDKwBC0EAIQMgAkEANgIcIAJBrws2AhAgAkECNgIMIAIgAUEBajYCFAzZAQtBAiEDDL8BC0ENIQMMvgELQSYhAwy9AQtBFSEDDLwBC0EWIQMMuwELQRghAwy6AQtBHCEDDLkBC0EdIQMMuAELQSAhAwy3AQtBISEDDLYBC0EjIQMMtQELQcYAIQMMtAELQS4hAwyzAQtBPSEDDLIBC0HLACEDDLEBC0HOACEDDLABC0HYACEDDK8BC0HZACEDDK4BC0HbACEDDK0BC0HxACEDDKwBC0H0ACEDDKsBC0GNASEDDKoBC0GXASEDDKkBC0GpASEDDKgBC0GvASEDDKcBC0GxASEDDKYBCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJB8Rs2AhAgAkEGNgIMDL0BCyACQQA2AgAgBkEBaiEBQSQLOgApIAIoAgQhACACQQA2AgQgAiAAIAEQJyIARQRAQeUAIQMMowELIAJB+QA2AhwgAiABNgIUIAIgADYCDEEAIQMMuwELIABBFUcEQCACQQA2AhwgAiABNgIUIAJBzA42AhAgAkEgNgIMQQAhAwy7AQsgAkH4ADYCHCACIAE2AhQgAkHKGDYCECACQRU2AgxBACEDDLoBCyACQQA2AhwgAiABNgIUIAJBjhs2AhAgAkEGNgIMQQAhAwy5AQsgAkEANgIcIAIgATYCFCACQf4RNgIQIAJBBzYCDEEAIQMMuAELIAJBADYCHCACIAE2AhQgAkGMHDYCECACQQc2AgxBACEDDLcBCyACQQA2AhwgAiABNgIUIAJBww82AhAgAkEHNgIMQQAhAwy2AQsgAkEANgIcIAIgATYCFCACQcMPNgIQIAJBBzYCDEEAIQMMtQELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0RIAJB5QA2AhwgAiABNgIUIAIgADYCDEEAIQMMtAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0gIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMswELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0iIAJB0gA2AhwgAiABNgIUIAIgADYCDEEAIQMMsgELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0OIAJB5QA2AhwgAiABNgIUIAIgADYCDEEAIQMMsQELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0dIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMsAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0fIAJB0gA2AhwgAiABNgIUIAIgADYCDEEAIQMMrwELIABBP0cNASABQQFqCyEBQQUhAwyUAQtBACEDIAJBADYCHCACIAE2AhQgAkH9EjYCECACQQc2AgwMrAELIAJBADYCHCACIAE2AhQgAkHcCDYCECACQQc2AgxBACEDDKsBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNByACQeUANgIcIAIgATYCFCACIAA2AgxBACEDDKoBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNFiACQdMANgIcIAIgATYCFCACIAA2AgxBACEDDKkBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNGCACQdIANgIcIAIgATYCFCACIAA2AgxBACEDDKgBCyACQQA2AhwgAiABNgIUIAJBxgo2AhAgAkEHNgIMQQAhAwynAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQMgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwymAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRIgAkHTADYCHCACIAE2AhQgAiAANgIMQQAhAwylAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRQgAkHSADYCHCACIAE2AhQgAiAANgIMQQAhAwykAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQAgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwyjAQtB1QAhAwyJAQsgAEEVRwRAIAJBADYCHCACIAE2AhQgAkG5DTYCECACQRo2AgxBACEDDKIBCyACQeQANgIcIAIgATYCFCACQeMXNgIQIAJBFTYCDEEAIQMMoQELIAJBADYCACAGQQFqIQEgAi0AKSIAQSNrQQtJDQQCQCAAQQZLDQBBASAAdEHKAHFFDQAMBQtBACEDIAJBADYCHCACIAE2AhQgAkH3CTYCECACQQg2AgwMoAELIAJBADYCACAGQQFqIQEgAi0AKUEhRg0DIAJBADYCHCACIAE2AhQgAkGbCjYCECACQQg2AgxBACEDDJ8BCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJBkDM2AhAgAkEINgIMDJ0BCyACQQA2AgAgBkEBaiEBIAItAClBI0kNACACQQA2AhwgAiABNgIUIAJB0wk2AhAgAkEINgIMQQAhAwycAQtB0QAhAwyCAQsgAS0AAEEwayIAQf8BcUEKSQRAIAIgADoAKiABQQFqIQFBzwAhAwyCAQsgAigCBCEAIAJBADYCBCACIAAgARAoIgBFDYYBIAJB3gA2AhwgAiABNgIUIAIgADYCDEEAIQMMmgELIAIoAgQhACACQQA2AgQgAiAAIAEQKCIARQ2GASACQdwANgIcIAIgATYCFCACIAA2AgxBACEDDJkBCyACKAIEIQAgAkEANgIEIAIgACAFECgiAEUEQCAFIQEMhwELIAJB2gA2AhwgAiAFNgIUIAIgADYCDAyYAQtBACEBQQEhAwsgAiADOgArIAVBAWohAwJAAkACQCACLQAtQRBxDQACQAJAAkAgAi0AKg4DAQACBAsgBkUNAwwCCyAADQEMAgsgAUUNAQsgAigCBCEAIAJBADYCBCACIAAgAxAoIgBFBEAgAyEBDAILIAJB2AA2AhwgAiADNgIUIAIgADYCDEEAIQMMmAELIAIoAgQhACACQQA2AgQgAiAAIAMQKCIARQRAIAMhAQyHAQsgAkHZADYCHCACIAM2AhQgAiAANgIMQQAhAwyXAQtBzAAhAwx9CyAAQRVHBEAgAkEANgIcIAIgATYCFCACQZQNNgIQIAJBITYCDEEAIQMMlgELIAJB1wA2AhwgAiABNgIUIAJByRc2AhAgAkEVNgIMQQAhAwyVAQtBACEDIAJBADYCHCACIAE2AhQgAkGAETYCECACQQk2AgwMlAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0AIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMkwELQckAIQMMeQsgAkEANgIcIAIgATYCFCACQcEoNgIQIAJBBzYCDCACQQA2AgBBACEDDJEBCyACKAIEIQBBACEDIAJBADYCBCACIAAgARAlIgBFDQAgAkHSADYCHCACIAE2AhQgAiAANgIMDJABC0HIACEDDHYLIAJBADYCACAFIQELIAJBgBI7ASogAUEBaiEBQQAhAAJAIAIoAjgiA0UNACADKAIwIgNFDQAgAiADEQAAIQALIAANAQtBxwAhAwxzCyAAQRVGBEAgAkHRADYCHCACIAE2AhQgAkHjFzYCECACQRU2AgxBACEDDIwBC0EAIQMgAkEANgIcIAIgATYCFCACQbkNNgIQIAJBGjYCDAyLAQtBACEDIAJBADYCHCACIAE2AhQgAkGgGTYCECACQR42AgwMigELIAEtAABBOkYEQCACKAIEIQBBACEDIAJBADYCBCACIAAgARApIgBFDQEgAkHDADYCHCACIAA2AgwgAiABQQFqNgIUDIoBC0EAIQMgAkEANgIcIAIgATYCFCACQbERNgIQIAJBCjYCDAyJAQsgAUEBaiEBQTshAwxvCyACQcMANgIcIAIgADYCDCACIAFBAWo2AhQMhwELQQAhAyACQQA2AhwgAiABNgIUIAJB8A42AhAgAkEcNgIMDIYBCyACIAIvATBBEHI7ATAMZgsCQCACLwEwIgBBCHFFDQAgAi0AKEEBRw0AIAItAC1BCHFFDQMLIAIgAEH3+wNxQYAEcjsBMAwECyABIARHBEACQANAIAEtAABBMGsiAEH/AXFBCk8EQEE1IQMMbgsgAikDICIKQpmz5syZs+bMGVYNASACIApCCn4iCjcDICAKIACtQv8BgyILQn+FVg0BIAIgCiALfDcDICAEIAFBAWoiAUcNAAtBOSEDDIUBCyACKAIEIQBBACEDIAJBADYCBCACIAAgAUEBaiIBECoiAA0MDHcLQTkhAwyDAQsgAi0AMEEgcQ0GQcUBIQMMaQtBACEDIAJBADYCBCACIAEgARAqIgBFDQQgAkE6NgIcIAIgADYCDCACIAFBAWo2AhQMgQELIAItAChBAUcNACACLQAtQQhxRQ0BC0E3IQMMZgsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIABEAgAkE7NgIcIAIgADYCDCACIAFBAWo2AhQMfwsgAUEBaiEBDG4LIAJBCDoALAwECyABQQFqIQEMbQtBACEDIAJBADYCHCACIAE2AhQgAkHkEjYCECACQQQ2AgwMewsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIARQ1sIAJBNzYCHCACIAE2AhQgAiAANgIMDHoLIAIgAi8BMEEgcjsBMAtBMCEDDF8LIAJBNjYCHCACIAE2AhQgAiAANgIMDHcLIABBLEcNASABQQFqIQBBASEBAkACQAJAAkACQCACLQAsQQVrDgQDAQIEAAsgACEBDAQLQQIhAQwBC0EEIQELIAJBAToALCACIAIvATAgAXI7ATAgACEBDAELIAIgAi8BMEEIcjsBMCAAIQELQTkhAwxcCyACQQA6ACwLQTQhAwxaCyABIARGBEBBLSEDDHMLAkACQANAAkAgAS0AAEEKaw4EAgAAAwALIAQgAUEBaiIBRw0AC0EtIQMMdAsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIARQ0CIAJBLDYCHCACIAE2AhQgAiAANgIMDHMLIAIoAgQhAEEAIQMgAkEANgIEIAIgACABECoiAEUEQCABQQFqIQEMAgsgAkEsNgIcIAIgADYCDCACIAFBAWo2AhQMcgsgAS0AAEENRgRAIAIoAgQhAEEAIQMgAkEANgIEIAIgACABECoiAEUEQCABQQFqIQEMAgsgAkEsNgIcIAIgADYCDCACIAFBAWo2AhQMcgsgAi0ALUEBcQRAQcQBIQMMWQsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIADQEMZQtBLyEDDFcLIAJBLjYCHCACIAE2AhQgAiAANgIMDG8LQQAhAyACQQA2AhwgAiABNgIUIAJB8BQ2AhAgAkEDNgIMDG4LQQEhAwJAAkACQAJAIAItACxBBWsOBAMBAgAECyACIAIvATBBCHI7ATAMAwtBAiEDDAELQQQhAwsgAkEBOgAsIAIgAi8BMCADcjsBMAtBKiEDDFMLQQAhAyACQQA2AhwgAiABNgIUIAJB4Q82AhAgAkEKNgIMDGsLQQEhAwJAAkACQAJAAkACQCACLQAsQQJrDgcFBAQDAQIABAsgAiACLwEwQQhyOwEwDAMLQQIhAwwBC0EEIQMLIAJBAToALCACIAIvATAgA3I7ATALQSshAwxSC0EAIQMgAkEANgIcIAIgATYCFCACQasSNgIQIAJBCzYCDAxqC0EAIQMgAkEANgIcIAIgATYCFCACQf0NNgIQIAJBHTYCDAxpCyABIARHBEADQCABLQAAQSBHDUggBCABQQFqIgFHDQALQSUhAwxpC0ElIQMMaAsgAi0ALUEBcQRAQcMBIQMMTwsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKSIABEAgAkEmNgIcIAIgADYCDCACIAFBAWo2AhQMaAsgAUEBaiEBDFwLIAFBAWohASACLwEwIgBBgAFxBEBBACEAAkAgAigCOCIDRQ0AIAMoAlQiA0UNACACIAMRAAAhAAsgAEUNBiAAQRVHDR8gAkEFNgIcIAIgATYCFCACQfkXNgIQIAJBFTYCDEEAIQMMZwsCQCAAQaAEcUGgBEcNACACLQAtQQJxDQBBACEDIAJBADYCHCACIAE2AhQgAkGWEzYCECACQQQ2AgwMZwsgAgJ/IAIvATBBFHFBFEYEQEEBIAItAChBAUYNARogAi8BMkHlAEYMAQsgAi0AKUEFRgs6AC5BACEAAkAgAigCOCIDRQ0AIAMoAiQiA0UNACACIAMRAAAhAAsCQAJAAkACQAJAIAAOFgIBAAQEBAQEBAQEBAQEBAQEBAQEBAMECyACQQE6AC4LIAIgAi8BMEHAAHI7ATALQSchAwxPCyACQSM2AhwgAiABNgIUIAJBpRY2AhAgAkEVNgIMQQAhAwxnC0EAIQMgAkEANgIcIAIgATYCFCACQdULNgIQIAJBETYCDAxmC0EAIQACQCACKAI4IgNFDQAgAygCLCIDRQ0AIAIgAxEAACEACyAADQELQQ4hAwxLCyAAQRVGBEAgAkECNgIcIAIgATYCFCACQbAYNgIQIAJBFTYCDEEAIQMMZAtBACEDIAJBADYCHCACIAE2AhQgAkGnDjYCECACQRI2AgwMYwtBACEDIAJBADYCHCACIAE2AhQgAkGqHDYCECACQQ82AgwMYgsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEgCqdqIgEQKyIARQ0AIAJBBTYCHCACIAE2AhQgAiAANgIMDGELQQ8hAwxHC0EAIQMgAkEANgIcIAIgATYCFCACQc0TNgIQIAJBDDYCDAxfC0IBIQoLIAFBAWohAQJAIAIpAyAiC0L//////////w9YBEAgAiALQgSGIAqENwMgDAELQQAhAyACQQA2AhwgAiABNgIUIAJBrQk2AhAgAkEMNgIMDF4LQSQhAwxEC0EAIQMgAkEANgIcIAIgATYCFCACQc0TNgIQIAJBDDYCDAxcCyACKAIEIQBBACEDIAJBADYCBCACIAAgARAsIgBFBEAgAUEBaiEBDFILIAJBFzYCHCACIAA2AgwgAiABQQFqNgIUDFsLIAIoAgQhAEEAIQMgAkEANgIEAkAgAiAAIAEQLCIARQRAIAFBAWohAQwBCyACQRY2AhwgAiAANgIMIAIgAUEBajYCFAxbC0EfIQMMQQtBACEDIAJBADYCHCACIAE2AhQgAkGaDzYCECACQSI2AgwMWQsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQLSIARQRAIAFBAWohAQxQCyACQRQ2AhwgAiAANgIMIAIgAUEBajYCFAxYCyACKAIEIQBBACEDIAJBADYCBAJAIAIgACABEC0iAEUEQCABQQFqIQEMAQsgAkETNgIcIAIgADYCDCACIAFBAWo2AhQMWAtBHiEDDD4LQQAhAyACQQA2AhwgAiABNgIUIAJBxgw2AhAgAkEjNgIMDFYLIAIoAgQhAEEAIQMgAkEANgIEIAIgACABEC0iAEUEQCABQQFqIQEMTgsgAkERNgIcIAIgADYCDCACIAFBAWo2AhQMVQsgAkEQNgIcIAIgATYCFCACIAA2AgwMVAtBACEDIAJBADYCHCACIAE2AhQgAkHGDDYCECACQSM2AgwMUwtBACEDIAJBADYCHCACIAE2AhQgAkHAFTYCECACQQI2AgwMUgsgAigCBCEAQQAhAyACQQA2AgQCQCACIAAgARAtIgBFBEAgAUEBaiEBDAELIAJBDjYCHCACIAA2AgwgAiABQQFqNgIUDFILQRshAww4C0EAIQMgAkEANgIcIAIgATYCFCACQcYMNgIQIAJBIzYCDAxQCyACKAIEIQBBACEDIAJBADYCBAJAIAIgACABECwiAEUEQCABQQFqIQEMAQsgAkENNgIcIAIgADYCDCACIAFBAWo2AhQMUAtBGiEDDDYLQQAhAyACQQA2AhwgAiABNgIUIAJBmg82AhAgAkEiNgIMDE4LIAIoAgQhAEEAIQMgAkEANgIEAkAgAiAAIAEQLCIARQRAIAFBAWohAQwBCyACQQw2AhwgAiAANgIMIAIgAUEBajYCFAxOC0EZIQMMNAtBACEDIAJBADYCHCACIAE2AhQgAkGaDzYCECACQSI2AgwMTAsgAEEVRwRAQQAhAyACQQA2AhwgAiABNgIUIAJBgww2AhAgAkETNgIMDEwLIAJBCjYCHCACIAE2AhQgAkHkFjYCECACQRU2AgxBACEDDEsLIAIoAgQhAEEAIQMgAkEANgIEIAIgACABIAqnaiIBECsiAARAIAJBBzYCHCACIAE2AhQgAiAANgIMDEsLQRMhAwwxCyAAQRVHBEBBACEDIAJBADYCHCACIAE2AhQgAkHaDTYCECACQRQ2AgwMSgsgAkEeNgIcIAIgATYCFCACQfkXNgIQIAJBFTYCDEEAIQMMSQtBACEAAkAgAigCOCIDRQ0AIAMoAiwiA0UNACACIAMRAAAhAAsgAEUNQSAAQRVGBEAgAkEDNgIcIAIgATYCFCACQbAYNgIQIAJBFTYCDEEAIQMMSQtBACEDIAJBADYCHCACIAE2AhQgAkGnDjYCECACQRI2AgwMSAtBACEDIAJBADYCHCACIAE2AhQgAkHaDTYCECACQRQ2AgwMRwtBACEDIAJBADYCHCACIAE2AhQgAkGnDjYCECACQRI2AgwMRgsgAkEAOgAvIAItAC1BBHFFDT8LIAJBADoALyACQQE6ADRBACEDDCsLQQAhAyACQQA2AhwgAkHkETYCECACQQc2AgwgAiABQQFqNgIUDEMLAkADQAJAIAEtAABBCmsOBAACAgACCyAEIAFBAWoiAUcNAAtB3QEhAwxDCwJAAkAgAi0ANEEBRw0AQQAhAAJAIAIoAjgiA0UNACADKAJYIgNFDQAgAiADEQAAIQALIABFDQAgAEEVRw0BIAJB3AE2AhwgAiABNgIUIAJB1RY2AhAgAkEVNgIMQQAhAwxEC0HBASEDDCoLIAJBADYCHCACIAE2AhQgAkHpCzYCECACQR82AgxBACEDDEILAkACQCACLQAoQQFrDgIEAQALQcABIQMMKQtBuQEhAwwoCyACQQI6AC9BACEAAkAgAigCOCIDRQ0AIAMoAgAiA0UNACACIAMRAAAhAAsgAEUEQEHCASEDDCgLIABBFUcEQCACQQA2AhwgAiABNgIUIAJBpAw2AhAgAkEQNgIMQQAhAwxBCyACQdsBNgIcIAIgATYCFCACQfoWNgIQIAJBFTYCDEEAIQMMQAsgASAERgRAQdoBIQMMQAsgAS0AAEHIAEYNASACQQE6ACgLQawBIQMMJQtBvwEhAwwkCyABIARHBEAgAkEQNgIIIAIgATYCBEG+ASEDDCQLQdkBIQMMPAsgASAERgRAQdgBIQMMPAsgAS0AAEHIAEcNBCABQQFqIQFBvQEhAwwiCyABIARGBEBB1wEhAww7CwJAAkAgAS0AAEHFAGsOEAAFBQUFBQUFBQUFBQUFBQEFCyABQQFqIQFBuwEhAwwiCyABQQFqIQFBvAEhAwwhC0HWASEDIAEgBEYNOSACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGD0ABqLQAARw0DIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAw6CyACKAIEIQAgAkIANwMAIAIgACAGQQFqIgEQJyIARQRAQcYBIQMMIQsgAkHVATYCHCACIAE2AhQgAiAANgIMQQAhAww5C0HUASEDIAEgBEYNOCACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGB0ABqLQAARw0CIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAw5CyACQYEEOwEoIAIoAgQhACACQgA3AwAgAiAAIAZBAWoiARAnIgANAwwCCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJB2Bs2AhAgAkEINgIMDDYLQboBIQMMHAsgAkHTATYCHCACIAE2AhQgAiAANgIMQQAhAww0C0EAIQACQCACKAI4IgNFDQAgAygCOCIDRQ0AIAIgAxEAACEACyAARQ0AIABBFUYNASACQQA2AhwgAiABNgIUIAJBzA42AhAgAkEgNgIMQQAhAwwzC0HkACEDDBkLIAJB+AA2AhwgAiABNgIUIAJByhg2AhAgAkEVNgIMQQAhAwwxC0HSASEDIAQgASIARg0wIAQgAWsgAigCACIBaiEFIAAgAWtBBGohBgJAA0AgAC0AACABQfzPAGotAABHDQEgAUEERg0DIAFBAWohASAEIABBAWoiAEcNAAsgAiAFNgIADDELIAJBADYCHCACIAA2AhQgAkGQMzYCECACQQg2AgwgAkEANgIAQQAhAwwwCyABIARHBEAgAkEONgIIIAIgATYCBEG3ASEDDBcLQdEBIQMMLwsgAkEANgIAIAZBAWohAQtBuAEhAwwUCyABIARGBEBB0AEhAwwtCyABLQAAQTBrIgBB/wFxQQpJBEAgAiAAOgAqIAFBAWohAUG2ASEDDBQLIAIoAgQhACACQQA2AgQgAiAAIAEQKCIARQ0UIAJBzwE2AhwgAiABNgIUIAIgADYCDEEAIQMMLAsgASAERgRAQc4BIQMMLAsCQCABLQAAQS5GBEAgAUEBaiEBDAELIAIoAgQhACACQQA2AgQgAiAAIAEQKCIARQ0VIAJBzQE2AhwgAiABNgIUIAIgADYCDEEAIQMMLAtBtQEhAwwSCyAEIAEiBUYEQEHMASEDDCsLQQAhAEEBIQFBASEGQQAhAwJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAIAUtAABBMGsOCgoJAAECAwQFBggLC0ECDAYLQQMMBQtBBAwEC0EFDAMLQQYMAgtBBwwBC0EICyEDQQAhAUEAIQYMAgtBCSEDQQEhAEEAIQFBACEGDAELQQAhAUEBIQMLIAIgAzoAKyAFQQFqIQMCQAJAIAItAC1BEHENAAJAAkACQCACLQAqDgMBAAIECyAGRQ0DDAILIAANAQwCCyABRQ0BCyACKAIEIQAgAkEANgIEIAIgACADECgiAEUEQCADIQEMAwsgAkHJATYCHCACIAM2AhQgAiAANgIMQQAhAwwtCyACKAIEIQAgAkEANgIEIAIgACADECgiAEUEQCADIQEMGAsgAkHKATYCHCACIAM2AhQgAiAANgIMQQAhAwwsCyACKAIEIQAgAkEANgIEIAIgACAFECgiAEUEQCAFIQEMFgsgAkHLATYCHCACIAU2AhQgAiAANgIMDCsLQbQBIQMMEQtBACEAAkAgAigCOCIDRQ0AIAMoAjwiA0UNACACIAMRAAAhAAsCQCAABEAgAEEVRg0BIAJBADYCHCACIAE2AhQgAkGUDTYCECACQSE2AgxBACEDDCsLQbIBIQMMEQsgAkHIATYCHCACIAE2AhQgAkHJFzYCECACQRU2AgxBACEDDCkLIAJBADYCACAGQQFqIQFB9QAhAwwPCyACLQApQQVGBEBB4wAhAwwPC0HiACEDDA4LIAAhASACQQA2AgALIAJBADoALEEJIQMMDAsgAkEANgIAIAdBAWohAUHAACEDDAsLQQELOgAsIAJBADYCACAGQQFqIQELQSkhAwwIC0E4IQMMBwsCQCABIARHBEADQCABLQAAQYA+ai0AACIAQQFHBEAgAEECRw0DIAFBAWohAQwFCyAEIAFBAWoiAUcNAAtBPiEDDCELQT4hAwwgCwsgAkEAOgAsDAELQQshAwwEC0E6IQMMAwsgAUEBaiEBQS0hAwwCCyACIAE6ACwgAkEANgIAIAZBAWohAUEMIQMMAQsgAkEANgIAIAZBAWohAUEKIQMMAAsAC0EAIQMgAkEANgIcIAIgATYCFCACQc0QNgIQIAJBCTYCDAwXC0EAIQMgAkEANgIcIAIgATYCFCACQekKNgIQIAJBCTYCDAwWC0EAIQMgAkEANgIcIAIgATYCFCACQbcQNgIQIAJBCTYCDAwVC0EAIQMgAkEANgIcIAIgATYCFCACQZwRNgIQIAJBCTYCDAwUC0EAIQMgAkEANgIcIAIgATYCFCACQc0QNgIQIAJBCTYCDAwTC0EAIQMgAkEANgIcIAIgATYCFCACQekKNgIQIAJBCTYCDAwSC0EAIQMgAkEANgIcIAIgATYCFCACQbcQNgIQIAJBCTYCDAwRC0EAIQMgAkEANgIcIAIgATYCFCACQZwRNgIQIAJBCTYCDAwQC0EAIQMgAkEANgIcIAIgATYCFCACQZcVNgIQIAJBDzYCDAwPC0EAIQMgAkEANgIcIAIgATYCFCACQZcVNgIQIAJBDzYCDAwOC0EAIQMgAkEANgIcIAIgATYCFCACQcASNgIQIAJBCzYCDAwNC0EAIQMgAkEANgIcIAIgATYCFCACQZUJNgIQIAJBCzYCDAwMC0EAIQMgAkEANgIcIAIgATYCFCACQeEPNgIQIAJBCjYCDAwLC0EAIQMgAkEANgIcIAIgATYCFCACQfsPNgIQIAJBCjYCDAwKC0EAIQMgAkEANgIcIAIgATYCFCACQfEZNgIQIAJBAjYCDAwJC0EAIQMgAkEANgIcIAIgATYCFCACQcQUNgIQIAJBAjYCDAwIC0EAIQMgAkEANgIcIAIgATYCFCACQfIVNgIQIAJBAjYCDAwHCyACQQI2AhwgAiABNgIUIAJBnBo2AhAgAkEWNgIMQQAhAwwGC0EBIQMMBQtB1AAhAyABIARGDQQgCEEIaiEJIAIoAgAhBQJAAkAgASAERwRAIAVB2MIAaiEHIAQgBWogAWshACAFQX9zQQpqIgUgAWohBgNAIAEtAAAgBy0AAEcEQEECIQcMAwsgBUUEQEEAIQcgBiEBDAMLIAVBAWshBSAHQQFqIQcgBCABQQFqIgFHDQALIAAhBSAEIQELIAlBATYCACACIAU2AgAMAQsgAkEANgIAIAkgBzYCAAsgCSABNgIEIAgoAgwhACAIKAIIDgMBBAIACwALIAJBADYCHCACQbUaNgIQIAJBFzYCDCACIABBAWo2AhRBACEDDAILIAJBADYCHCACIAA2AhQgAkHKGjYCECACQQk2AgxBACEDDAELIAEgBEYEQEEiIQMMAQsgAkEJNgIIIAIgATYCBEEhIQMLIAhBEGokACADRQRAIAIoAgwhAAwBCyACIAM2AhxBACEAIAIoAgQiAUUNACACIAEgBCACKAIIEQEAIgFFDQAgAiAENgIUIAIgATYCDCABIQALIAALvgIBAn8gAEEAOgAAIABB3ABqIgFBAWtBADoAACAAQQA6AAIgAEEAOgABIAFBA2tBADoAACABQQJrQQA6AAAgAEEAOgADIAFBBGtBADoAAEEAIABrQQNxIgEgAGoiAEEANgIAQdwAIAFrQXxxIgIgAGoiAUEEa0EANgIAAkAgAkEJSQ0AIABBADYCCCAAQQA2AgQgAUEIa0EANgIAIAFBDGtBADYCACACQRlJDQAgAEEANgIYIABBADYCFCAAQQA2AhAgAEEANgIMIAFBEGtBADYCACABQRRrQQA2AgAgAUEYa0EANgIAIAFBHGtBADYCACACIABBBHFBGHIiAmsiAUEgSQ0AIAAgAmohAANAIABCADcDGCAAQgA3AxAgAEIANwMIIABCADcDACAAQSBqIQAgAUEgayIBQR9LDQALCwtWAQF/AkAgACgCDA0AAkACQAJAAkAgAC0ALw4DAQADAgsgACgCOCIBRQ0AIAEoAiwiAUUNACAAIAERAAAiAQ0DC0EADwsACyAAQcMWNgIQQQ4hAQsgAQsaACAAKAIMRQRAIABB0Rs2AhAgAEEVNgIMCwsUACAAKAIMQRVGBEAgAEEANgIMCwsUACAAKAIMQRZGBEAgAEEANgIMCwsHACAAKAIMCwcAIAAoAhALCQAgACABNgIQCwcAIAAoAhQLFwAgAEEkTwRAAAsgAEECdEGgM2ooAgALFwAgAEEuTwRAAAsgAEECdEGwNGooAgALvwkBAX9B6yghAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABB5ABrDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhBgcICQoLDA0OD2FhYWFhEGFhYWFhYWFhYWFhEWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRITFBUWFxgZGhthYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2YTc4OTphYWFhYWFhYTthYWE8YWFhYT0+P2FhYWFhYWFhQGFhQWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYUJDREVGR0hJSktMTU5PUFFSU2FhYWFhYWFhVFVWV1hZWlthXF1hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFeYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhX2BhC0HhJw8LQaQhDwtByywPC0H+MQ8LQcAkDwtBqyQPC0GNKA8LQeImDwtBgDAPC0G5Lw8LQdckDwtB7x8PC0HhHw8LQfofDwtB8iAPC0GoLw8LQa4yDwtBiDAPC0HsJw8LQYIiDwtBjh0PC0HQLg8LQcojDwtBxTIPC0HfHA8LQdIcDwtBxCAPC0HXIA8LQaIfDwtB7S4PC0GrMA8LQdQlDwtBzC4PC0H6Lg8LQfwrDwtB0jAPC0HxHQ8LQbsgDwtB9ysPC0GQMQ8LQdcxDwtBoi0PC0HUJw8LQeArDwtBnywPC0HrMQ8LQdUfDwtByjEPC0HeJQ8LQdQeDwtB9BwPC0GnMg8LQbEdDwtBoB0PC0G5MQ8LQbwwDwtBkiEPC0GzJg8LQeksDwtBrB4PC0HUKw8LQfcmDwtBgCYPC0GwIQ8LQf4eDwtBjSMPC0GJLQ8LQfciDwtBoDEPC0GuHw8LQcYlDwtB6B4PC0GTIg8LQcIvDwtBwx0PC0GLLA8LQeEdDwtBjS8PC0HqIQ8LQbQtDwtB0i8PC0HfMg8LQdIyDwtB8DAPC0GpIg8LQfkjDwtBmR4PC0G1LA8LQZswDwtBkjIPC0G2Kw8LQcIiDwtB+DIPC0GeJQ8LQdAiDwtBuh4PC0GBHg8LAAtB1iEhAQsgAQsWACAAIAAtAC1B/gFxIAFBAEdyOgAtCxkAIAAgAC0ALUH9AXEgAUEAR0EBdHI6AC0LGQAgACAALQAtQfsBcSABQQBHQQJ0cjoALQsZACAAIAAtAC1B9wFxIAFBAEdBA3RyOgAtCz4BAn8CQCAAKAI4IgNFDQAgAygCBCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBxhE2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCCCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB9go2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCDCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB7Ro2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCECIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBlRA2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCFCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBqhs2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCGCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB7RM2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCKCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB9gg2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCHCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBwhk2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCICIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBlBQ2AhBBGCEECyAEC1kBAn8CQCAALQAoQQFGDQAgAC8BMiIBQeQAa0HkAEkNACABQcwBRg0AIAFBsAJGDQAgAC8BMCIAQcAAcQ0AQQEhAiAAQYgEcUGABEYNACAAQShxRSECCyACC4wBAQJ/AkACQAJAIAAtACpFDQAgAC0AK0UNACAALwEwIgFBAnFFDQEMAgsgAC8BMCIBQQFxRQ0BC0EBIQIgAC0AKEEBRg0AIAAvATIiAEHkAGtB5ABJDQAgAEHMAUYNACAAQbACRg0AIAFBwABxDQBBACECIAFBiARxQYAERg0AIAFBKHFBAEchAgsgAgtXACAAQRhqQgA3AwAgAEIANwMAIABBOGpCADcDACAAQTBqQgA3AwAgAEEoakIANwMAIABBIGpCADcDACAAQRBqQgA3AwAgAEEIakIANwMAIABB3QE2AhwLBgAgABAyC5otAQt/IwBBEGsiCiQAQaTQACgCACIJRQRAQeTTACgCACIFRQRAQfDTAEJ/NwIAQejTAEKAgISAgIDAADcCAEHk0wAgCkEIakFwcUHYqtWqBXMiBTYCAEH40wBBADYCAEHI0wBBADYCAAtBzNMAQYDUBDYCAEGc0ABBgNQENgIAQbDQACAFNgIAQazQAEF/NgIAQdDTAEGArAM2AgADQCABQcjQAGogAUG80ABqIgI2AgAgAiABQbTQAGoiAzYCACABQcDQAGogAzYCACABQdDQAGogAUHE0ABqIgM2AgAgAyACNgIAIAFB2NAAaiABQczQAGoiAjYCACACIAM2AgAgAUHU0ABqIAI2AgAgAUEgaiIBQYACRw0AC0GM1ARBwasDNgIAQajQAEH00wAoAgA2AgBBmNAAQcCrAzYCAEGk0ABBiNQENgIAQcz/B0E4NgIAQYjUBCEJCwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABB7AFNBEBBjNAAKAIAIgZBECAAQRNqQXBxIABBC0kbIgRBA3YiAHYiAUEDcQRAAkAgAUEBcSAAckEBcyICQQN0IgBBtNAAaiIBIABBvNAAaigCACIAKAIIIgNGBEBBjNAAIAZBfiACd3E2AgAMAQsgASADNgIIIAMgATYCDAsgAEEIaiEBIAAgAkEDdCICQQNyNgIEIAAgAmoiACAAKAIEQQFyNgIEDBELQZTQACgCACIIIARPDQEgAQRAAkBBAiAAdCICQQAgAmtyIAEgAHRxaCIAQQN0IgJBtNAAaiIBIAJBvNAAaigCACICKAIIIgNGBEBBjNAAIAZBfiAAd3EiBjYCAAwBCyABIAM2AgggAyABNgIMCyACIARBA3I2AgQgAEEDdCIAIARrIQUgACACaiAFNgIAIAIgBGoiBCAFQQFyNgIEIAgEQCAIQXhxQbTQAGohAEGg0AAoAgAhAwJ/QQEgCEEDdnQiASAGcUUEQEGM0AAgASAGcjYCACAADAELIAAoAggLIgEgAzYCDCAAIAM2AgggAyAANgIMIAMgATYCCAsgAkEIaiEBQaDQACAENgIAQZTQACAFNgIADBELQZDQACgCACILRQ0BIAtoQQJ0QbzSAGooAgAiACgCBEF4cSAEayEFIAAhAgNAAkAgAigCECIBRQRAIAJBFGooAgAiAUUNAQsgASgCBEF4cSAEayIDIAVJIQIgAyAFIAIbIQUgASAAIAIbIQAgASECDAELCyAAKAIYIQkgACgCDCIDIABHBEBBnNAAKAIAGiADIAAoAggiATYCCCABIAM2AgwMEAsgAEEUaiICKAIAIgFFBEAgACgCECIBRQ0DIABBEGohAgsDQCACIQcgASIDQRRqIgIoAgAiAQ0AIANBEGohAiADKAIQIgENAAsgB0EANgIADA8LQX8hBCAAQb9/Sw0AIABBE2oiAUFwcSEEQZDQACgCACIIRQ0AQQAgBGshBQJAAkACQAJ/QQAgBEGAAkkNABpBHyAEQf///wdLDQAaIARBJiABQQh2ZyIAa3ZBAXEgAEEBdGtBPmoLIgZBAnRBvNIAaigCACICRQRAQQAhAUEAIQMMAQtBACEBIARBGSAGQQF2a0EAIAZBH0cbdCEAQQAhAwNAAkAgAigCBEF4cSAEayIHIAVPDQAgAiEDIAciBQ0AQQAhBSACIQEMAwsgASACQRRqKAIAIgcgByACIABBHXZBBHFqQRBqKAIAIgJGGyABIAcbIQEgAEEBdCEAIAINAAsLIAEgA3JFBEBBACEDQQIgBnQiAEEAIABrciAIcSIARQ0DIABoQQJ0QbzSAGooAgAhAQsgAUUNAQsDQCABKAIEQXhxIARrIgIgBUkhACACIAUgABshBSABIAMgABshAyABKAIQIgAEfyAABSABQRRqKAIACyIBDQALCyADRQ0AIAVBlNAAKAIAIARrTw0AIAMoAhghByADIAMoAgwiAEcEQEGc0AAoAgAaIAAgAygCCCIBNgIIIAEgADYCDAwOCyADQRRqIgIoAgAiAUUEQCADKAIQIgFFDQMgA0EQaiECCwNAIAIhBiABIgBBFGoiAigCACIBDQAgAEEQaiECIAAoAhAiAQ0ACyAGQQA2AgAMDQtBlNAAKAIAIgMgBE8EQEGg0AAoAgAhAQJAIAMgBGsiAkEQTwRAIAEgBGoiACACQQFyNgIEIAEgA2ogAjYCACABIARBA3I2AgQMAQsgASADQQNyNgIEIAEgA2oiACAAKAIEQQFyNgIEQQAhAEEAIQILQZTQACACNgIAQaDQACAANgIAIAFBCGohAQwPC0GY0AAoAgAiAyAESwRAIAQgCWoiACADIARrIgFBAXI2AgRBpNAAIAA2AgBBmNAAIAE2AgAgCSAEQQNyNgIEIAlBCGohAQwPC0EAIQEgBAJ/QeTTACgCAARAQezTACgCAAwBC0Hw0wBCfzcCAEHo0wBCgICEgICAwAA3AgBB5NMAIApBDGpBcHFB2KrVqgVzNgIAQfjTAEEANgIAQcjTAEEANgIAQYCABAsiACAEQccAaiIFaiIGQQAgAGsiB3EiAk8EQEH80wBBMDYCAAwPCwJAQcTTACgCACIBRQ0AQbzTACgCACIIIAJqIQAgACABTSAAIAhLcQ0AQQAhAUH80wBBMDYCAAwPC0HI0wAtAABBBHENBAJAAkAgCQRAQczTACEBA0AgASgCACIAIAlNBEAgACABKAIEaiAJSw0DCyABKAIIIgENAAsLQQAQMyIAQX9GDQUgAiEGQejTACgCACIBQQFrIgMgAHEEQCACIABrIAAgA2pBACABa3FqIQYLIAQgBk8NBSAGQf7///8HSw0FQcTTACgCACIDBEBBvNMAKAIAIgcgBmohASABIAdNDQYgASADSw0GCyAGEDMiASAARw0BDAcLIAYgA2sgB3EiBkH+////B0sNBCAGEDMhACAAIAEoAgAgASgCBGpGDQMgACEBCwJAIAYgBEHIAGpPDQAgAUF/Rg0AQezTACgCACIAIAUgBmtqQQAgAGtxIgBB/v///wdLBEAgASEADAcLIAAQM0F/RwRAIAAgBmohBiABIQAMBwtBACAGaxAzGgwECyABIgBBf0cNBQwDC0EAIQMMDAtBACEADAoLIABBf0cNAgtByNMAQcjTACgCAEEEcjYCAAsgAkH+////B0sNASACEDMhAEEAEDMhASAAQX9GDQEgAUF/Rg0BIAAgAU8NASABIABrIgYgBEE4ak0NAQtBvNMAQbzTACgCACAGaiIBNgIAQcDTACgCACABSQRAQcDTACABNgIACwJAAkACQEGk0AAoAgAiAgRAQczTACEBA0AgACABKAIAIgMgASgCBCIFakYNAiABKAIIIgENAAsMAgtBnNAAKAIAIgFBAEcgACABT3FFBEBBnNAAIAA2AgALQQAhAUHQ0wAgBjYCAEHM0wAgADYCAEGs0ABBfzYCAEGw0ABB5NMAKAIANgIAQdjTAEEANgIAA0AgAUHI0ABqIAFBvNAAaiICNgIAIAIgAUG00ABqIgM2AgAgAUHA0ABqIAM2AgAgAUHQ0ABqIAFBxNAAaiIDNgIAIAMgAjYCACABQdjQAGogAUHM0ABqIgI2AgAgAiADNgIAIAFB1NAAaiACNgIAIAFBIGoiAUGAAkcNAAtBeCAAa0EPcSIBIABqIgIgBkE4ayIDIAFrIgFBAXI2AgRBqNAAQfTTACgCADYCAEGY0AAgATYCAEGk0AAgAjYCACAAIANqQTg2AgQMAgsgACACTQ0AIAIgA0kNACABKAIMQQhxDQBBeCACa0EPcSIAIAJqIgNBmNAAKAIAIAZqIgcgAGsiAEEBcjYCBCABIAUgBmo2AgRBqNAAQfTTACgCADYCAEGY0AAgADYCAEGk0AAgAzYCACACIAdqQTg2AgQMAQsgAEGc0AAoAgBJBEBBnNAAIAA2AgALIAAgBmohA0HM0wAhAQJAAkACQANAIAMgASgCAEcEQCABKAIIIgENAQwCCwsgAS0ADEEIcUUNAQtBzNMAIQEDQCABKAIAIgMgAk0EQCADIAEoAgRqIgUgAksNAwsgASgCCCEBDAALAAsgASAANgIAIAEgASgCBCAGajYCBCAAQXggAGtBD3FqIgkgBEEDcjYCBCADQXggA2tBD3FqIgYgBCAJaiIEayEBIAIgBkYEQEGk0AAgBDYCAEGY0ABBmNAAKAIAIAFqIgA2AgAgBCAAQQFyNgIEDAgLQaDQACgCACAGRgRAQaDQACAENgIAQZTQAEGU0AAoAgAgAWoiADYCACAEIABBAXI2AgQgACAEaiAANgIADAgLIAYoAgQiBUEDcUEBRw0GIAVBeHEhCCAFQf8BTQRAIAVBA3YhAyAGKAIIIgAgBigCDCICRgRAQYzQAEGM0AAoAgBBfiADd3E2AgAMBwsgAiAANgIIIAAgAjYCDAwGCyAGKAIYIQcgBiAGKAIMIgBHBEAgACAGKAIIIgI2AgggAiAANgIMDAULIAZBFGoiAigCACIFRQRAIAYoAhAiBUUNBCAGQRBqIQILA0AgAiEDIAUiAEEUaiICKAIAIgUNACAAQRBqIQIgACgCECIFDQALIANBADYCAAwEC0F4IABrQQ9xIgEgAGoiByAGQThrIgMgAWsiAUEBcjYCBCAAIANqQTg2AgQgAiAFQTcgBWtBD3FqQT9rIgMgAyACQRBqSRsiA0EjNgIEQajQAEH00wAoAgA2AgBBmNAAIAE2AgBBpNAAIAc2AgAgA0EQakHU0wApAgA3AgAgA0HM0wApAgA3AghB1NMAIANBCGo2AgBB0NMAIAY2AgBBzNMAIAA2AgBB2NMAQQA2AgAgA0EkaiEBA0AgAUEHNgIAIAUgAUEEaiIBSw0ACyACIANGDQAgAyADKAIEQX5xNgIEIAMgAyACayIFNgIAIAIgBUEBcjYCBCAFQf8BTQRAIAVBeHFBtNAAaiEAAn9BjNAAKAIAIgFBASAFQQN2dCIDcUUEQEGM0AAgASADcjYCACAADAELIAAoAggLIgEgAjYCDCAAIAI2AgggAiAANgIMIAIgATYCCAwBC0EfIQEgBUH///8HTQRAIAVBJiAFQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAQsgAiABNgIcIAJCADcCECABQQJ0QbzSAGohAEGQ0AAoAgAiA0EBIAF0IgZxRQRAIAAgAjYCAEGQ0AAgAyAGcjYCACACIAA2AhggAiACNgIIIAIgAjYCDAwBCyAFQRkgAUEBdmtBACABQR9HG3QhASAAKAIAIQMCQANAIAMiACgCBEF4cSAFRg0BIAFBHXYhAyABQQF0IQEgACADQQRxakEQaiIGKAIAIgMNAAsgBiACNgIAIAIgADYCGCACIAI2AgwgAiACNgIIDAELIAAoAggiASACNgIMIAAgAjYCCCACQQA2AhggAiAANgIMIAIgATYCCAtBmNAAKAIAIgEgBE0NAEGk0AAoAgAiACAEaiICIAEgBGsiAUEBcjYCBEGY0AAgATYCAEGk0AAgAjYCACAAIARBA3I2AgQgAEEIaiEBDAgLQQAhAUH80wBBMDYCAAwHC0EAIQALIAdFDQACQCAGKAIcIgJBAnRBvNIAaiIDKAIAIAZGBEAgAyAANgIAIAANAUGQ0ABBkNAAKAIAQX4gAndxNgIADAILIAdBEEEUIAcoAhAgBkYbaiAANgIAIABFDQELIAAgBzYCGCAGKAIQIgIEQCAAIAI2AhAgAiAANgIYCyAGQRRqKAIAIgJFDQAgAEEUaiACNgIAIAIgADYCGAsgASAIaiEBIAYgCGoiBigCBCEFCyAGIAVBfnE2AgQgASAEaiABNgIAIAQgAUEBcjYCBCABQf8BTQRAIAFBeHFBtNAAaiEAAn9BjNAAKAIAIgJBASABQQN2dCIBcUUEQEGM0AAgASACcjYCACAADAELIAAoAggLIgEgBDYCDCAAIAQ2AgggBCAANgIMIAQgATYCCAwBC0EfIQUgAUH///8HTQRAIAFBJiABQQh2ZyIAa3ZBAXEgAEEBdGtBPmohBQsgBCAFNgIcIARCADcCECAFQQJ0QbzSAGohAEGQ0AAoAgAiAkEBIAV0IgNxRQRAIAAgBDYCAEGQ0AAgAiADcjYCACAEIAA2AhggBCAENgIIIAQgBDYCDAwBCyABQRkgBUEBdmtBACAFQR9HG3QhBSAAKAIAIQACQANAIAAiAigCBEF4cSABRg0BIAVBHXYhACAFQQF0IQUgAiAAQQRxakEQaiIDKAIAIgANAAsgAyAENgIAIAQgAjYCGCAEIAQ2AgwgBCAENgIIDAELIAIoAggiACAENgIMIAIgBDYCCCAEQQA2AhggBCACNgIMIAQgADYCCAsgCUEIaiEBDAILAkAgB0UNAAJAIAMoAhwiAUECdEG80gBqIgIoAgAgA0YEQCACIAA2AgAgAA0BQZDQACAIQX4gAXdxIgg2AgAMAgsgB0EQQRQgBygCECADRhtqIAA2AgAgAEUNAQsgACAHNgIYIAMoAhAiAQRAIAAgATYCECABIAA2AhgLIANBFGooAgAiAUUNACAAQRRqIAE2AgAgASAANgIYCwJAIAVBD00EQCADIAQgBWoiAEEDcjYCBCAAIANqIgAgACgCBEEBcjYCBAwBCyADIARqIgIgBUEBcjYCBCADIARBA3I2AgQgAiAFaiAFNgIAIAVB/wFNBEAgBUF4cUG00ABqIQACf0GM0AAoAgAiAUEBIAVBA3Z0IgVxRQRAQYzQACABIAVyNgIAIAAMAQsgACgCCAsiASACNgIMIAAgAjYCCCACIAA2AgwgAiABNgIIDAELQR8hASAFQf///wdNBEAgBUEmIAVBCHZnIgBrdkEBcSAAQQF0a0E+aiEBCyACIAE2AhwgAkIANwIQIAFBAnRBvNIAaiEAQQEgAXQiBCAIcUUEQCAAIAI2AgBBkNAAIAQgCHI2AgAgAiAANgIYIAIgAjYCCCACIAI2AgwMAQsgBUEZIAFBAXZrQQAgAUEfRxt0IQEgACgCACEEAkADQCAEIgAoAgRBeHEgBUYNASABQR12IQQgAUEBdCEBIAAgBEEEcWpBEGoiBigCACIEDQALIAYgAjYCACACIAA2AhggAiACNgIMIAIgAjYCCAwBCyAAKAIIIgEgAjYCDCAAIAI2AgggAkEANgIYIAIgADYCDCACIAE2AggLIANBCGohAQwBCwJAIAlFDQACQCAAKAIcIgFBAnRBvNIAaiICKAIAIABGBEAgAiADNgIAIAMNAUGQ0AAgC0F+IAF3cTYCAAwCCyAJQRBBFCAJKAIQIABGG2ogAzYCACADRQ0BCyADIAk2AhggACgCECIBBEAgAyABNgIQIAEgAzYCGAsgAEEUaigCACIBRQ0AIANBFGogATYCACABIAM2AhgLAkAgBUEPTQRAIAAgBCAFaiIBQQNyNgIEIAAgAWoiASABKAIEQQFyNgIEDAELIAAgBGoiByAFQQFyNgIEIAAgBEEDcjYCBCAFIAdqIAU2AgAgCARAIAhBeHFBtNAAaiEBQaDQACgCACEDAn9BASAIQQN2dCICIAZxRQRAQYzQACACIAZyNgIAIAEMAQsgASgCCAsiAiADNgIMIAEgAzYCCCADIAE2AgwgAyACNgIIC0Gg0AAgBzYCAEGU0AAgBTYCAAsgAEEIaiEBCyAKQRBqJAAgAQtDACAARQRAPwBBEHQPCwJAIABB//8DcQ0AIABBAEgNACAAQRB2QAAiAEF/RgRAQfzTAEEwNgIAQX8PCyAAQRB0DwsACwvcPyIAQYAICwkBAAAAAgAAAAMAQZQICwUEAAAABQBBpAgLCQYAAAAHAAAACABB3AgLii1JbnZhbGlkIGNoYXIgaW4gdXJsIHF1ZXJ5AFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fYm9keQBDb250ZW50LUxlbmd0aCBvdmVyZmxvdwBDaHVuayBzaXplIG92ZXJmbG93AFJlc3BvbnNlIG92ZXJmbG93AEludmFsaWQgbWV0aG9kIGZvciBIVFRQL3gueCByZXF1ZXN0AEludmFsaWQgbWV0aG9kIGZvciBSVFNQL3gueCByZXF1ZXN0AEV4cGVjdGVkIFNPVVJDRSBtZXRob2QgZm9yIElDRS94LnggcmVxdWVzdABJbnZhbGlkIGNoYXIgaW4gdXJsIGZyYWdtZW50IHN0YXJ0AEV4cGVjdGVkIGRvdABTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3N0YXR1cwBJbnZhbGlkIHJlc3BvbnNlIHN0YXR1cwBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zAFVzZXIgY2FsbGJhY2sgZXJyb3IAYG9uX3Jlc2V0YCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfaGVhZGVyYCBjYWxsYmFjayBlcnJvcgBgb25fbWVzc2FnZV9iZWdpbmAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3N0YXR1c19jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX3ZlcnNpb25fY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl91cmxfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX2hlYWRlcl92YWx1ZV9jb21wbGV0ZWAgY2FsbGJhY2sgZXJyb3IAYG9uX21lc3NhZ2VfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXRob2RfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9oZWFkZXJfZmllbGRfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19leHRlbnNpb25fbmFtZWAgY2FsbGJhY2sgZXJyb3IAVW5leHBlY3RlZCBjaGFyIGluIHVybCBzZXJ2ZXIASW52YWxpZCBoZWFkZXIgdmFsdWUgY2hhcgBJbnZhbGlkIGhlYWRlciBmaWVsZCBjaGFyAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fdmVyc2lvbgBJbnZhbGlkIG1pbm9yIHZlcnNpb24ASW52YWxpZCBtYWpvciB2ZXJzaW9uAEV4cGVjdGVkIHNwYWNlIGFmdGVyIHZlcnNpb24ARXhwZWN0ZWQgQ1JMRiBhZnRlciB2ZXJzaW9uAEludmFsaWQgSFRUUCB2ZXJzaW9uAEludmFsaWQgaGVhZGVyIHRva2VuAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fdXJsAEludmFsaWQgY2hhcmFjdGVycyBpbiB1cmwAVW5leHBlY3RlZCBzdGFydCBjaGFyIGluIHVybABEb3VibGUgQCBpbiB1cmwARW1wdHkgQ29udGVudC1MZW5ndGgASW52YWxpZCBjaGFyYWN0ZXIgaW4gQ29udGVudC1MZW5ndGgARHVwbGljYXRlIENvbnRlbnQtTGVuZ3RoAEludmFsaWQgY2hhciBpbiB1cmwgcGF0aABDb250ZW50LUxlbmd0aCBjYW4ndCBiZSBwcmVzZW50IHdpdGggVHJhbnNmZXItRW5jb2RpbmcASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgc2l6ZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2hlYWRlcl92YWx1ZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2NodW5rX2V4dGVuc2lvbl92YWx1ZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIHZhbHVlAE1pc3NpbmcgZXhwZWN0ZWQgTEYgYWZ0ZXIgaGVhZGVyIHZhbHVlAEludmFsaWQgYFRyYW5zZmVyLUVuY29kaW5nYCBoZWFkZXIgdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBxdW90ZSB2YWx1ZQBJbnZhbGlkIGNoYXJhY3RlciBpbiBjaHVuayBleHRlbnNpb25zIHF1b3RlZCB2YWx1ZQBQYXVzZWQgYnkgb25faGVhZGVyc19jb21wbGV0ZQBJbnZhbGlkIEVPRiBzdGF0ZQBvbl9yZXNldCBwYXVzZQBvbl9jaHVua19oZWFkZXIgcGF1c2UAb25fbWVzc2FnZV9iZWdpbiBwYXVzZQBvbl9jaHVua19leHRlbnNpb25fdmFsdWUgcGF1c2UAb25fc3RhdHVzX2NvbXBsZXRlIHBhdXNlAG9uX3ZlcnNpb25fY29tcGxldGUgcGF1c2UAb25fdXJsX2NvbXBsZXRlIHBhdXNlAG9uX2NodW5rX2NvbXBsZXRlIHBhdXNlAG9uX2hlYWRlcl92YWx1ZV9jb21wbGV0ZSBwYXVzZQBvbl9tZXNzYWdlX2NvbXBsZXRlIHBhdXNlAG9uX21ldGhvZF9jb21wbGV0ZSBwYXVzZQBvbl9oZWFkZXJfZmllbGRfY29tcGxldGUgcGF1c2UAb25fY2h1bmtfZXh0ZW5zaW9uX25hbWUgcGF1c2UAVW5leHBlY3RlZCBzcGFjZSBhZnRlciBzdGFydCBsaW5lAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fY2h1bmtfZXh0ZW5zaW9uX25hbWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBuYW1lAFBhdXNlIG9uIENPTk5FQ1QvVXBncmFkZQBQYXVzZSBvbiBQUkkvVXBncmFkZQBFeHBlY3RlZCBIVFRQLzIgQ29ubmVjdGlvbiBQcmVmYWNlAFNwYW4gY2FsbGJhY2sgZXJyb3IgaW4gb25fbWV0aG9kAEV4cGVjdGVkIHNwYWNlIGFmdGVyIG1ldGhvZABTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2hlYWRlcl9maWVsZABQYXVzZWQASW52YWxpZCB3b3JkIGVuY291bnRlcmVkAEludmFsaWQgbWV0aG9kIGVuY291bnRlcmVkAFVuZXhwZWN0ZWQgY2hhciBpbiB1cmwgc2NoZW1hAFJlcXVlc3QgaGFzIGludmFsaWQgYFRyYW5zZmVyLUVuY29kaW5nYABTV0lUQ0hfUFJPWFkAVVNFX1BST1hZAE1LQUNUSVZJVFkAVU5QUk9DRVNTQUJMRV9FTlRJVFkAQ09QWQBNT1ZFRF9QRVJNQU5FTlRMWQBUT09fRUFSTFkATk9USUZZAEZBSUxFRF9ERVBFTkRFTkNZAEJBRF9HQVRFV0FZAFBMQVkAUFVUAENIRUNLT1VUAEdBVEVXQVlfVElNRU9VVABSRVFVRVNUX1RJTUVPVVQATkVUV09SS19DT05ORUNUX1RJTUVPVVQAQ09OTkVDVElPTl9USU1FT1VUAExPR0lOX1RJTUVPVVQATkVUV09SS19SRUFEX1RJTUVPVVQAUE9TVABNSVNESVJFQ1RFRF9SRVFVRVNUAENMSUVOVF9DTE9TRURfUkVRVUVTVABDTElFTlRfQ0xPU0VEX0xPQURfQkFMQU5DRURfUkVRVUVTVABCQURfUkVRVUVTVABIVFRQX1JFUVVFU1RfU0VOVF9UT19IVFRQU19QT1JUAFJFUE9SVABJTV9BX1RFQVBPVABSRVNFVF9DT05URU5UAE5PX0NPTlRFTlQAUEFSVElBTF9DT05URU5UAEhQRV9JTlZBTElEX0NPTlNUQU5UAEhQRV9DQl9SRVNFVABHRVQASFBFX1NUUklDVABDT05GTElDVABURU1QT1JBUllfUkVESVJFQ1QAUEVSTUFORU5UX1JFRElSRUNUAENPTk5FQ1QATVVMVElfU1RBVFVTAEhQRV9JTlZBTElEX1NUQVRVUwBUT09fTUFOWV9SRVFVRVNUUwBFQVJMWV9ISU5UUwBVTkFWQUlMQUJMRV9GT1JfTEVHQUxfUkVBU09OUwBPUFRJT05TAFNXSVRDSElOR19QUk9UT0NPTFMAVkFSSUFOVF9BTFNPX05FR09USUFURVMATVVMVElQTEVfQ0hPSUNFUwBJTlRFUk5BTF9TRVJWRVJfRVJST1IAV0VCX1NFUlZFUl9VTktOT1dOX0VSUk9SAFJBSUxHVU5fRVJST1IASURFTlRJVFlfUFJPVklERVJfQVVUSEVOVElDQVRJT05fRVJST1IAU1NMX0NFUlRJRklDQVRFX0VSUk9SAElOVkFMSURfWF9GT1JXQVJERURfRk9SAFNFVF9QQVJBTUVURVIAR0VUX1BBUkFNRVRFUgBIUEVfVVNFUgBTRUVfT1RIRVIASFBFX0NCX0NIVU5LX0hFQURFUgBNS0NBTEVOREFSAFNFVFVQAFdFQl9TRVJWRVJfSVNfRE9XTgBURUFSRE9XTgBIUEVfQ0xPU0VEX0NPTk5FQ1RJT04ASEVVUklTVElDX0VYUElSQVRJT04ARElTQ09OTkVDVEVEX09QRVJBVElPTgBOT05fQVVUSE9SSVRBVElWRV9JTkZPUk1BVElPTgBIUEVfSU5WQUxJRF9WRVJTSU9OAEhQRV9DQl9NRVNTQUdFX0JFR0lOAFNJVEVfSVNfRlJPWkVOAEhQRV9JTlZBTElEX0hFQURFUl9UT0tFTgBJTlZBTElEX1RPS0VOAEZPUkJJRERFTgBFTkhBTkNFX1lPVVJfQ0FMTQBIUEVfSU5WQUxJRF9VUkwAQkxPQ0tFRF9CWV9QQVJFTlRBTF9DT05UUk9MAE1LQ09MAEFDTABIUEVfSU5URVJOQUwAUkVRVUVTVF9IRUFERVJfRklFTERTX1RPT19MQVJHRV9VTk9GRklDSUFMAEhQRV9PSwBVTkxJTksAVU5MT0NLAFBSSQBSRVRSWV9XSVRIAEhQRV9JTlZBTElEX0NPTlRFTlRfTEVOR1RIAEhQRV9VTkVYUEVDVEVEX0NPTlRFTlRfTEVOR1RIAEZMVVNIAFBST1BQQVRDSABNLVNFQVJDSABVUklfVE9PX0xPTkcAUFJPQ0VTU0lORwBNSVNDRUxMQU5FT1VTX1BFUlNJU1RFTlRfV0FSTklORwBNSVNDRUxMQU5FT1VTX1dBUk5JTkcASFBFX0lOVkFMSURfVFJBTlNGRVJfRU5DT0RJTkcARXhwZWN0ZWQgQ1JMRgBIUEVfSU5WQUxJRF9DSFVOS19TSVpFAE1PVkUAQ09OVElOVUUASFBFX0NCX1NUQVRVU19DT01QTEVURQBIUEVfQ0JfSEVBREVSU19DT01QTEVURQBIUEVfQ0JfVkVSU0lPTl9DT01QTEVURQBIUEVfQ0JfVVJMX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19DT01QTEVURQBIUEVfQ0JfSEVBREVSX1ZBTFVFX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19FWFRFTlNJT05fVkFMVUVfQ09NUExFVEUASFBFX0NCX0NIVU5LX0VYVEVOU0lPTl9OQU1FX0NPTVBMRVRFAEhQRV9DQl9NRVNTQUdFX0NPTVBMRVRFAEhQRV9DQl9NRVRIT0RfQ09NUExFVEUASFBFX0NCX0hFQURFUl9GSUVMRF9DT01QTEVURQBERUxFVEUASFBFX0lOVkFMSURfRU9GX1NUQVRFAElOVkFMSURfU1NMX0NFUlRJRklDQVRFAFBBVVNFAE5PX1JFU1BPTlNFAFVOU1VQUE9SVEVEX01FRElBX1RZUEUAR09ORQBOT1RfQUNDRVBUQUJMRQBTRVJWSUNFX1VOQVZBSUxBQkxFAFJBTkdFX05PVF9TQVRJU0ZJQUJMRQBPUklHSU5fSVNfVU5SRUFDSEFCTEUAUkVTUE9OU0VfSVNfU1RBTEUAUFVSR0UATUVSR0UAUkVRVUVTVF9IRUFERVJfRklFTERTX1RPT19MQVJHRQBSRVFVRVNUX0hFQURFUl9UT09fTEFSR0UAUEFZTE9BRF9UT09fTEFSR0UASU5TVUZGSUNJRU5UX1NUT1JBR0UASFBFX1BBVVNFRF9VUEdSQURFAEhQRV9QQVVTRURfSDJfVVBHUkFERQBTT1VSQ0UAQU5OT1VOQ0UAVFJBQ0UASFBFX1VORVhQRUNURURfU1BBQ0UAREVTQ1JJQkUAVU5TVUJTQ1JJQkUAUkVDT1JEAEhQRV9JTlZBTElEX01FVEhPRABOT1RfRk9VTkQAUFJPUEZJTkQAVU5CSU5EAFJFQklORABVTkFVVEhPUklaRUQATUVUSE9EX05PVF9BTExPV0VEAEhUVFBfVkVSU0lPTl9OT1RfU1VQUE9SVEVEAEFMUkVBRFlfUkVQT1JURUQAQUNDRVBURUQATk9UX0lNUExFTUVOVEVEAExPT1BfREVURUNURUQASFBFX0NSX0VYUEVDVEVEAEhQRV9MRl9FWFBFQ1RFRABDUkVBVEVEAElNX1VTRUQASFBFX1BBVVNFRABUSU1FT1VUX09DQ1VSRUQAUEFZTUVOVF9SRVFVSVJFRABQUkVDT05ESVRJT05fUkVRVUlSRUQAUFJPWFlfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQATkVUV09SS19BVVRIRU5USUNBVElPTl9SRVFVSVJFRABMRU5HVEhfUkVRVUlSRUQAU1NMX0NFUlRJRklDQVRFX1JFUVVJUkVEAFVQR1JBREVfUkVRVUlSRUQAUEFHRV9FWFBJUkVEAFBSRUNPTkRJVElPTl9GQUlMRUQARVhQRUNUQVRJT05fRkFJTEVEAFJFVkFMSURBVElPTl9GQUlMRUQAU1NMX0hBTkRTSEFLRV9GQUlMRUQATE9DS0VEAFRSQU5TRk9STUFUSU9OX0FQUExJRUQATk9UX01PRElGSUVEAE5PVF9FWFRFTkRFRABCQU5EV0lEVEhfTElNSVRfRVhDRUVERUQAU0lURV9JU19PVkVSTE9BREVEAEhFQUQARXhwZWN0ZWQgSFRUUC8AAF4TAAAmEwAAMBAAAPAXAACdEwAAFRIAADkXAADwEgAAChAAAHUSAACtEgAAghMAAE8UAAB/EAAAoBUAACMUAACJEgAAixQAAE0VAADUEQAAzxQAABAYAADJFgAA3BYAAMERAADgFwAAuxQAAHQUAAB8FQAA5RQAAAgXAAAfEAAAZRUAAKMUAAAoFQAAAhUAAJkVAAAsEAAAixkAAE8PAADUDgAAahAAAM4QAAACFwAAiQ4AAG4TAAAcEwAAZhQAAFYXAADBEwAAzRMAAGwTAABoFwAAZhcAAF8XAAAiEwAAzg8AAGkOAADYDgAAYxYAAMsTAACqDgAAKBcAACYXAADFEwAAXRYAAOgRAABnEwAAZRMAAPIWAABzEwAAHRcAAPkWAADzEQAAzw4AAM4VAAAMEgAAsxEAAKURAABhEAAAMhcAALsTAEH5NQsBAQBBkDYL4AEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBB/TcLAQEAQZE4C14CAwICAgICAAACAgACAgACAgICAgICAgICAAQAAAAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgACAEH9OQsBAQBBkToLXgIAAgICAgIAAAICAAICAAICAgICAgICAgIAAwAEAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgIAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgICAgACAAIAQfA7Cw1sb3NlZWVwLWFsaXZlAEGJPAsBAQBBoDwL4AEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBBiT4LAQEAQaA+C+cBAQEBAQEBAQEBAQEBAgEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQFjaHVua2VkAEGwwAALXwEBAAEBAQEBAAABAQABAQABAQEBAQEBAQEBAAAAAAAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQABAEGQwgALIWVjdGlvbmVudC1sZW5ndGhvbnJveHktY29ubmVjdGlvbgBBwMIACy1yYW5zZmVyLWVuY29kaW5ncGdyYWRlDQoNCg0KU00NCg0KVFRQL0NFL1RTUC8AQfnCAAsFAQIAAQMAQZDDAAvgAQQBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAEH5xAALBQECAAEDAEGQxQAL4AEEAQEFAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBB+cYACwQBAAABAEGRxwAL3wEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAEH6yAALBAEAAAIAQZDJAAtfAwQAAAQEBAQEBAQEBAQEBQQEBAQEBAQEBAQEBAAEAAYHBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQABAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAAAAQAQfrKAAsEAQAAAQBBkMsACwEBAEGqywALQQIAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAEH6zAALBAEAAAEAQZDNAAsBAQBBms0ACwYCAAAAAAIAQbHNAAs6AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBB8M4AC5YBTk9VTkNFRUNLT1VUTkVDVEVURUNSSUJFTFVTSEVURUFEU0VBUkNIUkdFQ1RJVklUWUxFTkRBUlZFT1RJRllQVElPTlNDSFNFQVlTVEFUQ0hHRU9SRElSRUNUT1JUUkNIUEFSQU1FVEVSVVJDRUJTQ1JJQkVBUkRPV05BQ0VJTkROS0NLVUJTQ1JJQkVIVFRQL0FEVFAv', 'base64')\n","'use strict'\n\nconst { Buffer } = require('node:buffer')\n\nmodule.exports = Buffer.from('AGFzbQEAAAABJwdgAX8Bf2ADf39/AX9gAX8AYAJ/fwBgBH9/f38Bf2AAAGADf39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQAEA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAAy0sBQYAAAIAAAAAAAACAQIAAgICAAADAAAAAAMDAwMBAQEBAQEBAQEAAAIAAAAEBQFwARISBQMBAAIGCAF/AUGA1AQLB9EFIgZtZW1vcnkCAAtfaW5pdGlhbGl6ZQAIGV9faW5kaXJlY3RfZnVuY3Rpb25fdGFibGUBAAtsbGh0dHBfaW5pdAAJGGxsaHR0cF9zaG91bGRfa2VlcF9hbGl2ZQAvDGxsaHR0cF9hbGxvYwALBm1hbGxvYwAxC2xsaHR0cF9mcmVlAAwEZnJlZQAMD2xsaHR0cF9nZXRfdHlwZQANFWxsaHR0cF9nZXRfaHR0cF9tYWpvcgAOFWxsaHR0cF9nZXRfaHR0cF9taW5vcgAPEWxsaHR0cF9nZXRfbWV0aG9kABAWbGxodHRwX2dldF9zdGF0dXNfY29kZQAREmxsaHR0cF9nZXRfdXBncmFkZQASDGxsaHR0cF9yZXNldAATDmxsaHR0cF9leGVjdXRlABQUbGxodHRwX3NldHRpbmdzX2luaXQAFQ1sbGh0dHBfZmluaXNoABYMbGxodHRwX3BhdXNlABcNbGxodHRwX3Jlc3VtZQAYG2xsaHR0cF9yZXN1bWVfYWZ0ZXJfdXBncmFkZQAZEGxsaHR0cF9nZXRfZXJybm8AGhdsbGh0dHBfZ2V0X2Vycm9yX3JlYXNvbgAbF2xsaHR0cF9zZXRfZXJyb3JfcmVhc29uABwUbGxodHRwX2dldF9lcnJvcl9wb3MAHRFsbGh0dHBfZXJybm9fbmFtZQAeEmxsaHR0cF9tZXRob2RfbmFtZQAfEmxsaHR0cF9zdGF0dXNfbmFtZQAgGmxsaHR0cF9zZXRfbGVuaWVudF9oZWFkZXJzACEhbGxodHRwX3NldF9sZW5pZW50X2NodW5rZWRfbGVuZ3RoACIdbGxodHRwX3NldF9sZW5pZW50X2tlZXBfYWxpdmUAIyRsbGh0dHBfc2V0X2xlbmllbnRfdHJhbnNmZXJfZW5jb2RpbmcAJBhsbGh0dHBfbWVzc2FnZV9uZWVkc19lb2YALgkXAQBBAQsRAQIDBAUKBgcrLSwqKSglJyYK77MCLBYAQYjQACgCAARAAAtBiNAAQQE2AgALFAAgABAwIAAgAjYCOCAAIAE6ACgLFAAgACAALwEyIAAtAC4gABAvEAALHgEBf0HAABAyIgEQMCABQYAINgI4IAEgADoAKCABC48MAQd/AkAgAEUNACAAQQhrIgEgAEEEaygCACIAQXhxIgRqIQUCQCAAQQFxDQAgAEEDcUUNASABIAEoAgAiAGsiAUGc0AAoAgBJDQEgACAEaiEEAkACQEGg0AAoAgAgAUcEQCAAQf8BTQRAIABBA3YhAyABKAIIIgAgASgCDCICRgRAQYzQAEGM0AAoAgBBfiADd3E2AgAMBQsgAiAANgIIIAAgAjYCDAwECyABKAIYIQYgASABKAIMIgBHBEAgACABKAIIIgI2AgggAiAANgIMDAMLIAFBFGoiAygCACICRQRAIAEoAhAiAkUNAiABQRBqIQMLA0AgAyEHIAIiAEEUaiIDKAIAIgINACAAQRBqIQMgACgCECICDQALIAdBADYCAAwCCyAFKAIEIgBBA3FBA0cNAiAFIABBfnE2AgRBlNAAIAQ2AgAgBSAENgIAIAEgBEEBcjYCBAwDC0EAIQALIAZFDQACQCABKAIcIgJBAnRBvNIAaiIDKAIAIAFGBEAgAyAANgIAIAANAUGQ0ABBkNAAKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgAUYbaiAANgIAIABFDQELIAAgBjYCGCABKAIQIgIEQCAAIAI2AhAgAiAANgIYCyABQRRqKAIAIgJFDQAgAEEUaiACNgIAIAIgADYCGAsgASAFTw0AIAUoAgQiAEEBcUUNAAJAAkACQAJAIABBAnFFBEBBpNAAKAIAIAVGBEBBpNAAIAE2AgBBmNAAQZjQACgCACAEaiIANgIAIAEgAEEBcjYCBCABQaDQACgCAEcNBkGU0ABBADYCAEGg0ABBADYCAAwGC0Gg0AAoAgAgBUYEQEGg0AAgATYCAEGU0ABBlNAAKAIAIARqIgA2AgAgASAAQQFyNgIEIAAgAWogADYCAAwGCyAAQXhxIARqIQQgAEH/AU0EQCAAQQN2IQMgBSgCCCIAIAUoAgwiAkYEQEGM0ABBjNAAKAIAQX4gA3dxNgIADAULIAIgADYCCCAAIAI2AgwMBAsgBSgCGCEGIAUgBSgCDCIARwRAQZzQACgCABogACAFKAIIIgI2AgggAiAANgIMDAMLIAVBFGoiAygCACICRQRAIAUoAhAiAkUNAiAFQRBqIQMLA0AgAyEHIAIiAEEUaiIDKAIAIgINACAAQRBqIQMgACgCECICDQALIAdBADYCAAwCCyAFIABBfnE2AgQgASAEaiAENgIAIAEgBEEBcjYCBAwDC0EAIQALIAZFDQACQCAFKAIcIgJBAnRBvNIAaiIDKAIAIAVGBEAgAyAANgIAIAANAUGQ0ABBkNAAKAIAQX4gAndxNgIADAILIAZBEEEUIAYoAhAgBUYbaiAANgIAIABFDQELIAAgBjYCGCAFKAIQIgIEQCAAIAI2AhAgAiAANgIYCyAFQRRqKAIAIgJFDQAgAEEUaiACNgIAIAIgADYCGAsgASAEaiAENgIAIAEgBEEBcjYCBCABQaDQACgCAEcNAEGU0AAgBDYCAAwBCyAEQf8BTQRAIARBeHFBtNAAaiEAAn9BjNAAKAIAIgJBASAEQQN2dCIDcUUEQEGM0AAgAiADcjYCACAADAELIAAoAggLIgIgATYCDCAAIAE2AgggASAANgIMIAEgAjYCCAwBC0EfIQIgBEH///8HTQRAIARBJiAEQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAgsgASACNgIcIAFCADcCECACQQJ0QbzSAGohAAJAQZDQACgCACIDQQEgAnQiB3FFBEAgACABNgIAQZDQACADIAdyNgIAIAEgADYCGCABIAE2AgggASABNgIMDAELIARBGSACQQF2a0EAIAJBH0cbdCECIAAoAgAhAAJAA0AgACIDKAIEQXhxIARGDQEgAkEddiEAIAJBAXQhAiADIABBBHFqQRBqIgcoAgAiAA0ACyAHIAE2AgAgASADNgIYIAEgATYCDCABIAE2AggMAQsgAygCCCIAIAE2AgwgAyABNgIIIAFBADYCGCABIAM2AgwgASAANgIIC0Gs0ABBrNAAKAIAQQFrIgBBfyAAGzYCAAsLBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LQAEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABAwIAAgBDYCOCAAIAM6ACggACACOgAtIAAgATYCGAu74gECB38DfiABIAJqIQQCQCAAIgIoAgwiAA0AIAIoAgQEQCACIAE2AgQLIwBBEGsiCCQAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAIoAhwiA0EBaw7dAdoBAdkBAgMEBQYHCAkKCwwNDtgBDxDXARES1gETFBUWFxgZGhvgAd8BHB0e1QEfICEiIyQl1AEmJygpKiss0wHSAS0u0QHQAS8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRtsBR0hJSs8BzgFLzQFMzAFNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AAYEBggGDAYQBhQGGAYcBiAGJAYoBiwGMAY0BjgGPAZABkQGSAZMBlAGVAZYBlwGYAZkBmgGbAZwBnQGeAZ8BoAGhAaIBowGkAaUBpgGnAagBqQGqAasBrAGtAa4BrwGwAbEBsgGzAbQBtQG2AbcBywHKAbgByQG5AcgBugG7AbwBvQG+Ab8BwAHBAcIBwwHEAcUBxgEA3AELQQAMxgELQQ4MxQELQQ0MxAELQQ8MwwELQRAMwgELQRMMwQELQRQMwAELQRUMvwELQRYMvgELQRgMvQELQRkMvAELQRoMuwELQRsMugELQRwMuQELQR0MuAELQQgMtwELQR4MtgELQSAMtQELQR8MtAELQQcMswELQSEMsgELQSIMsQELQSMMsAELQSQMrwELQRIMrgELQREMrQELQSUMrAELQSYMqwELQScMqgELQSgMqQELQcMBDKgBC0EqDKcBC0ErDKYBC0EsDKUBC0EtDKQBC0EuDKMBC0EvDKIBC0HEAQyhAQtBMAygAQtBNAyfAQtBDAyeAQtBMQydAQtBMgycAQtBMwybAQtBOQyaAQtBNQyZAQtBxQEMmAELQQsMlwELQToMlgELQTYMlQELQQoMlAELQTcMkwELQTgMkgELQTwMkQELQTsMkAELQT0MjwELQQkMjgELQSkMjQELQT4MjAELQT8MiwELQcAADIoBC0HBAAyJAQtBwgAMiAELQcMADIcBC0HEAAyGAQtBxQAMhQELQcYADIQBC0EXDIMBC0HHAAyCAQtByAAMgQELQckADIABC0HKAAx/C0HLAAx+C0HNAAx9C0HMAAx8C0HOAAx7C0HPAAx6C0HQAAx5C0HRAAx4C0HSAAx3C0HTAAx2C0HUAAx1C0HWAAx0C0HVAAxzC0EGDHILQdcADHELQQUMcAtB2AAMbwtBBAxuC0HZAAxtC0HaAAxsC0HbAAxrC0HcAAxqC0EDDGkLQd0ADGgLQd4ADGcLQd8ADGYLQeEADGULQeAADGQLQeIADGMLQeMADGILQQIMYQtB5AAMYAtB5QAMXwtB5gAMXgtB5wAMXQtB6AAMXAtB6QAMWwtB6gAMWgtB6wAMWQtB7AAMWAtB7QAMVwtB7gAMVgtB7wAMVQtB8AAMVAtB8QAMUwtB8gAMUgtB8wAMUQtB9AAMUAtB9QAMTwtB9gAMTgtB9wAMTQtB+AAMTAtB+QAMSwtB+gAMSgtB+wAMSQtB/AAMSAtB/QAMRwtB/gAMRgtB/wAMRQtBgAEMRAtBgQEMQwtBggEMQgtBgwEMQQtBhAEMQAtBhQEMPwtBhgEMPgtBhwEMPQtBiAEMPAtBiQEMOwtBigEMOgtBiwEMOQtBjAEMOAtBjQEMNwtBjgEMNgtBjwEMNQtBkAEMNAtBkQEMMwtBkgEMMgtBkwEMMQtBlAEMMAtBlQEMLwtBlgEMLgtBlwEMLQtBmAEMLAtBmQEMKwtBmgEMKgtBmwEMKQtBnAEMKAtBnQEMJwtBngEMJgtBnwEMJQtBoAEMJAtBoQEMIwtBogEMIgtBowEMIQtBpAEMIAtBpQEMHwtBpgEMHgtBpwEMHQtBqAEMHAtBqQEMGwtBqgEMGgtBqwEMGQtBrAEMGAtBrQEMFwtBrgEMFgtBAQwVC0GvAQwUC0GwAQwTC0GxAQwSC0GzAQwRC0GyAQwQC0G0AQwPC0G1AQwOC0G2AQwNC0G3AQwMC0G4AQwLC0G5AQwKC0G6AQwJC0G7AQwIC0HGAQwHC0G8AQwGC0G9AQwFC0G+AQwEC0G/AQwDC0HAAQwCC0HCAQwBC0HBAQshAwNAAkACQAJAAkACQAJAAkACQAJAIAICfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAgJ/AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACfwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACfwJAAkACQAJAAn8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCADDsYBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHyAhIyUmKCorLC8wMTIzNDU2Nzk6Ozw9lANAQkRFRklLTk9QUVJTVFVWWFpbXF1eX2BhYmNkZWZnaGpsb3Bxc3V2eHl6e3x/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAYsBjAGNAY4BjwGQAZEBkgGTAZQBlQGWAZcBmAGZAZoBmwGcAZ0BngGfAaABoQGiAaMBpAGlAaYBpwGoAakBqgGrAawBrQGuAa8BsAGxAbIBswG0AbUBtgG3AbgBuQG6AbsBvAG9Ab4BvwHAAcEBwgHDAcQBxQHGAccByAHJAcsBzAHNAc4BzwGKA4kDiAOHA4QDgwOAA/sC+gL5AvgC9wL0AvMC8gLLAsECsALZAQsgASAERw3wAkHdASEDDLMDCyABIARHDcgBQcMBIQMMsgMLIAEgBEcNe0H3ACEDDLEDCyABIARHDXBB7wAhAwywAwsgASAERw1pQeoAIQMMrwMLIAEgBEcNZUHoACEDDK4DCyABIARHDWJB5gAhAwytAwsgASAERw0aQRghAwysAwsgASAERw0VQRIhAwyrAwsgASAERw1CQcUAIQMMqgMLIAEgBEcNNEE/IQMMqQMLIAEgBEcNMkE8IQMMqAMLIAEgBEcNK0ExIQMMpwMLIAItAC5BAUYNnwMMwQILQQAhAAJAAkACQCACLQAqRQ0AIAItACtFDQAgAi8BMCIDQQJxRQ0BDAILIAIvATAiA0EBcUUNAQtBASEAIAItAChBAUYNACACLwEyIgVB5ABrQeQASQ0AIAVBzAFGDQAgBUGwAkYNACADQcAAcQ0AQQAhACADQYgEcUGABEYNACADQShxQQBHIQALIAJBADsBMCACQQA6AC8gAEUN3wIgAkIANwMgDOACC0EAIQACQCACKAI4IgNFDQAgAygCLCIDRQ0AIAIgAxEAACEACyAARQ3MASAAQRVHDd0CIAJBBDYCHCACIAE2AhQgAkGwGDYCECACQRU2AgxBACEDDKQDCyABIARGBEBBBiEDDKQDCyABQQFqIQFBACEAAkAgAigCOCIDRQ0AIAMoAlQiA0UNACACIAMRAAAhAAsgAA3ZAgwcCyACQgA3AyBBEiEDDIkDCyABIARHDRZBHSEDDKEDCyABIARHBEAgAUEBaiEBQRAhAwyIAwtBByEDDKADCyACIAIpAyAiCiAEIAFrrSILfSIMQgAgCiAMWhs3AyAgCiALWA3UAkEIIQMMnwMLIAEgBEcEQCACQQk2AgggAiABNgIEQRQhAwyGAwtBCSEDDJ4DCyACKQMgQgBSDccBIAIgAi8BMEGAAXI7ATAMQgsgASAERw0/QdAAIQMMnAMLIAEgBEYEQEELIQMMnAMLIAFBAWohAUEAIQACQCACKAI4IgNFDQAgAygCUCIDRQ0AIAIgAxEAACEACyAADc8CDMYBC0EAIQACQCACKAI4IgNFDQAgAygCSCIDRQ0AIAIgAxEAACEACyAARQ3GASAAQRVHDc0CIAJBCzYCHCACIAE2AhQgAkGCGTYCECACQRU2AgxBACEDDJoDC0EAIQACQCACKAI4IgNFDQAgAygCSCIDRQ0AIAIgAxEAACEACyAARQ0MIABBFUcNygIgAkEaNgIcIAIgATYCFCACQYIZNgIQIAJBFTYCDEEAIQMMmQMLQQAhAAJAIAIoAjgiA0UNACADKAJMIgNFDQAgAiADEQAAIQALIABFDcQBIABBFUcNxwIgAkELNgIcIAIgATYCFCACQZEXNgIQIAJBFTYCDEEAIQMMmAMLIAEgBEYEQEEPIQMMmAMLIAEtAAAiAEE7Rg0HIABBDUcNxAIgAUEBaiEBDMMBC0EAIQACQCACKAI4IgNFDQAgAygCTCIDRQ0AIAIgAxEAACEACyAARQ3DASAAQRVHDcICIAJBDzYCHCACIAE2AhQgAkGRFzYCECACQRU2AgxBACEDDJYDCwNAIAEtAABB8DVqLQAAIgBBAUcEQCAAQQJHDcECIAIoAgQhAEEAIQMgAkEANgIEIAIgACABQQFqIgEQLSIADcICDMUBCyAEIAFBAWoiAUcNAAtBEiEDDJUDC0EAIQACQCACKAI4IgNFDQAgAygCTCIDRQ0AIAIgAxEAACEACyAARQ3FASAAQRVHDb0CIAJBGzYCHCACIAE2AhQgAkGRFzYCECACQRU2AgxBACEDDJQDCyABIARGBEBBFiEDDJQDCyACQQo2AgggAiABNgIEQQAhAAJAIAIoAjgiA0UNACADKAJIIgNFDQAgAiADEQAAIQALIABFDcIBIABBFUcNuQIgAkEVNgIcIAIgATYCFCACQYIZNgIQIAJBFTYCDEEAIQMMkwMLIAEgBEcEQANAIAEtAABB8DdqLQAAIgBBAkcEQAJAIABBAWsOBMQCvQIAvgK9AgsgAUEBaiEBQQghAwz8AgsgBCABQQFqIgFHDQALQRUhAwyTAwtBFSEDDJIDCwNAIAEtAABB8DlqLQAAIgBBAkcEQCAAQQFrDgTFArcCwwK4ArcCCyAEIAFBAWoiAUcNAAtBGCEDDJEDCyABIARHBEAgAkELNgIIIAIgATYCBEEHIQMM+AILQRkhAwyQAwsgAUEBaiEBDAILIAEgBEYEQEEaIQMMjwMLAkAgAS0AAEENaw4UtQG/Ab8BvwG/Ab8BvwG/Ab8BvwG/Ab8BvwG/Ab8BvwG/Ab8BvwEAvwELQQAhAyACQQA2AhwgAkGvCzYCECACQQI2AgwgAiABQQFqNgIUDI4DCyABIARGBEBBGyEDDI4DCyABLQAAIgBBO0cEQCAAQQ1HDbECIAFBAWohAQy6AQsgAUEBaiEBC0EiIQMM8wILIAEgBEYEQEEcIQMMjAMLQgAhCgJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgAS0AAEEwaw43wQLAAgABAgMEBQYH0AHQAdAB0AHQAdAB0AEICQoLDA3QAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdAB0AHQAdABDg8QERIT0AELQgIhCgzAAgtCAyEKDL8CC0IEIQoMvgILQgUhCgy9AgtCBiEKDLwCC0IHIQoMuwILQgghCgy6AgtCCSEKDLkCC0IKIQoMuAILQgshCgy3AgtCDCEKDLYCC0INIQoMtQILQg4hCgy0AgtCDyEKDLMCC0IKIQoMsgILQgshCgyxAgtCDCEKDLACC0INIQoMrwILQg4hCgyuAgtCDyEKDK0CC0IAIQoCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAEtAABBMGsON8ACvwIAAQIDBAUGB74CvgK+Ar4CvgK+Ar4CCAkKCwwNvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ar4CvgK+Ag4PEBESE74CC0ICIQoMvwILQgMhCgy+AgtCBCEKDL0CC0IFIQoMvAILQgYhCgy7AgtCByEKDLoCC0IIIQoMuQILQgkhCgy4AgtCCiEKDLcCC0ILIQoMtgILQgwhCgy1AgtCDSEKDLQCC0IOIQoMswILQg8hCgyyAgtCCiEKDLECC0ILIQoMsAILQgwhCgyvAgtCDSEKDK4CC0IOIQoMrQILQg8hCgysAgsgAiACKQMgIgogBCABa60iC30iDEIAIAogDFobNwMgIAogC1gNpwJBHyEDDIkDCyABIARHBEAgAkEJNgIIIAIgATYCBEElIQMM8AILQSAhAwyIAwtBASEFIAIvATAiA0EIcUUEQCACKQMgQgBSIQULAkAgAi0ALgRAQQEhACACLQApQQVGDQEgA0HAAHFFIAVxRQ0BC0EAIQAgA0HAAHENAEECIQAgA0EIcQ0AIANBgARxBEACQCACLQAoQQFHDQAgAi0ALUEKcQ0AQQUhAAwCC0EEIQAMAQsgA0EgcUUEQAJAIAItAChBAUYNACACLwEyIgBB5ABrQeQASQ0AIABBzAFGDQAgAEGwAkYNAEEEIQAgA0EocUUNAiADQYgEcUGABEYNAgtBACEADAELQQBBAyACKQMgUBshAAsgAEEBaw4FvgIAsAEBpAKhAgtBESEDDO0CCyACQQE6AC8MhAMLIAEgBEcNnQJBJCEDDIQDCyABIARHDRxBxgAhAwyDAwtBACEAAkAgAigCOCIDRQ0AIAMoAkQiA0UNACACIAMRAAAhAAsgAEUNJyAAQRVHDZgCIAJB0AA2AhwgAiABNgIUIAJBkRg2AhAgAkEVNgIMQQAhAwyCAwsgASAERgRAQSghAwyCAwtBACEDIAJBADYCBCACQQw2AgggAiABIAEQKiIARQ2UAiACQSc2AhwgAiABNgIUIAIgADYCDAyBAwsgASAERgRAQSkhAwyBAwsgAS0AACIAQSBGDRMgAEEJRw2VAiABQQFqIQEMFAsgASAERwRAIAFBAWohAQwWC0EqIQMM/wILIAEgBEYEQEErIQMM/wILIAEtAAAiAEEJRyAAQSBHcQ2QAiACLQAsQQhHDd0CIAJBADoALAzdAgsgASAERgRAQSwhAwz+AgsgAS0AAEEKRw2OAiABQQFqIQEMsAELIAEgBEcNigJBLyEDDPwCCwNAIAEtAAAiAEEgRwRAIABBCmsOBIQCiAKIAoQChgILIAQgAUEBaiIBRw0AC0ExIQMM+wILQTIhAyABIARGDfoCIAIoAgAiACAEIAFraiEHIAEgAGtBA2ohBgJAA0AgAEHwO2otAAAgAS0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDQEgAEEDRgRAQQYhAQziAgsgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAc2AgAM+wILIAJBADYCAAyGAgtBMyEDIAQgASIARg35AiAEIAFrIAIoAgAiAWohByAAIAFrQQhqIQYCQANAIAFB9DtqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBCEYEQEEFIQEM4QILIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADPoCCyACQQA2AgAgACEBDIUCC0E0IQMgBCABIgBGDfgCIAQgAWsgAigCACIBaiEHIAAgAWtBBWohBgJAA0AgAUHQwgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw0BIAFBBUYEQEEHIQEM4AILIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADPkCCyACQQA2AgAgACEBDIQCCyABIARHBEADQCABLQAAQYA+ai0AACIAQQFHBEAgAEECRg0JDIECCyAEIAFBAWoiAUcNAAtBMCEDDPgCC0EwIQMM9wILIAEgBEcEQANAIAEtAAAiAEEgRwRAIABBCmsOBP8B/gH+Af8B/gELIAQgAUEBaiIBRw0AC0E4IQMM9wILQTghAwz2AgsDQCABLQAAIgBBIEcgAEEJR3EN9gEgBCABQQFqIgFHDQALQTwhAwz1AgsDQCABLQAAIgBBIEcEQAJAIABBCmsOBPkBBAT5AQALIABBLEYN9QEMAwsgBCABQQFqIgFHDQALQT8hAwz0AgtBwAAhAyABIARGDfMCIAIoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAEGAQGstAAAgAS0AAEEgckcNASAAQQZGDdsCIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADPQCCyACQQA2AgALQTYhAwzZAgsgASAERgRAQcEAIQMM8gILIAJBDDYCCCACIAE2AgQgAi0ALEEBaw4E+wHuAewB6wHUAgsgAUEBaiEBDPoBCyABIARHBEADQAJAIAEtAAAiAEEgciAAIABBwQBrQf8BcUEaSRtB/wFxIgBBCUYNACAAQSBGDQACQAJAAkACQCAAQeMAaw4TAAMDAwMDAwMBAwMDAwMDAwMDAgMLIAFBAWohAUExIQMM3AILIAFBAWohAUEyIQMM2wILIAFBAWohAUEzIQMM2gILDP4BCyAEIAFBAWoiAUcNAAtBNSEDDPACC0E1IQMM7wILIAEgBEcEQANAIAEtAABBgDxqLQAAQQFHDfcBIAQgAUEBaiIBRw0AC0E9IQMM7wILQT0hAwzuAgtBACEAAkAgAigCOCIDRQ0AIAMoAkAiA0UNACACIAMRAAAhAAsgAEUNASAAQRVHDeYBIAJBwgA2AhwgAiABNgIUIAJB4xg2AhAgAkEVNgIMQQAhAwztAgsgAUEBaiEBC0E8IQMM0gILIAEgBEYEQEHCACEDDOsCCwJAA0ACQCABLQAAQQlrDhgAAswCzALRAswCzALMAswCzALMAswCzALMAswCzALMAswCzALMAswCzALMAgDMAgsgBCABQQFqIgFHDQALQcIAIQMM6wILIAFBAWohASACLQAtQQFxRQ3+AQtBLCEDDNACCyABIARHDd4BQcQAIQMM6AILA0AgAS0AAEGQwABqLQAAQQFHDZwBIAQgAUEBaiIBRw0AC0HFACEDDOcCCyABLQAAIgBBIEYN/gEgAEE6Rw3AAiACKAIEIQBBACEDIAJBADYCBCACIAAgARApIgAN3gEM3QELQccAIQMgBCABIgBGDeUCIAQgAWsgAigCACIBaiEHIAAgAWtBBWohBgNAIAFBkMIAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNvwIgAUEFRg3CAiABQQFqIQEgBCAAQQFqIgBHDQALIAIgBzYCAAzlAgtByAAhAyAEIAEiAEYN5AIgBCABayACKAIAIgFqIQcgACABa0EJaiEGA0AgAUGWwgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw2+AkECIAFBCUYNwgIaIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADOQCCyABIARGBEBByQAhAwzkAgsCQAJAIAEtAAAiAEEgciAAIABBwQBrQf8BcUEaSRtB/wFxQe4Aaw4HAL8CvwK/Ar8CvwIBvwILIAFBAWohAUE+IQMMywILIAFBAWohAUE/IQMMygILQcoAIQMgBCABIgBGDeICIAQgAWsgAigCACIBaiEGIAAgAWtBAWohBwNAIAFBoMIAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNvAIgAUEBRg2+AiABQQFqIQEgBCAAQQFqIgBHDQALIAIgBjYCAAziAgtBywAhAyAEIAEiAEYN4QIgBCABayACKAIAIgFqIQcgACABa0EOaiEGA0AgAUGiwgBqLQAAIAAtAAAiBUEgciAFIAVBwQBrQf8BcUEaSRtB/wFxRw27AiABQQ5GDb4CIAFBAWohASAEIABBAWoiAEcNAAsgAiAHNgIADOECC0HMACEDIAQgASIARg3gAiAEIAFrIAIoAgAiAWohByAAIAFrQQ9qIQYDQCABQcDCAGotAAAgAC0AACIFQSByIAUgBUHBAGtB/wFxQRpJG0H/AXFHDboCQQMgAUEPRg2+AhogAUEBaiEBIAQgAEEBaiIARw0ACyACIAc2AgAM4AILQc0AIQMgBCABIgBGDd8CIAQgAWsgAigCACIBaiEHIAAgAWtBBWohBgNAIAFB0MIAai0AACAALQAAIgVBIHIgBSAFQcEAa0H/AXFBGkkbQf8BcUcNuQJBBCABQQVGDb0CGiABQQFqIQEgBCAAQQFqIgBHDQALIAIgBzYCAAzfAgsgASAERgRAQc4AIQMM3wILAkACQAJAAkAgAS0AACIAQSByIAAgAEHBAGtB/wFxQRpJG0H/AXFB4wBrDhMAvAK8ArwCvAK8ArwCvAK8ArwCvAK8ArwCAbwCvAK8AgIDvAILIAFBAWohAUHBACEDDMgCCyABQQFqIQFBwgAhAwzHAgsgAUEBaiEBQcMAIQMMxgILIAFBAWohAUHEACEDDMUCCyABIARHBEAgAkENNgIIIAIgATYCBEHFACEDDMUCC0HPACEDDN0CCwJAAkAgAS0AAEEKaw4EAZABkAEAkAELIAFBAWohAQtBKCEDDMMCCyABIARGBEBB0QAhAwzcAgsgAS0AAEEgRw0AIAFBAWohASACLQAtQQFxRQ3QAQtBFyEDDMECCyABIARHDcsBQdIAIQMM2QILQdMAIQMgASAERg3YAiACKAIAIgAgBCABa2ohBiABIABrQQFqIQUDQCABLQAAIABB1sIAai0AAEcNxwEgAEEBRg3KASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBjYCAAzYAgsgASAERgRAQdUAIQMM2AILIAEtAABBCkcNwgEgAUEBaiEBDMoBCyABIARGBEBB1gAhAwzXAgsCQAJAIAEtAABBCmsOBADDAcMBAcMBCyABQQFqIQEMygELIAFBAWohAUHKACEDDL0CC0EAIQACQCACKAI4IgNFDQAgAygCPCIDRQ0AIAIgAxEAACEACyAADb8BQc0AIQMMvAILIAItAClBIkYNzwIMiQELIAQgASIFRgRAQdsAIQMM1AILQQAhAEEBIQFBASEGQQAhAwJAAn8CQAJAAkACQAJAAkACQCAFLQAAQTBrDgrFAcQBAAECAwQFBgjDAQtBAgwGC0EDDAULQQQMBAtBBQwDC0EGDAILQQcMAQtBCAshA0EAIQFBACEGDL0BC0EJIQNBASEAQQAhAUEAIQYMvAELIAEgBEYEQEHdACEDDNMCCyABLQAAQS5HDbgBIAFBAWohAQyIAQsgASAERw22AUHfACEDDNECCyABIARHBEAgAkEONgIIIAIgATYCBEHQACEDDLgCC0HgACEDDNACC0HhACEDIAEgBEYNzwIgAigCACIAIAQgAWtqIQUgASAAa0EDaiEGA0AgAS0AACAAQeLCAGotAABHDbEBIABBA0YNswEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMzwILQeIAIQMgASAERg3OAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYDQCABLQAAIABB5sIAai0AAEcNsAEgAEECRg2vASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAzOAgtB4wAhAyABIARGDc0CIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgNAIAEtAAAgAEHpwgBqLQAARw2vASAAQQNGDa0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADM0CCyABIARGBEBB5QAhAwzNAgsgAUEBaiEBQQAhAAJAIAIoAjgiA0UNACADKAIwIgNFDQAgAiADEQAAIQALIAANqgFB1gAhAwyzAgsgASAERwRAA0AgAS0AACIAQSBHBEACQAJAAkAgAEHIAGsOCwABswGzAbMBswGzAbMBswGzAQKzAQsgAUEBaiEBQdIAIQMMtwILIAFBAWohAUHTACEDDLYCCyABQQFqIQFB1AAhAwy1AgsgBCABQQFqIgFHDQALQeQAIQMMzAILQeQAIQMMywILA0AgAS0AAEHwwgBqLQAAIgBBAUcEQCAAQQJrDgOnAaYBpQGkAQsgBCABQQFqIgFHDQALQeYAIQMMygILIAFBAWogASAERw0CGkHnACEDDMkCCwNAIAEtAABB8MQAai0AACIAQQFHBEACQCAAQQJrDgSiAaEBoAEAnwELQdcAIQMMsQILIAQgAUEBaiIBRw0AC0HoACEDDMgCCyABIARGBEBB6QAhAwzIAgsCQCABLQAAIgBBCmsOGrcBmwGbAbQBmwGbAZsBmwGbAZsBmwGbAZsBmwGbAZsBmwGbAZsBmwGbAZsBpAGbAZsBAJkBCyABQQFqCyEBQQYhAwytAgsDQCABLQAAQfDGAGotAABBAUcNfSAEIAFBAWoiAUcNAAtB6gAhAwzFAgsgAUEBaiABIARHDQIaQesAIQMMxAILIAEgBEYEQEHsACEDDMQCCyABQQFqDAELIAEgBEYEQEHtACEDDMMCCyABQQFqCyEBQQQhAwyoAgsgASAERgRAQe4AIQMMwQILAkACQAJAIAEtAABB8MgAai0AAEEBaw4HkAGPAY4BAHwBAo0BCyABQQFqIQEMCwsgAUEBagyTAQtBACEDIAJBADYCHCACQZsSNgIQIAJBBzYCDCACIAFBAWo2AhQMwAILAkADQCABLQAAQfDIAGotAAAiAEEERwRAAkACQCAAQQFrDgeUAZMBkgGNAQAEAY0BC0HaACEDDKoCCyABQQFqIQFB3AAhAwypAgsgBCABQQFqIgFHDQALQe8AIQMMwAILIAFBAWoMkQELIAQgASIARgRAQfAAIQMMvwILIAAtAABBL0cNASAAQQFqIQEMBwsgBCABIgBGBEBB8QAhAwy+AgsgAC0AACIBQS9GBEAgAEEBaiEBQd0AIQMMpQILIAFBCmsiA0EWSw0AIAAhAUEBIAN0QYmAgAJxDfkBC0EAIQMgAkEANgIcIAIgADYCFCACQYwcNgIQIAJBBzYCDAy8AgsgASAERwRAIAFBAWohAUHeACEDDKMCC0HyACEDDLsCCyABIARGBEBB9AAhAwy7AgsCQCABLQAAQfDMAGotAABBAWsOA/cBcwCCAQtB4QAhAwyhAgsgASAERwRAA0AgAS0AAEHwygBqLQAAIgBBA0cEQAJAIABBAWsOAvkBAIUBC0HfACEDDKMCCyAEIAFBAWoiAUcNAAtB8wAhAwy6AgtB8wAhAwy5AgsgASAERwRAIAJBDzYCCCACIAE2AgRB4AAhAwygAgtB9QAhAwy4AgsgASAERgRAQfYAIQMMuAILIAJBDzYCCCACIAE2AgQLQQMhAwydAgsDQCABLQAAQSBHDY4CIAQgAUEBaiIBRw0AC0H3ACEDDLUCCyABIARGBEBB+AAhAwy1AgsgAS0AAEEgRw16IAFBAWohAQxbC0EAIQACQCACKAI4IgNFDQAgAygCOCIDRQ0AIAIgAxEAACEACyAADXgMgAILIAEgBEYEQEH6ACEDDLMCCyABLQAAQcwARw10IAFBAWohAUETDHYLQfsAIQMgASAERg2xAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYDQCABLQAAIABB8M4Aai0AAEcNcyAAQQVGDXUgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMsQILIAEgBEYEQEH8ACEDDLECCwJAAkAgAS0AAEHDAGsODAB0dHR0dHR0dHR0AXQLIAFBAWohAUHmACEDDJgCCyABQQFqIQFB5wAhAwyXAgtB/QAhAyABIARGDa8CIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQe3PAGotAABHDXIgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADLACCyACQQA2AgAgBkEBaiEBQRAMcwtB/gAhAyABIARGDa4CIAIoAgAiACAEIAFraiEFIAEgAGtBBWohBgJAA0AgAS0AACAAQfbOAGotAABHDXEgAEEFRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADK8CCyACQQA2AgAgBkEBaiEBQRYMcgtB/wAhAyABIARGDa0CIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQfzOAGotAABHDXAgAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADK4CCyACQQA2AgAgBkEBaiEBQQUMcQsgASAERgRAQYABIQMMrQILIAEtAABB2QBHDW4gAUEBaiEBQQgMcAsgASAERgRAQYEBIQMMrAILAkACQCABLQAAQc4Aaw4DAG8BbwsgAUEBaiEBQesAIQMMkwILIAFBAWohAUHsACEDDJICCyABIARGBEBBggEhAwyrAgsCQAJAIAEtAABByABrDggAbm5ubm5uAW4LIAFBAWohAUHqACEDDJICCyABQQFqIQFB7QAhAwyRAgtBgwEhAyABIARGDakCIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQYDPAGotAABHDWwgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADKoCCyACQQA2AgAgBkEBaiEBQQAMbQtBhAEhAyABIARGDagCIAIoAgAiACAEIAFraiEFIAEgAGtBBGohBgJAA0AgAS0AACAAQYPPAGotAABHDWsgAEEERg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADKkCCyACQQA2AgAgBkEBaiEBQSMMbAsgASAERgRAQYUBIQMMqAILAkACQCABLQAAQcwAaw4IAGtra2trawFrCyABQQFqIQFB7wAhAwyPAgsgAUEBaiEBQfAAIQMMjgILIAEgBEYEQEGGASEDDKcCCyABLQAAQcUARw1oIAFBAWohAQxgC0GHASEDIAEgBEYNpQIgAigCACIAIAQgAWtqIQUgASAAa0EDaiEGAkADQCABLQAAIABBiM8Aai0AAEcNaCAAQQNGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMpgILIAJBADYCACAGQQFqIQFBLQxpC0GIASEDIAEgBEYNpAIgAigCACIAIAQgAWtqIQUgASAAa0EIaiEGAkADQCABLQAAIABB0M8Aai0AAEcNZyAAQQhGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMpQILIAJBADYCACAGQQFqIQFBKQxoCyABIARGBEBBiQEhAwykAgtBASABLQAAQd8ARw1nGiABQQFqIQEMXgtBigEhAyABIARGDaICIAIoAgAiACAEIAFraiEFIAEgAGtBAWohBgNAIAEtAAAgAEGMzwBqLQAARw1kIABBAUYN+gEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMogILQYsBIQMgASAERg2hAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGOzwBqLQAARw1kIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyiAgsgAkEANgIAIAZBAWohAUECDGULQYwBIQMgASAERg2gAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHwzwBqLQAARw1jIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyhAgsgAkEANgIAIAZBAWohAUEfDGQLQY0BIQMgASAERg2fAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHyzwBqLQAARw1iIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAygAgsgAkEANgIAIAZBAWohAUEJDGMLIAEgBEYEQEGOASEDDJ8CCwJAAkAgAS0AAEHJAGsOBwBiYmJiYgFiCyABQQFqIQFB+AAhAwyGAgsgAUEBaiEBQfkAIQMMhQILQY8BIQMgASAERg2dAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGRzwBqLQAARw1gIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyeAgsgAkEANgIAIAZBAWohAUEYDGELQZABIQMgASAERg2cAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGXzwBqLQAARw1fIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAydAgsgAkEANgIAIAZBAWohAUEXDGALQZEBIQMgASAERg2bAiACKAIAIgAgBCABa2ohBSABIABrQQZqIQYCQANAIAEtAAAgAEGazwBqLQAARw1eIABBBkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAycAgsgAkEANgIAIAZBAWohAUEVDF8LQZIBIQMgASAERg2aAiACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEGhzwBqLQAARw1dIABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAybAgsgAkEANgIAIAZBAWohAUEeDF4LIAEgBEYEQEGTASEDDJoCCyABLQAAQcwARw1bIAFBAWohAUEKDF0LIAEgBEYEQEGUASEDDJkCCwJAAkAgAS0AAEHBAGsODwBcXFxcXFxcXFxcXFxcAVwLIAFBAWohAUH+ACEDDIACCyABQQFqIQFB/wAhAwz/AQsgASAERgRAQZUBIQMMmAILAkACQCABLQAAQcEAaw4DAFsBWwsgAUEBaiEBQf0AIQMM/wELIAFBAWohAUGAASEDDP4BC0GWASEDIAEgBEYNlgIgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBp88Aai0AAEcNWSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMlwILIAJBADYCACAGQQFqIQFBCwxaCyABIARGBEBBlwEhAwyWAgsCQAJAAkACQCABLQAAQS1rDiMAW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1sBW1tbW1sCW1tbA1sLIAFBAWohAUH7ACEDDP8BCyABQQFqIQFB/AAhAwz+AQsgAUEBaiEBQYEBIQMM/QELIAFBAWohAUGCASEDDPwBC0GYASEDIAEgBEYNlAIgAigCACIAIAQgAWtqIQUgASAAa0EEaiEGAkADQCABLQAAIABBqc8Aai0AAEcNVyAAQQRGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMlQILIAJBADYCACAGQQFqIQFBGQxYC0GZASEDIAEgBEYNkwIgAigCACIAIAQgAWtqIQUgASAAa0EFaiEGAkADQCABLQAAIABBrs8Aai0AAEcNViAAQQVGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMlAILIAJBADYCACAGQQFqIQFBBgxXC0GaASEDIAEgBEYNkgIgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBtM8Aai0AAEcNVSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMkwILIAJBADYCACAGQQFqIQFBHAxWC0GbASEDIAEgBEYNkQIgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABBts8Aai0AAEcNVCAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAMkgILIAJBADYCACAGQQFqIQFBJwxVCyABIARGBEBBnAEhAwyRAgsCQAJAIAEtAABB1ABrDgIAAVQLIAFBAWohAUGGASEDDPgBCyABQQFqIQFBhwEhAwz3AQtBnQEhAyABIARGDY8CIAIoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQbjPAGotAABHDVIgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADJACCyACQQA2AgAgBkEBaiEBQSYMUwtBngEhAyABIARGDY4CIAIoAgAiACAEIAFraiEFIAEgAGtBAWohBgJAA0AgAS0AACAAQbrPAGotAABHDVEgAEEBRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADI8CCyACQQA2AgAgBkEBaiEBQQMMUgtBnwEhAyABIARGDY0CIAIoAgAiACAEIAFraiEFIAEgAGtBAmohBgJAA0AgAS0AACAAQe3PAGotAABHDVAgAEECRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADI4CCyACQQA2AgAgBkEBaiEBQQwMUQtBoAEhAyABIARGDYwCIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQbzPAGotAABHDU8gAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADI0CCyACQQA2AgAgBkEBaiEBQQ0MUAsgASAERgRAQaEBIQMMjAILAkACQCABLQAAQcYAaw4LAE9PT09PT09PTwFPCyABQQFqIQFBiwEhAwzzAQsgAUEBaiEBQYwBIQMM8gELIAEgBEYEQEGiASEDDIsCCyABLQAAQdAARw1MIAFBAWohAQxGCyABIARGBEBBowEhAwyKAgsCQAJAIAEtAABByQBrDgcBTU1NTU0ATQsgAUEBaiEBQY4BIQMM8QELIAFBAWohAUEiDE0LQaQBIQMgASAERg2IAiACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEHAzwBqLQAARw1LIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyJAgsgAkEANgIAIAZBAWohAUEdDEwLIAEgBEYEQEGlASEDDIgCCwJAAkAgAS0AAEHSAGsOAwBLAUsLIAFBAWohAUGQASEDDO8BCyABQQFqIQFBBAxLCyABIARGBEBBpgEhAwyHAgsCQAJAAkACQAJAIAEtAABBwQBrDhUATU1NTU1NTU1NTQFNTQJNTQNNTQRNCyABQQFqIQFBiAEhAwzxAQsgAUEBaiEBQYkBIQMM8AELIAFBAWohAUGKASEDDO8BCyABQQFqIQFBjwEhAwzuAQsgAUEBaiEBQZEBIQMM7QELQacBIQMgASAERg2FAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHtzwBqLQAARw1IIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyGAgsgAkEANgIAIAZBAWohAUERDEkLQagBIQMgASAERg2EAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHCzwBqLQAARw1HIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyFAgsgAkEANgIAIAZBAWohAUEsDEgLQakBIQMgASAERg2DAiACKAIAIgAgBCABa2ohBSABIABrQQRqIQYCQANAIAEtAAAgAEHFzwBqLQAARw1GIABBBEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyEAgsgAkEANgIAIAZBAWohAUErDEcLQaoBIQMgASAERg2CAiACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHKzwBqLQAARw1FIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyDAgsgAkEANgIAIAZBAWohAUEUDEYLIAEgBEYEQEGrASEDDIICCwJAAkACQAJAIAEtAABBwgBrDg8AAQJHR0dHR0dHR0dHRwNHCyABQQFqIQFBkwEhAwzrAQsgAUEBaiEBQZQBIQMM6gELIAFBAWohAUGVASEDDOkBCyABQQFqIQFBlgEhAwzoAQsgASAERgRAQawBIQMMgQILIAEtAABBxQBHDUIgAUEBaiEBDD0LQa0BIQMgASAERg3/ASACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHNzwBqLQAARw1CIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAyAAgsgAkEANgIAIAZBAWohAUEODEMLIAEgBEYEQEGuASEDDP8BCyABLQAAQdAARw1AIAFBAWohAUElDEILQa8BIQMgASAERg39ASACKAIAIgAgBCABa2ohBSABIABrQQhqIQYCQANAIAEtAAAgAEHQzwBqLQAARw1AIABBCEYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAz+AQsgAkEANgIAIAZBAWohAUEqDEELIAEgBEYEQEGwASEDDP0BCwJAAkAgAS0AAEHVAGsOCwBAQEBAQEBAQEABQAsgAUEBaiEBQZoBIQMM5AELIAFBAWohAUGbASEDDOMBCyABIARGBEBBsQEhAwz8AQsCQAJAIAEtAABBwQBrDhQAPz8/Pz8/Pz8/Pz8/Pz8/Pz8/AT8LIAFBAWohAUGZASEDDOMBCyABQQFqIQFBnAEhAwziAQtBsgEhAyABIARGDfoBIAIoAgAiACAEIAFraiEFIAEgAGtBA2ohBgJAA0AgAS0AACAAQdnPAGotAABHDT0gAEEDRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADPsBCyACQQA2AgAgBkEBaiEBQSEMPgtBswEhAyABIARGDfkBIAIoAgAiACAEIAFraiEFIAEgAGtBBmohBgJAA0AgAS0AACAAQd3PAGotAABHDTwgAEEGRg0BIABBAWohACAEIAFBAWoiAUcNAAsgAiAFNgIADPoBCyACQQA2AgAgBkEBaiEBQRoMPQsgASAERgRAQbQBIQMM+QELAkACQAJAIAEtAABBxQBrDhEAPT09PT09PT09AT09PT09Aj0LIAFBAWohAUGdASEDDOEBCyABQQFqIQFBngEhAwzgAQsgAUEBaiEBQZ8BIQMM3wELQbUBIQMgASAERg33ASACKAIAIgAgBCABa2ohBSABIABrQQVqIQYCQANAIAEtAAAgAEHkzwBqLQAARw06IABBBUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAz4AQsgAkEANgIAIAZBAWohAUEoDDsLQbYBIQMgASAERg32ASACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEHqzwBqLQAARw05IABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAz3AQsgAkEANgIAIAZBAWohAUEHDDoLIAEgBEYEQEG3ASEDDPYBCwJAAkAgAS0AAEHFAGsODgA5OTk5OTk5OTk5OTkBOQsgAUEBaiEBQaEBIQMM3QELIAFBAWohAUGiASEDDNwBC0G4ASEDIAEgBEYN9AEgAigCACIAIAQgAWtqIQUgASAAa0ECaiEGAkADQCABLQAAIABB7c8Aai0AAEcNNyAAQQJGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM9QELIAJBADYCACAGQQFqIQFBEgw4C0G5ASEDIAEgBEYN8wEgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB8M8Aai0AAEcNNiAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM9AELIAJBADYCACAGQQFqIQFBIAw3C0G6ASEDIAEgBEYN8gEgAigCACIAIAQgAWtqIQUgASAAa0EBaiEGAkADQCABLQAAIABB8s8Aai0AAEcNNSAAQQFGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM8wELIAJBADYCACAGQQFqIQFBDww2CyABIARGBEBBuwEhAwzyAQsCQAJAIAEtAABByQBrDgcANTU1NTUBNQsgAUEBaiEBQaUBIQMM2QELIAFBAWohAUGmASEDDNgBC0G8ASEDIAEgBEYN8AEgAigCACIAIAQgAWtqIQUgASAAa0EHaiEGAkADQCABLQAAIABB9M8Aai0AAEcNMyAAQQdGDQEgAEEBaiEAIAQgAUEBaiIBRw0ACyACIAU2AgAM8QELIAJBADYCACAGQQFqIQFBGww0CyABIARGBEBBvQEhAwzwAQsCQAJAAkAgAS0AAEHCAGsOEgA0NDQ0NDQ0NDQBNDQ0NDQ0AjQLIAFBAWohAUGkASEDDNgBCyABQQFqIQFBpwEhAwzXAQsgAUEBaiEBQagBIQMM1gELIAEgBEYEQEG+ASEDDO8BCyABLQAAQc4ARw0wIAFBAWohAQwsCyABIARGBEBBvwEhAwzuAQsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCABLQAAQcEAaw4VAAECAz8EBQY/Pz8HCAkKCz8MDQ4PPwsgAUEBaiEBQegAIQMM4wELIAFBAWohAUHpACEDDOIBCyABQQFqIQFB7gAhAwzhAQsgAUEBaiEBQfIAIQMM4AELIAFBAWohAUHzACEDDN8BCyABQQFqIQFB9gAhAwzeAQsgAUEBaiEBQfcAIQMM3QELIAFBAWohAUH6ACEDDNwBCyABQQFqIQFBgwEhAwzbAQsgAUEBaiEBQYQBIQMM2gELIAFBAWohAUGFASEDDNkBCyABQQFqIQFBkgEhAwzYAQsgAUEBaiEBQZgBIQMM1wELIAFBAWohAUGgASEDDNYBCyABQQFqIQFBowEhAwzVAQsgAUEBaiEBQaoBIQMM1AELIAEgBEcEQCACQRA2AgggAiABNgIEQasBIQMM1AELQcABIQMM7AELQQAhAAJAIAIoAjgiA0UNACADKAI0IgNFDQAgAiADEQAAIQALIABFDV4gAEEVRw0HIAJB0QA2AhwgAiABNgIUIAJBsBc2AhAgAkEVNgIMQQAhAwzrAQsgAUEBaiABIARHDQgaQcIBIQMM6gELA0ACQCABLQAAQQprDgQIAAALAAsgBCABQQFqIgFHDQALQcMBIQMM6QELIAEgBEcEQCACQRE2AgggAiABNgIEQQEhAwzQAQtBxAEhAwzoAQsgASAERgRAQcUBIQMM6AELAkACQCABLQAAQQprDgQBKCgAKAsgAUEBagwJCyABQQFqDAULIAEgBEYEQEHGASEDDOcBCwJAAkAgAS0AAEEKaw4XAQsLAQsLCwsLCwsLCwsLCwsLCwsLCwALCyABQQFqIQELQbABIQMMzQELIAEgBEYEQEHIASEDDOYBCyABLQAAQSBHDQkgAkEAOwEyIAFBAWohAUGzASEDDMwBCwNAIAEhAAJAIAEgBEcEQCABLQAAQTBrQf8BcSIDQQpJDQEMJwtBxwEhAwzmAQsCQCACLwEyIgFBmTNLDQAgAiABQQpsIgU7ATIgBUH+/wNxIANB//8Dc0sNACAAQQFqIQEgAiADIAVqIgM7ATIgA0H//wNxQegHSQ0BCwtBACEDIAJBADYCHCACQcEJNgIQIAJBDTYCDCACIABBAWo2AhQM5AELIAJBADYCHCACIAE2AhQgAkHwDDYCECACQRs2AgxBACEDDOMBCyACKAIEIQAgAkEANgIEIAIgACABECYiAA0BIAFBAWoLIQFBrQEhAwzIAQsgAkHBATYCHCACIAA2AgwgAiABQQFqNgIUQQAhAwzgAQsgAigCBCEAIAJBADYCBCACIAAgARAmIgANASABQQFqCyEBQa4BIQMMxQELIAJBwgE2AhwgAiAANgIMIAIgAUEBajYCFEEAIQMM3QELIAJBADYCHCACIAE2AhQgAkGXCzYCECACQQ02AgxBACEDDNwBCyACQQA2AhwgAiABNgIUIAJB4xA2AhAgAkEJNgIMQQAhAwzbAQsgAkECOgAoDKwBC0EAIQMgAkEANgIcIAJBrws2AhAgAkECNgIMIAIgAUEBajYCFAzZAQtBAiEDDL8BC0ENIQMMvgELQSYhAwy9AQtBFSEDDLwBC0EWIQMMuwELQRghAwy6AQtBHCEDDLkBC0EdIQMMuAELQSAhAwy3AQtBISEDDLYBC0EjIQMMtQELQcYAIQMMtAELQS4hAwyzAQtBPSEDDLIBC0HLACEDDLEBC0HOACEDDLABC0HYACEDDK8BC0HZACEDDK4BC0HbACEDDK0BC0HxACEDDKwBC0H0ACEDDKsBC0GNASEDDKoBC0GXASEDDKkBC0GpASEDDKgBC0GvASEDDKcBC0GxASEDDKYBCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJB8Rs2AhAgAkEGNgIMDL0BCyACQQA2AgAgBkEBaiEBQSQLOgApIAIoAgQhACACQQA2AgQgAiAAIAEQJyIARQRAQeUAIQMMowELIAJB+QA2AhwgAiABNgIUIAIgADYCDEEAIQMMuwELIABBFUcEQCACQQA2AhwgAiABNgIUIAJBzA42AhAgAkEgNgIMQQAhAwy7AQsgAkH4ADYCHCACIAE2AhQgAkHKGDYCECACQRU2AgxBACEDDLoBCyACQQA2AhwgAiABNgIUIAJBjhs2AhAgAkEGNgIMQQAhAwy5AQsgAkEANgIcIAIgATYCFCACQf4RNgIQIAJBBzYCDEEAIQMMuAELIAJBADYCHCACIAE2AhQgAkGMHDYCECACQQc2AgxBACEDDLcBCyACQQA2AhwgAiABNgIUIAJBww82AhAgAkEHNgIMQQAhAwy2AQsgAkEANgIcIAIgATYCFCACQcMPNgIQIAJBBzYCDEEAIQMMtQELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0RIAJB5QA2AhwgAiABNgIUIAIgADYCDEEAIQMMtAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0gIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMswELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0iIAJB0gA2AhwgAiABNgIUIAIgADYCDEEAIQMMsgELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0OIAJB5QA2AhwgAiABNgIUIAIgADYCDEEAIQMMsQELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0dIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMsAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0fIAJB0gA2AhwgAiABNgIUIAIgADYCDEEAIQMMrwELIABBP0cNASABQQFqCyEBQQUhAwyUAQtBACEDIAJBADYCHCACIAE2AhQgAkH9EjYCECACQQc2AgwMrAELIAJBADYCHCACIAE2AhQgAkHcCDYCECACQQc2AgxBACEDDKsBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNByACQeUANgIcIAIgATYCFCACIAA2AgxBACEDDKoBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNFiACQdMANgIcIAIgATYCFCACIAA2AgxBACEDDKkBCyACKAIEIQAgAkEANgIEIAIgACABECUiAEUNGCACQdIANgIcIAIgATYCFCACIAA2AgxBACEDDKgBCyACQQA2AhwgAiABNgIUIAJBxgo2AhAgAkEHNgIMQQAhAwynAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQMgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwymAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRIgAkHTADYCHCACIAE2AhQgAiAANgIMQQAhAwylAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDRQgAkHSADYCHCACIAE2AhQgAiAANgIMQQAhAwykAQsgAigCBCEAIAJBADYCBCACIAAgARAlIgBFDQAgAkHlADYCHCACIAE2AhQgAiAANgIMQQAhAwyjAQtB1QAhAwyJAQsgAEEVRwRAIAJBADYCHCACIAE2AhQgAkG5DTYCECACQRo2AgxBACEDDKIBCyACQeQANgIcIAIgATYCFCACQeMXNgIQIAJBFTYCDEEAIQMMoQELIAJBADYCACAGQQFqIQEgAi0AKSIAQSNrQQtJDQQCQCAAQQZLDQBBASAAdEHKAHFFDQAMBQtBACEDIAJBADYCHCACIAE2AhQgAkH3CTYCECACQQg2AgwMoAELIAJBADYCACAGQQFqIQEgAi0AKUEhRg0DIAJBADYCHCACIAE2AhQgAkGbCjYCECACQQg2AgxBACEDDJ8BCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJBkDM2AhAgAkEINgIMDJ0BCyACQQA2AgAgBkEBaiEBIAItAClBI0kNACACQQA2AhwgAiABNgIUIAJB0wk2AhAgAkEINgIMQQAhAwycAQtB0QAhAwyCAQsgAS0AAEEwayIAQf8BcUEKSQRAIAIgADoAKiABQQFqIQFBzwAhAwyCAQsgAigCBCEAIAJBADYCBCACIAAgARAoIgBFDYYBIAJB3gA2AhwgAiABNgIUIAIgADYCDEEAIQMMmgELIAIoAgQhACACQQA2AgQgAiAAIAEQKCIARQ2GASACQdwANgIcIAIgATYCFCACIAA2AgxBACEDDJkBCyACKAIEIQAgAkEANgIEIAIgACAFECgiAEUEQCAFIQEMhwELIAJB2gA2AhwgAiAFNgIUIAIgADYCDAyYAQtBACEBQQEhAwsgAiADOgArIAVBAWohAwJAAkACQCACLQAtQRBxDQACQAJAAkAgAi0AKg4DAQACBAsgBkUNAwwCCyAADQEMAgsgAUUNAQsgAigCBCEAIAJBADYCBCACIAAgAxAoIgBFBEAgAyEBDAILIAJB2AA2AhwgAiADNgIUIAIgADYCDEEAIQMMmAELIAIoAgQhACACQQA2AgQgAiAAIAMQKCIARQRAIAMhAQyHAQsgAkHZADYCHCACIAM2AhQgAiAANgIMQQAhAwyXAQtBzAAhAwx9CyAAQRVHBEAgAkEANgIcIAIgATYCFCACQZQNNgIQIAJBITYCDEEAIQMMlgELIAJB1wA2AhwgAiABNgIUIAJByRc2AhAgAkEVNgIMQQAhAwyVAQtBACEDIAJBADYCHCACIAE2AhQgAkGAETYCECACQQk2AgwMlAELIAIoAgQhACACQQA2AgQgAiAAIAEQJSIARQ0AIAJB0wA2AhwgAiABNgIUIAIgADYCDEEAIQMMkwELQckAIQMMeQsgAkEANgIcIAIgATYCFCACQcEoNgIQIAJBBzYCDCACQQA2AgBBACEDDJEBCyACKAIEIQBBACEDIAJBADYCBCACIAAgARAlIgBFDQAgAkHSADYCHCACIAE2AhQgAiAANgIMDJABC0HIACEDDHYLIAJBADYCACAFIQELIAJBgBI7ASogAUEBaiEBQQAhAAJAIAIoAjgiA0UNACADKAIwIgNFDQAgAiADEQAAIQALIAANAQtBxwAhAwxzCyAAQRVGBEAgAkHRADYCHCACIAE2AhQgAkHjFzYCECACQRU2AgxBACEDDIwBC0EAIQMgAkEANgIcIAIgATYCFCACQbkNNgIQIAJBGjYCDAyLAQtBACEDIAJBADYCHCACIAE2AhQgAkGgGTYCECACQR42AgwMigELIAEtAABBOkYEQCACKAIEIQBBACEDIAJBADYCBCACIAAgARApIgBFDQEgAkHDADYCHCACIAA2AgwgAiABQQFqNgIUDIoBC0EAIQMgAkEANgIcIAIgATYCFCACQbERNgIQIAJBCjYCDAyJAQsgAUEBaiEBQTshAwxvCyACQcMANgIcIAIgADYCDCACIAFBAWo2AhQMhwELQQAhAyACQQA2AhwgAiABNgIUIAJB8A42AhAgAkEcNgIMDIYBCyACIAIvATBBEHI7ATAMZgsCQCACLwEwIgBBCHFFDQAgAi0AKEEBRw0AIAItAC1BCHFFDQMLIAIgAEH3+wNxQYAEcjsBMAwECyABIARHBEACQANAIAEtAABBMGsiAEH/AXFBCk8EQEE1IQMMbgsgAikDICIKQpmz5syZs+bMGVYNASACIApCCn4iCjcDICAKIACtQv8BgyILQn+FVg0BIAIgCiALfDcDICAEIAFBAWoiAUcNAAtBOSEDDIUBCyACKAIEIQBBACEDIAJBADYCBCACIAAgAUEBaiIBECoiAA0MDHcLQTkhAwyDAQsgAi0AMEEgcQ0GQcUBIQMMaQtBACEDIAJBADYCBCACIAEgARAqIgBFDQQgAkE6NgIcIAIgADYCDCACIAFBAWo2AhQMgQELIAItAChBAUcNACACLQAtQQhxRQ0BC0E3IQMMZgsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIABEAgAkE7NgIcIAIgADYCDCACIAFBAWo2AhQMfwsgAUEBaiEBDG4LIAJBCDoALAwECyABQQFqIQEMbQtBACEDIAJBADYCHCACIAE2AhQgAkHkEjYCECACQQQ2AgwMewsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIARQ1sIAJBNzYCHCACIAE2AhQgAiAANgIMDHoLIAIgAi8BMEEgcjsBMAtBMCEDDF8LIAJBNjYCHCACIAE2AhQgAiAANgIMDHcLIABBLEcNASABQQFqIQBBASEBAkACQAJAAkACQCACLQAsQQVrDgQDAQIEAAsgACEBDAQLQQIhAQwBC0EEIQELIAJBAToALCACIAIvATAgAXI7ATAgACEBDAELIAIgAi8BMEEIcjsBMCAAIQELQTkhAwxcCyACQQA6ACwLQTQhAwxaCyABIARGBEBBLSEDDHMLAkACQANAAkAgAS0AAEEKaw4EAgAAAwALIAQgAUEBaiIBRw0AC0EtIQMMdAsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIARQ0CIAJBLDYCHCACIAE2AhQgAiAANgIMDHMLIAIoAgQhAEEAIQMgAkEANgIEIAIgACABECoiAEUEQCABQQFqIQEMAgsgAkEsNgIcIAIgADYCDCACIAFBAWo2AhQMcgsgAS0AAEENRgRAIAIoAgQhAEEAIQMgAkEANgIEIAIgACABECoiAEUEQCABQQFqIQEMAgsgAkEsNgIcIAIgADYCDCACIAFBAWo2AhQMcgsgAi0ALUEBcQRAQcQBIQMMWQsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKiIADQEMZQtBLyEDDFcLIAJBLjYCHCACIAE2AhQgAiAANgIMDG8LQQAhAyACQQA2AhwgAiABNgIUIAJB8BQ2AhAgAkEDNgIMDG4LQQEhAwJAAkACQAJAIAItACxBBWsOBAMBAgAECyACIAIvATBBCHI7ATAMAwtBAiEDDAELQQQhAwsgAkEBOgAsIAIgAi8BMCADcjsBMAtBKiEDDFMLQQAhAyACQQA2AhwgAiABNgIUIAJB4Q82AhAgAkEKNgIMDGsLQQEhAwJAAkACQAJAAkACQCACLQAsQQJrDgcFBAQDAQIABAsgAiACLwEwQQhyOwEwDAMLQQIhAwwBC0EEIQMLIAJBAToALCACIAIvATAgA3I7ATALQSshAwxSC0EAIQMgAkEANgIcIAIgATYCFCACQasSNgIQIAJBCzYCDAxqC0EAIQMgAkEANgIcIAIgATYCFCACQf0NNgIQIAJBHTYCDAxpCyABIARHBEADQCABLQAAQSBHDUggBCABQQFqIgFHDQALQSUhAwxpC0ElIQMMaAsgAi0ALUEBcQRAQcMBIQMMTwsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQKSIABEAgAkEmNgIcIAIgADYCDCACIAFBAWo2AhQMaAsgAUEBaiEBDFwLIAFBAWohASACLwEwIgBBgAFxBEBBACEAAkAgAigCOCIDRQ0AIAMoAlQiA0UNACACIAMRAAAhAAsgAEUNBiAAQRVHDR8gAkEFNgIcIAIgATYCFCACQfkXNgIQIAJBFTYCDEEAIQMMZwsCQCAAQaAEcUGgBEcNACACLQAtQQJxDQBBACEDIAJBADYCHCACIAE2AhQgAkGWEzYCECACQQQ2AgwMZwsgAgJ/IAIvATBBFHFBFEYEQEEBIAItAChBAUYNARogAi8BMkHlAEYMAQsgAi0AKUEFRgs6AC5BACEAAkAgAigCOCIDRQ0AIAMoAiQiA0UNACACIAMRAAAhAAsCQAJAAkACQAJAIAAOFgIBAAQEBAQEBAQEBAQEBAQEBAQEBAMECyACQQE6AC4LIAIgAi8BMEHAAHI7ATALQSchAwxPCyACQSM2AhwgAiABNgIUIAJBpRY2AhAgAkEVNgIMQQAhAwxnC0EAIQMgAkEANgIcIAIgATYCFCACQdULNgIQIAJBETYCDAxmC0EAIQACQCACKAI4IgNFDQAgAygCLCIDRQ0AIAIgAxEAACEACyAADQELQQ4hAwxLCyAAQRVGBEAgAkECNgIcIAIgATYCFCACQbAYNgIQIAJBFTYCDEEAIQMMZAtBACEDIAJBADYCHCACIAE2AhQgAkGnDjYCECACQRI2AgwMYwtBACEDIAJBADYCHCACIAE2AhQgAkGqHDYCECACQQ82AgwMYgsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEgCqdqIgEQKyIARQ0AIAJBBTYCHCACIAE2AhQgAiAANgIMDGELQQ8hAwxHC0EAIQMgAkEANgIcIAIgATYCFCACQc0TNgIQIAJBDDYCDAxfC0IBIQoLIAFBAWohAQJAIAIpAyAiC0L//////////w9YBEAgAiALQgSGIAqENwMgDAELQQAhAyACQQA2AhwgAiABNgIUIAJBrQk2AhAgAkEMNgIMDF4LQSQhAwxEC0EAIQMgAkEANgIcIAIgATYCFCACQc0TNgIQIAJBDDYCDAxcCyACKAIEIQBBACEDIAJBADYCBCACIAAgARAsIgBFBEAgAUEBaiEBDFILIAJBFzYCHCACIAA2AgwgAiABQQFqNgIUDFsLIAIoAgQhAEEAIQMgAkEANgIEAkAgAiAAIAEQLCIARQRAIAFBAWohAQwBCyACQRY2AhwgAiAANgIMIAIgAUEBajYCFAxbC0EfIQMMQQtBACEDIAJBADYCHCACIAE2AhQgAkGaDzYCECACQSI2AgwMWQsgAigCBCEAQQAhAyACQQA2AgQgAiAAIAEQLSIARQRAIAFBAWohAQxQCyACQRQ2AhwgAiAANgIMIAIgAUEBajYCFAxYCyACKAIEIQBBACEDIAJBADYCBAJAIAIgACABEC0iAEUEQCABQQFqIQEMAQsgAkETNgIcIAIgADYCDCACIAFBAWo2AhQMWAtBHiEDDD4LQQAhAyACQQA2AhwgAiABNgIUIAJBxgw2AhAgAkEjNgIMDFYLIAIoAgQhAEEAIQMgAkEANgIEIAIgACABEC0iAEUEQCABQQFqIQEMTgsgAkERNgIcIAIgADYCDCACIAFBAWo2AhQMVQsgAkEQNgIcIAIgATYCFCACIAA2AgwMVAtBACEDIAJBADYCHCACIAE2AhQgAkHGDDYCECACQSM2AgwMUwtBACEDIAJBADYCHCACIAE2AhQgAkHAFTYCECACQQI2AgwMUgsgAigCBCEAQQAhAyACQQA2AgQCQCACIAAgARAtIgBFBEAgAUEBaiEBDAELIAJBDjYCHCACIAA2AgwgAiABQQFqNgIUDFILQRshAww4C0EAIQMgAkEANgIcIAIgATYCFCACQcYMNgIQIAJBIzYCDAxQCyACKAIEIQBBACEDIAJBADYCBAJAIAIgACABECwiAEUEQCABQQFqIQEMAQsgAkENNgIcIAIgADYCDCACIAFBAWo2AhQMUAtBGiEDDDYLQQAhAyACQQA2AhwgAiABNgIUIAJBmg82AhAgAkEiNgIMDE4LIAIoAgQhAEEAIQMgAkEANgIEAkAgAiAAIAEQLCIARQRAIAFBAWohAQwBCyACQQw2AhwgAiAANgIMIAIgAUEBajYCFAxOC0EZIQMMNAtBACEDIAJBADYCHCACIAE2AhQgAkGaDzYCECACQSI2AgwMTAsgAEEVRwRAQQAhAyACQQA2AhwgAiABNgIUIAJBgww2AhAgAkETNgIMDEwLIAJBCjYCHCACIAE2AhQgAkHkFjYCECACQRU2AgxBACEDDEsLIAIoAgQhAEEAIQMgAkEANgIEIAIgACABIAqnaiIBECsiAARAIAJBBzYCHCACIAE2AhQgAiAANgIMDEsLQRMhAwwxCyAAQRVHBEBBACEDIAJBADYCHCACIAE2AhQgAkHaDTYCECACQRQ2AgwMSgsgAkEeNgIcIAIgATYCFCACQfkXNgIQIAJBFTYCDEEAIQMMSQtBACEAAkAgAigCOCIDRQ0AIAMoAiwiA0UNACACIAMRAAAhAAsgAEUNQSAAQRVGBEAgAkEDNgIcIAIgATYCFCACQbAYNgIQIAJBFTYCDEEAIQMMSQtBACEDIAJBADYCHCACIAE2AhQgAkGnDjYCECACQRI2AgwMSAtBACEDIAJBADYCHCACIAE2AhQgAkHaDTYCECACQRQ2AgwMRwtBACEDIAJBADYCHCACIAE2AhQgAkGnDjYCECACQRI2AgwMRgsgAkEAOgAvIAItAC1BBHFFDT8LIAJBADoALyACQQE6ADRBACEDDCsLQQAhAyACQQA2AhwgAkHkETYCECACQQc2AgwgAiABQQFqNgIUDEMLAkADQAJAIAEtAABBCmsOBAACAgACCyAEIAFBAWoiAUcNAAtB3QEhAwxDCwJAAkAgAi0ANEEBRw0AQQAhAAJAIAIoAjgiA0UNACADKAJYIgNFDQAgAiADEQAAIQALIABFDQAgAEEVRw0BIAJB3AE2AhwgAiABNgIUIAJB1RY2AhAgAkEVNgIMQQAhAwxEC0HBASEDDCoLIAJBADYCHCACIAE2AhQgAkHpCzYCECACQR82AgxBACEDDEILAkACQCACLQAoQQFrDgIEAQALQcABIQMMKQtBuQEhAwwoCyACQQI6AC9BACEAAkAgAigCOCIDRQ0AIAMoAgAiA0UNACACIAMRAAAhAAsgAEUEQEHCASEDDCgLIABBFUcEQCACQQA2AhwgAiABNgIUIAJBpAw2AhAgAkEQNgIMQQAhAwxBCyACQdsBNgIcIAIgATYCFCACQfoWNgIQIAJBFTYCDEEAIQMMQAsgASAERgRAQdoBIQMMQAsgAS0AAEHIAEYNASACQQE6ACgLQawBIQMMJQtBvwEhAwwkCyABIARHBEAgAkEQNgIIIAIgATYCBEG+ASEDDCQLQdkBIQMMPAsgASAERgRAQdgBIQMMPAsgAS0AAEHIAEcNBCABQQFqIQFBvQEhAwwiCyABIARGBEBB1wEhAww7CwJAAkAgAS0AAEHFAGsOEAAFBQUFBQUFBQUFBQUFBQEFCyABQQFqIQFBuwEhAwwiCyABQQFqIQFBvAEhAwwhC0HWASEDIAEgBEYNOSACKAIAIgAgBCABa2ohBSABIABrQQJqIQYCQANAIAEtAAAgAEGD0ABqLQAARw0DIABBAkYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAw6CyACKAIEIQAgAkIANwMAIAIgACAGQQFqIgEQJyIARQRAQcYBIQMMIQsgAkHVATYCHCACIAE2AhQgAiAANgIMQQAhAww5C0HUASEDIAEgBEYNOCACKAIAIgAgBCABa2ohBSABIABrQQFqIQYCQANAIAEtAAAgAEGB0ABqLQAARw0CIABBAUYNASAAQQFqIQAgBCABQQFqIgFHDQALIAIgBTYCAAw5CyACQYEEOwEoIAIoAgQhACACQgA3AwAgAiAAIAZBAWoiARAnIgANAwwCCyACQQA2AgALQQAhAyACQQA2AhwgAiABNgIUIAJB2Bs2AhAgAkEINgIMDDYLQboBIQMMHAsgAkHTATYCHCACIAE2AhQgAiAANgIMQQAhAww0C0EAIQACQCACKAI4IgNFDQAgAygCOCIDRQ0AIAIgAxEAACEACyAARQ0AIABBFUYNASACQQA2AhwgAiABNgIUIAJBzA42AhAgAkEgNgIMQQAhAwwzC0HkACEDDBkLIAJB+AA2AhwgAiABNgIUIAJByhg2AhAgAkEVNgIMQQAhAwwxC0HSASEDIAQgASIARg0wIAQgAWsgAigCACIBaiEFIAAgAWtBBGohBgJAA0AgAC0AACABQfzPAGotAABHDQEgAUEERg0DIAFBAWohASAEIABBAWoiAEcNAAsgAiAFNgIADDELIAJBADYCHCACIAA2AhQgAkGQMzYCECACQQg2AgwgAkEANgIAQQAhAwwwCyABIARHBEAgAkEONgIIIAIgATYCBEG3ASEDDBcLQdEBIQMMLwsgAkEANgIAIAZBAWohAQtBuAEhAwwUCyABIARGBEBB0AEhAwwtCyABLQAAQTBrIgBB/wFxQQpJBEAgAiAAOgAqIAFBAWohAUG2ASEDDBQLIAIoAgQhACACQQA2AgQgAiAAIAEQKCIARQ0UIAJBzwE2AhwgAiABNgIUIAIgADYCDEEAIQMMLAsgASAERgRAQc4BIQMMLAsCQCABLQAAQS5GBEAgAUEBaiEBDAELIAIoAgQhACACQQA2AgQgAiAAIAEQKCIARQ0VIAJBzQE2AhwgAiABNgIUIAIgADYCDEEAIQMMLAtBtQEhAwwSCyAEIAEiBUYEQEHMASEDDCsLQQAhAEEBIQFBASEGQQAhAwJAAkACQAJAAkACfwJAAkACQAJAAkACQAJAIAUtAABBMGsOCgoJAAECAwQFBggLC0ECDAYLQQMMBQtBBAwEC0EFDAMLQQYMAgtBBwwBC0EICyEDQQAhAUEAIQYMAgtBCSEDQQEhAEEAIQFBACEGDAELQQAhAUEBIQMLIAIgAzoAKyAFQQFqIQMCQAJAIAItAC1BEHENAAJAAkACQCACLQAqDgMBAAIECyAGRQ0DDAILIAANAQwCCyABRQ0BCyACKAIEIQAgAkEANgIEIAIgACADECgiAEUEQCADIQEMAwsgAkHJATYCHCACIAM2AhQgAiAANgIMQQAhAwwtCyACKAIEIQAgAkEANgIEIAIgACADECgiAEUEQCADIQEMGAsgAkHKATYCHCACIAM2AhQgAiAANgIMQQAhAwwsCyACKAIEIQAgAkEANgIEIAIgACAFECgiAEUEQCAFIQEMFgsgAkHLATYCHCACIAU2AhQgAiAANgIMDCsLQbQBIQMMEQtBACEAAkAgAigCOCIDRQ0AIAMoAjwiA0UNACACIAMRAAAhAAsCQCAABEAgAEEVRg0BIAJBADYCHCACIAE2AhQgAkGUDTYCECACQSE2AgxBACEDDCsLQbIBIQMMEQsgAkHIATYCHCACIAE2AhQgAkHJFzYCECACQRU2AgxBACEDDCkLIAJBADYCACAGQQFqIQFB9QAhAwwPCyACLQApQQVGBEBB4wAhAwwPC0HiACEDDA4LIAAhASACQQA2AgALIAJBADoALEEJIQMMDAsgAkEANgIAIAdBAWohAUHAACEDDAsLQQELOgAsIAJBADYCACAGQQFqIQELQSkhAwwIC0E4IQMMBwsCQCABIARHBEADQCABLQAAQYA+ai0AACIAQQFHBEAgAEECRw0DIAFBAWohAQwFCyAEIAFBAWoiAUcNAAtBPiEDDCELQT4hAwwgCwsgAkEAOgAsDAELQQshAwwEC0E6IQMMAwsgAUEBaiEBQS0hAwwCCyACIAE6ACwgAkEANgIAIAZBAWohAUEMIQMMAQsgAkEANgIAIAZBAWohAUEKIQMMAAsAC0EAIQMgAkEANgIcIAIgATYCFCACQc0QNgIQIAJBCTYCDAwXC0EAIQMgAkEANgIcIAIgATYCFCACQekKNgIQIAJBCTYCDAwWC0EAIQMgAkEANgIcIAIgATYCFCACQbcQNgIQIAJBCTYCDAwVC0EAIQMgAkEANgIcIAIgATYCFCACQZwRNgIQIAJBCTYCDAwUC0EAIQMgAkEANgIcIAIgATYCFCACQc0QNgIQIAJBCTYCDAwTC0EAIQMgAkEANgIcIAIgATYCFCACQekKNgIQIAJBCTYCDAwSC0EAIQMgAkEANgIcIAIgATYCFCACQbcQNgIQIAJBCTYCDAwRC0EAIQMgAkEANgIcIAIgATYCFCACQZwRNgIQIAJBCTYCDAwQC0EAIQMgAkEANgIcIAIgATYCFCACQZcVNgIQIAJBDzYCDAwPC0EAIQMgAkEANgIcIAIgATYCFCACQZcVNgIQIAJBDzYCDAwOC0EAIQMgAkEANgIcIAIgATYCFCACQcASNgIQIAJBCzYCDAwNC0EAIQMgAkEANgIcIAIgATYCFCACQZUJNgIQIAJBCzYCDAwMC0EAIQMgAkEANgIcIAIgATYCFCACQeEPNgIQIAJBCjYCDAwLC0EAIQMgAkEANgIcIAIgATYCFCACQfsPNgIQIAJBCjYCDAwKC0EAIQMgAkEANgIcIAIgATYCFCACQfEZNgIQIAJBAjYCDAwJC0EAIQMgAkEANgIcIAIgATYCFCACQcQUNgIQIAJBAjYCDAwIC0EAIQMgAkEANgIcIAIgATYCFCACQfIVNgIQIAJBAjYCDAwHCyACQQI2AhwgAiABNgIUIAJBnBo2AhAgAkEWNgIMQQAhAwwGC0EBIQMMBQtB1AAhAyABIARGDQQgCEEIaiEJIAIoAgAhBQJAAkAgASAERwRAIAVB2MIAaiEHIAQgBWogAWshACAFQX9zQQpqIgUgAWohBgNAIAEtAAAgBy0AAEcEQEECIQcMAwsgBUUEQEEAIQcgBiEBDAMLIAVBAWshBSAHQQFqIQcgBCABQQFqIgFHDQALIAAhBSAEIQELIAlBATYCACACIAU2AgAMAQsgAkEANgIAIAkgBzYCAAsgCSABNgIEIAgoAgwhACAIKAIIDgMBBAIACwALIAJBADYCHCACQbUaNgIQIAJBFzYCDCACIABBAWo2AhRBACEDDAILIAJBADYCHCACIAA2AhQgAkHKGjYCECACQQk2AgxBACEDDAELIAEgBEYEQEEiIQMMAQsgAkEJNgIIIAIgATYCBEEhIQMLIAhBEGokACADRQRAIAIoAgwhAAwBCyACIAM2AhxBACEAIAIoAgQiAUUNACACIAEgBCACKAIIEQEAIgFFDQAgAiAENgIUIAIgATYCDCABIQALIAALvgIBAn8gAEEAOgAAIABB3ABqIgFBAWtBADoAACAAQQA6AAIgAEEAOgABIAFBA2tBADoAACABQQJrQQA6AAAgAEEAOgADIAFBBGtBADoAAEEAIABrQQNxIgEgAGoiAEEANgIAQdwAIAFrQXxxIgIgAGoiAUEEa0EANgIAAkAgAkEJSQ0AIABBADYCCCAAQQA2AgQgAUEIa0EANgIAIAFBDGtBADYCACACQRlJDQAgAEEANgIYIABBADYCFCAAQQA2AhAgAEEANgIMIAFBEGtBADYCACABQRRrQQA2AgAgAUEYa0EANgIAIAFBHGtBADYCACACIABBBHFBGHIiAmsiAUEgSQ0AIAAgAmohAANAIABCADcDGCAAQgA3AxAgAEIANwMIIABCADcDACAAQSBqIQAgAUEgayIBQR9LDQALCwtWAQF/AkAgACgCDA0AAkACQAJAAkAgAC0ALw4DAQADAgsgACgCOCIBRQ0AIAEoAiwiAUUNACAAIAERAAAiAQ0DC0EADwsACyAAQcMWNgIQQQ4hAQsgAQsaACAAKAIMRQRAIABB0Rs2AhAgAEEVNgIMCwsUACAAKAIMQRVGBEAgAEEANgIMCwsUACAAKAIMQRZGBEAgAEEANgIMCwsHACAAKAIMCwcAIAAoAhALCQAgACABNgIQCwcAIAAoAhQLFwAgAEEkTwRAAAsgAEECdEGgM2ooAgALFwAgAEEuTwRAAAsgAEECdEGwNGooAgALvwkBAX9B6yghAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABB5ABrDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhBgcICQoLDA0OD2FhYWFhEGFhYWFhYWFhYWFhEWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYRITFBUWFxgZGhthYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2YTc4OTphYWFhYWFhYTthYWE8YWFhYT0+P2FhYWFhYWFhQGFhQWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYUJDREVGR0hJSktMTU5PUFFSU2FhYWFhYWFhVFVWV1hZWlthXF1hYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFeYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhX2BhC0HhJw8LQaQhDwtByywPC0H+MQ8LQcAkDwtBqyQPC0GNKA8LQeImDwtBgDAPC0G5Lw8LQdckDwtB7x8PC0HhHw8LQfofDwtB8iAPC0GoLw8LQa4yDwtBiDAPC0HsJw8LQYIiDwtBjh0PC0HQLg8LQcojDwtBxTIPC0HfHA8LQdIcDwtBxCAPC0HXIA8LQaIfDwtB7S4PC0GrMA8LQdQlDwtBzC4PC0H6Lg8LQfwrDwtB0jAPC0HxHQ8LQbsgDwtB9ysPC0GQMQ8LQdcxDwtBoi0PC0HUJw8LQeArDwtBnywPC0HrMQ8LQdUfDwtByjEPC0HeJQ8LQdQeDwtB9BwPC0GnMg8LQbEdDwtBoB0PC0G5MQ8LQbwwDwtBkiEPC0GzJg8LQeksDwtBrB4PC0HUKw8LQfcmDwtBgCYPC0GwIQ8LQf4eDwtBjSMPC0GJLQ8LQfciDwtBoDEPC0GuHw8LQcYlDwtB6B4PC0GTIg8LQcIvDwtBwx0PC0GLLA8LQeEdDwtBjS8PC0HqIQ8LQbQtDwtB0i8PC0HfMg8LQdIyDwtB8DAPC0GpIg8LQfkjDwtBmR4PC0G1LA8LQZswDwtBkjIPC0G2Kw8LQcIiDwtB+DIPC0GeJQ8LQdAiDwtBuh4PC0GBHg8LAAtB1iEhAQsgAQsWACAAIAAtAC1B/gFxIAFBAEdyOgAtCxkAIAAgAC0ALUH9AXEgAUEAR0EBdHI6AC0LGQAgACAALQAtQfsBcSABQQBHQQJ0cjoALQsZACAAIAAtAC1B9wFxIAFBAEdBA3RyOgAtCz4BAn8CQCAAKAI4IgNFDQAgAygCBCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBxhE2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCCCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB9go2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCDCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB7Ro2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCECIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBlRA2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCFCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBqhs2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCGCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB7RM2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCKCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABB9gg2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCHCIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBwhk2AhBBGCEECyAECz4BAn8CQCAAKAI4IgNFDQAgAygCICIDRQ0AIAAgASACIAFrIAMRAQAiBEF/Rw0AIABBlBQ2AhBBGCEECyAEC1kBAn8CQCAALQAoQQFGDQAgAC8BMiIBQeQAa0HkAEkNACABQcwBRg0AIAFBsAJGDQAgAC8BMCIAQcAAcQ0AQQEhAiAAQYgEcUGABEYNACAAQShxRSECCyACC4wBAQJ/AkACQAJAIAAtACpFDQAgAC0AK0UNACAALwEwIgFBAnFFDQEMAgsgAC8BMCIBQQFxRQ0BC0EBIQIgAC0AKEEBRg0AIAAvATIiAEHkAGtB5ABJDQAgAEHMAUYNACAAQbACRg0AIAFBwABxDQBBACECIAFBiARxQYAERg0AIAFBKHFBAEchAgsgAgtzACAAQRBq/QwAAAAAAAAAAAAAAAAAAAAA/QsDACAA/QwAAAAAAAAAAAAAAAAAAAAA/QsDACAAQTBq/QwAAAAAAAAAAAAAAAAAAAAA/QsDACAAQSBq/QwAAAAAAAAAAAAAAAAAAAAA/QsDACAAQd0BNgIcCwYAIAAQMguaLQELfyMAQRBrIgokAEGk0AAoAgAiCUUEQEHk0wAoAgAiBUUEQEHw0wBCfzcCAEHo0wBCgICEgICAwAA3AgBB5NMAIApBCGpBcHFB2KrVqgVzIgU2AgBB+NMAQQA2AgBByNMAQQA2AgALQczTAEGA1AQ2AgBBnNAAQYDUBDYCAEGw0AAgBTYCAEGs0ABBfzYCAEHQ0wBBgKwDNgIAA0AgAUHI0ABqIAFBvNAAaiICNgIAIAIgAUG00ABqIgM2AgAgAUHA0ABqIAM2AgAgAUHQ0ABqIAFBxNAAaiIDNgIAIAMgAjYCACABQdjQAGogAUHM0ABqIgI2AgAgAiADNgIAIAFB1NAAaiACNgIAIAFBIGoiAUGAAkcNAAtBjNQEQcGrAzYCAEGo0ABB9NMAKAIANgIAQZjQAEHAqwM2AgBBpNAAQYjUBDYCAEHM/wdBODYCAEGI1AQhCQsCQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAAQewBTQRAQYzQACgCACIGQRAgAEETakFwcSAAQQtJGyIEQQN2IgB2IgFBA3EEQAJAIAFBAXEgAHJBAXMiAkEDdCIAQbTQAGoiASAAQbzQAGooAgAiACgCCCIDRgRAQYzQACAGQX4gAndxNgIADAELIAEgAzYCCCADIAE2AgwLIABBCGohASAAIAJBA3QiAkEDcjYCBCAAIAJqIgAgACgCBEEBcjYCBAwRC0GU0AAoAgAiCCAETw0BIAEEQAJAQQIgAHQiAkEAIAJrciABIAB0cWgiAEEDdCICQbTQAGoiASACQbzQAGooAgAiAigCCCIDRgRAQYzQACAGQX4gAHdxIgY2AgAMAQsgASADNgIIIAMgATYCDAsgAiAEQQNyNgIEIABBA3QiACAEayEFIAAgAmogBTYCACACIARqIgQgBUEBcjYCBCAIBEAgCEF4cUG00ABqIQBBoNAAKAIAIQMCf0EBIAhBA3Z0IgEgBnFFBEBBjNAAIAEgBnI2AgAgAAwBCyAAKAIICyIBIAM2AgwgACADNgIIIAMgADYCDCADIAE2AggLIAJBCGohAUGg0AAgBDYCAEGU0AAgBTYCAAwRC0GQ0AAoAgAiC0UNASALaEECdEG80gBqKAIAIgAoAgRBeHEgBGshBSAAIQIDQAJAIAIoAhAiAUUEQCACQRRqKAIAIgFFDQELIAEoAgRBeHEgBGsiAyAFSSECIAMgBSACGyEFIAEgACACGyEAIAEhAgwBCwsgACgCGCEJIAAoAgwiAyAARwRAQZzQACgCABogAyAAKAIIIgE2AgggASADNgIMDBALIABBFGoiAigCACIBRQRAIAAoAhAiAUUNAyAAQRBqIQILA0AgAiEHIAEiA0EUaiICKAIAIgENACADQRBqIQIgAygCECIBDQALIAdBADYCAAwPC0F/IQQgAEG/f0sNACAAQRNqIgFBcHEhBEGQ0AAoAgAiCEUNAEEAIARrIQUCQAJAAkACf0EAIARBgAJJDQAaQR8gBEH///8HSw0AGiAEQSYgAUEIdmciAGt2QQFxIABBAXRrQT5qCyIGQQJ0QbzSAGooAgAiAkUEQEEAIQFBACEDDAELQQAhASAEQRkgBkEBdmtBACAGQR9HG3QhAEEAIQMDQAJAIAIoAgRBeHEgBGsiByAFTw0AIAIhAyAHIgUNAEEAIQUgAiEBDAMLIAEgAkEUaigCACIHIAcgAiAAQR12QQRxakEQaigCACICRhsgASAHGyEBIABBAXQhACACDQALCyABIANyRQRAQQAhA0ECIAZ0IgBBACAAa3IgCHEiAEUNAyAAaEECdEG80gBqKAIAIQELIAFFDQELA0AgASgCBEF4cSAEayICIAVJIQAgAiAFIAAbIQUgASADIAAbIQMgASgCECIABH8gAAUgAUEUaigCAAsiAQ0ACwsgA0UNACAFQZTQACgCACAEa08NACADKAIYIQcgAyADKAIMIgBHBEBBnNAAKAIAGiAAIAMoAggiATYCCCABIAA2AgwMDgsgA0EUaiICKAIAIgFFBEAgAygCECIBRQ0DIANBEGohAgsDQCACIQYgASIAQRRqIgIoAgAiAQ0AIABBEGohAiAAKAIQIgENAAsgBkEANgIADA0LQZTQACgCACIDIARPBEBBoNAAKAIAIQECQCADIARrIgJBEE8EQCABIARqIgAgAkEBcjYCBCABIANqIAI2AgAgASAEQQNyNgIEDAELIAEgA0EDcjYCBCABIANqIgAgACgCBEEBcjYCBEEAIQBBACECC0GU0AAgAjYCAEGg0AAgADYCACABQQhqIQEMDwtBmNAAKAIAIgMgBEsEQCAEIAlqIgAgAyAEayIBQQFyNgIEQaTQACAANgIAQZjQACABNgIAIAkgBEEDcjYCBCAJQQhqIQEMDwtBACEBIAQCf0Hk0wAoAgAEQEHs0wAoAgAMAQtB8NMAQn83AgBB6NMAQoCAhICAgMAANwIAQeTTACAKQQxqQXBxQdiq1aoFczYCAEH40wBBADYCAEHI0wBBADYCAEGAgAQLIgAgBEHHAGoiBWoiBkEAIABrIgdxIgJPBEBB/NMAQTA2AgAMDwsCQEHE0wAoAgAiAUUNAEG80wAoAgAiCCACaiEAIAAgAU0gACAIS3ENAEEAIQFB/NMAQTA2AgAMDwtByNMALQAAQQRxDQQCQAJAIAkEQEHM0wAhAQNAIAEoAgAiACAJTQRAIAAgASgCBGogCUsNAwsgASgCCCIBDQALC0EAEDMiAEF/Rg0FIAIhBkHo0wAoAgAiAUEBayIDIABxBEAgAiAAayAAIANqQQAgAWtxaiEGCyAEIAZPDQUgBkH+////B0sNBUHE0wAoAgAiAwRAQbzTACgCACIHIAZqIQEgASAHTQ0GIAEgA0sNBgsgBhAzIgEgAEcNAQwHCyAGIANrIAdxIgZB/v///wdLDQQgBhAzIQAgACABKAIAIAEoAgRqRg0DIAAhAQsCQCAGIARByABqTw0AIAFBf0YNAEHs0wAoAgAiACAFIAZrakEAIABrcSIAQf7///8HSwRAIAEhAAwHCyAAEDNBf0cEQCAAIAZqIQYgASEADAcLQQAgBmsQMxoMBAsgASIAQX9HDQUMAwtBACEDDAwLQQAhAAwKCyAAQX9HDQILQcjTAEHI0wAoAgBBBHI2AgALIAJB/v///wdLDQEgAhAzIQBBABAzIQEgAEF/Rg0BIAFBf0YNASAAIAFPDQEgASAAayIGIARBOGpNDQELQbzTAEG80wAoAgAgBmoiATYCAEHA0wAoAgAgAUkEQEHA0wAgATYCAAsCQAJAAkBBpNAAKAIAIgIEQEHM0wAhAQNAIAAgASgCACIDIAEoAgQiBWpGDQIgASgCCCIBDQALDAILQZzQACgCACIBQQBHIAAgAU9xRQRAQZzQACAANgIAC0EAIQFB0NMAIAY2AgBBzNMAIAA2AgBBrNAAQX82AgBBsNAAQeTTACgCADYCAEHY0wBBADYCAANAIAFByNAAaiABQbzQAGoiAjYCACACIAFBtNAAaiIDNgIAIAFBwNAAaiADNgIAIAFB0NAAaiABQcTQAGoiAzYCACADIAI2AgAgAUHY0ABqIAFBzNAAaiICNgIAIAIgAzYCACABQdTQAGogAjYCACABQSBqIgFBgAJHDQALQXggAGtBD3EiASAAaiICIAZBOGsiAyABayIBQQFyNgIEQajQAEH00wAoAgA2AgBBmNAAIAE2AgBBpNAAIAI2AgAgACADakE4NgIEDAILIAAgAk0NACACIANJDQAgASgCDEEIcQ0AQXggAmtBD3EiACACaiIDQZjQACgCACAGaiIHIABrIgBBAXI2AgQgASAFIAZqNgIEQajQAEH00wAoAgA2AgBBmNAAIAA2AgBBpNAAIAM2AgAgAiAHakE4NgIEDAELIABBnNAAKAIASQRAQZzQACAANgIACyAAIAZqIQNBzNMAIQECQAJAAkADQCADIAEoAgBHBEAgASgCCCIBDQEMAgsLIAEtAAxBCHFFDQELQczTACEBA0AgASgCACIDIAJNBEAgAyABKAIEaiIFIAJLDQMLIAEoAgghAQwACwALIAEgADYCACABIAEoAgQgBmo2AgQgAEF4IABrQQ9xaiIJIARBA3I2AgQgA0F4IANrQQ9xaiIGIAQgCWoiBGshASACIAZGBEBBpNAAIAQ2AgBBmNAAQZjQACgCACABaiIANgIAIAQgAEEBcjYCBAwIC0Gg0AAoAgAgBkYEQEGg0AAgBDYCAEGU0ABBlNAAKAIAIAFqIgA2AgAgBCAAQQFyNgIEIAAgBGogADYCAAwICyAGKAIEIgVBA3FBAUcNBiAFQXhxIQggBUH/AU0EQCAFQQN2IQMgBigCCCIAIAYoAgwiAkYEQEGM0ABBjNAAKAIAQX4gA3dxNgIADAcLIAIgADYCCCAAIAI2AgwMBgsgBigCGCEHIAYgBigCDCIARwRAIAAgBigCCCICNgIIIAIgADYCDAwFCyAGQRRqIgIoAgAiBUUEQCAGKAIQIgVFDQQgBkEQaiECCwNAIAIhAyAFIgBBFGoiAigCACIFDQAgAEEQaiECIAAoAhAiBQ0ACyADQQA2AgAMBAtBeCAAa0EPcSIBIABqIgcgBkE4ayIDIAFrIgFBAXI2AgQgACADakE4NgIEIAIgBUE3IAVrQQ9xakE/ayIDIAMgAkEQakkbIgNBIzYCBEGo0ABB9NMAKAIANgIAQZjQACABNgIAQaTQACAHNgIAIANBEGpB1NMAKQIANwIAIANBzNMAKQIANwIIQdTTACADQQhqNgIAQdDTACAGNgIAQczTACAANgIAQdjTAEEANgIAIANBJGohAQNAIAFBBzYCACAFIAFBBGoiAUsNAAsgAiADRg0AIAMgAygCBEF+cTYCBCADIAMgAmsiBTYCACACIAVBAXI2AgQgBUH/AU0EQCAFQXhxQbTQAGohAAJ/QYzQACgCACIBQQEgBUEDdnQiA3FFBEBBjNAAIAEgA3I2AgAgAAwBCyAAKAIICyIBIAI2AgwgACACNgIIIAIgADYCDCACIAE2AggMAQtBHyEBIAVB////B00EQCAFQSYgBUEIdmciAGt2QQFxIABBAXRrQT5qIQELIAIgATYCHCACQgA3AhAgAUECdEG80gBqIQBBkNAAKAIAIgNBASABdCIGcUUEQCAAIAI2AgBBkNAAIAMgBnI2AgAgAiAANgIYIAIgAjYCCCACIAI2AgwMAQsgBUEZIAFBAXZrQQAgAUEfRxt0IQEgACgCACEDAkADQCADIgAoAgRBeHEgBUYNASABQR12IQMgAUEBdCEBIAAgA0EEcWpBEGoiBigCACIDDQALIAYgAjYCACACIAA2AhggAiACNgIMIAIgAjYCCAwBCyAAKAIIIgEgAjYCDCAAIAI2AgggAkEANgIYIAIgADYCDCACIAE2AggLQZjQACgCACIBIARNDQBBpNAAKAIAIgAgBGoiAiABIARrIgFBAXI2AgRBmNAAIAE2AgBBpNAAIAI2AgAgACAEQQNyNgIEIABBCGohAQwIC0EAIQFB/NMAQTA2AgAMBwtBACEACyAHRQ0AAkAgBigCHCICQQJ0QbzSAGoiAygCACAGRgRAIAMgADYCACAADQFBkNAAQZDQACgCAEF+IAJ3cTYCAAwCCyAHQRBBFCAHKAIQIAZGG2ogADYCACAARQ0BCyAAIAc2AhggBigCECICBEAgACACNgIQIAIgADYCGAsgBkEUaigCACICRQ0AIABBFGogAjYCACACIAA2AhgLIAEgCGohASAGIAhqIgYoAgQhBQsgBiAFQX5xNgIEIAEgBGogATYCACAEIAFBAXI2AgQgAUH/AU0EQCABQXhxQbTQAGohAAJ/QYzQACgCACICQQEgAUEDdnQiAXFFBEBBjNAAIAEgAnI2AgAgAAwBCyAAKAIICyIBIAQ2AgwgACAENgIIIAQgADYCDCAEIAE2AggMAQtBHyEFIAFB////B00EQCABQSYgAUEIdmciAGt2QQFxIABBAXRrQT5qIQULIAQgBTYCHCAEQgA3AhAgBUECdEG80gBqIQBBkNAAKAIAIgJBASAFdCIDcUUEQCAAIAQ2AgBBkNAAIAIgA3I2AgAgBCAANgIYIAQgBDYCCCAEIAQ2AgwMAQsgAUEZIAVBAXZrQQAgBUEfRxt0IQUgACgCACEAAkADQCAAIgIoAgRBeHEgAUYNASAFQR12IQAgBUEBdCEFIAIgAEEEcWpBEGoiAygCACIADQALIAMgBDYCACAEIAI2AhggBCAENgIMIAQgBDYCCAwBCyACKAIIIgAgBDYCDCACIAQ2AgggBEEANgIYIAQgAjYCDCAEIAA2AggLIAlBCGohAQwCCwJAIAdFDQACQCADKAIcIgFBAnRBvNIAaiICKAIAIANGBEAgAiAANgIAIAANAUGQ0AAgCEF+IAF3cSIINgIADAILIAdBEEEUIAcoAhAgA0YbaiAANgIAIABFDQELIAAgBzYCGCADKAIQIgEEQCAAIAE2AhAgASAANgIYCyADQRRqKAIAIgFFDQAgAEEUaiABNgIAIAEgADYCGAsCQCAFQQ9NBEAgAyAEIAVqIgBBA3I2AgQgACADaiIAIAAoAgRBAXI2AgQMAQsgAyAEaiICIAVBAXI2AgQgAyAEQQNyNgIEIAIgBWogBTYCACAFQf8BTQRAIAVBeHFBtNAAaiEAAn9BjNAAKAIAIgFBASAFQQN2dCIFcUUEQEGM0AAgASAFcjYCACAADAELIAAoAggLIgEgAjYCDCAAIAI2AgggAiAANgIMIAIgATYCCAwBC0EfIQEgBUH///8HTQRAIAVBJiAFQQh2ZyIAa3ZBAXEgAEEBdGtBPmohAQsgAiABNgIcIAJCADcCECABQQJ0QbzSAGohAEEBIAF0IgQgCHFFBEAgACACNgIAQZDQACAEIAhyNgIAIAIgADYCGCACIAI2AgggAiACNgIMDAELIAVBGSABQQF2a0EAIAFBH0cbdCEBIAAoAgAhBAJAA0AgBCIAKAIEQXhxIAVGDQEgAUEddiEEIAFBAXQhASAAIARBBHFqQRBqIgYoAgAiBA0ACyAGIAI2AgAgAiAANgIYIAIgAjYCDCACIAI2AggMAQsgACgCCCIBIAI2AgwgACACNgIIIAJBADYCGCACIAA2AgwgAiABNgIICyADQQhqIQEMAQsCQCAJRQ0AAkAgACgCHCIBQQJ0QbzSAGoiAigCACAARgRAIAIgAzYCACADDQFBkNAAIAtBfiABd3E2AgAMAgsgCUEQQRQgCSgCECAARhtqIAM2AgAgA0UNAQsgAyAJNgIYIAAoAhAiAQRAIAMgATYCECABIAM2AhgLIABBFGooAgAiAUUNACADQRRqIAE2AgAgASADNgIYCwJAIAVBD00EQCAAIAQgBWoiAUEDcjYCBCAAIAFqIgEgASgCBEEBcjYCBAwBCyAAIARqIgcgBUEBcjYCBCAAIARBA3I2AgQgBSAHaiAFNgIAIAgEQCAIQXhxQbTQAGohAUGg0AAoAgAhAwJ/QQEgCEEDdnQiAiAGcUUEQEGM0AAgAiAGcjYCACABDAELIAEoAggLIgIgAzYCDCABIAM2AgggAyABNgIMIAMgAjYCCAtBoNAAIAc2AgBBlNAAIAU2AgALIABBCGohAQsgCkEQaiQAIAELQwAgAEUEQD8AQRB0DwsCQCAAQf//A3ENACAAQQBIDQAgAEEQdkAAIgBBf0YEQEH80wBBMDYCAEF/DwsgAEEQdA8LAAsL3D8iAEGACAsJAQAAAAIAAAADAEGUCAsFBAAAAAUAQaQICwkGAAAABwAAAAgAQdwIC4otSW52YWxpZCBjaGFyIGluIHVybCBxdWVyeQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2JvZHkAQ29udGVudC1MZW5ndGggb3ZlcmZsb3cAQ2h1bmsgc2l6ZSBvdmVyZmxvdwBSZXNwb25zZSBvdmVyZmxvdwBJbnZhbGlkIG1ldGhvZCBmb3IgSFRUUC94LnggcmVxdWVzdABJbnZhbGlkIG1ldGhvZCBmb3IgUlRTUC94LnggcmVxdWVzdABFeHBlY3RlZCBTT1VSQ0UgbWV0aG9kIGZvciBJQ0UveC54IHJlcXVlc3QASW52YWxpZCBjaGFyIGluIHVybCBmcmFnbWVudCBzdGFydABFeHBlY3RlZCBkb3QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9zdGF0dXMASW52YWxpZCByZXNwb25zZSBzdGF0dXMASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucwBVc2VyIGNhbGxiYWNrIGVycm9yAGBvbl9yZXNldGAgY2FsbGJhY2sgZXJyb3IAYG9uX2NodW5rX2hlYWRlcmAgY2FsbGJhY2sgZXJyb3IAYG9uX21lc3NhZ2VfYmVnaW5gIGNhbGxiYWNrIGVycm9yAGBvbl9jaHVua19leHRlbnNpb25fdmFsdWVgIGNhbGxiYWNrIGVycm9yAGBvbl9zdGF0dXNfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl92ZXJzaW9uX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fdXJsX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGVgIGNhbGxiYWNrIGVycm9yAGBvbl9tZXNzYWdlX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fbWV0aG9kX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlYCBjYWxsYmFjayBlcnJvcgBgb25fY2h1bmtfZXh0ZW5zaW9uX25hbWVgIGNhbGxiYWNrIGVycm9yAFVuZXhwZWN0ZWQgY2hhciBpbiB1cmwgc2VydmVyAEludmFsaWQgaGVhZGVyIHZhbHVlIGNoYXIASW52YWxpZCBoZWFkZXIgZmllbGQgY2hhcgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3ZlcnNpb24ASW52YWxpZCBtaW5vciB2ZXJzaW9uAEludmFsaWQgbWFqb3IgdmVyc2lvbgBFeHBlY3RlZCBzcGFjZSBhZnRlciB2ZXJzaW9uAEV4cGVjdGVkIENSTEYgYWZ0ZXIgdmVyc2lvbgBJbnZhbGlkIEhUVFAgdmVyc2lvbgBJbnZhbGlkIGhlYWRlciB0b2tlbgBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX3VybABJbnZhbGlkIGNoYXJhY3RlcnMgaW4gdXJsAFVuZXhwZWN0ZWQgc3RhcnQgY2hhciBpbiB1cmwARG91YmxlIEAgaW4gdXJsAEVtcHR5IENvbnRlbnQtTGVuZ3RoAEludmFsaWQgY2hhcmFjdGVyIGluIENvbnRlbnQtTGVuZ3RoAER1cGxpY2F0ZSBDb250ZW50LUxlbmd0aABJbnZhbGlkIGNoYXIgaW4gdXJsIHBhdGgAQ29udGVudC1MZW5ndGggY2FuJ3QgYmUgcHJlc2VudCB3aXRoIFRyYW5zZmVyLUVuY29kaW5nAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIHNpemUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfdmFsdWUAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9jaHVua19leHRlbnNpb25fdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyB2YWx1ZQBNaXNzaW5nIGV4cGVjdGVkIExGIGFmdGVyIGhlYWRlciB2YWx1ZQBJbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AgaGVhZGVyIHZhbHVlAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgcXVvdGUgdmFsdWUASW52YWxpZCBjaGFyYWN0ZXIgaW4gY2h1bmsgZXh0ZW5zaW9ucyBxdW90ZWQgdmFsdWUAUGF1c2VkIGJ5IG9uX2hlYWRlcnNfY29tcGxldGUASW52YWxpZCBFT0Ygc3RhdGUAb25fcmVzZXQgcGF1c2UAb25fY2h1bmtfaGVhZGVyIHBhdXNlAG9uX21lc3NhZ2VfYmVnaW4gcGF1c2UAb25fY2h1bmtfZXh0ZW5zaW9uX3ZhbHVlIHBhdXNlAG9uX3N0YXR1c19jb21wbGV0ZSBwYXVzZQBvbl92ZXJzaW9uX2NvbXBsZXRlIHBhdXNlAG9uX3VybF9jb21wbGV0ZSBwYXVzZQBvbl9jaHVua19jb21wbGV0ZSBwYXVzZQBvbl9oZWFkZXJfdmFsdWVfY29tcGxldGUgcGF1c2UAb25fbWVzc2FnZV9jb21wbGV0ZSBwYXVzZQBvbl9tZXRob2RfY29tcGxldGUgcGF1c2UAb25faGVhZGVyX2ZpZWxkX2NvbXBsZXRlIHBhdXNlAG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lIHBhdXNlAFVuZXhwZWN0ZWQgc3BhY2UgYWZ0ZXIgc3RhcnQgbGluZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX2NodW5rX2V4dGVuc2lvbl9uYW1lAEludmFsaWQgY2hhcmFjdGVyIGluIGNodW5rIGV4dGVuc2lvbnMgbmFtZQBQYXVzZSBvbiBDT05ORUNUL1VwZ3JhZGUAUGF1c2Ugb24gUFJJL1VwZ3JhZGUARXhwZWN0ZWQgSFRUUC8yIENvbm5lY3Rpb24gUHJlZmFjZQBTcGFuIGNhbGxiYWNrIGVycm9yIGluIG9uX21ldGhvZABFeHBlY3RlZCBzcGFjZSBhZnRlciBtZXRob2QAU3BhbiBjYWxsYmFjayBlcnJvciBpbiBvbl9oZWFkZXJfZmllbGQAUGF1c2VkAEludmFsaWQgd29yZCBlbmNvdW50ZXJlZABJbnZhbGlkIG1ldGhvZCBlbmNvdW50ZXJlZABVbmV4cGVjdGVkIGNoYXIgaW4gdXJsIHNjaGVtYQBSZXF1ZXN0IGhhcyBpbnZhbGlkIGBUcmFuc2Zlci1FbmNvZGluZ2AAU1dJVENIX1BST1hZAFVTRV9QUk9YWQBNS0FDVElWSVRZAFVOUFJPQ0VTU0FCTEVfRU5USVRZAENPUFkATU9WRURfUEVSTUFORU5UTFkAVE9PX0VBUkxZAE5PVElGWQBGQUlMRURfREVQRU5ERU5DWQBCQURfR0FURVdBWQBQTEFZAFBVVABDSEVDS09VVABHQVRFV0FZX1RJTUVPVVQAUkVRVUVTVF9USU1FT1VUAE5FVFdPUktfQ09OTkVDVF9USU1FT1VUAENPTk5FQ1RJT05fVElNRU9VVABMT0dJTl9USU1FT1VUAE5FVFdPUktfUkVBRF9USU1FT1VUAFBPU1QATUlTRElSRUNURURfUkVRVUVTVABDTElFTlRfQ0xPU0VEX1JFUVVFU1QAQ0xJRU5UX0NMT1NFRF9MT0FEX0JBTEFOQ0VEX1JFUVVFU1QAQkFEX1JFUVVFU1QASFRUUF9SRVFVRVNUX1NFTlRfVE9fSFRUUFNfUE9SVABSRVBPUlQASU1fQV9URUFQT1QAUkVTRVRfQ09OVEVOVABOT19DT05URU5UAFBBUlRJQUxfQ09OVEVOVABIUEVfSU5WQUxJRF9DT05TVEFOVABIUEVfQ0JfUkVTRVQAR0VUAEhQRV9TVFJJQ1QAQ09ORkxJQ1QAVEVNUE9SQVJZX1JFRElSRUNUAFBFUk1BTkVOVF9SRURJUkVDVABDT05ORUNUAE1VTFRJX1NUQVRVUwBIUEVfSU5WQUxJRF9TVEFUVVMAVE9PX01BTllfUkVRVUVTVFMARUFSTFlfSElOVFMAVU5BVkFJTEFCTEVfRk9SX0xFR0FMX1JFQVNPTlMAT1BUSU9OUwBTV0lUQ0hJTkdfUFJPVE9DT0xTAFZBUklBTlRfQUxTT19ORUdPVElBVEVTAE1VTFRJUExFX0NIT0lDRVMASU5URVJOQUxfU0VSVkVSX0VSUk9SAFdFQl9TRVJWRVJfVU5LTk9XTl9FUlJPUgBSQUlMR1VOX0VSUk9SAElERU5USVRZX1BST1ZJREVSX0FVVEhFTlRJQ0FUSU9OX0VSUk9SAFNTTF9DRVJUSUZJQ0FURV9FUlJPUgBJTlZBTElEX1hfRk9SV0FSREVEX0ZPUgBTRVRfUEFSQU1FVEVSAEdFVF9QQVJBTUVURVIASFBFX1VTRVIAU0VFX09USEVSAEhQRV9DQl9DSFVOS19IRUFERVIATUtDQUxFTkRBUgBTRVRVUABXRUJfU0VSVkVSX0lTX0RPV04AVEVBUkRPV04ASFBFX0NMT1NFRF9DT05ORUNUSU9OAEhFVVJJU1RJQ19FWFBJUkFUSU9OAERJU0NPTk5FQ1RFRF9PUEVSQVRJT04ATk9OX0FVVEhPUklUQVRJVkVfSU5GT1JNQVRJT04ASFBFX0lOVkFMSURfVkVSU0lPTgBIUEVfQ0JfTUVTU0FHRV9CRUdJTgBTSVRFX0lTX0ZST1pFTgBIUEVfSU5WQUxJRF9IRUFERVJfVE9LRU4ASU5WQUxJRF9UT0tFTgBGT1JCSURERU4ARU5IQU5DRV9ZT1VSX0NBTE0ASFBFX0lOVkFMSURfVVJMAEJMT0NLRURfQllfUEFSRU5UQUxfQ09OVFJPTABNS0NPTABBQ0wASFBFX0lOVEVSTkFMAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0VfVU5PRkZJQ0lBTABIUEVfT0sAVU5MSU5LAFVOTE9DSwBQUkkAUkVUUllfV0lUSABIUEVfSU5WQUxJRF9DT05URU5UX0xFTkdUSABIUEVfVU5FWFBFQ1RFRF9DT05URU5UX0xFTkdUSABGTFVTSABQUk9QUEFUQ0gATS1TRUFSQ0gAVVJJX1RPT19MT05HAFBST0NFU1NJTkcATUlTQ0VMTEFORU9VU19QRVJTSVNURU5UX1dBUk5JTkcATUlTQ0VMTEFORU9VU19XQVJOSU5HAEhQRV9JTlZBTElEX1RSQU5TRkVSX0VOQ09ESU5HAEV4cGVjdGVkIENSTEYASFBFX0lOVkFMSURfQ0hVTktfU0laRQBNT1ZFAENPTlRJTlVFAEhQRV9DQl9TVEFUVVNfQ09NUExFVEUASFBFX0NCX0hFQURFUlNfQ09NUExFVEUASFBFX0NCX1ZFUlNJT05fQ09NUExFVEUASFBFX0NCX1VSTF9DT01QTEVURQBIUEVfQ0JfQ0hVTktfQ09NUExFVEUASFBFX0NCX0hFQURFUl9WQUxVRV9DT01QTEVURQBIUEVfQ0JfQ0hVTktfRVhURU5TSU9OX1ZBTFVFX0NPTVBMRVRFAEhQRV9DQl9DSFVOS19FWFRFTlNJT05fTkFNRV9DT01QTEVURQBIUEVfQ0JfTUVTU0FHRV9DT01QTEVURQBIUEVfQ0JfTUVUSE9EX0NPTVBMRVRFAEhQRV9DQl9IRUFERVJfRklFTERfQ09NUExFVEUAREVMRVRFAEhQRV9JTlZBTElEX0VPRl9TVEFURQBJTlZBTElEX1NTTF9DRVJUSUZJQ0FURQBQQVVTRQBOT19SRVNQT05TRQBVTlNVUFBPUlRFRF9NRURJQV9UWVBFAEdPTkUATk9UX0FDQ0VQVEFCTEUAU0VSVklDRV9VTkFWQUlMQUJMRQBSQU5HRV9OT1RfU0FUSVNGSUFCTEUAT1JJR0lOX0lTX1VOUkVBQ0hBQkxFAFJFU1BPTlNFX0lTX1NUQUxFAFBVUkdFAE1FUkdFAFJFUVVFU1RfSEVBREVSX0ZJRUxEU19UT09fTEFSR0UAUkVRVUVTVF9IRUFERVJfVE9PX0xBUkdFAFBBWUxPQURfVE9PX0xBUkdFAElOU1VGRklDSUVOVF9TVE9SQUdFAEhQRV9QQVVTRURfVVBHUkFERQBIUEVfUEFVU0VEX0gyX1VQR1JBREUAU09VUkNFAEFOTk9VTkNFAFRSQUNFAEhQRV9VTkVYUEVDVEVEX1NQQUNFAERFU0NSSUJFAFVOU1VCU0NSSUJFAFJFQ09SRABIUEVfSU5WQUxJRF9NRVRIT0QATk9UX0ZPVU5EAFBST1BGSU5EAFVOQklORABSRUJJTkQAVU5BVVRIT1JJWkVEAE1FVEhPRF9OT1RfQUxMT1dFRABIVFRQX1ZFUlNJT05fTk9UX1NVUFBPUlRFRABBTFJFQURZX1JFUE9SVEVEAEFDQ0VQVEVEAE5PVF9JTVBMRU1FTlRFRABMT09QX0RFVEVDVEVEAEhQRV9DUl9FWFBFQ1RFRABIUEVfTEZfRVhQRUNURUQAQ1JFQVRFRABJTV9VU0VEAEhQRV9QQVVTRUQAVElNRU9VVF9PQ0NVUkVEAFBBWU1FTlRfUkVRVUlSRUQAUFJFQ09ORElUSU9OX1JFUVVJUkVEAFBST1hZX0FVVEhFTlRJQ0FUSU9OX1JFUVVJUkVEAE5FVFdPUktfQVVUSEVOVElDQVRJT05fUkVRVUlSRUQATEVOR1RIX1JFUVVJUkVEAFNTTF9DRVJUSUZJQ0FURV9SRVFVSVJFRABVUEdSQURFX1JFUVVJUkVEAFBBR0VfRVhQSVJFRABQUkVDT05ESVRJT05fRkFJTEVEAEVYUEVDVEFUSU9OX0ZBSUxFRABSRVZBTElEQVRJT05fRkFJTEVEAFNTTF9IQU5EU0hBS0VfRkFJTEVEAExPQ0tFRABUUkFOU0ZPUk1BVElPTl9BUFBMSUVEAE5PVF9NT0RJRklFRABOT1RfRVhURU5ERUQAQkFORFdJRFRIX0xJTUlUX0VYQ0VFREVEAFNJVEVfSVNfT1ZFUkxPQURFRABIRUFEAEV4cGVjdGVkIEhUVFAvAABeEwAAJhMAADAQAADwFwAAnRMAABUSAAA5FwAA8BIAAAoQAAB1EgAArRIAAIITAABPFAAAfxAAAKAVAAAjFAAAiRIAAIsUAABNFQAA1BEAAM8UAAAQGAAAyRYAANwWAADBEQAA4BcAALsUAAB0FAAAfBUAAOUUAAAIFwAAHxAAAGUVAACjFAAAKBUAAAIVAACZFQAALBAAAIsZAABPDwAA1A4AAGoQAADOEAAAAhcAAIkOAABuEwAAHBMAAGYUAABWFwAAwRMAAM0TAABsEwAAaBcAAGYXAABfFwAAIhMAAM4PAABpDgAA2A4AAGMWAADLEwAAqg4AACgXAAAmFwAAxRMAAF0WAADoEQAAZxMAAGUTAADyFgAAcxMAAB0XAAD5FgAA8xEAAM8OAADOFQAADBIAALMRAAClEQAAYRAAADIXAAC7EwBB+TULAQEAQZA2C+ABAQECAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAQf03CwEBAEGROAteAgMCAgICAgAAAgIAAgIAAgICAgICAgICAgAEAAAAAAACAgICAgICAgICAgICAgICAgICAgICAgICAgAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAgICAAIAAgBB/TkLAQEAQZE6C14CAAICAgICAAACAgACAgACAgICAgICAgICAAMABAAAAAICAgICAgICAgICAgICAgICAgICAgICAgICAAAAAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIAAgACAEHwOwsNbG9zZWVlcC1hbGl2ZQBBiTwLAQEAQaA8C+ABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAQYk+CwEBAEGgPgvnAQEBAQEBAQEBAQEBAQIBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBY2h1bmtlZABBsMAAC18BAQABAQEBAQAAAQEAAQEAAQEBAQEBAQEBAQAAAAAAAAABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQBBkMIACyFlY3Rpb25lbnQtbGVuZ3Rob25yb3h5LWNvbm5lY3Rpb24AQcDCAAstcmFuc2Zlci1lbmNvZGluZ3BncmFkZQ0KDQoNClNNDQoNClRUUC9DRS9UU1AvAEH5wgALBQECAAEDAEGQwwAL4AEEAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBB+cQACwUBAgABAwBBkMUAC+ABBAEBBQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEAQfnGAAsEAQAAAQBBkccAC98BAQEAAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQBB+sgACwQBAAACAEGQyQALXwMEAAAEBAQEBAQEBAQEBAUEBAQEBAQEBAQEBAQABAAGBwQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAAEAAQABAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQAAAAEAEH6ygALBAEAAAEAQZDLAAsBAQBBqssAC0ECAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwBB+swACwQBAAABAEGQzQALAQEAQZrNAAsGAgAAAAACAEGxzQALOgMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAQfDOAAuWAU5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw==', 'base64')\n","'use strict'\n\nconst corsSafeListedMethods = /** @type {const} */ (['GET', 'HEAD', 'POST'])\nconst corsSafeListedMethodsSet = new Set(corsSafeListedMethods)\n\nconst nullBodyStatus = /** @type {const} */ ([101, 204, 205, 304])\n\nconst redirectStatus = /** @type {const} */ ([301, 302, 303, 307, 308])\nconst redirectStatusSet = new Set(redirectStatus)\n\n/**\n * @see https://fetch.spec.whatwg.org/#block-bad-port\n */\nconst badPorts = /** @type {const} */ ([\n '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79',\n '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137',\n '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532',\n '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723',\n '2049', '3659', '4045', '4190', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6679',\n '6697', '10080'\n])\nconst badPortsSet = new Set(badPorts)\n\n/**\n * @see https://w3c.github.io/webappsec-referrer-policy/#referrer-policies\n */\nconst referrerPolicy = /** @type {const} */ ([\n '',\n 'no-referrer',\n 'no-referrer-when-downgrade',\n 'same-origin',\n 'origin',\n 'strict-origin',\n 'origin-when-cross-origin',\n 'strict-origin-when-cross-origin',\n 'unsafe-url'\n])\nconst referrerPolicySet = new Set(referrerPolicy)\n\nconst requestRedirect = /** @type {const} */ (['follow', 'manual', 'error'])\n\nconst safeMethods = /** @type {const} */ (['GET', 'HEAD', 'OPTIONS', 'TRACE'])\nconst safeMethodsSet = new Set(safeMethods)\n\nconst requestMode = /** @type {const} */ (['navigate', 'same-origin', 'no-cors', 'cors'])\n\nconst requestCredentials = /** @type {const} */ (['omit', 'same-origin', 'include'])\n\nconst requestCache = /** @type {const} */ ([\n 'default',\n 'no-store',\n 'reload',\n 'no-cache',\n 'force-cache',\n 'only-if-cached'\n])\n\n/**\n * @see https://fetch.spec.whatwg.org/#request-body-header-name\n */\nconst requestBodyHeader = /** @type {const} */ ([\n 'content-encoding',\n 'content-language',\n 'content-location',\n 'content-type',\n // See https://github.com/nodejs/undici/issues/2021\n // 'Content-Length' is a forbidden header name, which is typically\n // removed in the Headers implementation. However, undici doesn't\n // filter out headers, so we add it here.\n 'content-length'\n])\n\n/**\n * @see https://fetch.spec.whatwg.org/#enumdef-requestduplex\n */\nconst requestDuplex = /** @type {const} */ ([\n 'half'\n])\n\n/**\n * @see http://fetch.spec.whatwg.org/#forbidden-method\n */\nconst forbiddenMethods = /** @type {const} */ (['CONNECT', 'TRACE', 'TRACK'])\nconst forbiddenMethodsSet = new Set(forbiddenMethods)\n\nconst subresource = /** @type {const} */ ([\n 'audio',\n 'audioworklet',\n 'font',\n 'image',\n 'manifest',\n 'paintworklet',\n 'script',\n 'style',\n 'track',\n 'video',\n 'xslt',\n ''\n])\nconst subresourceSet = new Set(subresource)\n\nmodule.exports = {\n subresource,\n forbiddenMethods,\n requestBodyHeader,\n referrerPolicy,\n requestRedirect,\n requestMode,\n requestCredentials,\n requestCache,\n redirectStatus,\n corsSafeListedMethods,\n nullBodyStatus,\n safeMethods,\n badPorts,\n requestDuplex,\n subresourceSet,\n badPortsSet,\n redirectStatusSet,\n corsSafeListedMethodsSet,\n safeMethodsSet,\n forbiddenMethodsSet,\n referrerPolicySet\n}\n","'use strict'\n\n// In case of breaking changes, increase the version\n// number to avoid conflicts.\nconst globalOrigin = Symbol.for('undici.globalOrigin.1')\n\nfunction getGlobalOrigin () {\n return globalThis[globalOrigin]\n}\n\nfunction setGlobalOrigin (newOrigin) {\n if (newOrigin === undefined) {\n Object.defineProperty(globalThis, globalOrigin, {\n value: undefined,\n writable: true,\n enumerable: false,\n configurable: false\n })\n\n return\n }\n\n const parsedURL = new URL(newOrigin)\n\n if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') {\n throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`)\n }\n\n Object.defineProperty(globalThis, globalOrigin, {\n value: parsedURL,\n writable: true,\n enumerable: false,\n configurable: false\n })\n}\n\nmodule.exports = {\n getGlobalOrigin,\n setGlobalOrigin\n}\n","'use strict'\n\nconst assert = require('node:assert')\n\nconst encoder = new TextEncoder()\n\n/**\n * @see https://mimesniff.spec.whatwg.org/#http-token-code-point\n */\nconst HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+\\-.^_|~A-Za-z0-9]+$/\nconst HTTP_WHITESPACE_REGEX = /[\\u000A\\u000D\\u0009\\u0020]/ // eslint-disable-line\nconst ASCII_WHITESPACE_REPLACE_REGEX = /[\\u0009\\u000A\\u000C\\u000D\\u0020]/g // eslint-disable-line\n/**\n * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point\n */\nconst HTTP_QUOTED_STRING_TOKENS = /^[\\u0009\\u0020-\\u007E\\u0080-\\u00FF]+$/ // eslint-disable-line\n\n// https://fetch.spec.whatwg.org/#data-url-processor\n/** @param {URL} dataURL */\nfunction dataURLProcessor (dataURL) {\n // 1. Assert: dataURL’s scheme is \"data\".\n assert(dataURL.protocol === 'data:')\n\n // 2. Let input be the result of running the URL\n // serializer on dataURL with exclude fragment\n // set to true.\n let input = URLSerializer(dataURL, true)\n\n // 3. Remove the leading \"data:\" string from input.\n input = input.slice(5)\n\n // 4. Let position point at the start of input.\n const position = { position: 0 }\n\n // 5. Let mimeType be the result of collecting a\n // sequence of code points that are not equal\n // to U+002C (,), given position.\n let mimeType = collectASequenceOfCodePointsFast(\n ',',\n input,\n position\n )\n\n // 6. Strip leading and trailing ASCII whitespace\n // from mimeType.\n // Undici implementation note: we need to store the\n // length because if the mimetype has spaces removed,\n // the wrong amount will be sliced from the input in\n // step #9\n const mimeTypeLength = mimeType.length\n mimeType = removeASCIIWhitespace(mimeType, true, true)\n\n // 7. If position is past the end of input, then\n // return failure\n if (position.position >= input.length) {\n return 'failure'\n }\n\n // 8. Advance position by 1.\n position.position++\n\n // 9. Let encodedBody be the remainder of input.\n const encodedBody = input.slice(mimeTypeLength + 1)\n\n // 10. Let body be the percent-decoding of encodedBody.\n let body = stringPercentDecode(encodedBody)\n\n // 11. If mimeType ends with U+003B (;), followed by\n // zero or more U+0020 SPACE, followed by an ASCII\n // case-insensitive match for \"base64\", then:\n if (/;(\\u0020){0,}base64$/i.test(mimeType)) {\n // 1. Let stringBody be the isomorphic decode of body.\n const stringBody = isomorphicDecode(body)\n\n // 2. Set body to the forgiving-base64 decode of\n // stringBody.\n body = forgivingBase64(stringBody)\n\n // 3. If body is failure, then return failure.\n if (body === 'failure') {\n return 'failure'\n }\n\n // 4. Remove the last 6 code points from mimeType.\n mimeType = mimeType.slice(0, -6)\n\n // 5. Remove trailing U+0020 SPACE code points from mimeType,\n // if any.\n mimeType = mimeType.replace(/(\\u0020)+$/, '')\n\n // 6. Remove the last U+003B (;) code point from mimeType.\n mimeType = mimeType.slice(0, -1)\n }\n\n // 12. If mimeType starts with U+003B (;), then prepend\n // \"text/plain\" to mimeType.\n if (mimeType.startsWith(';')) {\n mimeType = 'text/plain' + mimeType\n }\n\n // 13. Let mimeTypeRecord be the result of parsing\n // mimeType.\n let mimeTypeRecord = parseMIMEType(mimeType)\n\n // 14. If mimeTypeRecord is failure, then set\n // mimeTypeRecord to text/plain;charset=US-ASCII.\n if (mimeTypeRecord === 'failure') {\n mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII')\n }\n\n // 15. Return a new data: URL struct whose MIME\n // type is mimeTypeRecord and body is body.\n // https://fetch.spec.whatwg.org/#data-url-struct\n return { mimeType: mimeTypeRecord, body }\n}\n\n// https://url.spec.whatwg.org/#concept-url-serializer\n/**\n * @param {URL} url\n * @param {boolean} excludeFragment\n */\nfunction URLSerializer (url, excludeFragment = false) {\n if (!excludeFragment) {\n return url.href\n }\n\n const href = url.href\n const hashLength = url.hash.length\n\n const serialized = hashLength === 0 ? href : href.substring(0, href.length - hashLength)\n\n if (!hashLength && href.endsWith('#')) {\n return serialized.slice(0, -1)\n }\n\n return serialized\n}\n\n// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points\n/**\n * @param {(char: string) => boolean} condition\n * @param {string} input\n * @param {{ position: number }} position\n */\nfunction collectASequenceOfCodePoints (condition, input, position) {\n // 1. Let result be the empty string.\n let result = ''\n\n // 2. While position doesn’t point past the end of input and the\n // code point at position within input meets the condition condition:\n while (position.position < input.length && condition(input[position.position])) {\n // 1. Append that code point to the end of result.\n result += input[position.position]\n\n // 2. Advance position by 1.\n position.position++\n }\n\n // 3. Return result.\n return result\n}\n\n/**\n * A faster collectASequenceOfCodePoints that only works when comparing a single character.\n * @param {string} char\n * @param {string} input\n * @param {{ position: number }} position\n */\nfunction collectASequenceOfCodePointsFast (char, input, position) {\n const idx = input.indexOf(char, position.position)\n const start = position.position\n\n if (idx === -1) {\n position.position = input.length\n return input.slice(start)\n }\n\n position.position = idx\n return input.slice(start, position.position)\n}\n\n// https://url.spec.whatwg.org/#string-percent-decode\n/** @param {string} input */\nfunction stringPercentDecode (input) {\n // 1. Let bytes be the UTF-8 encoding of input.\n const bytes = encoder.encode(input)\n\n // 2. Return the percent-decoding of bytes.\n return percentDecode(bytes)\n}\n\n/**\n * @param {number} byte\n */\nfunction isHexCharByte (byte) {\n // 0-9 A-F a-f\n return (byte >= 0x30 && byte <= 0x39) || (byte >= 0x41 && byte <= 0x46) || (byte >= 0x61 && byte <= 0x66)\n}\n\n/**\n * @param {number} byte\n */\nfunction hexByteToNumber (byte) {\n return (\n // 0-9\n byte >= 0x30 && byte <= 0x39\n ? (byte - 48)\n // Convert to uppercase\n // ((byte & 0xDF) - 65) + 10\n : ((byte & 0xDF) - 55)\n )\n}\n\n// https://url.spec.whatwg.org/#percent-decode\n/** @param {Uint8Array} input */\nfunction percentDecode (input) {\n const length = input.length\n // 1. Let output be an empty byte sequence.\n /** @type {Uint8Array} */\n const output = new Uint8Array(length)\n let j = 0\n // 2. For each byte byte in input:\n for (let i = 0; i < length; ++i) {\n const byte = input[i]\n\n // 1. If byte is not 0x25 (%), then append byte to output.\n if (byte !== 0x25) {\n output[j++] = byte\n\n // 2. Otherwise, if byte is 0x25 (%) and the next two bytes\n // after byte in input are not in the ranges\n // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F),\n // and 0x61 (a) to 0x66 (f), all inclusive, append byte\n // to output.\n } else if (\n byte === 0x25 &&\n !(isHexCharByte(input[i + 1]) && isHexCharByte(input[i + 2]))\n ) {\n output[j++] = 0x25\n\n // 3. Otherwise:\n } else {\n // 1. Let bytePoint be the two bytes after byte in input,\n // decoded, and then interpreted as hexadecimal number.\n // 2. Append a byte whose value is bytePoint to output.\n output[j++] = (hexByteToNumber(input[i + 1]) << 4) | hexByteToNumber(input[i + 2])\n\n // 3. Skip the next two bytes in input.\n i += 2\n }\n }\n\n // 3. Return output.\n return length === j ? output : output.subarray(0, j)\n}\n\n// https://mimesniff.spec.whatwg.org/#parse-a-mime-type\n/** @param {string} input */\nfunction parseMIMEType (input) {\n // 1. Remove any leading and trailing HTTP whitespace\n // from input.\n input = removeHTTPWhitespace(input, true, true)\n\n // 2. Let position be a position variable for input,\n // initially pointing at the start of input.\n const position = { position: 0 }\n\n // 3. Let type be the result of collecting a sequence\n // of code points that are not U+002F (/) from\n // input, given position.\n const type = collectASequenceOfCodePointsFast(\n '/',\n input,\n position\n )\n\n // 4. If type is the empty string or does not solely\n // contain HTTP token code points, then return failure.\n // https://mimesniff.spec.whatwg.org/#http-token-code-point\n if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) {\n return 'failure'\n }\n\n // 5. If position is past the end of input, then return\n // failure\n if (position.position > input.length) {\n return 'failure'\n }\n\n // 6. Advance position by 1. (This skips past U+002F (/).)\n position.position++\n\n // 7. Let subtype be the result of collecting a sequence of\n // code points that are not U+003B (;) from input, given\n // position.\n let subtype = collectASequenceOfCodePointsFast(\n ';',\n input,\n position\n )\n\n // 8. Remove any trailing HTTP whitespace from subtype.\n subtype = removeHTTPWhitespace(subtype, false, true)\n\n // 9. If subtype is the empty string or does not solely\n // contain HTTP token code points, then return failure.\n if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) {\n return 'failure'\n }\n\n const typeLowercase = type.toLowerCase()\n const subtypeLowercase = subtype.toLowerCase()\n\n // 10. Let mimeType be a new MIME type record whose type\n // is type, in ASCII lowercase, and subtype is subtype,\n // in ASCII lowercase.\n // https://mimesniff.spec.whatwg.org/#mime-type\n const mimeType = {\n type: typeLowercase,\n subtype: subtypeLowercase,\n /** @type {Map} */\n parameters: new Map(),\n // https://mimesniff.spec.whatwg.org/#mime-type-essence\n essence: `${typeLowercase}/${subtypeLowercase}`\n }\n\n // 11. While position is not past the end of input:\n while (position.position < input.length) {\n // 1. Advance position by 1. (This skips past U+003B (;).)\n position.position++\n\n // 2. Collect a sequence of code points that are HTTP\n // whitespace from input given position.\n collectASequenceOfCodePoints(\n // https://fetch.spec.whatwg.org/#http-whitespace\n char => HTTP_WHITESPACE_REGEX.test(char),\n input,\n position\n )\n\n // 3. Let parameterName be the result of collecting a\n // sequence of code points that are not U+003B (;)\n // or U+003D (=) from input, given position.\n let parameterName = collectASequenceOfCodePoints(\n (char) => char !== ';' && char !== '=',\n input,\n position\n )\n\n // 4. Set parameterName to parameterName, in ASCII\n // lowercase.\n parameterName = parameterName.toLowerCase()\n\n // 5. If position is not past the end of input, then:\n if (position.position < input.length) {\n // 1. If the code point at position within input is\n // U+003B (;), then continue.\n if (input[position.position] === ';') {\n continue\n }\n\n // 2. Advance position by 1. (This skips past U+003D (=).)\n position.position++\n }\n\n // 6. If position is past the end of input, then break.\n if (position.position > input.length) {\n break\n }\n\n // 7. Let parameterValue be null.\n let parameterValue = null\n\n // 8. If the code point at position within input is\n // U+0022 (\"), then:\n if (input[position.position] === '\"') {\n // 1. Set parameterValue to the result of collecting\n // an HTTP quoted string from input, given position\n // and the extract-value flag.\n parameterValue = collectAnHTTPQuotedString(input, position, true)\n\n // 2. Collect a sequence of code points that are not\n // U+003B (;) from input, given position.\n collectASequenceOfCodePointsFast(\n ';',\n input,\n position\n )\n\n // 9. Otherwise:\n } else {\n // 1. Set parameterValue to the result of collecting\n // a sequence of code points that are not U+003B (;)\n // from input, given position.\n parameterValue = collectASequenceOfCodePointsFast(\n ';',\n input,\n position\n )\n\n // 2. Remove any trailing HTTP whitespace from parameterValue.\n parameterValue = removeHTTPWhitespace(parameterValue, false, true)\n\n // 3. If parameterValue is the empty string, then continue.\n if (parameterValue.length === 0) {\n continue\n }\n }\n\n // 10. If all of the following are true\n // - parameterName is not the empty string\n // - parameterName solely contains HTTP token code points\n // - parameterValue solely contains HTTP quoted-string token code points\n // - mimeType’s parameters[parameterName] does not exist\n // then set mimeType’s parameters[parameterName] to parameterValue.\n if (\n parameterName.length !== 0 &&\n HTTP_TOKEN_CODEPOINTS.test(parameterName) &&\n (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) &&\n !mimeType.parameters.has(parameterName)\n ) {\n mimeType.parameters.set(parameterName, parameterValue)\n }\n }\n\n // 12. Return mimeType.\n return mimeType\n}\n\n// https://infra.spec.whatwg.org/#forgiving-base64-decode\n/** @param {string} data */\nfunction forgivingBase64 (data) {\n // 1. Remove all ASCII whitespace from data.\n data = data.replace(ASCII_WHITESPACE_REPLACE_REGEX, '') // eslint-disable-line\n\n let dataLength = data.length\n // 2. If data’s code point length divides by 4 leaving\n // no remainder, then:\n if (dataLength % 4 === 0) {\n // 1. If data ends with one or two U+003D (=) code points,\n // then remove them from data.\n if (data.charCodeAt(dataLength - 1) === 0x003D) {\n --dataLength\n if (data.charCodeAt(dataLength - 1) === 0x003D) {\n --dataLength\n }\n }\n }\n\n // 3. If data’s code point length divides by 4 leaving\n // a remainder of 1, then return failure.\n if (dataLength % 4 === 1) {\n return 'failure'\n }\n\n // 4. If data contains a code point that is not one of\n // U+002B (+)\n // U+002F (/)\n // ASCII alphanumeric\n // then return failure.\n if (/[^+/0-9A-Za-z]/.test(data.length === dataLength ? data : data.substring(0, dataLength))) {\n return 'failure'\n }\n\n const buffer = Buffer.from(data, 'base64')\n return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength)\n}\n\n// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string\n// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string\n/**\n * @param {string} input\n * @param {{ position: number }} position\n * @param {boolean?} extractValue\n */\nfunction collectAnHTTPQuotedString (input, position, extractValue) {\n // 1. Let positionStart be position.\n const positionStart = position.position\n\n // 2. Let value be the empty string.\n let value = ''\n\n // 3. Assert: the code point at position within input\n // is U+0022 (\").\n assert(input[position.position] === '\"')\n\n // 4. Advance position by 1.\n position.position++\n\n // 5. While true:\n while (true) {\n // 1. Append the result of collecting a sequence of code points\n // that are not U+0022 (\") or U+005C (\\) from input, given\n // position, to value.\n value += collectASequenceOfCodePoints(\n (char) => char !== '\"' && char !== '\\\\',\n input,\n position\n )\n\n // 2. If position is past the end of input, then break.\n if (position.position >= input.length) {\n break\n }\n\n // 3. Let quoteOrBackslash be the code point at position within\n // input.\n const quoteOrBackslash = input[position.position]\n\n // 4. Advance position by 1.\n position.position++\n\n // 5. If quoteOrBackslash is U+005C (\\), then:\n if (quoteOrBackslash === '\\\\') {\n // 1. If position is past the end of input, then append\n // U+005C (\\) to value and break.\n if (position.position >= input.length) {\n value += '\\\\'\n break\n }\n\n // 2. Append the code point at position within input to value.\n value += input[position.position]\n\n // 3. Advance position by 1.\n position.position++\n\n // 6. Otherwise:\n } else {\n // 1. Assert: quoteOrBackslash is U+0022 (\").\n assert(quoteOrBackslash === '\"')\n\n // 2. Break.\n break\n }\n }\n\n // 6. If the extract-value flag is set, then return value.\n if (extractValue) {\n return value\n }\n\n // 7. Return the code points from positionStart to position,\n // inclusive, within input.\n return input.slice(positionStart, position.position)\n}\n\n/**\n * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type\n */\nfunction serializeAMimeType (mimeType) {\n assert(mimeType !== 'failure')\n const { parameters, essence } = mimeType\n\n // 1. Let serialization be the concatenation of mimeType’s\n // type, U+002F (/), and mimeType’s subtype.\n let serialization = essence\n\n // 2. For each name → value of mimeType’s parameters:\n for (let [name, value] of parameters.entries()) {\n // 1. Append U+003B (;) to serialization.\n serialization += ';'\n\n // 2. Append name to serialization.\n serialization += name\n\n // 3. Append U+003D (=) to serialization.\n serialization += '='\n\n // 4. If value does not solely contain HTTP token code\n // points or value is the empty string, then:\n if (!HTTP_TOKEN_CODEPOINTS.test(value)) {\n // 1. Precede each occurrence of U+0022 (\") or\n // U+005C (\\) in value with U+005C (\\).\n value = value.replace(/(\\\\|\")/g, '\\\\$1')\n\n // 2. Prepend U+0022 (\") to value.\n value = '\"' + value\n\n // 3. Append U+0022 (\") to value.\n value += '\"'\n }\n\n // 5. Append value to serialization.\n serialization += value\n }\n\n // 3. Return serialization.\n return serialization\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#http-whitespace\n * @param {number} char\n */\nfunction isHTTPWhiteSpace (char) {\n // \"\\r\\n\\t \"\n return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x020\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#http-whitespace\n * @param {string} str\n * @param {boolean} [leading=true]\n * @param {boolean} [trailing=true]\n */\nfunction removeHTTPWhitespace (str, leading = true, trailing = true) {\n return removeChars(str, leading, trailing, isHTTPWhiteSpace)\n}\n\n/**\n * @see https://infra.spec.whatwg.org/#ascii-whitespace\n * @param {number} char\n */\nfunction isASCIIWhitespace (char) {\n // \"\\r\\n\\t\\f \"\n return char === 0x00d || char === 0x00a || char === 0x009 || char === 0x00c || char === 0x020\n}\n\n/**\n * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace\n * @param {string} str\n * @param {boolean} [leading=true]\n * @param {boolean} [trailing=true]\n */\nfunction removeASCIIWhitespace (str, leading = true, trailing = true) {\n return removeChars(str, leading, trailing, isASCIIWhitespace)\n}\n\n/**\n * @param {string} str\n * @param {boolean} leading\n * @param {boolean} trailing\n * @param {(charCode: number) => boolean} predicate\n * @returns\n */\nfunction removeChars (str, leading, trailing, predicate) {\n let lead = 0\n let trail = str.length - 1\n\n if (leading) {\n while (lead < str.length && predicate(str.charCodeAt(lead))) lead++\n }\n\n if (trailing) {\n while (trail > 0 && predicate(str.charCodeAt(trail))) trail--\n }\n\n return lead === 0 && trail === str.length - 1 ? str : str.slice(lead, trail + 1)\n}\n\n/**\n * @see https://infra.spec.whatwg.org/#isomorphic-decode\n * @param {Uint8Array} input\n * @returns {string}\n */\nfunction isomorphicDecode (input) {\n // 1. To isomorphic decode a byte sequence input, return a string whose code point\n // length is equal to input’s length and whose code points have the same values\n // as the values of input’s bytes, in the same order.\n const length = input.length\n if ((2 << 15) - 1 > length) {\n return String.fromCharCode.apply(null, input)\n }\n let result = ''; let i = 0\n let addition = (2 << 15) - 1\n while (i < length) {\n if (i + addition > length) {\n addition = length - i\n }\n result += String.fromCharCode.apply(null, input.subarray(i, i += addition))\n }\n return result\n}\n\n/**\n * @see https://mimesniff.spec.whatwg.org/#minimize-a-supported-mime-type\n * @param {Exclude, 'failure'>} mimeType\n */\nfunction minimizeSupportedMimeType (mimeType) {\n switch (mimeType.essence) {\n case 'application/ecmascript':\n case 'application/javascript':\n case 'application/x-ecmascript':\n case 'application/x-javascript':\n case 'text/ecmascript':\n case 'text/javascript':\n case 'text/javascript1.0':\n case 'text/javascript1.1':\n case 'text/javascript1.2':\n case 'text/javascript1.3':\n case 'text/javascript1.4':\n case 'text/javascript1.5':\n case 'text/jscript':\n case 'text/livescript':\n case 'text/x-ecmascript':\n case 'text/x-javascript':\n // 1. If mimeType is a JavaScript MIME type, then return \"text/javascript\".\n return 'text/javascript'\n case 'application/json':\n case 'text/json':\n // 2. If mimeType is a JSON MIME type, then return \"application/json\".\n return 'application/json'\n case 'image/svg+xml':\n // 3. If mimeType’s essence is \"image/svg+xml\", then return \"image/svg+xml\".\n return 'image/svg+xml'\n case 'text/xml':\n case 'application/xml':\n // 4. If mimeType is an XML MIME type, then return \"application/xml\".\n return 'application/xml'\n }\n\n // 2. If mimeType is a JSON MIME type, then return \"application/json\".\n if (mimeType.subtype.endsWith('+json')) {\n return 'application/json'\n }\n\n // 4. If mimeType is an XML MIME type, then return \"application/xml\".\n if (mimeType.subtype.endsWith('+xml')) {\n return 'application/xml'\n }\n\n // 5. If mimeType is supported by the user agent, then return mimeType’s essence.\n // Technically, node doesn't support any mimetypes.\n\n // 6. Return the empty string.\n return ''\n}\n\nmodule.exports = {\n dataURLProcessor,\n URLSerializer,\n collectASequenceOfCodePoints,\n collectASequenceOfCodePointsFast,\n stringPercentDecode,\n parseMIMEType,\n collectAnHTTPQuotedString,\n serializeAMimeType,\n removeChars,\n removeHTTPWhitespace,\n minimizeSupportedMimeType,\n HTTP_TOKEN_CODEPOINTS,\n isomorphicDecode\n}\n","'use strict'\n\nconst { types, inspect } = require('node:util')\nconst { markAsUncloneable } = require('node:worker_threads')\nconst { toUSVString } = require('../../core/util')\n\n/** @type {import('../../../types/webidl').Webidl} */\nconst webidl = {}\nwebidl.converters = {}\nwebidl.util = {}\nwebidl.errors = {}\n\nwebidl.errors.exception = function (message) {\n return new TypeError(`${message.header}: ${message.message}`)\n}\n\nwebidl.errors.conversionFailed = function (context) {\n const plural = context.types.length === 1 ? '' : ' one of'\n const message =\n `${context.argument} could not be converted to` +\n `${plural}: ${context.types.join(', ')}.`\n\n return webidl.errors.exception({\n header: context.prefix,\n message\n })\n}\n\nwebidl.errors.invalidArgument = function (context) {\n return webidl.errors.exception({\n header: context.prefix,\n message: `\"${context.value}\" is an invalid ${context.type}.`\n })\n}\n\n// https://webidl.spec.whatwg.org/#implements\nwebidl.brandCheck = function (V, I, opts) {\n if (opts?.strict !== false) {\n if (!(V instanceof I)) {\n const err = new TypeError('Illegal invocation')\n err.code = 'ERR_INVALID_THIS' // node compat.\n throw err\n }\n } else {\n if (V?.[Symbol.toStringTag] !== I.prototype[Symbol.toStringTag]) {\n const err = new TypeError('Illegal invocation')\n err.code = 'ERR_INVALID_THIS' // node compat.\n throw err\n }\n }\n}\n\nwebidl.argumentLengthCheck = function ({ length }, min, ctx) {\n if (length < min) {\n throw webidl.errors.exception({\n message: `${min} argument${min !== 1 ? 's' : ''} required, ` +\n `but${length ? ' only' : ''} ${length} found.`,\n header: ctx\n })\n }\n}\n\nwebidl.illegalConstructor = function () {\n throw webidl.errors.exception({\n header: 'TypeError',\n message: 'Illegal constructor'\n })\n}\n\n// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values\nwebidl.util.Type = function (V) {\n switch (typeof V) {\n case 'undefined': return 'Undefined'\n case 'boolean': return 'Boolean'\n case 'string': return 'String'\n case 'symbol': return 'Symbol'\n case 'number': return 'Number'\n case 'bigint': return 'BigInt'\n case 'function':\n case 'object': {\n if (V === null) {\n return 'Null'\n }\n\n return 'Object'\n }\n }\n}\n\nwebidl.util.markAsUncloneable = markAsUncloneable || (() => {})\n// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint\nwebidl.util.ConvertToInt = function (V, bitLength, signedness, opts) {\n let upperBound\n let lowerBound\n\n // 1. If bitLength is 64, then:\n if (bitLength === 64) {\n // 1. Let upperBound be 2^53 − 1.\n upperBound = Math.pow(2, 53) - 1\n\n // 2. If signedness is \"unsigned\", then let lowerBound be 0.\n if (signedness === 'unsigned') {\n lowerBound = 0\n } else {\n // 3. Otherwise let lowerBound be −2^53 + 1.\n lowerBound = Math.pow(-2, 53) + 1\n }\n } else if (signedness === 'unsigned') {\n // 2. Otherwise, if signedness is \"unsigned\", then:\n\n // 1. Let lowerBound be 0.\n lowerBound = 0\n\n // 2. Let upperBound be 2^bitLength − 1.\n upperBound = Math.pow(2, bitLength) - 1\n } else {\n // 3. Otherwise:\n\n // 1. Let lowerBound be -2^bitLength − 1.\n lowerBound = Math.pow(-2, bitLength) - 1\n\n // 2. Let upperBound be 2^bitLength − 1 − 1.\n upperBound = Math.pow(2, bitLength - 1) - 1\n }\n\n // 4. Let x be ? ToNumber(V).\n let x = Number(V)\n\n // 5. If x is −0, then set x to +0.\n if (x === 0) {\n x = 0\n }\n\n // 6. If the conversion is to an IDL type associated\n // with the [EnforceRange] extended attribute, then:\n if (opts?.enforceRange === true) {\n // 1. If x is NaN, +∞, or −∞, then throw a TypeError.\n if (\n Number.isNaN(x) ||\n x === Number.POSITIVE_INFINITY ||\n x === Number.NEGATIVE_INFINITY\n ) {\n throw webidl.errors.exception({\n header: 'Integer conversion',\n message: `Could not convert ${webidl.util.Stringify(V)} to an integer.`\n })\n }\n\n // 2. Set x to IntegerPart(x).\n x = webidl.util.IntegerPart(x)\n\n // 3. If x < lowerBound or x > upperBound, then\n // throw a TypeError.\n if (x < lowerBound || x > upperBound) {\n throw webidl.errors.exception({\n header: 'Integer conversion',\n message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.`\n })\n }\n\n // 4. Return x.\n return x\n }\n\n // 7. If x is not NaN and the conversion is to an IDL\n // type associated with the [Clamp] extended\n // attribute, then:\n if (!Number.isNaN(x) && opts?.clamp === true) {\n // 1. Set x to min(max(x, lowerBound), upperBound).\n x = Math.min(Math.max(x, lowerBound), upperBound)\n\n // 2. Round x to the nearest integer, choosing the\n // even integer if it lies halfway between two,\n // and choosing +0 rather than −0.\n if (Math.floor(x) % 2 === 0) {\n x = Math.floor(x)\n } else {\n x = Math.ceil(x)\n }\n\n // 3. Return x.\n return x\n }\n\n // 8. If x is NaN, +0, +∞, or −∞, then return +0.\n if (\n Number.isNaN(x) ||\n (x === 0 && Object.is(0, x)) ||\n x === Number.POSITIVE_INFINITY ||\n x === Number.NEGATIVE_INFINITY\n ) {\n return 0\n }\n\n // 9. Set x to IntegerPart(x).\n x = webidl.util.IntegerPart(x)\n\n // 10. Set x to x modulo 2^bitLength.\n x = x % Math.pow(2, bitLength)\n\n // 11. If signedness is \"signed\" and x ≥ 2^bitLength − 1,\n // then return x − 2^bitLength.\n if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) {\n return x - Math.pow(2, bitLength)\n }\n\n // 12. Otherwise, return x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart\nwebidl.util.IntegerPart = function (n) {\n // 1. Let r be floor(abs(n)).\n const r = Math.floor(Math.abs(n))\n\n // 2. If n < 0, then return -1 × r.\n if (n < 0) {\n return -1 * r\n }\n\n // 3. Otherwise, return r.\n return r\n}\n\nwebidl.util.Stringify = function (V) {\n const type = webidl.util.Type(V)\n\n switch (type) {\n case 'Symbol':\n return `Symbol(${V.description})`\n case 'Object':\n return inspect(V)\n case 'String':\n return `\"${V}\"`\n default:\n return `${V}`\n }\n}\n\n// https://webidl.spec.whatwg.org/#es-sequence\nwebidl.sequenceConverter = function (converter) {\n return (V, prefix, argument, Iterable) => {\n // 1. If Type(V) is not Object, throw a TypeError.\n if (webidl.util.Type(V) !== 'Object') {\n throw webidl.errors.exception({\n header: prefix,\n message: `${argument} (${webidl.util.Stringify(V)}) is not iterable.`\n })\n }\n\n // 2. Let method be ? GetMethod(V, @@iterator).\n /** @type {Generator} */\n const method = typeof Iterable === 'function' ? Iterable() : V?.[Symbol.iterator]?.()\n const seq = []\n let index = 0\n\n // 3. If method is undefined, throw a TypeError.\n if (\n method === undefined ||\n typeof method.next !== 'function'\n ) {\n throw webidl.errors.exception({\n header: prefix,\n message: `${argument} is not iterable.`\n })\n }\n\n // https://webidl.spec.whatwg.org/#create-sequence-from-iterable\n while (true) {\n const { done, value } = method.next()\n\n if (done) {\n break\n }\n\n seq.push(converter(value, prefix, `${argument}[${index++}]`))\n }\n\n return seq\n }\n}\n\n// https://webidl.spec.whatwg.org/#es-to-record\nwebidl.recordConverter = function (keyConverter, valueConverter) {\n return (O, prefix, argument) => {\n // 1. If Type(O) is not Object, throw a TypeError.\n if (webidl.util.Type(O) !== 'Object') {\n throw webidl.errors.exception({\n header: prefix,\n message: `${argument} (\"${webidl.util.Type(O)}\") is not an Object.`\n })\n }\n\n // 2. Let result be a new empty instance of record.\n const result = {}\n\n if (!types.isProxy(O)) {\n // 1. Let desc be ? O.[[GetOwnProperty]](key).\n const keys = [...Object.getOwnPropertyNames(O), ...Object.getOwnPropertySymbols(O)]\n\n for (const key of keys) {\n // 1. Let typedKey be key converted to an IDL value of type K.\n const typedKey = keyConverter(key, prefix, argument)\n\n // 2. Let value be ? Get(O, key).\n // 3. Let typedValue be value converted to an IDL value of type V.\n const typedValue = valueConverter(O[key], prefix, argument)\n\n // 4. Set result[typedKey] to typedValue.\n result[typedKey] = typedValue\n }\n\n // 5. Return result.\n return result\n }\n\n // 3. Let keys be ? O.[[OwnPropertyKeys]]().\n const keys = Reflect.ownKeys(O)\n\n // 4. For each key of keys.\n for (const key of keys) {\n // 1. Let desc be ? O.[[GetOwnProperty]](key).\n const desc = Reflect.getOwnPropertyDescriptor(O, key)\n\n // 2. If desc is not undefined and desc.[[Enumerable]] is true:\n if (desc?.enumerable) {\n // 1. Let typedKey be key converted to an IDL value of type K.\n const typedKey = keyConverter(key, prefix, argument)\n\n // 2. Let value be ? Get(O, key).\n // 3. Let typedValue be value converted to an IDL value of type V.\n const typedValue = valueConverter(O[key], prefix, argument)\n\n // 4. Set result[typedKey] to typedValue.\n result[typedKey] = typedValue\n }\n }\n\n // 5. Return result.\n return result\n }\n}\n\nwebidl.interfaceConverter = function (i) {\n return (V, prefix, argument, opts) => {\n if (opts?.strict !== false && !(V instanceof i)) {\n throw webidl.errors.exception({\n header: prefix,\n message: `Expected ${argument} (\"${webidl.util.Stringify(V)}\") to be an instance of ${i.name}.`\n })\n }\n\n return V\n }\n}\n\nwebidl.dictionaryConverter = function (converters) {\n return (dictionary, prefix, argument) => {\n const type = webidl.util.Type(dictionary)\n const dict = {}\n\n if (type === 'Null' || type === 'Undefined') {\n return dict\n } else if (type !== 'Object') {\n throw webidl.errors.exception({\n header: prefix,\n message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`\n })\n }\n\n for (const options of converters) {\n const { key, defaultValue, required, converter } = options\n\n if (required === true) {\n if (!Object.hasOwn(dictionary, key)) {\n throw webidl.errors.exception({\n header: prefix,\n message: `Missing required key \"${key}\".`\n })\n }\n }\n\n let value = dictionary[key]\n const hasDefault = Object.hasOwn(options, 'defaultValue')\n\n // Only use defaultValue if value is undefined and\n // a defaultValue options was provided.\n if (hasDefault && value !== null) {\n value ??= defaultValue()\n }\n\n // A key can be optional and have no default value.\n // When this happens, do not perform a conversion,\n // and do not assign the key a value.\n if (required || hasDefault || value !== undefined) {\n value = converter(value, prefix, `${argument}.${key}`)\n\n if (\n options.allowedValues &&\n !options.allowedValues.includes(value)\n ) {\n throw webidl.errors.exception({\n header: prefix,\n message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.`\n })\n }\n\n dict[key] = value\n }\n }\n\n return dict\n }\n}\n\nwebidl.nullableConverter = function (converter) {\n return (V, prefix, argument) => {\n if (V === null) {\n return V\n }\n\n return converter(V, prefix, argument)\n }\n}\n\n// https://webidl.spec.whatwg.org/#es-DOMString\nwebidl.converters.DOMString = function (V, prefix, argument, opts) {\n // 1. If V is null and the conversion is to an IDL type\n // associated with the [LegacyNullToEmptyString]\n // extended attribute, then return the DOMString value\n // that represents the empty string.\n if (V === null && opts?.legacyNullToEmptyString) {\n return ''\n }\n\n // 2. Let x be ? ToString(V).\n if (typeof V === 'symbol') {\n throw webidl.errors.exception({\n header: prefix,\n message: `${argument} is a symbol, which cannot be converted to a DOMString.`\n })\n }\n\n // 3. Return the IDL DOMString value that represents the\n // same sequence of code units as the one the\n // ECMAScript String value x represents.\n return String(V)\n}\n\n// https://webidl.spec.whatwg.org/#es-ByteString\nwebidl.converters.ByteString = function (V, prefix, argument) {\n // 1. Let x be ? ToString(V).\n // Note: DOMString converter perform ? ToString(V)\n const x = webidl.converters.DOMString(V, prefix, argument)\n\n // 2. If the value of any element of x is greater than\n // 255, then throw a TypeError.\n for (let index = 0; index < x.length; index++) {\n if (x.charCodeAt(index) > 255) {\n throw new TypeError(\n 'Cannot convert argument to a ByteString because the character at ' +\n `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.`\n )\n }\n }\n\n // 3. Return an IDL ByteString value whose length is the\n // length of x, and where the value of each element is\n // the value of the corresponding element of x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#es-USVString\n// TODO: rewrite this so we can control the errors thrown\nwebidl.converters.USVString = toUSVString\n\n// https://webidl.spec.whatwg.org/#es-boolean\nwebidl.converters.boolean = function (V) {\n // 1. Let x be the result of computing ToBoolean(V).\n const x = Boolean(V)\n\n // 2. Return the IDL boolean value that is the one that represents\n // the same truth value as the ECMAScript Boolean value x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#es-any\nwebidl.converters.any = function (V) {\n return V\n}\n\n// https://webidl.spec.whatwg.org/#es-long-long\nwebidl.converters['long long'] = function (V, prefix, argument) {\n // 1. Let x be ? ConvertToInt(V, 64, \"signed\").\n const x = webidl.util.ConvertToInt(V, 64, 'signed', undefined, prefix, argument)\n\n // 2. Return the IDL long long value that represents\n // the same numeric value as x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#es-unsigned-long-long\nwebidl.converters['unsigned long long'] = function (V, prefix, argument) {\n // 1. Let x be ? ConvertToInt(V, 64, \"unsigned\").\n const x = webidl.util.ConvertToInt(V, 64, 'unsigned', undefined, prefix, argument)\n\n // 2. Return the IDL unsigned long long value that\n // represents the same numeric value as x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#es-unsigned-long\nwebidl.converters['unsigned long'] = function (V, prefix, argument) {\n // 1. Let x be ? ConvertToInt(V, 32, \"unsigned\").\n const x = webidl.util.ConvertToInt(V, 32, 'unsigned', undefined, prefix, argument)\n\n // 2. Return the IDL unsigned long value that\n // represents the same numeric value as x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#es-unsigned-short\nwebidl.converters['unsigned short'] = function (V, prefix, argument, opts) {\n // 1. Let x be ? ConvertToInt(V, 16, \"unsigned\").\n const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts, prefix, argument)\n\n // 2. Return the IDL unsigned short value that represents\n // the same numeric value as x.\n return x\n}\n\n// https://webidl.spec.whatwg.org/#idl-ArrayBuffer\nwebidl.converters.ArrayBuffer = function (V, prefix, argument, opts) {\n // 1. If Type(V) is not Object, or V does not have an\n // [[ArrayBufferData]] internal slot, then throw a\n // TypeError.\n // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances\n // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances\n if (\n webidl.util.Type(V) !== 'Object' ||\n !types.isAnyArrayBuffer(V)\n ) {\n throw webidl.errors.conversionFailed({\n prefix,\n argument: `${argument} (\"${webidl.util.Stringify(V)}\")`,\n types: ['ArrayBuffer']\n })\n }\n\n // 2. If the conversion is not to an IDL type associated\n // with the [AllowShared] extended attribute, and\n // IsSharedArrayBuffer(V) is true, then throw a\n // TypeError.\n if (opts?.allowShared === false && types.isSharedArrayBuffer(V)) {\n throw webidl.errors.exception({\n header: 'ArrayBuffer',\n message: 'SharedArrayBuffer is not allowed.'\n })\n }\n\n // 3. If the conversion is not to an IDL type associated\n // with the [AllowResizable] extended attribute, and\n // IsResizableArrayBuffer(V) is true, then throw a\n // TypeError.\n if (V.resizable || V.growable) {\n throw webidl.errors.exception({\n header: 'ArrayBuffer',\n message: 'Received a resizable ArrayBuffer.'\n })\n }\n\n // 4. Return the IDL ArrayBuffer value that is a\n // reference to the same object as V.\n return V\n}\n\nwebidl.converters.TypedArray = function (V, T, prefix, name, opts) {\n // 1. Let T be the IDL type V is being converted to.\n\n // 2. If Type(V) is not Object, or V does not have a\n // [[TypedArrayName]] internal slot with a value\n // equal to T’s name, then throw a TypeError.\n if (\n webidl.util.Type(V) !== 'Object' ||\n !types.isTypedArray(V) ||\n V.constructor.name !== T.name\n ) {\n throw webidl.errors.conversionFailed({\n prefix,\n argument: `${name} (\"${webidl.util.Stringify(V)}\")`,\n types: [T.name]\n })\n }\n\n // 3. If the conversion is not to an IDL type associated\n // with the [AllowShared] extended attribute, and\n // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is\n // true, then throw a TypeError.\n if (opts?.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {\n throw webidl.errors.exception({\n header: 'ArrayBuffer',\n message: 'SharedArrayBuffer is not allowed.'\n })\n }\n\n // 4. If the conversion is not to an IDL type associated\n // with the [AllowResizable] extended attribute, and\n // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is\n // true, then throw a TypeError.\n if (V.buffer.resizable || V.buffer.growable) {\n throw webidl.errors.exception({\n header: 'ArrayBuffer',\n message: 'Received a resizable ArrayBuffer.'\n })\n }\n\n // 5. Return the IDL value of type T that is a reference\n // to the same object as V.\n return V\n}\n\nwebidl.converters.DataView = function (V, prefix, name, opts) {\n // 1. If Type(V) is not Object, or V does not have a\n // [[DataView]] internal slot, then throw a TypeError.\n if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) {\n throw webidl.errors.exception({\n header: prefix,\n message: `${name} is not a DataView.`\n })\n }\n\n // 2. If the conversion is not to an IDL type associated\n // with the [AllowShared] extended attribute, and\n // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true,\n // then throw a TypeError.\n if (opts?.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {\n throw webidl.errors.exception({\n header: 'ArrayBuffer',\n message: 'SharedArrayBuffer is not allowed.'\n })\n }\n\n // 3. If the conversion is not to an IDL type associated\n // with the [AllowResizable] extended attribute, and\n // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is\n // true, then throw a TypeError.\n if (V.buffer.resizable || V.buffer.growable) {\n throw webidl.errors.exception({\n header: 'ArrayBuffer',\n message: 'Received a resizable ArrayBuffer.'\n })\n }\n\n // 4. Return the IDL DataView value that is a reference\n // to the same object as V.\n return V\n}\n\n// https://webidl.spec.whatwg.org/#BufferSource\nwebidl.converters.BufferSource = function (V, prefix, name, opts) {\n if (types.isAnyArrayBuffer(V)) {\n return webidl.converters.ArrayBuffer(V, prefix, name, { ...opts, allowShared: false })\n }\n\n if (types.isTypedArray(V)) {\n return webidl.converters.TypedArray(V, V.constructor, prefix, name, { ...opts, allowShared: false })\n }\n\n if (types.isDataView(V)) {\n return webidl.converters.DataView(V, prefix, name, { ...opts, allowShared: false })\n }\n\n throw webidl.errors.conversionFailed({\n prefix,\n argument: `${name} (\"${webidl.util.Stringify(V)}\")`,\n types: ['BufferSource']\n })\n}\n\nwebidl.converters['sequence'] = webidl.sequenceConverter(\n webidl.converters.ByteString\n)\n\nwebidl.converters['sequence>'] = webidl.sequenceConverter(\n webidl.converters['sequence']\n)\n\nwebidl.converters['record'] = webidl.recordConverter(\n webidl.converters.ByteString,\n webidl.converters.ByteString\n)\n\nmodule.exports = {\n webidl\n}\n","'use strict'\n\nconst { Transform } = require('node:stream')\nconst zlib = require('node:zlib')\nconst { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = require('./constants')\nconst { getGlobalOrigin } = require('./global')\nconst { collectASequenceOfCodePoints, collectAnHTTPQuotedString, removeChars, parseMIMEType } = require('./data-url')\nconst { performance } = require('node:perf_hooks')\nconst { isBlobLike, ReadableStreamFrom, isValidHTTPToken, normalizedMethodRecordsBase } = require('../../core/util')\nconst assert = require('node:assert')\nconst { isUint8Array } = require('node:util/types')\nconst { webidl } = require('./webidl')\n\nlet supportedHashes = []\n\n// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable\n/** @type {import('crypto')} */\nlet crypto\ntry {\n crypto = require('node:crypto')\n const possibleRelevantHashes = ['sha256', 'sha384', 'sha512']\n supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash))\n/* c8 ignore next 3 */\n} catch {\n\n}\n\nfunction responseURL (response) {\n // https://fetch.spec.whatwg.org/#responses\n // A response has an associated URL. It is a pointer to the last URL\n // in response’s URL list and null if response’s URL list is empty.\n const urlList = response.urlList\n const length = urlList.length\n return length === 0 ? null : urlList[length - 1].toString()\n}\n\n// https://fetch.spec.whatwg.org/#concept-response-location-url\nfunction responseLocationURL (response, requestFragment) {\n // 1. If response’s status is not a redirect status, then return null.\n if (!redirectStatusSet.has(response.status)) {\n return null\n }\n\n // 2. Let location be the result of extracting header list values given\n // `Location` and response’s header list.\n let location = response.headersList.get('location', true)\n\n // 3. If location is a header value, then set location to the result of\n // parsing location with response’s URL.\n if (location !== null && isValidHeaderValue(location)) {\n if (!isValidEncodedURL(location)) {\n // Some websites respond location header in UTF-8 form without encoding them as ASCII\n // and major browsers redirect them to correctly UTF-8 encoded addresses.\n // Here, we handle that behavior in the same way.\n location = normalizeBinaryStringToUtf8(location)\n }\n location = new URL(location, responseURL(response))\n }\n\n // 4. If location is a URL whose fragment is null, then set location’s\n // fragment to requestFragment.\n if (location && !location.hash) {\n location.hash = requestFragment\n }\n\n // 5. Return location.\n return location\n}\n\n/**\n * @see https://www.rfc-editor.org/rfc/rfc1738#section-2.2\n * @param {string} url\n * @returns {boolean}\n */\nfunction isValidEncodedURL (url) {\n for (let i = 0; i < url.length; ++i) {\n const code = url.charCodeAt(i)\n\n if (\n code > 0x7E || // Non-US-ASCII + DEL\n code < 0x20 // Control characters NUL - US\n ) {\n return false\n }\n }\n return true\n}\n\n/**\n * If string contains non-ASCII characters, assumes it's UTF-8 encoded and decodes it.\n * Since UTF-8 is a superset of ASCII, this will work for ASCII strings as well.\n * @param {string} value\n * @returns {string}\n */\nfunction normalizeBinaryStringToUtf8 (value) {\n return Buffer.from(value, 'binary').toString('utf8')\n}\n\n/** @returns {URL} */\nfunction requestCurrentURL (request) {\n return request.urlList[request.urlList.length - 1]\n}\n\nfunction requestBadPort (request) {\n // 1. Let url be request’s current URL.\n const url = requestCurrentURL(request)\n\n // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port,\n // then return blocked.\n if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) {\n return 'blocked'\n }\n\n // 3. Return allowed.\n return 'allowed'\n}\n\nfunction isErrorLike (object) {\n return object instanceof Error || (\n object?.constructor?.name === 'Error' ||\n object?.constructor?.name === 'DOMException'\n )\n}\n\n// Check whether |statusText| is a ByteString and\n// matches the Reason-Phrase token production.\n// RFC 2616: https://tools.ietf.org/html/rfc2616\n// RFC 7230: https://tools.ietf.org/html/rfc7230\n// \"reason-phrase = *( HTAB / SP / VCHAR / obs-text )\"\n// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116\nfunction isValidReasonPhrase (statusText) {\n for (let i = 0; i < statusText.length; ++i) {\n const c = statusText.charCodeAt(i)\n if (\n !(\n (\n c === 0x09 || // HTAB\n (c >= 0x20 && c <= 0x7e) || // SP / VCHAR\n (c >= 0x80 && c <= 0xff)\n ) // obs-text\n )\n ) {\n return false\n }\n }\n return true\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#header-name\n * @param {string} potentialValue\n */\nconst isValidHeaderName = isValidHTTPToken\n\n/**\n * @see https://fetch.spec.whatwg.org/#header-value\n * @param {string} potentialValue\n */\nfunction isValidHeaderValue (potentialValue) {\n // - Has no leading or trailing HTTP tab or space bytes.\n // - Contains no 0x00 (NUL) or HTTP newline bytes.\n return (\n potentialValue[0] === '\\t' ||\n potentialValue[0] === ' ' ||\n potentialValue[potentialValue.length - 1] === '\\t' ||\n potentialValue[potentialValue.length - 1] === ' ' ||\n potentialValue.includes('\\n') ||\n potentialValue.includes('\\r') ||\n potentialValue.includes('\\0')\n ) === false\n}\n\n// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect\nfunction setRequestReferrerPolicyOnRedirect (request, actualResponse) {\n // Given a request request and a response actualResponse, this algorithm\n // updates request’s referrer policy according to the Referrer-Policy\n // header (if any) in actualResponse.\n\n // 1. Let policy be the result of executing § 8.1 Parse a referrer policy\n // from a Referrer-Policy header on actualResponse.\n\n // 8.1 Parse a referrer policy from a Referrer-Policy header\n // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list.\n const { headersList } = actualResponse\n // 2. Let policy be the empty string.\n // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token.\n // 4. Return policy.\n const policyHeader = (headersList.get('referrer-policy', true) ?? '').split(',')\n\n // Note: As the referrer-policy can contain multiple policies\n // separated by comma, we need to loop through all of them\n // and pick the first valid one.\n // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy\n let policy = ''\n if (policyHeader.length > 0) {\n // The right-most policy takes precedence.\n // The left-most policy is the fallback.\n for (let i = policyHeader.length; i !== 0; i--) {\n const token = policyHeader[i - 1].trim()\n if (referrerPolicyTokens.has(token)) {\n policy = token\n break\n }\n }\n }\n\n // 2. If policy is not the empty string, then set request’s referrer policy to policy.\n if (policy !== '') {\n request.referrerPolicy = policy\n }\n}\n\n// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check\nfunction crossOriginResourcePolicyCheck () {\n // TODO\n return 'allowed'\n}\n\n// https://fetch.spec.whatwg.org/#concept-cors-check\nfunction corsCheck () {\n // TODO\n return 'success'\n}\n\n// https://fetch.spec.whatwg.org/#concept-tao-check\nfunction TAOCheck () {\n // TODO\n return 'success'\n}\n\nfunction appendFetchMetadata (httpRequest) {\n // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header\n // TODO\n\n // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header\n\n // 1. Assert: r’s url is a potentially trustworthy URL.\n // TODO\n\n // 2. Let header be a Structured Header whose value is a token.\n let header = null\n\n // 3. Set header’s value to r’s mode.\n header = httpRequest.mode\n\n // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list.\n httpRequest.headersList.set('sec-fetch-mode', header, true)\n\n // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header\n // TODO\n\n // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header\n // TODO\n}\n\n// https://fetch.spec.whatwg.org/#append-a-request-origin-header\nfunction appendRequestOriginHeader (request) {\n // 1. Let serializedOrigin be the result of byte-serializing a request origin\n // with request.\n // TODO: implement \"byte-serializing a request origin\"\n let serializedOrigin = request.origin\n\n // - \"'client' is changed to an origin during fetching.\"\n // This doesn't happen in undici (in most cases) because undici, by default,\n // has no concept of origin.\n // - request.origin can also be set to request.client.origin (client being\n // an environment settings object), which is undefined without using\n // setGlobalOrigin.\n if (serializedOrigin === 'client' || serializedOrigin === undefined) {\n return\n }\n\n // 2. If request’s response tainting is \"cors\" or request’s mode is \"websocket\",\n // then append (`Origin`, serializedOrigin) to request’s header list.\n // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then:\n if (request.responseTainting === 'cors' || request.mode === 'websocket') {\n request.headersList.append('origin', serializedOrigin, true)\n } else if (request.method !== 'GET' && request.method !== 'HEAD') {\n // 1. Switch on request’s referrer policy:\n switch (request.referrerPolicy) {\n case 'no-referrer':\n // Set serializedOrigin to `null`.\n serializedOrigin = null\n break\n case 'no-referrer-when-downgrade':\n case 'strict-origin':\n case 'strict-origin-when-cross-origin':\n // If request’s origin is a tuple origin, its scheme is \"https\", and\n // request’s current URL’s scheme is not \"https\", then set\n // serializedOrigin to `null`.\n if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) {\n serializedOrigin = null\n }\n break\n case 'same-origin':\n // If request’s origin is not same origin with request’s current URL’s\n // origin, then set serializedOrigin to `null`.\n if (!sameOrigin(request, requestCurrentURL(request))) {\n serializedOrigin = null\n }\n break\n default:\n // Do nothing.\n }\n\n // 2. Append (`Origin`, serializedOrigin) to request’s header list.\n request.headersList.append('origin', serializedOrigin, true)\n }\n}\n\n// https://w3c.github.io/hr-time/#dfn-coarsen-time\nfunction coarsenTime (timestamp, crossOriginIsolatedCapability) {\n // TODO\n return timestamp\n}\n\n// https://fetch.spec.whatwg.org/#clamp-and-coarsen-connection-timing-info\nfunction clampAndCoarsenConnectionTimingInfo (connectionTimingInfo, defaultStartTime, crossOriginIsolatedCapability) {\n if (!connectionTimingInfo?.startTime || connectionTimingInfo.startTime < defaultStartTime) {\n return {\n domainLookupStartTime: defaultStartTime,\n domainLookupEndTime: defaultStartTime,\n connectionStartTime: defaultStartTime,\n connectionEndTime: defaultStartTime,\n secureConnectionStartTime: defaultStartTime,\n ALPNNegotiatedProtocol: connectionTimingInfo?.ALPNNegotiatedProtocol\n }\n }\n\n return {\n domainLookupStartTime: coarsenTime(connectionTimingInfo.domainLookupStartTime, crossOriginIsolatedCapability),\n domainLookupEndTime: coarsenTime(connectionTimingInfo.domainLookupEndTime, crossOriginIsolatedCapability),\n connectionStartTime: coarsenTime(connectionTimingInfo.connectionStartTime, crossOriginIsolatedCapability),\n connectionEndTime: coarsenTime(connectionTimingInfo.connectionEndTime, crossOriginIsolatedCapability),\n secureConnectionStartTime: coarsenTime(connectionTimingInfo.secureConnectionStartTime, crossOriginIsolatedCapability),\n ALPNNegotiatedProtocol: connectionTimingInfo.ALPNNegotiatedProtocol\n }\n}\n\n// https://w3c.github.io/hr-time/#dfn-coarsened-shared-current-time\nfunction coarsenedSharedCurrentTime (crossOriginIsolatedCapability) {\n return coarsenTime(performance.now(), crossOriginIsolatedCapability)\n}\n\n// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info\nfunction createOpaqueTimingInfo (timingInfo) {\n return {\n startTime: timingInfo.startTime ?? 0,\n redirectStartTime: 0,\n redirectEndTime: 0,\n postRedirectStartTime: timingInfo.startTime ?? 0,\n finalServiceWorkerStartTime: 0,\n finalNetworkResponseStartTime: 0,\n finalNetworkRequestStartTime: 0,\n endTime: 0,\n encodedBodySize: 0,\n decodedBodySize: 0,\n finalConnectionTimingInfo: null\n }\n}\n\n// https://html.spec.whatwg.org/multipage/origin.html#policy-container\nfunction makePolicyContainer () {\n // Note: the fetch spec doesn't make use of embedder policy or CSP list\n return {\n referrerPolicy: 'strict-origin-when-cross-origin'\n }\n}\n\n// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container\nfunction clonePolicyContainer (policyContainer) {\n return {\n referrerPolicy: policyContainer.referrerPolicy\n }\n}\n\n// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer\nfunction determineRequestsReferrer (request) {\n // 1. Let policy be request's referrer policy.\n const policy = request.referrerPolicy\n\n // Note: policy cannot (shouldn't) be null or an empty string.\n assert(policy)\n\n // 2. Let environment be request’s client.\n\n let referrerSource = null\n\n // 3. Switch on request’s referrer:\n if (request.referrer === 'client') {\n // Note: node isn't a browser and doesn't implement document/iframes,\n // so we bypass this step and replace it with our own.\n\n const globalOrigin = getGlobalOrigin()\n\n if (!globalOrigin || globalOrigin.origin === 'null') {\n return 'no-referrer'\n }\n\n // note: we need to clone it as it's mutated\n referrerSource = new URL(globalOrigin)\n } else if (request.referrer instanceof URL) {\n // Let referrerSource be request’s referrer.\n referrerSource = request.referrer\n }\n\n // 4. Let request’s referrerURL be the result of stripping referrerSource for\n // use as a referrer.\n let referrerURL = stripURLForReferrer(referrerSource)\n\n // 5. Let referrerOrigin be the result of stripping referrerSource for use as\n // a referrer, with the origin-only flag set to true.\n const referrerOrigin = stripURLForReferrer(referrerSource, true)\n\n // 6. If the result of serializing referrerURL is a string whose length is\n // greater than 4096, set referrerURL to referrerOrigin.\n if (referrerURL.toString().length > 4096) {\n referrerURL = referrerOrigin\n }\n\n const areSameOrigin = sameOrigin(request, referrerURL)\n const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) &&\n !isURLPotentiallyTrustworthy(request.url)\n\n // 8. Execute the switch statements corresponding to the value of policy:\n switch (policy) {\n case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true)\n case 'unsafe-url': return referrerURL\n case 'same-origin':\n return areSameOrigin ? referrerOrigin : 'no-referrer'\n case 'origin-when-cross-origin':\n return areSameOrigin ? referrerURL : referrerOrigin\n case 'strict-origin-when-cross-origin': {\n const currentURL = requestCurrentURL(request)\n\n // 1. If the origin of referrerURL and the origin of request’s current\n // URL are the same, then return referrerURL.\n if (sameOrigin(referrerURL, currentURL)) {\n return referrerURL\n }\n\n // 2. If referrerURL is a potentially trustworthy URL and request’s\n // current URL is not a potentially trustworthy URL, then return no\n // referrer.\n if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {\n return 'no-referrer'\n }\n\n // 3. Return referrerOrigin.\n return referrerOrigin\n }\n case 'strict-origin': // eslint-disable-line\n /**\n * 1. If referrerURL is a potentially trustworthy URL and\n * request’s current URL is not a potentially trustworthy URL,\n * then return no referrer.\n * 2. Return referrerOrigin\n */\n case 'no-referrer-when-downgrade': // eslint-disable-line\n /**\n * 1. If referrerURL is a potentially trustworthy URL and\n * request’s current URL is not a potentially trustworthy URL,\n * then return no referrer.\n * 2. Return referrerOrigin\n */\n\n default: // eslint-disable-line\n return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin\n }\n}\n\n/**\n * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url\n * @param {URL} url\n * @param {boolean|undefined} originOnly\n */\nfunction stripURLForReferrer (url, originOnly) {\n // 1. Assert: url is a URL.\n assert(url instanceof URL)\n\n url = new URL(url)\n\n // 2. If url’s scheme is a local scheme, then return no referrer.\n if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') {\n return 'no-referrer'\n }\n\n // 3. Set url’s username to the empty string.\n url.username = ''\n\n // 4. Set url’s password to the empty string.\n url.password = ''\n\n // 5. Set url’s fragment to null.\n url.hash = ''\n\n // 6. If the origin-only flag is true, then:\n if (originOnly) {\n // 1. Set url’s path to « the empty string ».\n url.pathname = ''\n\n // 2. Set url’s query to null.\n url.search = ''\n }\n\n // 7. Return url.\n return url\n}\n\nfunction isURLPotentiallyTrustworthy (url) {\n if (!(url instanceof URL)) {\n return false\n }\n\n // If child of about, return true\n if (url.href === 'about:blank' || url.href === 'about:srcdoc') {\n return true\n }\n\n // If scheme is data, return true\n if (url.protocol === 'data:') return true\n\n // If file, return true\n if (url.protocol === 'file:') return true\n\n return isOriginPotentiallyTrustworthy(url.origin)\n\n function isOriginPotentiallyTrustworthy (origin) {\n // If origin is explicitly null, return false\n if (origin == null || origin === 'null') return false\n\n const originAsURL = new URL(origin)\n\n // If secure, return true\n if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') {\n return true\n }\n\n // If localhost or variants, return true\n if (/^127(?:\\.[0-9]+){0,2}\\.[0-9]+$|^\\[(?:0*:)*?:?0*1\\]$/.test(originAsURL.hostname) ||\n (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) ||\n (originAsURL.hostname.endsWith('.localhost'))) {\n return true\n }\n\n // If any other, return false\n return false\n }\n}\n\n/**\n * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist\n * @param {Uint8Array} bytes\n * @param {string} metadataList\n */\nfunction bytesMatch (bytes, metadataList) {\n // If node is not built with OpenSSL support, we cannot check\n // a request's integrity, so allow it by default (the spec will\n // allow requests if an invalid hash is given, as precedence).\n /* istanbul ignore if: only if node is built with --without-ssl */\n if (crypto === undefined) {\n return true\n }\n\n // 1. Let parsedMetadata be the result of parsing metadataList.\n const parsedMetadata = parseMetadata(metadataList)\n\n // 2. If parsedMetadata is no metadata, return true.\n if (parsedMetadata === 'no metadata') {\n return true\n }\n\n // 3. If response is not eligible for integrity validation, return false.\n // TODO\n\n // 4. If parsedMetadata is the empty set, return true.\n if (parsedMetadata.length === 0) {\n return true\n }\n\n // 5. Let metadata be the result of getting the strongest\n // metadata from parsedMetadata.\n const strongest = getStrongestMetadata(parsedMetadata)\n const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest)\n\n // 6. For each item in metadata:\n for (const item of metadata) {\n // 1. Let algorithm be the alg component of item.\n const algorithm = item.algo\n\n // 2. Let expectedValue be the val component of item.\n const expectedValue = item.hash\n\n // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e\n // \"be liberal with padding\". This is annoying, and it's not even in the spec.\n\n // 3. Let actualValue be the result of applying algorithm to bytes.\n let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64')\n\n if (actualValue[actualValue.length - 1] === '=') {\n if (actualValue[actualValue.length - 2] === '=') {\n actualValue = actualValue.slice(0, -2)\n } else {\n actualValue = actualValue.slice(0, -1)\n }\n }\n\n // 4. If actualValue is a case-sensitive match for expectedValue,\n // return true.\n if (compareBase64Mixed(actualValue, expectedValue)) {\n return true\n }\n }\n\n // 7. Return false.\n return false\n}\n\n// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options\n// https://www.w3.org/TR/CSP2/#source-list-syntax\n// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1\nconst parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\\s|$)( +[!-~]*)?)?/i\n\n/**\n * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata\n * @param {string} metadata\n */\nfunction parseMetadata (metadata) {\n // 1. Let result be the empty set.\n /** @type {{ algo: string, hash: string }[]} */\n const result = []\n\n // 2. Let empty be equal to true.\n let empty = true\n\n // 3. For each token returned by splitting metadata on spaces:\n for (const token of metadata.split(' ')) {\n // 1. Set empty to false.\n empty = false\n\n // 2. Parse token as a hash-with-options.\n const parsedToken = parseHashWithOptions.exec(token)\n\n // 3. If token does not parse, continue to the next token.\n if (\n parsedToken === null ||\n parsedToken.groups === undefined ||\n parsedToken.groups.algo === undefined\n ) {\n // Note: Chromium blocks the request at this point, but Firefox\n // gives a warning that an invalid integrity was given. The\n // correct behavior is to ignore these, and subsequently not\n // check the integrity of the resource.\n continue\n }\n\n // 4. Let algorithm be the hash-algo component of token.\n const algorithm = parsedToken.groups.algo.toLowerCase()\n\n // 5. If algorithm is a hash function recognized by the user\n // agent, add the parsed token to result.\n if (supportedHashes.includes(algorithm)) {\n result.push(parsedToken.groups)\n }\n }\n\n // 4. Return no metadata if empty is true, otherwise return result.\n if (empty === true) {\n return 'no metadata'\n }\n\n return result\n}\n\n/**\n * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList\n */\nfunction getStrongestMetadata (metadataList) {\n // Let algorithm be the algo component of the first item in metadataList.\n // Can be sha256\n let algorithm = metadataList[0].algo\n // If the algorithm is sha512, then it is the strongest\n // and we can return immediately\n if (algorithm[3] === '5') {\n return algorithm\n }\n\n for (let i = 1; i < metadataList.length; ++i) {\n const metadata = metadataList[i]\n // If the algorithm is sha512, then it is the strongest\n // and we can break the loop immediately\n if (metadata.algo[3] === '5') {\n algorithm = 'sha512'\n break\n // If the algorithm is sha384, then a potential sha256 or sha384 is ignored\n } else if (algorithm[3] === '3') {\n continue\n // algorithm is sha256, check if algorithm is sha384 and if so, set it as\n // the strongest\n } else if (metadata.algo[3] === '3') {\n algorithm = 'sha384'\n }\n }\n return algorithm\n}\n\nfunction filterMetadataListByAlgorithm (metadataList, algorithm) {\n if (metadataList.length === 1) {\n return metadataList\n }\n\n let pos = 0\n for (let i = 0; i < metadataList.length; ++i) {\n if (metadataList[i].algo === algorithm) {\n metadataList[pos++] = metadataList[i]\n }\n }\n\n metadataList.length = pos\n\n return metadataList\n}\n\n/**\n * Compares two base64 strings, allowing for base64url\n * in the second string.\n *\n* @param {string} actualValue always base64\n * @param {string} expectedValue base64 or base64url\n * @returns {boolean}\n */\nfunction compareBase64Mixed (actualValue, expectedValue) {\n if (actualValue.length !== expectedValue.length) {\n return false\n }\n for (let i = 0; i < actualValue.length; ++i) {\n if (actualValue[i] !== expectedValue[i]) {\n if (\n (actualValue[i] === '+' && expectedValue[i] === '-') ||\n (actualValue[i] === '/' && expectedValue[i] === '_')\n ) {\n continue\n }\n return false\n }\n }\n\n return true\n}\n\n// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request\nfunction tryUpgradeRequestToAPotentiallyTrustworthyURL (request) {\n // TODO\n}\n\n/**\n * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin}\n * @param {URL} A\n * @param {URL} B\n */\nfunction sameOrigin (A, B) {\n // 1. If A and B are the same opaque origin, then return true.\n if (A.origin === B.origin && A.origin === 'null') {\n return true\n }\n\n // 2. If A and B are both tuple origins and their schemes,\n // hosts, and port are identical, then return true.\n if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) {\n return true\n }\n\n // 3. Return false.\n return false\n}\n\nfunction createDeferredPromise () {\n let res\n let rej\n const promise = new Promise((resolve, reject) => {\n res = resolve\n rej = reject\n })\n\n return { promise, resolve: res, reject: rej }\n}\n\nfunction isAborted (fetchParams) {\n return fetchParams.controller.state === 'aborted'\n}\n\nfunction isCancelled (fetchParams) {\n return fetchParams.controller.state === 'aborted' ||\n fetchParams.controller.state === 'terminated'\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-method-normalize\n * @param {string} method\n */\nfunction normalizeMethod (method) {\n return normalizedMethodRecordsBase[method.toLowerCase()] ?? method\n}\n\n// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string\nfunction serializeJavascriptValueToJSONString (value) {\n // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »).\n const result = JSON.stringify(value)\n\n // 2. If result is undefined, then throw a TypeError.\n if (result === undefined) {\n throw new TypeError('Value is not JSON serializable')\n }\n\n // 3. Assert: result is a string.\n assert(typeof result === 'string')\n\n // 4. Return result.\n return result\n}\n\n// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object\nconst esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))\n\n/**\n * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object\n * @param {string} name name of the instance\n * @param {symbol} kInternalIterator\n * @param {string | number} [keyIndex]\n * @param {string | number} [valueIndex]\n */\nfunction createIterator (name, kInternalIterator, keyIndex = 0, valueIndex = 1) {\n class FastIterableIterator {\n /** @type {any} */\n #target\n /** @type {'key' | 'value' | 'key+value'} */\n #kind\n /** @type {number} */\n #index\n\n /**\n * @see https://webidl.spec.whatwg.org/#dfn-default-iterator-object\n * @param {unknown} target\n * @param {'key' | 'value' | 'key+value'} kind\n */\n constructor (target, kind) {\n this.#target = target\n this.#kind = kind\n this.#index = 0\n }\n\n next () {\n // 1. Let interface be the interface for which the iterator prototype object exists.\n // 2. Let thisValue be the this value.\n // 3. Let object be ? ToObject(thisValue).\n // 4. If object is a platform object, then perform a security\n // check, passing:\n // 5. If object is not a default iterator object for interface,\n // then throw a TypeError.\n if (typeof this !== 'object' || this === null || !(#target in this)) {\n throw new TypeError(\n `'next' called on an object that does not implement interface ${name} Iterator.`\n )\n }\n\n // 6. Let index be object’s index.\n // 7. Let kind be object’s kind.\n // 8. Let values be object’s target's value pairs to iterate over.\n const index = this.#index\n const values = this.#target[kInternalIterator]\n\n // 9. Let len be the length of values.\n const len = values.length\n\n // 10. If index is greater than or equal to len, then return\n // CreateIterResultObject(undefined, true).\n if (index >= len) {\n return {\n value: undefined,\n done: true\n }\n }\n\n // 11. Let pair be the entry in values at index index.\n const { [keyIndex]: key, [valueIndex]: value } = values[index]\n\n // 12. Set object’s index to index + 1.\n this.#index = index + 1\n\n // 13. Return the iterator result for pair and kind.\n\n // https://webidl.spec.whatwg.org/#iterator-result\n\n // 1. Let result be a value determined by the value of kind:\n let result\n switch (this.#kind) {\n case 'key':\n // 1. Let idlKey be pair’s key.\n // 2. Let key be the result of converting idlKey to an\n // ECMAScript value.\n // 3. result is key.\n result = key\n break\n case 'value':\n // 1. Let idlValue be pair’s value.\n // 2. Let value be the result of converting idlValue to\n // an ECMAScript value.\n // 3. result is value.\n result = value\n break\n case 'key+value':\n // 1. Let idlKey be pair’s key.\n // 2. Let idlValue be pair’s value.\n // 3. Let key be the result of converting idlKey to an\n // ECMAScript value.\n // 4. Let value be the result of converting idlValue to\n // an ECMAScript value.\n // 5. Let array be ! ArrayCreate(2).\n // 6. Call ! CreateDataProperty(array, \"0\", key).\n // 7. Call ! CreateDataProperty(array, \"1\", value).\n // 8. result is array.\n result = [key, value]\n break\n }\n\n // 2. Return CreateIterResultObject(result, false).\n return {\n value: result,\n done: false\n }\n }\n }\n\n // https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object\n // @ts-ignore\n delete FastIterableIterator.prototype.constructor\n\n Object.setPrototypeOf(FastIterableIterator.prototype, esIteratorPrototype)\n\n Object.defineProperties(FastIterableIterator.prototype, {\n [Symbol.toStringTag]: {\n writable: false,\n enumerable: false,\n configurable: true,\n value: `${name} Iterator`\n },\n next: { writable: true, enumerable: true, configurable: true }\n })\n\n /**\n * @param {unknown} target\n * @param {'key' | 'value' | 'key+value'} kind\n * @returns {IterableIterator}\n */\n return function (target, kind) {\n return new FastIterableIterator(target, kind)\n }\n}\n\n/**\n * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object\n * @param {string} name name of the instance\n * @param {any} object class\n * @param {symbol} kInternalIterator\n * @param {string | number} [keyIndex]\n * @param {string | number} [valueIndex]\n */\nfunction iteratorMixin (name, object, kInternalIterator, keyIndex = 0, valueIndex = 1) {\n const makeIterator = createIterator(name, kInternalIterator, keyIndex, valueIndex)\n\n const properties = {\n keys: {\n writable: true,\n enumerable: true,\n configurable: true,\n value: function keys () {\n webidl.brandCheck(this, object)\n return makeIterator(this, 'key')\n }\n },\n values: {\n writable: true,\n enumerable: true,\n configurable: true,\n value: function values () {\n webidl.brandCheck(this, object)\n return makeIterator(this, 'value')\n }\n },\n entries: {\n writable: true,\n enumerable: true,\n configurable: true,\n value: function entries () {\n webidl.brandCheck(this, object)\n return makeIterator(this, 'key+value')\n }\n },\n forEach: {\n writable: true,\n enumerable: true,\n configurable: true,\n value: function forEach (callbackfn, thisArg = globalThis) {\n webidl.brandCheck(this, object)\n webidl.argumentLengthCheck(arguments, 1, `${name}.forEach`)\n if (typeof callbackfn !== 'function') {\n throw new TypeError(\n `Failed to execute 'forEach' on '${name}': parameter 1 is not of type 'Function'.`\n )\n }\n for (const { 0: key, 1: value } of makeIterator(this, 'key+value')) {\n callbackfn.call(thisArg, value, key, this)\n }\n }\n }\n }\n\n return Object.defineProperties(object.prototype, {\n ...properties,\n [Symbol.iterator]: {\n writable: true,\n enumerable: false,\n configurable: true,\n value: properties.entries.value\n }\n })\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#body-fully-read\n */\nasync function fullyReadBody (body, processBody, processBodyError) {\n // 1. If taskDestination is null, then set taskDestination to\n // the result of starting a new parallel queue.\n\n // 2. Let successSteps given a byte sequence bytes be to queue a\n // fetch task to run processBody given bytes, with taskDestination.\n const successSteps = processBody\n\n // 3. Let errorSteps be to queue a fetch task to run processBodyError,\n // with taskDestination.\n const errorSteps = processBodyError\n\n // 4. Let reader be the result of getting a reader for body’s stream.\n // If that threw an exception, then run errorSteps with that\n // exception and return.\n let reader\n\n try {\n reader = body.stream.getReader()\n } catch (e) {\n errorSteps(e)\n return\n }\n\n // 5. Read all bytes from reader, given successSteps and errorSteps.\n try {\n successSteps(await readAllBytes(reader))\n } catch (e) {\n errorSteps(e)\n }\n}\n\nfunction isReadableStreamLike (stream) {\n return stream instanceof ReadableStream || (\n stream[Symbol.toStringTag] === 'ReadableStream' &&\n typeof stream.tee === 'function'\n )\n}\n\n/**\n * @param {ReadableStreamController} controller\n */\nfunction readableStreamClose (controller) {\n try {\n controller.close()\n controller.byobRequest?.respond(0)\n } catch (err) {\n // TODO: add comment explaining why this error occurs.\n if (!err.message.includes('Controller is already closed') && !err.message.includes('ReadableStream is already closed')) {\n throw err\n }\n }\n}\n\nconst invalidIsomorphicEncodeValueRegex = /[^\\x00-\\xFF]/ // eslint-disable-line\n\n/**\n * @see https://infra.spec.whatwg.org/#isomorphic-encode\n * @param {string} input\n */\nfunction isomorphicEncode (input) {\n // 1. Assert: input contains no code points greater than U+00FF.\n assert(!invalidIsomorphicEncodeValueRegex.test(input))\n\n // 2. Return a byte sequence whose length is equal to input’s code\n // point length and whose bytes have the same values as the\n // values of input’s code points, in the same order\n return input\n}\n\n/**\n * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes\n * @see https://streams.spec.whatwg.org/#read-loop\n * @param {ReadableStreamDefaultReader} reader\n */\nasync function readAllBytes (reader) {\n const bytes = []\n let byteLength = 0\n\n while (true) {\n const { done, value: chunk } = await reader.read()\n\n if (done) {\n // 1. Call successSteps with bytes.\n return Buffer.concat(bytes, byteLength)\n }\n\n // 1. If chunk is not a Uint8Array object, call failureSteps\n // with a TypeError and abort these steps.\n if (!isUint8Array(chunk)) {\n throw new TypeError('Received non-Uint8Array chunk')\n }\n\n // 2. Append the bytes represented by chunk to bytes.\n bytes.push(chunk)\n byteLength += chunk.length\n\n // 3. Read-loop given reader, bytes, successSteps, and failureSteps.\n }\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#is-local\n * @param {URL} url\n */\nfunction urlIsLocal (url) {\n assert('protocol' in url) // ensure it's a url object\n\n const protocol = url.protocol\n\n return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:'\n}\n\n/**\n * @param {string|URL} url\n * @returns {boolean}\n */\nfunction urlHasHttpsScheme (url) {\n return (\n (\n typeof url === 'string' &&\n url[5] === ':' &&\n url[0] === 'h' &&\n url[1] === 't' &&\n url[2] === 't' &&\n url[3] === 'p' &&\n url[4] === 's'\n ) ||\n url.protocol === 'https:'\n )\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#http-scheme\n * @param {URL} url\n */\nfunction urlIsHttpHttpsScheme (url) {\n assert('protocol' in url) // ensure it's a url object\n\n const protocol = url.protocol\n\n return protocol === 'http:' || protocol === 'https:'\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#simple-range-header-value\n * @param {string} value\n * @param {boolean} allowWhitespace\n */\nfunction simpleRangeHeaderValue (value, allowWhitespace) {\n // 1. Let data be the isomorphic decoding of value.\n // Note: isomorphic decoding takes a sequence of bytes (ie. a Uint8Array) and turns it into a string,\n // nothing more. We obviously don't need to do that if value is a string already.\n const data = value\n\n // 2. If data does not start with \"bytes\", then return failure.\n if (!data.startsWith('bytes')) {\n return 'failure'\n }\n\n // 3. Let position be a position variable for data, initially pointing at the 5th code point of data.\n const position = { position: 5 }\n\n // 4. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space,\n // from data given position.\n if (allowWhitespace) {\n collectASequenceOfCodePoints(\n (char) => char === '\\t' || char === ' ',\n data,\n position\n )\n }\n\n // 5. If the code point at position within data is not U+003D (=), then return failure.\n if (data.charCodeAt(position.position) !== 0x3D) {\n return 'failure'\n }\n\n // 6. Advance position by 1.\n position.position++\n\n // 7. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space, from\n // data given position.\n if (allowWhitespace) {\n collectASequenceOfCodePoints(\n (char) => char === '\\t' || char === ' ',\n data,\n position\n )\n }\n\n // 8. Let rangeStart be the result of collecting a sequence of code points that are ASCII digits,\n // from data given position.\n const rangeStart = collectASequenceOfCodePoints(\n (char) => {\n const code = char.charCodeAt(0)\n\n return code >= 0x30 && code <= 0x39\n },\n data,\n position\n )\n\n // 9. Let rangeStartValue be rangeStart, interpreted as decimal number, if rangeStart is not the\n // empty string; otherwise null.\n const rangeStartValue = rangeStart.length ? Number(rangeStart) : null\n\n // 10. If allowWhitespace is true, collect a sequence of code points that are HTTP tab or space,\n // from data given position.\n if (allowWhitespace) {\n collectASequenceOfCodePoints(\n (char) => char === '\\t' || char === ' ',\n data,\n position\n )\n }\n\n // 11. If the code point at position within data is not U+002D (-), then return failure.\n if (data.charCodeAt(position.position) !== 0x2D) {\n return 'failure'\n }\n\n // 12. Advance position by 1.\n position.position++\n\n // 13. If allowWhitespace is true, collect a sequence of code points that are HTTP tab\n // or space, from data given position.\n // Note from Khafra: its the same step as in #8 again lol\n if (allowWhitespace) {\n collectASequenceOfCodePoints(\n (char) => char === '\\t' || char === ' ',\n data,\n position\n )\n }\n\n // 14. Let rangeEnd be the result of collecting a sequence of code points that are\n // ASCII digits, from data given position.\n // Note from Khafra: you wouldn't guess it, but this is also the same step as #8\n const rangeEnd = collectASequenceOfCodePoints(\n (char) => {\n const code = char.charCodeAt(0)\n\n return code >= 0x30 && code <= 0x39\n },\n data,\n position\n )\n\n // 15. Let rangeEndValue be rangeEnd, interpreted as decimal number, if rangeEnd\n // is not the empty string; otherwise null.\n // Note from Khafra: THE SAME STEP, AGAIN!!!\n // Note: why interpret as a decimal if we only collect ascii digits?\n const rangeEndValue = rangeEnd.length ? Number(rangeEnd) : null\n\n // 16. If position is not past the end of data, then return failure.\n if (position.position < data.length) {\n return 'failure'\n }\n\n // 17. If rangeEndValue and rangeStartValue are null, then return failure.\n if (rangeEndValue === null && rangeStartValue === null) {\n return 'failure'\n }\n\n // 18. If rangeStartValue and rangeEndValue are numbers, and rangeStartValue is\n // greater than rangeEndValue, then return failure.\n // Note: ... when can they not be numbers?\n if (rangeStartValue > rangeEndValue) {\n return 'failure'\n }\n\n // 19. Return (rangeStartValue, rangeEndValue).\n return { rangeStartValue, rangeEndValue }\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#build-a-content-range\n * @param {number} rangeStart\n * @param {number} rangeEnd\n * @param {number} fullLength\n */\nfunction buildContentRange (rangeStart, rangeEnd, fullLength) {\n // 1. Let contentRange be `bytes `.\n let contentRange = 'bytes '\n\n // 2. Append rangeStart, serialized and isomorphic encoded, to contentRange.\n contentRange += isomorphicEncode(`${rangeStart}`)\n\n // 3. Append 0x2D (-) to contentRange.\n contentRange += '-'\n\n // 4. Append rangeEnd, serialized and isomorphic encoded to contentRange.\n contentRange += isomorphicEncode(`${rangeEnd}`)\n\n // 5. Append 0x2F (/) to contentRange.\n contentRange += '/'\n\n // 6. Append fullLength, serialized and isomorphic encoded to contentRange.\n contentRange += isomorphicEncode(`${fullLength}`)\n\n // 7. Return contentRange.\n return contentRange\n}\n\n// A Stream, which pipes the response to zlib.createInflate() or\n// zlib.createInflateRaw() depending on the first byte of the Buffer.\n// If the lower byte of the first byte is 0x08, then the stream is\n// interpreted as a zlib stream, otherwise it's interpreted as a\n// raw deflate stream.\nclass InflateStream extends Transform {\n #zlibOptions\n\n /** @param {zlib.ZlibOptions} [zlibOptions] */\n constructor (zlibOptions) {\n super()\n this.#zlibOptions = zlibOptions\n }\n\n _transform (chunk, encoding, callback) {\n if (!this._inflateStream) {\n if (chunk.length === 0) {\n callback()\n return\n }\n this._inflateStream = (chunk[0] & 0x0F) === 0x08\n ? zlib.createInflate(this.#zlibOptions)\n : zlib.createInflateRaw(this.#zlibOptions)\n\n this._inflateStream.on('data', this.push.bind(this))\n this._inflateStream.on('end', () => this.push(null))\n this._inflateStream.on('error', (err) => this.destroy(err))\n }\n\n this._inflateStream.write(chunk, encoding, callback)\n }\n\n _final (callback) {\n if (this._inflateStream) {\n this._inflateStream.end()\n this._inflateStream = null\n }\n callback()\n }\n}\n\n/**\n * @param {zlib.ZlibOptions} [zlibOptions]\n * @returns {InflateStream}\n */\nfunction createInflate (zlibOptions) {\n return new InflateStream(zlibOptions)\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-header-extract-mime-type\n * @param {import('./headers').HeadersList} headers\n */\nfunction extractMimeType (headers) {\n // 1. Let charset be null.\n let charset = null\n\n // 2. Let essence be null.\n let essence = null\n\n // 3. Let mimeType be null.\n let mimeType = null\n\n // 4. Let values be the result of getting, decoding, and splitting `Content-Type` from headers.\n const values = getDecodeSplit('content-type', headers)\n\n // 5. If values is null, then return failure.\n if (values === null) {\n return 'failure'\n }\n\n // 6. For each value of values:\n for (const value of values) {\n // 6.1. Let temporaryMimeType be the result of parsing value.\n const temporaryMimeType = parseMIMEType(value)\n\n // 6.2. If temporaryMimeType is failure or its essence is \"*/*\", then continue.\n if (temporaryMimeType === 'failure' || temporaryMimeType.essence === '*/*') {\n continue\n }\n\n // 6.3. Set mimeType to temporaryMimeType.\n mimeType = temporaryMimeType\n\n // 6.4. If mimeType’s essence is not essence, then:\n if (mimeType.essence !== essence) {\n // 6.4.1. Set charset to null.\n charset = null\n\n // 6.4.2. If mimeType’s parameters[\"charset\"] exists, then set charset to\n // mimeType’s parameters[\"charset\"].\n if (mimeType.parameters.has('charset')) {\n charset = mimeType.parameters.get('charset')\n }\n\n // 6.4.3. Set essence to mimeType’s essence.\n essence = mimeType.essence\n } else if (!mimeType.parameters.has('charset') && charset !== null) {\n // 6.5. Otherwise, if mimeType’s parameters[\"charset\"] does not exist, and\n // charset is non-null, set mimeType’s parameters[\"charset\"] to charset.\n mimeType.parameters.set('charset', charset)\n }\n }\n\n // 7. If mimeType is null, then return failure.\n if (mimeType == null) {\n return 'failure'\n }\n\n // 8. Return mimeType.\n return mimeType\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#header-value-get-decode-and-split\n * @param {string|null} value\n */\nfunction gettingDecodingSplitting (value) {\n // 1. Let input be the result of isomorphic decoding value.\n const input = value\n\n // 2. Let position be a position variable for input, initially pointing at the start of input.\n const position = { position: 0 }\n\n // 3. Let values be a list of strings, initially empty.\n const values = []\n\n // 4. Let temporaryValue be the empty string.\n let temporaryValue = ''\n\n // 5. While position is not past the end of input:\n while (position.position < input.length) {\n // 5.1. Append the result of collecting a sequence of code points that are not U+0022 (\")\n // or U+002C (,) from input, given position, to temporaryValue.\n temporaryValue += collectASequenceOfCodePoints(\n (char) => char !== '\"' && char !== ',',\n input,\n position\n )\n\n // 5.2. If position is not past the end of input, then:\n if (position.position < input.length) {\n // 5.2.1. If the code point at position within input is U+0022 (\"), then:\n if (input.charCodeAt(position.position) === 0x22) {\n // 5.2.1.1. Append the result of collecting an HTTP quoted string from input, given position, to temporaryValue.\n temporaryValue += collectAnHTTPQuotedString(\n input,\n position\n )\n\n // 5.2.1.2. If position is not past the end of input, then continue.\n if (position.position < input.length) {\n continue\n }\n } else {\n // 5.2.2. Otherwise:\n\n // 5.2.2.1. Assert: the code point at position within input is U+002C (,).\n assert(input.charCodeAt(position.position) === 0x2C)\n\n // 5.2.2.2. Advance position by 1.\n position.position++\n }\n }\n\n // 5.3. Remove all HTTP tab or space from the start and end of temporaryValue.\n temporaryValue = removeChars(temporaryValue, true, true, (char) => char === 0x9 || char === 0x20)\n\n // 5.4. Append temporaryValue to values.\n values.push(temporaryValue)\n\n // 5.6. Set temporaryValue to the empty string.\n temporaryValue = ''\n }\n\n // 6. Return values.\n return values\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-header-list-get-decode-split\n * @param {string} name lowercase header name\n * @param {import('./headers').HeadersList} list\n */\nfunction getDecodeSplit (name, list) {\n // 1. Let value be the result of getting name from list.\n const value = list.get(name, true)\n\n // 2. If value is null, then return null.\n if (value === null) {\n return null\n }\n\n // 3. Return the result of getting, decoding, and splitting value.\n return gettingDecodingSplitting(value)\n}\n\nconst textDecoder = new TextDecoder()\n\n/**\n * @see https://encoding.spec.whatwg.org/#utf-8-decode\n * @param {Buffer} buffer\n */\nfunction utf8DecodeBytes (buffer) {\n if (buffer.length === 0) {\n return ''\n }\n\n // 1. Let buffer be the result of peeking three bytes from\n // ioQueue, converted to a byte sequence.\n\n // 2. If buffer is 0xEF 0xBB 0xBF, then read three\n // bytes from ioQueue. (Do nothing with those bytes.)\n if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {\n buffer = buffer.subarray(3)\n }\n\n // 3. Process a queue with an instance of UTF-8’s\n // decoder, ioQueue, output, and \"replacement\".\n const output = textDecoder.decode(buffer)\n\n // 4. Return output.\n return output\n}\n\nclass EnvironmentSettingsObjectBase {\n get baseUrl () {\n return getGlobalOrigin()\n }\n\n get origin () {\n return this.baseUrl?.origin\n }\n\n policyContainer = makePolicyContainer()\n}\n\nclass EnvironmentSettingsObject {\n settingsObject = new EnvironmentSettingsObjectBase()\n}\n\nconst environmentSettingsObject = new EnvironmentSettingsObject()\n\nmodule.exports = {\n isAborted,\n isCancelled,\n isValidEncodedURL,\n createDeferredPromise,\n ReadableStreamFrom,\n tryUpgradeRequestToAPotentiallyTrustworthyURL,\n clampAndCoarsenConnectionTimingInfo,\n coarsenedSharedCurrentTime,\n determineRequestsReferrer,\n makePolicyContainer,\n clonePolicyContainer,\n appendFetchMetadata,\n appendRequestOriginHeader,\n TAOCheck,\n corsCheck,\n crossOriginResourcePolicyCheck,\n createOpaqueTimingInfo,\n setRequestReferrerPolicyOnRedirect,\n isValidHTTPToken,\n requestBadPort,\n requestCurrentURL,\n responseURL,\n responseLocationURL,\n isBlobLike,\n isURLPotentiallyTrustworthy,\n isValidReasonPhrase,\n sameOrigin,\n normalizeMethod,\n serializeJavascriptValueToJSONString,\n iteratorMixin,\n createIterator,\n isValidHeaderName,\n isValidHeaderValue,\n isErrorLike,\n fullyReadBody,\n bytesMatch,\n isReadableStreamLike,\n readableStreamClose,\n isomorphicEncode,\n urlIsLocal,\n urlHasHttpsScheme,\n urlIsHttpHttpsScheme,\n readAllBytes,\n simpleRangeHeaderValue,\n buildContentRange,\n parseMetadata,\n createInflate,\n extractMimeType,\n getDecodeSplit,\n utf8DecodeBytes,\n environmentSettingsObject\n}\n","'use strict'\n\nmodule.exports = {\n kUrl: Symbol('url'),\n kHeaders: Symbol('headers'),\n kSignal: Symbol('signal'),\n kState: Symbol('state'),\n kDispatcher: Symbol('dispatcher')\n}\n","'use strict'\n\nconst { Blob, File } = require('node:buffer')\nconst { kState } = require('./symbols')\nconst { webidl } = require('./webidl')\n\n// TODO(@KhafraDev): remove\nclass FileLike {\n constructor (blobLike, fileName, options = {}) {\n // TODO: argument idl type check\n\n // The File constructor is invoked with two or three parameters, depending\n // on whether the optional dictionary parameter is used. When the File()\n // constructor is invoked, user agents must run the following steps:\n\n // 1. Let bytes be the result of processing blob parts given fileBits and\n // options.\n\n // 2. Let n be the fileName argument to the constructor.\n const n = fileName\n\n // 3. Process FilePropertyBag dictionary argument by running the following\n // substeps:\n\n // 1. If the type member is provided and is not the empty string, let t\n // be set to the type dictionary member. If t contains any characters\n // outside the range U+0020 to U+007E, then set t to the empty string\n // and return from these substeps.\n // TODO\n const t = options.type\n\n // 2. Convert every character in t to ASCII lowercase.\n // TODO\n\n // 3. If the lastModified member is provided, let d be set to the\n // lastModified dictionary member. If it is not provided, set d to the\n // current date and time represented as the number of milliseconds since\n // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).\n const d = options.lastModified ?? Date.now()\n\n // 4. Return a new File object F such that:\n // F refers to the bytes byte sequence.\n // F.size is set to the number of total bytes in bytes.\n // F.name is set to n.\n // F.type is set to t.\n // F.lastModified is set to d.\n\n this[kState] = {\n blobLike,\n name: n,\n type: t,\n lastModified: d\n }\n }\n\n stream (...args) {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.stream(...args)\n }\n\n arrayBuffer (...args) {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.arrayBuffer(...args)\n }\n\n slice (...args) {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.slice(...args)\n }\n\n text (...args) {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.text(...args)\n }\n\n get size () {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.size\n }\n\n get type () {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].blobLike.type\n }\n\n get name () {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].name\n }\n\n get lastModified () {\n webidl.brandCheck(this, FileLike)\n\n return this[kState].lastModified\n }\n\n get [Symbol.toStringTag] () {\n return 'File'\n }\n}\n\nwebidl.converters.Blob = webidl.interfaceConverter(Blob)\n\n// If this function is moved to ./util.js, some tools (such as\n// rollup) will warn about circular dependencies. See:\n// https://github.com/nodejs/undici/issues/1629\nfunction isFileLike (object) {\n return (\n (object instanceof File) ||\n (\n object &&\n (typeof object.stream === 'function' ||\n typeof object.arrayBuffer === 'function') &&\n object[Symbol.toStringTag] === 'File'\n )\n )\n}\n\nmodule.exports = { FileLike, isFileLike }\n","'use strict'\n\nconst { isBlobLike, iteratorMixin } = require('./util')\nconst { kState } = require('./symbols')\nconst { kEnumerableProperty } = require('../../core/util')\nconst { FileLike, isFileLike } = require('./file')\nconst { webidl } = require('./webidl')\nconst { File: NativeFile } = require('node:buffer')\nconst nodeUtil = require('node:util')\n\n/** @type {globalThis['File']} */\nconst File = globalThis.File ?? NativeFile\n\n// https://xhr.spec.whatwg.org/#formdata\nclass FormData {\n constructor (form) {\n webidl.util.markAsUncloneable(this)\n\n if (form !== undefined) {\n throw webidl.errors.conversionFailed({\n prefix: 'FormData constructor',\n argument: 'Argument 1',\n types: ['undefined']\n })\n }\n\n this[kState] = []\n }\n\n append (name, value, filename = undefined) {\n webidl.brandCheck(this, FormData)\n\n const prefix = 'FormData.append'\n webidl.argumentLengthCheck(arguments, 2, prefix)\n\n if (arguments.length === 3 && !isBlobLike(value)) {\n throw new TypeError(\n \"Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'\"\n )\n }\n\n // 1. Let value be value if given; otherwise blobValue.\n\n name = webidl.converters.USVString(name, prefix, 'name')\n value = isBlobLike(value)\n ? webidl.converters.Blob(value, prefix, 'value', { strict: false })\n : webidl.converters.USVString(value, prefix, 'value')\n filename = arguments.length === 3\n ? webidl.converters.USVString(filename, prefix, 'filename')\n : undefined\n\n // 2. Let entry be the result of creating an entry with\n // name, value, and filename if given.\n const entry = makeEntry(name, value, filename)\n\n // 3. Append entry to this’s entry list.\n this[kState].push(entry)\n }\n\n delete (name) {\n webidl.brandCheck(this, FormData)\n\n const prefix = 'FormData.delete'\n webidl.argumentLengthCheck(arguments, 1, prefix)\n\n name = webidl.converters.USVString(name, prefix, 'name')\n\n // The delete(name) method steps are to remove all entries whose name\n // is name from this’s entry list.\n this[kState] = this[kState].filter(entry => entry.name !== name)\n }\n\n get (name) {\n webidl.brandCheck(this, FormData)\n\n const prefix = 'FormData.get'\n webidl.argumentLengthCheck(arguments, 1, prefix)\n\n name = webidl.converters.USVString(name, prefix, 'name')\n\n // 1. If there is no entry whose name is name in this’s entry list,\n // then return null.\n const idx = this[kState].findIndex((entry) => entry.name === name)\n if (idx === -1) {\n return null\n }\n\n // 2. Return the value of the first entry whose name is name from\n // this’s entry list.\n return this[kState][idx].value\n }\n\n getAll (name) {\n webidl.brandCheck(this, FormData)\n\n const prefix = 'FormData.getAll'\n webidl.argumentLengthCheck(arguments, 1, prefix)\n\n name = webidl.converters.USVString(name, prefix, 'name')\n\n // 1. If there is no entry whose name is name in this’s entry list,\n // then return the empty list.\n // 2. Return the values of all entries whose name is name, in order,\n // from this’s entry list.\n return this[kState]\n .filter((entry) => entry.name === name)\n .map((entry) => entry.value)\n }\n\n has (name) {\n webidl.brandCheck(this, FormData)\n\n const prefix = 'FormData.has'\n webidl.argumentLengthCheck(arguments, 1, prefix)\n\n name = webidl.converters.USVString(name, prefix, 'name')\n\n // The has(name) method steps are to return true if there is an entry\n // whose name is name in this’s entry list; otherwise false.\n return this[kState].findIndex((entry) => entry.name === name) !== -1\n }\n\n set (name, value, filename = undefined) {\n webidl.brandCheck(this, FormData)\n\n const prefix = 'FormData.set'\n webidl.argumentLengthCheck(arguments, 2, prefix)\n\n if (arguments.length === 3 && !isBlobLike(value)) {\n throw new TypeError(\n \"Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'\"\n )\n }\n\n // The set(name, value) and set(name, blobValue, filename) method steps\n // are:\n\n // 1. Let value be value if given; otherwise blobValue.\n\n name = webidl.converters.USVString(name, prefix, 'name')\n value = isBlobLike(value)\n ? webidl.converters.Blob(value, prefix, 'name', { strict: false })\n : webidl.converters.USVString(value, prefix, 'name')\n filename = arguments.length === 3\n ? webidl.converters.USVString(filename, prefix, 'name')\n : undefined\n\n // 2. Let entry be the result of creating an entry with name, value, and\n // filename if given.\n const entry = makeEntry(name, value, filename)\n\n // 3. If there are entries in this’s entry list whose name is name, then\n // replace the first such entry with entry and remove the others.\n const idx = this[kState].findIndex((entry) => entry.name === name)\n if (idx !== -1) {\n this[kState] = [\n ...this[kState].slice(0, idx),\n entry,\n ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name)\n ]\n } else {\n // 4. Otherwise, append entry to this’s entry list.\n this[kState].push(entry)\n }\n }\n\n [nodeUtil.inspect.custom] (depth, options) {\n const state = this[kState].reduce((a, b) => {\n if (a[b.name]) {\n if (Array.isArray(a[b.name])) {\n a[b.name].push(b.value)\n } else {\n a[b.name] = [a[b.name], b.value]\n }\n } else {\n a[b.name] = b.value\n }\n\n return a\n }, { __proto__: null })\n\n options.depth ??= depth\n options.colors ??= true\n\n const output = nodeUtil.formatWithOptions(options, state)\n\n // remove [Object null prototype]\n return `FormData ${output.slice(output.indexOf(']') + 2)}`\n }\n}\n\niteratorMixin('FormData', FormData, kState, 'name', 'value')\n\nObject.defineProperties(FormData.prototype, {\n append: kEnumerableProperty,\n delete: kEnumerableProperty,\n get: kEnumerableProperty,\n getAll: kEnumerableProperty,\n has: kEnumerableProperty,\n set: kEnumerableProperty,\n [Symbol.toStringTag]: {\n value: 'FormData',\n configurable: true\n }\n})\n\n/**\n * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry\n * @param {string} name\n * @param {string|Blob} value\n * @param {?string} filename\n * @returns\n */\nfunction makeEntry (name, value, filename) {\n // 1. Set name to the result of converting name into a scalar value string.\n // Note: This operation was done by the webidl converter USVString.\n\n // 2. If value is a string, then set value to the result of converting\n // value into a scalar value string.\n if (typeof value === 'string') {\n // Note: This operation was done by the webidl converter USVString.\n } else {\n // 3. Otherwise:\n\n // 1. If value is not a File object, then set value to a new File object,\n // representing the same bytes, whose name attribute value is \"blob\"\n if (!isFileLike(value)) {\n value = value instanceof Blob\n ? new File([value], 'blob', { type: value.type })\n : new FileLike(value, 'blob', { type: value.type })\n }\n\n // 2. If filename is given, then set value to a new File object,\n // representing the same bytes, whose name attribute is filename.\n if (filename !== undefined) {\n /** @type {FilePropertyBag} */\n const options = {\n type: value.type,\n lastModified: value.lastModified\n }\n\n value = value instanceof NativeFile\n ? new File([value], filename, options)\n : new FileLike(value, filename, options)\n }\n }\n\n // 4. Return an entry whose name is name and whose value is value.\n return { name, value }\n}\n\nmodule.exports = { FormData, makeEntry }\n","'use strict'\n\nconst { isUSVString, bufferToLowerCasedHeaderName } = require('../../core/util')\nconst { utf8DecodeBytes } = require('./util')\nconst { HTTP_TOKEN_CODEPOINTS, isomorphicDecode } = require('./data-url')\nconst { isFileLike } = require('./file')\nconst { makeEntry } = require('./formdata')\nconst assert = require('node:assert')\nconst { File: NodeFile } = require('node:buffer')\n\nconst File = globalThis.File ?? NodeFile\n\nconst formDataNameBuffer = Buffer.from('form-data; name=\"')\nconst filenameBuffer = Buffer.from('; filename')\nconst dd = Buffer.from('--')\nconst ddcrlf = Buffer.from('--\\r\\n')\n\n/**\n * @param {string} chars\n */\nfunction isAsciiString (chars) {\n for (let i = 0; i < chars.length; ++i) {\n if ((chars.charCodeAt(i) & ~0x7F) !== 0) {\n return false\n }\n }\n return true\n}\n\n/**\n * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-boundary\n * @param {string} boundary\n */\nfunction validateBoundary (boundary) {\n const length = boundary.length\n\n // - its length is greater or equal to 27 and lesser or equal to 70, and\n if (length < 27 || length > 70) {\n return false\n }\n\n // - it is composed by bytes in the ranges 0x30 to 0x39, 0x41 to 0x5A, or\n // 0x61 to 0x7A, inclusive (ASCII alphanumeric), or which are 0x27 ('),\n // 0x2D (-) or 0x5F (_).\n for (let i = 0; i < length; ++i) {\n const cp = boundary.charCodeAt(i)\n\n if (!(\n (cp >= 0x30 && cp <= 0x39) ||\n (cp >= 0x41 && cp <= 0x5a) ||\n (cp >= 0x61 && cp <= 0x7a) ||\n cp === 0x27 ||\n cp === 0x2d ||\n cp === 0x5f\n )) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * @see https://andreubotella.github.io/multipart-form-data/#multipart-form-data-parser\n * @param {Buffer} input\n * @param {ReturnType} mimeType\n */\nfunction multipartFormDataParser (input, mimeType) {\n // 1. Assert: mimeType’s essence is \"multipart/form-data\".\n assert(mimeType !== 'failure' && mimeType.essence === 'multipart/form-data')\n\n const boundaryString = mimeType.parameters.get('boundary')\n\n // 2. If mimeType’s parameters[\"boundary\"] does not exist, return failure.\n // Otherwise, let boundary be the result of UTF-8 decoding mimeType’s\n // parameters[\"boundary\"].\n if (boundaryString === undefined) {\n return 'failure'\n }\n\n const boundary = Buffer.from(`--${boundaryString}`, 'utf8')\n\n // 3. Let entry list be an empty entry list.\n const entryList = []\n\n // 4. Let position be a pointer to a byte in input, initially pointing at\n // the first byte.\n const position = { position: 0 }\n\n // Note: undici addition, allows leading and trailing CRLFs.\n while (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) {\n position.position += 2\n }\n\n let trailing = input.length\n\n while (input[trailing - 1] === 0x0a && input[trailing - 2] === 0x0d) {\n trailing -= 2\n }\n\n if (trailing !== input.length) {\n input = input.subarray(0, trailing)\n }\n\n // 5. While true:\n while (true) {\n // 5.1. If position points to a sequence of bytes starting with 0x2D 0x2D\n // (`--`) followed by boundary, advance position by 2 + the length of\n // boundary. Otherwise, return failure.\n // Note: boundary is padded with 2 dashes already, no need to add 2.\n if (input.subarray(position.position, position.position + boundary.length).equals(boundary)) {\n position.position += boundary.length\n } else {\n return 'failure'\n }\n\n // 5.2. If position points to the sequence of bytes 0x2D 0x2D 0x0D 0x0A\n // (`--` followed by CR LF) followed by the end of input, return entry list.\n // Note: a body does NOT need to end with CRLF. It can end with --.\n if (\n (position.position === input.length - 2 && bufferStartsWith(input, dd, position)) ||\n (position.position === input.length - 4 && bufferStartsWith(input, ddcrlf, position))\n ) {\n return entryList\n }\n\n // 5.3. If position does not point to a sequence of bytes starting with 0x0D\n // 0x0A (CR LF), return failure.\n if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) {\n return 'failure'\n }\n\n // 5.4. Advance position by 2. (This skips past the newline.)\n position.position += 2\n\n // 5.5. Let name, filename and contentType be the result of parsing\n // multipart/form-data headers on input and position, if the result\n // is not failure. Otherwise, return failure.\n const result = parseMultipartFormDataHeaders(input, position)\n\n if (result === 'failure') {\n return 'failure'\n }\n\n let { name, filename, contentType, encoding } = result\n\n // 5.6. Advance position by 2. (This skips past the empty line that marks\n // the end of the headers.)\n position.position += 2\n\n // 5.7. Let body be the empty byte sequence.\n let body\n\n // 5.8. Body loop: While position is not past the end of input:\n // TODO: the steps here are completely wrong\n {\n const boundaryIndex = input.indexOf(boundary.subarray(2), position.position)\n\n if (boundaryIndex === -1) {\n return 'failure'\n }\n\n body = input.subarray(position.position, boundaryIndex - 4)\n\n position.position += body.length\n\n // Note: position must be advanced by the body's length before being\n // decoded, otherwise the parsing will fail.\n if (encoding === 'base64') {\n body = Buffer.from(body.toString(), 'base64')\n }\n }\n\n // 5.9. If position does not point to a sequence of bytes starting with\n // 0x0D 0x0A (CR LF), return failure. Otherwise, advance position by 2.\n if (input[position.position] !== 0x0d || input[position.position + 1] !== 0x0a) {\n return 'failure'\n } else {\n position.position += 2\n }\n\n // 5.10. If filename is not null:\n let value\n\n if (filename !== null) {\n // 5.10.1. If contentType is null, set contentType to \"text/plain\".\n contentType ??= 'text/plain'\n\n // 5.10.2. If contentType is not an ASCII string, set contentType to the empty string.\n\n // Note: `buffer.isAscii` can be used at zero-cost, but converting a string to a buffer is a high overhead.\n // Content-Type is a relatively small string, so it is faster to use `String#charCodeAt`.\n if (!isAsciiString(contentType)) {\n contentType = ''\n }\n\n // 5.10.3. Let value be a new File object with name filename, type contentType, and body body.\n value = new File([body], filename, { type: contentType })\n } else {\n // 5.11. Otherwise:\n\n // 5.11.1. Let value be the UTF-8 decoding without BOM of body.\n value = utf8DecodeBytes(Buffer.from(body))\n }\n\n // 5.12. Assert: name is a scalar value string and value is either a scalar value string or a File object.\n assert(isUSVString(name))\n assert((typeof value === 'string' && isUSVString(value)) || isFileLike(value))\n\n // 5.13. Create an entry with name and value, and append it to entry list.\n entryList.push(makeEntry(name, value, filename))\n }\n}\n\n/**\n * @see https://andreubotella.github.io/multipart-form-data/#parse-multipart-form-data-headers\n * @param {Buffer} input\n * @param {{ position: number }} position\n */\nfunction parseMultipartFormDataHeaders (input, position) {\n // 1. Let name, filename and contentType be null.\n let name = null\n let filename = null\n let contentType = null\n let encoding = null\n\n // 2. While true:\n while (true) {\n // 2.1. If position points to a sequence of bytes starting with 0x0D 0x0A (CR LF):\n if (input[position.position] === 0x0d && input[position.position + 1] === 0x0a) {\n // 2.1.1. If name is null, return failure.\n if (name === null) {\n return 'failure'\n }\n\n // 2.1.2. Return name, filename and contentType.\n return { name, filename, contentType, encoding }\n }\n\n // 2.2. Let header name be the result of collecting a sequence of bytes that are\n // not 0x0A (LF), 0x0D (CR) or 0x3A (:), given position.\n let headerName = collectASequenceOfBytes(\n (char) => char !== 0x0a && char !== 0x0d && char !== 0x3a,\n input,\n position\n )\n\n // 2.3. Remove any HTTP tab or space bytes from the start or end of header name.\n headerName = removeChars(headerName, true, true, (char) => char === 0x9 || char === 0x20)\n\n // 2.4. If header name does not match the field-name token production, return failure.\n if (!HTTP_TOKEN_CODEPOINTS.test(headerName.toString())) {\n return 'failure'\n }\n\n // 2.5. If the byte at position is not 0x3A (:), return failure.\n if (input[position.position] !== 0x3a) {\n return 'failure'\n }\n\n // 2.6. Advance position by 1.\n position.position++\n\n // 2.7. Collect a sequence of bytes that are HTTP tab or space bytes given position.\n // (Do nothing with those bytes.)\n collectASequenceOfBytes(\n (char) => char === 0x20 || char === 0x09,\n input,\n position\n )\n\n // 2.8. Byte-lowercase header name and switch on the result:\n switch (bufferToLowerCasedHeaderName(headerName)) {\n case 'content-disposition': {\n // 1. Set name and filename to null.\n name = filename = null\n\n // 2. If position does not point to a sequence of bytes starting with\n // `form-data; name=\"`, return failure.\n if (!bufferStartsWith(input, formDataNameBuffer, position)) {\n return 'failure'\n }\n\n // 3. Advance position so it points at the byte after the next 0x22 (\")\n // byte (the one in the sequence of bytes matched above).\n position.position += 17\n\n // 4. Set name to the result of parsing a multipart/form-data name given\n // input and position, if the result is not failure. Otherwise, return\n // failure.\n name = parseMultipartFormDataName(input, position)\n\n if (name === null) {\n return 'failure'\n }\n\n // 5. If position points to a sequence of bytes starting with `; filename=\"`:\n if (bufferStartsWith(input, filenameBuffer, position)) {\n // Note: undici also handles filename*\n let check = position.position + filenameBuffer.length\n\n if (input[check] === 0x2a) {\n position.position += 1\n check += 1\n }\n\n if (input[check] !== 0x3d || input[check + 1] !== 0x22) { // =\"\n return 'failure'\n }\n\n // 1. Advance position so it points at the byte after the next 0x22 (\") byte\n // (the one in the sequence of bytes matched above).\n position.position += 12\n\n // 2. Set filename to the result of parsing a multipart/form-data name given\n // input and position, if the result is not failure. Otherwise, return failure.\n filename = parseMultipartFormDataName(input, position)\n\n if (filename === null) {\n return 'failure'\n }\n }\n\n break\n }\n case 'content-type': {\n // 1. Let header value be the result of collecting a sequence of bytes that are\n // not 0x0A (LF) or 0x0D (CR), given position.\n let headerValue = collectASequenceOfBytes(\n (char) => char !== 0x0a && char !== 0x0d,\n input,\n position\n )\n\n // 2. Remove any HTTP tab or space bytes from the end of header value.\n headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20)\n\n // 3. Set contentType to the isomorphic decoding of header value.\n contentType = isomorphicDecode(headerValue)\n\n break\n }\n case 'content-transfer-encoding': {\n let headerValue = collectASequenceOfBytes(\n (char) => char !== 0x0a && char !== 0x0d,\n input,\n position\n )\n\n headerValue = removeChars(headerValue, false, true, (char) => char === 0x9 || char === 0x20)\n\n encoding = isomorphicDecode(headerValue)\n\n break\n }\n default: {\n // Collect a sequence of bytes that are not 0x0A (LF) or 0x0D (CR), given position.\n // (Do nothing with those bytes.)\n collectASequenceOfBytes(\n (char) => char !== 0x0a && char !== 0x0d,\n input,\n position\n )\n }\n }\n\n // 2.9. If position does not point to a sequence of bytes starting with 0x0D 0x0A\n // (CR LF), return failure. Otherwise, advance position by 2 (past the newline).\n if (input[position.position] !== 0x0d && input[position.position + 1] !== 0x0a) {\n return 'failure'\n } else {\n position.position += 2\n }\n }\n}\n\n/**\n * @see https://andreubotella.github.io/multipart-form-data/#parse-a-multipart-form-data-name\n * @param {Buffer} input\n * @param {{ position: number }} position\n */\nfunction parseMultipartFormDataName (input, position) {\n // 1. Assert: The byte at (position - 1) is 0x22 (\").\n assert(input[position.position - 1] === 0x22)\n\n // 2. Let name be the result of collecting a sequence of bytes that are not 0x0A (LF), 0x0D (CR) or 0x22 (\"), given position.\n /** @type {string | Buffer} */\n let name = collectASequenceOfBytes(\n (char) => char !== 0x0a && char !== 0x0d && char !== 0x22,\n input,\n position\n )\n\n // 3. If the byte at position is not 0x22 (\"), return failure. Otherwise, advance position by 1.\n if (input[position.position] !== 0x22) {\n return null // name could be 'failure'\n } else {\n position.position++\n }\n\n // 4. Replace any occurrence of the following subsequences in name with the given byte:\n // - `%0A`: 0x0A (LF)\n // - `%0D`: 0x0D (CR)\n // - `%22`: 0x22 (\")\n name = new TextDecoder().decode(name)\n .replace(/%0A/ig, '\\n')\n .replace(/%0D/ig, '\\r')\n .replace(/%22/g, '\"')\n\n // 5. Return the UTF-8 decoding without BOM of name.\n return name\n}\n\n/**\n * @param {(char: number) => boolean} condition\n * @param {Buffer} input\n * @param {{ position: number }} position\n */\nfunction collectASequenceOfBytes (condition, input, position) {\n let start = position.position\n\n while (start < input.length && condition(input[start])) {\n ++start\n }\n\n return input.subarray(position.position, (position.position = start))\n}\n\n/**\n * @param {Buffer} buf\n * @param {boolean} leading\n * @param {boolean} trailing\n * @param {(charCode: number) => boolean} predicate\n * @returns {Buffer}\n */\nfunction removeChars (buf, leading, trailing, predicate) {\n let lead = 0\n let trail = buf.length - 1\n\n if (leading) {\n while (lead < buf.length && predicate(buf[lead])) lead++\n }\n\n if (trailing) {\n while (trail > 0 && predicate(buf[trail])) trail--\n }\n\n return lead === 0 && trail === buf.length - 1 ? buf : buf.subarray(lead, trail + 1)\n}\n\n/**\n * Checks if {@param buffer} starts with {@param start}\n * @param {Buffer} buffer\n * @param {Buffer} start\n * @param {{ position: number }} position\n */\nfunction bufferStartsWith (buffer, start, position) {\n if (buffer.length < start.length) {\n return false\n }\n\n for (let i = 0; i < start.length; i++) {\n if (start[i] !== buffer[position.position + i]) {\n return false\n }\n }\n\n return true\n}\n\nmodule.exports = {\n multipartFormDataParser,\n validateBoundary\n}\n","'use strict'\n\nconst util = require('../../core/util')\nconst {\n ReadableStreamFrom,\n isBlobLike,\n isReadableStreamLike,\n readableStreamClose,\n createDeferredPromise,\n fullyReadBody,\n extractMimeType,\n utf8DecodeBytes\n} = require('./util')\nconst { FormData } = require('./formdata')\nconst { kState } = require('./symbols')\nconst { webidl } = require('./webidl')\nconst { Blob } = require('node:buffer')\nconst assert = require('node:assert')\nconst { isErrored, isDisturbed } = require('node:stream')\nconst { isArrayBuffer } = require('node:util/types')\nconst { serializeAMimeType } = require('./data-url')\nconst { multipartFormDataParser } = require('./formdata-parser')\nlet random\n\ntry {\n const crypto = require('node:crypto')\n random = (max) => crypto.randomInt(0, max)\n} catch {\n random = (max) => Math.floor(Math.random(max))\n}\n\nconst textEncoder = new TextEncoder()\nfunction noop () {}\n\nconst hasFinalizationRegistry = globalThis.FinalizationRegistry && process.version.indexOf('v18') !== 0\nlet streamRegistry\n\nif (hasFinalizationRegistry) {\n streamRegistry = new FinalizationRegistry((weakRef) => {\n const stream = weakRef.deref()\n if (stream && !stream.locked && !isDisturbed(stream) && !isErrored(stream)) {\n stream.cancel('Response object has been garbage collected').catch(noop)\n }\n })\n}\n\n// https://fetch.spec.whatwg.org/#concept-bodyinit-extract\nfunction extractBody (object, keepalive = false) {\n // 1. Let stream be null.\n let stream = null\n\n // 2. If object is a ReadableStream object, then set stream to object.\n if (object instanceof ReadableStream) {\n stream = object\n } else if (isBlobLike(object)) {\n // 3. Otherwise, if object is a Blob object, set stream to the\n // result of running object’s get stream.\n stream = object.stream()\n } else {\n // 4. Otherwise, set stream to a new ReadableStream object, and set\n // up stream with byte reading support.\n stream = new ReadableStream({\n async pull (controller) {\n const buffer = typeof source === 'string' ? textEncoder.encode(source) : source\n\n if (buffer.byteLength) {\n controller.enqueue(buffer)\n }\n\n queueMicrotask(() => readableStreamClose(controller))\n },\n start () {},\n type: 'bytes'\n })\n }\n\n // 5. Assert: stream is a ReadableStream object.\n assert(isReadableStreamLike(stream))\n\n // 6. Let action be null.\n let action = null\n\n // 7. Let source be null.\n let source = null\n\n // 8. Let length be null.\n let length = null\n\n // 9. Let type be null.\n let type = null\n\n // 10. Switch on object:\n if (typeof object === 'string') {\n // Set source to the UTF-8 encoding of object.\n // Note: setting source to a Uint8Array here breaks some mocking assumptions.\n source = object\n\n // Set type to `text/plain;charset=UTF-8`.\n type = 'text/plain;charset=UTF-8'\n } else if (object instanceof URLSearchParams) {\n // URLSearchParams\n\n // spec says to run application/x-www-form-urlencoded on body.list\n // this is implemented in Node.js as apart of an URLSearchParams instance toString method\n // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490\n // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100\n\n // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list.\n source = object.toString()\n\n // Set type to `application/x-www-form-urlencoded;charset=UTF-8`.\n type = 'application/x-www-form-urlencoded;charset=UTF-8'\n } else if (isArrayBuffer(object)) {\n // BufferSource/ArrayBuffer\n\n // Set source to a copy of the bytes held by object.\n source = new Uint8Array(object.slice())\n } else if (ArrayBuffer.isView(object)) {\n // BufferSource/ArrayBufferView\n\n // Set source to a copy of the bytes held by object.\n source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength))\n } else if (util.isFormDataLike(object)) {\n const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}`\n const prefix = `--${boundary}\\r\\nContent-Disposition: form-data`\n\n /*! formdata-polyfill. MIT License. Jimmy Wärting */\n const escape = (str) =>\n str.replace(/\\n/g, '%0A').replace(/\\r/g, '%0D').replace(/\"/g, '%22')\n const normalizeLinefeeds = (value) => value.replace(/\\r?\\n|\\r/g, '\\r\\n')\n\n // Set action to this step: run the multipart/form-data\n // encoding algorithm, with object’s entry list and UTF-8.\n // - This ensures that the body is immutable and can't be changed afterwords\n // - That the content-length is calculated in advance.\n // - And that all parts are pre-encoded and ready to be sent.\n\n const blobParts = []\n const rn = new Uint8Array([13, 10]) // '\\r\\n'\n length = 0\n let hasUnknownSizeValue = false\n\n for (const [name, value] of object) {\n if (typeof value === 'string') {\n const chunk = textEncoder.encode(prefix +\n `; name=\"${escape(normalizeLinefeeds(name))}\"` +\n `\\r\\n\\r\\n${normalizeLinefeeds(value)}\\r\\n`)\n blobParts.push(chunk)\n length += chunk.byteLength\n } else {\n const chunk = textEncoder.encode(`${prefix}; name=\"${escape(normalizeLinefeeds(name))}\"` +\n (value.name ? `; filename=\"${escape(value.name)}\"` : '') + '\\r\\n' +\n `Content-Type: ${\n value.type || 'application/octet-stream'\n }\\r\\n\\r\\n`)\n blobParts.push(chunk, value, rn)\n if (typeof value.size === 'number') {\n length += chunk.byteLength + value.size + rn.byteLength\n } else {\n hasUnknownSizeValue = true\n }\n }\n }\n\n // CRLF is appended to the body to function with legacy servers and match other implementations.\n // https://github.com/curl/curl/blob/3434c6b46e682452973972e8313613dfa58cd690/lib/mime.c#L1029-L1030\n // https://github.com/form-data/form-data/issues/63\n const chunk = textEncoder.encode(`--${boundary}--\\r\\n`)\n blobParts.push(chunk)\n length += chunk.byteLength\n if (hasUnknownSizeValue) {\n length = null\n }\n\n // Set source to object.\n source = object\n\n action = async function * () {\n for (const part of blobParts) {\n if (part.stream) {\n yield * part.stream()\n } else {\n yield part\n }\n }\n }\n\n // Set type to `multipart/form-data; boundary=`,\n // followed by the multipart/form-data boundary string generated\n // by the multipart/form-data encoding algorithm.\n type = `multipart/form-data; boundary=${boundary}`\n } else if (isBlobLike(object)) {\n // Blob\n\n // Set source to object.\n source = object\n\n // Set length to object’s size.\n length = object.size\n\n // If object’s type attribute is not the empty byte sequence, set\n // type to its value.\n if (object.type) {\n type = object.type\n }\n } else if (typeof object[Symbol.asyncIterator] === 'function') {\n // If keepalive is true, then throw a TypeError.\n if (keepalive) {\n throw new TypeError('keepalive')\n }\n\n // If object is disturbed or locked, then throw a TypeError.\n if (util.isDisturbed(object) || object.locked) {\n throw new TypeError(\n 'Response body object should not be disturbed or locked'\n )\n }\n\n stream =\n object instanceof ReadableStream ? object : ReadableStreamFrom(object)\n }\n\n // 11. If source is a byte sequence, then set action to a\n // step that returns source and length to source’s length.\n if (typeof source === 'string' || util.isBuffer(source)) {\n length = Buffer.byteLength(source)\n }\n\n // 12. If action is non-null, then run these steps in in parallel:\n if (action != null) {\n // Run action.\n let iterator\n stream = new ReadableStream({\n async start () {\n iterator = action(object)[Symbol.asyncIterator]()\n },\n async pull (controller) {\n const { value, done } = await iterator.next()\n if (done) {\n // When running action is done, close stream.\n queueMicrotask(() => {\n controller.close()\n controller.byobRequest?.respond(0)\n })\n } else {\n // Whenever one or more bytes are available and stream is not errored,\n // enqueue a Uint8Array wrapping an ArrayBuffer containing the available\n // bytes into stream.\n if (!isErrored(stream)) {\n const buffer = new Uint8Array(value)\n if (buffer.byteLength) {\n controller.enqueue(buffer)\n }\n }\n }\n return controller.desiredSize > 0\n },\n async cancel (reason) {\n await iterator.return()\n },\n type: 'bytes'\n })\n }\n\n // 13. Let body be a body whose stream is stream, source is source,\n // and length is length.\n const body = { stream, source, length }\n\n // 14. Return (body, type).\n return [body, type]\n}\n\n// https://fetch.spec.whatwg.org/#bodyinit-safely-extract\nfunction safelyExtractBody (object, keepalive = false) {\n // To safely extract a body and a `Content-Type` value from\n // a byte sequence or BodyInit object object, run these steps:\n\n // 1. If object is a ReadableStream object, then:\n if (object instanceof ReadableStream) {\n // Assert: object is neither disturbed nor locked.\n // istanbul ignore next\n assert(!util.isDisturbed(object), 'The body has already been consumed.')\n // istanbul ignore next\n assert(!object.locked, 'The stream is locked.')\n }\n\n // 2. Return the results of extracting object.\n return extractBody(object, keepalive)\n}\n\nfunction cloneBody (instance, body) {\n // To clone a body body, run these steps:\n\n // https://fetch.spec.whatwg.org/#concept-body-clone\n\n // 1. Let « out1, out2 » be the result of teeing body’s stream.\n const [out1, out2] = body.stream.tee()\n\n // 2. Set body’s stream to out1.\n body.stream = out1\n\n // 3. Return a body whose stream is out2 and other members are copied from body.\n return {\n stream: out2,\n length: body.length,\n source: body.source\n }\n}\n\nfunction throwIfAborted (state) {\n if (state.aborted) {\n throw new DOMException('The operation was aborted.', 'AbortError')\n }\n}\n\nfunction bodyMixinMethods (instance) {\n const methods = {\n blob () {\n // The blob() method steps are to return the result of\n // running consume body with this and the following step\n // given a byte sequence bytes: return a Blob whose\n // contents are bytes and whose type attribute is this’s\n // MIME type.\n return consumeBody(this, (bytes) => {\n let mimeType = bodyMimeType(this)\n\n if (mimeType === null) {\n mimeType = ''\n } else if (mimeType) {\n mimeType = serializeAMimeType(mimeType)\n }\n\n // Return a Blob whose contents are bytes and type attribute\n // is mimeType.\n return new Blob([bytes], { type: mimeType })\n }, instance)\n },\n\n arrayBuffer () {\n // The arrayBuffer() method steps are to return the result\n // of running consume body with this and the following step\n // given a byte sequence bytes: return a new ArrayBuffer\n // whose contents are bytes.\n return consumeBody(this, (bytes) => {\n return new Uint8Array(bytes).buffer\n }, instance)\n },\n\n text () {\n // The text() method steps are to return the result of running\n // consume body with this and UTF-8 decode.\n return consumeBody(this, utf8DecodeBytes, instance)\n },\n\n json () {\n // The json() method steps are to return the result of running\n // consume body with this and parse JSON from bytes.\n return consumeBody(this, parseJSONFromBytes, instance)\n },\n\n formData () {\n // The formData() method steps are to return the result of running\n // consume body with this and the following step given a byte sequence bytes:\n return consumeBody(this, (value) => {\n // 1. Let mimeType be the result of get the MIME type with this.\n const mimeType = bodyMimeType(this)\n\n // 2. If mimeType is non-null, then switch on mimeType’s essence and run\n // the corresponding steps:\n if (mimeType !== null) {\n switch (mimeType.essence) {\n case 'multipart/form-data': {\n // 1. ... [long step]\n const parsed = multipartFormDataParser(value, mimeType)\n\n // 2. If that fails for some reason, then throw a TypeError.\n if (parsed === 'failure') {\n throw new TypeError('Failed to parse body as FormData.')\n }\n\n // 3. Return a new FormData object, appending each entry,\n // resulting from the parsing operation, to its entry list.\n const fd = new FormData()\n fd[kState] = parsed\n\n return fd\n }\n case 'application/x-www-form-urlencoded': {\n // 1. Let entries be the result of parsing bytes.\n const entries = new URLSearchParams(value.toString())\n\n // 2. If entries is failure, then throw a TypeError.\n\n // 3. Return a new FormData object whose entry list is entries.\n const fd = new FormData()\n\n for (const [name, value] of entries) {\n fd.append(name, value)\n }\n\n return fd\n }\n }\n }\n\n // 3. Throw a TypeError.\n throw new TypeError(\n 'Content-Type was not one of \"multipart/form-data\" or \"application/x-www-form-urlencoded\".'\n )\n }, instance)\n },\n\n bytes () {\n // The bytes() method steps are to return the result of running consume body\n // with this and the following step given a byte sequence bytes: return the\n // result of creating a Uint8Array from bytes in this’s relevant realm.\n return consumeBody(this, (bytes) => {\n return new Uint8Array(bytes)\n }, instance)\n }\n }\n\n return methods\n}\n\nfunction mixinBody (prototype) {\n Object.assign(prototype.prototype, bodyMixinMethods(prototype))\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-body-consume-body\n * @param {Response|Request} object\n * @param {(value: unknown) => unknown} convertBytesToJSValue\n * @param {Response|Request} instance\n */\nasync function consumeBody (object, convertBytesToJSValue, instance) {\n webidl.brandCheck(object, instance)\n\n // 1. If object is unusable, then return a promise rejected\n // with a TypeError.\n if (bodyUnusable(object)) {\n throw new TypeError('Body is unusable: Body has already been read')\n }\n\n throwIfAborted(object[kState])\n\n // 2. Let promise be a new promise.\n const promise = createDeferredPromise()\n\n // 3. Let errorSteps given error be to reject promise with error.\n const errorSteps = (error) => promise.reject(error)\n\n // 4. Let successSteps given a byte sequence data be to resolve\n // promise with the result of running convertBytesToJSValue\n // with data. If that threw an exception, then run errorSteps\n // with that exception.\n const successSteps = (data) => {\n try {\n promise.resolve(convertBytesToJSValue(data))\n } catch (e) {\n errorSteps(e)\n }\n }\n\n // 5. If object’s body is null, then run successSteps with an\n // empty byte sequence.\n if (object[kState].body == null) {\n successSteps(Buffer.allocUnsafe(0))\n return promise.promise\n }\n\n // 6. Otherwise, fully read object’s body given successSteps,\n // errorSteps, and object’s relevant global object.\n await fullyReadBody(object[kState].body, successSteps, errorSteps)\n\n // 7. Return promise.\n return promise.promise\n}\n\n// https://fetch.spec.whatwg.org/#body-unusable\nfunction bodyUnusable (object) {\n const body = object[kState].body\n\n // An object including the Body interface mixin is\n // said to be unusable if its body is non-null and\n // its body’s stream is disturbed or locked.\n return body != null && (body.stream.locked || util.isDisturbed(body.stream))\n}\n\n/**\n * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value\n * @param {Uint8Array} bytes\n */\nfunction parseJSONFromBytes (bytes) {\n return JSON.parse(utf8DecodeBytes(bytes))\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-body-mime-type\n * @param {import('./response').Response|import('./request').Request} requestOrResponse\n */\nfunction bodyMimeType (requestOrResponse) {\n // 1. Let headers be null.\n // 2. If requestOrResponse is a Request object, then set headers to requestOrResponse’s request’s header list.\n // 3. Otherwise, set headers to requestOrResponse’s response’s header list.\n /** @type {import('./headers').HeadersList} */\n const headers = requestOrResponse[kState].headersList\n\n // 4. Let mimeType be the result of extracting a MIME type from headers.\n const mimeType = extractMimeType(headers)\n\n // 5. If mimeType is failure, then return null.\n if (mimeType === 'failure') {\n return null\n }\n\n // 6. Return mimeType.\n return mimeType\n}\n\nmodule.exports = {\n extractBody,\n safelyExtractBody,\n cloneBody,\n mixinBody,\n streamRegistry,\n hasFinalizationRegistry,\n bodyUnusable\n}\n","'use strict'\n\n/* global WebAssembly */\n\nconst assert = require('node:assert')\nconst util = require('../core/util.js')\nconst { channels } = require('../core/diagnostics.js')\nconst timers = require('../util/timers.js')\nconst {\n RequestContentLengthMismatchError,\n ResponseContentLengthMismatchError,\n RequestAbortedError,\n HeadersTimeoutError,\n HeadersOverflowError,\n SocketError,\n InformationalError,\n BodyTimeoutError,\n HTTPParserError,\n ResponseExceededMaxSizeError\n} = require('../core/errors.js')\nconst {\n kUrl,\n kReset,\n kClient,\n kParser,\n kBlocking,\n kRunning,\n kPending,\n kSize,\n kWriting,\n kQueue,\n kNoRef,\n kKeepAliveDefaultTimeout,\n kHostHeader,\n kPendingIdx,\n kRunningIdx,\n kError,\n kPipelining,\n kSocket,\n kKeepAliveTimeoutValue,\n kMaxHeadersSize,\n kKeepAliveMaxTimeout,\n kKeepAliveTimeoutThreshold,\n kHeadersTimeout,\n kBodyTimeout,\n kStrictContentLength,\n kMaxRequests,\n kCounter,\n kMaxResponseSize,\n kOnError,\n kResume,\n kHTTPContext\n} = require('../core/symbols.js')\n\nconst constants = require('../llhttp/constants.js')\nconst EMPTY_BUF = Buffer.alloc(0)\nconst FastBuffer = Buffer[Symbol.species]\nconst addListener = util.addListener\nconst removeAllListeners = util.removeAllListeners\n\nlet extractBody\n\nasync function lazyllhttp () {\n const llhttpWasmData = process.env.JEST_WORKER_ID ? require('../llhttp/llhttp-wasm.js') : undefined\n\n let mod\n try {\n mod = await WebAssembly.compile(require('../llhttp/llhttp_simd-wasm.js'))\n } catch (e) {\n /* istanbul ignore next */\n\n // We could check if the error was caused by the simd option not\n // being enabled, but the occurring of this other error\n // * https://github.com/emscripten-core/emscripten/issues/11495\n // got me to remove that check to avoid breaking Node 12.\n mod = await WebAssembly.compile(llhttpWasmData || require('../llhttp/llhttp-wasm.js'))\n }\n\n return await WebAssembly.instantiate(mod, {\n env: {\n /* eslint-disable camelcase */\n\n wasm_on_url: (p, at, len) => {\n /* istanbul ignore next */\n return 0\n },\n wasm_on_status: (p, at, len) => {\n assert(currentParser.ptr === p)\n const start = at - currentBufferPtr + currentBufferRef.byteOffset\n return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0\n },\n wasm_on_message_begin: (p) => {\n assert(currentParser.ptr === p)\n return currentParser.onMessageBegin() || 0\n },\n wasm_on_header_field: (p, at, len) => {\n assert(currentParser.ptr === p)\n const start = at - currentBufferPtr + currentBufferRef.byteOffset\n return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0\n },\n wasm_on_header_value: (p, at, len) => {\n assert(currentParser.ptr === p)\n const start = at - currentBufferPtr + currentBufferRef.byteOffset\n return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0\n },\n wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {\n assert(currentParser.ptr === p)\n return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0\n },\n wasm_on_body: (p, at, len) => {\n assert(currentParser.ptr === p)\n const start = at - currentBufferPtr + currentBufferRef.byteOffset\n return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0\n },\n wasm_on_message_complete: (p) => {\n assert(currentParser.ptr === p)\n return currentParser.onMessageComplete() || 0\n }\n\n /* eslint-enable camelcase */\n }\n })\n}\n\nlet llhttpInstance = null\nlet llhttpPromise = lazyllhttp()\nllhttpPromise.catch()\n\nlet currentParser = null\nlet currentBufferRef = null\nlet currentBufferSize = 0\nlet currentBufferPtr = null\n\nconst USE_NATIVE_TIMER = 0\nconst USE_FAST_TIMER = 1\n\n// Use fast timers for headers and body to take eventual event loop\n// latency into account.\nconst TIMEOUT_HEADERS = 2 | USE_FAST_TIMER\nconst TIMEOUT_BODY = 4 | USE_FAST_TIMER\n\n// Use native timers to ignore event loop latency for keep-alive\n// handling.\nconst TIMEOUT_KEEP_ALIVE = 8 | USE_NATIVE_TIMER\n\nclass Parser {\n constructor (client, socket, { exports }) {\n assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0)\n\n this.llhttp = exports\n this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)\n this.client = client\n this.socket = socket\n this.timeout = null\n this.timeoutValue = null\n this.timeoutType = null\n this.statusCode = null\n this.statusText = ''\n this.upgrade = false\n this.headers = []\n this.headersSize = 0\n this.headersMaxSize = client[kMaxHeadersSize]\n this.shouldKeepAlive = false\n this.paused = false\n this.resume = this.resume.bind(this)\n\n this.bytesRead = 0\n\n this.keepAlive = ''\n this.contentLength = ''\n this.connection = ''\n this.maxResponseSize = client[kMaxResponseSize]\n }\n\n setTimeout (delay, type) {\n // If the existing timer and the new timer are of different timer type\n // (fast or native) or have different delay, we need to clear the existing\n // timer and set a new one.\n if (\n delay !== this.timeoutValue ||\n (type & USE_FAST_TIMER) ^ (this.timeoutType & USE_FAST_TIMER)\n ) {\n // If a timeout is already set, clear it with clearTimeout of the fast\n // timer implementation, as it can clear fast and native timers.\n if (this.timeout) {\n timers.clearTimeout(this.timeout)\n this.timeout = null\n }\n\n if (delay) {\n if (type & USE_FAST_TIMER) {\n this.timeout = timers.setFastTimeout(onParserTimeout, delay, new WeakRef(this))\n } else {\n this.timeout = setTimeout(onParserTimeout, delay, new WeakRef(this))\n this.timeout.unref()\n }\n }\n\n this.timeoutValue = delay\n } else if (this.timeout) {\n // istanbul ignore else: only for jest\n if (this.timeout.refresh) {\n this.timeout.refresh()\n }\n }\n\n this.timeoutType = type\n }\n\n resume () {\n if (this.socket.destroyed || !this.paused) {\n return\n }\n\n assert(this.ptr != null)\n assert(currentParser == null)\n\n this.llhttp.llhttp_resume(this.ptr)\n\n assert(this.timeoutType === TIMEOUT_BODY)\n if (this.timeout) {\n // istanbul ignore else: only for jest\n if (this.timeout.refresh) {\n this.timeout.refresh()\n }\n }\n\n this.paused = false\n this.execute(this.socket.read() || EMPTY_BUF) // Flush parser.\n this.readMore()\n }\n\n readMore () {\n while (!this.paused && this.ptr) {\n const chunk = this.socket.read()\n if (chunk === null) {\n break\n }\n this.execute(chunk)\n }\n }\n\n execute (data) {\n assert(this.ptr != null)\n assert(currentParser == null)\n assert(!this.paused)\n\n const { socket, llhttp } = this\n\n if (data.length > currentBufferSize) {\n if (currentBufferPtr) {\n llhttp.free(currentBufferPtr)\n }\n currentBufferSize = Math.ceil(data.length / 4096) * 4096\n currentBufferPtr = llhttp.malloc(currentBufferSize)\n }\n\n new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data)\n\n // Call `execute` on the wasm parser.\n // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data,\n // and finally the length of bytes to parse.\n // The return value is an error code or `constants.ERROR.OK`.\n try {\n let ret\n\n try {\n currentBufferRef = data\n currentParser = this\n ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length)\n /* eslint-disable-next-line no-useless-catch */\n } catch (err) {\n /* istanbul ignore next: difficult to make a test case for */\n throw err\n } finally {\n currentParser = null\n currentBufferRef = null\n }\n\n const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr\n\n if (ret === constants.ERROR.PAUSED_UPGRADE) {\n this.onUpgrade(data.slice(offset))\n } else if (ret === constants.ERROR.PAUSED) {\n this.paused = true\n socket.unshift(data.slice(offset))\n } else if (ret !== constants.ERROR.OK) {\n const ptr = llhttp.llhttp_get_error_reason(this.ptr)\n let message = ''\n /* istanbul ignore else: difficult to make a test case for */\n if (ptr) {\n const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)\n message =\n 'Response does not match the HTTP/1.1 protocol (' +\n Buffer.from(llhttp.memory.buffer, ptr, len).toString() +\n ')'\n }\n throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset))\n }\n } catch (err) {\n util.destroy(socket, err)\n }\n }\n\n destroy () {\n assert(this.ptr != null)\n assert(currentParser == null)\n\n this.llhttp.llhttp_free(this.ptr)\n this.ptr = null\n\n this.timeout && timers.clearTimeout(this.timeout)\n this.timeout = null\n this.timeoutValue = null\n this.timeoutType = null\n\n this.paused = false\n }\n\n onStatus (buf) {\n this.statusText = buf.toString()\n }\n\n onMessageBegin () {\n const { socket, client } = this\n\n /* istanbul ignore next: difficult to make a test case for */\n if (socket.destroyed) {\n return -1\n }\n\n const request = client[kQueue][client[kRunningIdx]]\n if (!request) {\n return -1\n }\n request.onResponseStarted()\n }\n\n onHeaderField (buf) {\n const len = this.headers.length\n\n if ((len & 1) === 0) {\n this.headers.push(buf)\n } else {\n this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])\n }\n\n this.trackHeader(buf.length)\n }\n\n onHeaderValue (buf) {\n let len = this.headers.length\n\n if ((len & 1) === 1) {\n this.headers.push(buf)\n len += 1\n } else {\n this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])\n }\n\n const key = this.headers[len - 2]\n if (key.length === 10) {\n const headerName = util.bufferToLowerCasedHeaderName(key)\n if (headerName === 'keep-alive') {\n this.keepAlive += buf.toString()\n } else if (headerName === 'connection') {\n this.connection += buf.toString()\n }\n } else if (key.length === 14 && util.bufferToLowerCasedHeaderName(key) === 'content-length') {\n this.contentLength += buf.toString()\n }\n\n this.trackHeader(buf.length)\n }\n\n trackHeader (len) {\n this.headersSize += len\n if (this.headersSize >= this.headersMaxSize) {\n util.destroy(this.socket, new HeadersOverflowError())\n }\n }\n\n onUpgrade (head) {\n const { upgrade, client, socket, headers, statusCode } = this\n\n assert(upgrade)\n assert(client[kSocket] === socket)\n assert(!socket.destroyed)\n assert(!this.paused)\n assert((headers.length & 1) === 0)\n\n const request = client[kQueue][client[kRunningIdx]]\n assert(request)\n assert(request.upgrade || request.method === 'CONNECT')\n\n this.statusCode = null\n this.statusText = ''\n this.shouldKeepAlive = null\n\n this.headers = []\n this.headersSize = 0\n\n socket.unshift(head)\n\n socket[kParser].destroy()\n socket[kParser] = null\n\n socket[kClient] = null\n socket[kError] = null\n\n removeAllListeners(socket)\n\n client[kSocket] = null\n client[kHTTPContext] = null // TODO (fix): This is hacky...\n client[kQueue][client[kRunningIdx]++] = null\n client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))\n\n try {\n request.onUpgrade(statusCode, headers, socket)\n } catch (err) {\n util.destroy(socket, err)\n }\n\n client[kResume]()\n }\n\n onHeadersComplete (statusCode, upgrade, shouldKeepAlive) {\n const { client, socket, headers, statusText } = this\n\n /* istanbul ignore next: difficult to make a test case for */\n if (socket.destroyed) {\n return -1\n }\n\n const request = client[kQueue][client[kRunningIdx]]\n\n /* istanbul ignore next: difficult to make a test case for */\n if (!request) {\n return -1\n }\n\n assert(!this.upgrade)\n assert(this.statusCode < 200)\n\n if (statusCode === 100) {\n util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))\n return -1\n }\n\n /* this can only happen if server is misbehaving */\n if (upgrade && !request.upgrade) {\n util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket)))\n return -1\n }\n\n assert(this.timeoutType === TIMEOUT_HEADERS)\n\n this.statusCode = statusCode\n this.shouldKeepAlive = (\n shouldKeepAlive ||\n // Override llhttp value which does not allow keepAlive for HEAD.\n (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive')\n )\n\n if (this.statusCode >= 200) {\n const bodyTimeout = request.bodyTimeout != null\n ? request.bodyTimeout\n : client[kBodyTimeout]\n this.setTimeout(bodyTimeout, TIMEOUT_BODY)\n } else if (this.timeout) {\n // istanbul ignore else: only for jest\n if (this.timeout.refresh) {\n this.timeout.refresh()\n }\n }\n\n if (request.method === 'CONNECT') {\n assert(client[kRunning] === 1)\n this.upgrade = true\n return 2\n }\n\n if (upgrade) {\n assert(client[kRunning] === 1)\n this.upgrade = true\n return 2\n }\n\n assert((this.headers.length & 1) === 0)\n this.headers = []\n this.headersSize = 0\n\n if (this.shouldKeepAlive && client[kPipelining]) {\n const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null\n\n if (keepAliveTimeout != null) {\n const timeout = Math.min(\n keepAliveTimeout - client[kKeepAliveTimeoutThreshold],\n client[kKeepAliveMaxTimeout]\n )\n if (timeout <= 0) {\n socket[kReset] = true\n } else {\n client[kKeepAliveTimeoutValue] = timeout\n }\n } else {\n client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]\n }\n } else {\n // Stop more requests from being dispatched.\n socket[kReset] = true\n }\n\n const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false\n\n if (request.aborted) {\n return -1\n }\n\n if (request.method === 'HEAD') {\n return 1\n }\n\n if (statusCode < 200) {\n return 1\n }\n\n if (socket[kBlocking]) {\n socket[kBlocking] = false\n client[kResume]()\n }\n\n return pause ? constants.ERROR.PAUSED : 0\n }\n\n onBody (buf) {\n const { client, socket, statusCode, maxResponseSize } = this\n\n if (socket.destroyed) {\n return -1\n }\n\n const request = client[kQueue][client[kRunningIdx]]\n assert(request)\n\n assert(this.timeoutType === TIMEOUT_BODY)\n if (this.timeout) {\n // istanbul ignore else: only for jest\n if (this.timeout.refresh) {\n this.timeout.refresh()\n }\n }\n\n assert(statusCode >= 200)\n\n if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {\n util.destroy(socket, new ResponseExceededMaxSizeError())\n return -1\n }\n\n this.bytesRead += buf.length\n\n if (request.onData(buf) === false) {\n return constants.ERROR.PAUSED\n }\n }\n\n onMessageComplete () {\n const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this\n\n if (socket.destroyed && (!statusCode || shouldKeepAlive)) {\n return -1\n }\n\n if (upgrade) {\n return\n }\n\n assert(statusCode >= 100)\n assert((this.headers.length & 1) === 0)\n\n const request = client[kQueue][client[kRunningIdx]]\n assert(request)\n\n this.statusCode = null\n this.statusText = ''\n this.bytesRead = 0\n this.contentLength = ''\n this.keepAlive = ''\n this.connection = ''\n\n this.headers = []\n this.headersSize = 0\n\n if (statusCode < 200) {\n return\n }\n\n /* istanbul ignore next: should be handled by llhttp? */\n if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) {\n util.destroy(socket, new ResponseContentLengthMismatchError())\n return -1\n }\n\n request.onComplete(headers)\n\n client[kQueue][client[kRunningIdx]++] = null\n\n if (socket[kWriting]) {\n assert(client[kRunning] === 0)\n // Response completed before request.\n util.destroy(socket, new InformationalError('reset'))\n return constants.ERROR.PAUSED\n } else if (!shouldKeepAlive) {\n util.destroy(socket, new InformationalError('reset'))\n return constants.ERROR.PAUSED\n } else if (socket[kReset] && client[kRunning] === 0) {\n // Destroy socket once all requests have completed.\n // The request at the tail of the pipeline is the one\n // that requested reset and no further requests should\n // have been queued since then.\n util.destroy(socket, new InformationalError('reset'))\n return constants.ERROR.PAUSED\n } else if (client[kPipelining] == null || client[kPipelining] === 1) {\n // We must wait a full event loop cycle to reuse this socket to make sure\n // that non-spec compliant servers are not closing the connection even if they\n // said they won't.\n setImmediate(() => client[kResume]())\n } else {\n client[kResume]()\n }\n }\n}\n\nfunction onParserTimeout (parser) {\n const { socket, timeoutType, client, paused } = parser.deref()\n\n /* istanbul ignore else */\n if (timeoutType === TIMEOUT_HEADERS) {\n if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {\n assert(!paused, 'cannot be paused while waiting for headers')\n util.destroy(socket, new HeadersTimeoutError())\n }\n } else if (timeoutType === TIMEOUT_BODY) {\n if (!paused) {\n util.destroy(socket, new BodyTimeoutError())\n }\n } else if (timeoutType === TIMEOUT_KEEP_ALIVE) {\n assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue])\n util.destroy(socket, new InformationalError('socket idle timeout'))\n }\n}\n\nasync function connectH1 (client, socket) {\n client[kSocket] = socket\n\n if (!llhttpInstance) {\n llhttpInstance = await llhttpPromise\n llhttpPromise = null\n }\n\n socket[kNoRef] = false\n socket[kWriting] = false\n socket[kReset] = false\n socket[kBlocking] = false\n socket[kParser] = new Parser(client, socket, llhttpInstance)\n\n addListener(socket, 'error', function (err) {\n assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')\n\n const parser = this[kParser]\n\n // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded\n // to the user.\n if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) {\n // We treat all incoming data so for as a valid response.\n parser.onMessageComplete()\n return\n }\n\n this[kError] = err\n\n this[kClient][kOnError](err)\n })\n addListener(socket, 'readable', function () {\n const parser = this[kParser]\n\n if (parser) {\n parser.readMore()\n }\n })\n addListener(socket, 'end', function () {\n const parser = this[kParser]\n\n if (parser.statusCode && !parser.shouldKeepAlive) {\n // We treat all incoming data so far as a valid response.\n parser.onMessageComplete()\n return\n }\n\n util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))\n })\n addListener(socket, 'close', function () {\n const client = this[kClient]\n const parser = this[kParser]\n\n if (parser) {\n if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {\n // We treat all incoming data so far as a valid response.\n parser.onMessageComplete()\n }\n\n this[kParser].destroy()\n this[kParser] = null\n }\n\n const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))\n\n client[kSocket] = null\n client[kHTTPContext] = null // TODO (fix): This is hacky...\n\n if (client.destroyed) {\n assert(client[kPending] === 0)\n\n // Fail entire queue.\n const requests = client[kQueue].splice(client[kRunningIdx])\n for (let i = 0; i < requests.length; i++) {\n const request = requests[i]\n util.errorRequest(client, request, err)\n }\n } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') {\n // Fail head of pipeline.\n const request = client[kQueue][client[kRunningIdx]]\n client[kQueue][client[kRunningIdx]++] = null\n\n util.errorRequest(client, request, err)\n }\n\n client[kPendingIdx] = client[kRunningIdx]\n\n assert(client[kRunning] === 0)\n\n client.emit('disconnect', client[kUrl], [client], err)\n\n client[kResume]()\n })\n\n let closed = false\n socket.on('close', () => {\n closed = true\n })\n\n return {\n version: 'h1',\n defaultPipelining: 1,\n write (...args) {\n return writeH1(client, ...args)\n },\n resume () {\n resumeH1(client)\n },\n destroy (err, callback) {\n if (closed) {\n queueMicrotask(callback)\n } else {\n socket.destroy(err).on('close', callback)\n }\n },\n get destroyed () {\n return socket.destroyed\n },\n busy (request) {\n if (socket[kWriting] || socket[kReset] || socket[kBlocking]) {\n return true\n }\n\n if (request) {\n if (client[kRunning] > 0 && !request.idempotent) {\n // Non-idempotent request cannot be retried.\n // Ensure that no other requests are inflight and\n // could cause failure.\n return true\n }\n\n if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) {\n // Don't dispatch an upgrade until all preceding requests have completed.\n // A misbehaving server might upgrade the connection before all pipelined\n // request has completed.\n return true\n }\n\n if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 &&\n (util.isStream(request.body) || util.isAsyncIterable(request.body) || util.isFormDataLike(request.body))) {\n // Request with stream or iterator body can error while other requests\n // are inflight and indirectly error those as well.\n // Ensure this doesn't happen by waiting for inflight\n // to complete before dispatching.\n\n // Request with stream or iterator body cannot be retried.\n // Ensure that no other requests are inflight and\n // could cause failure.\n return true\n }\n }\n\n return false\n }\n }\n}\n\nfunction resumeH1 (client) {\n const socket = client[kSocket]\n\n if (socket && !socket.destroyed) {\n if (client[kSize] === 0) {\n if (!socket[kNoRef] && socket.unref) {\n socket.unref()\n socket[kNoRef] = true\n }\n } else if (socket[kNoRef] && socket.ref) {\n socket.ref()\n socket[kNoRef] = false\n }\n\n if (client[kSize] === 0) {\n if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) {\n socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE)\n }\n } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {\n if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {\n const request = client[kQueue][client[kRunningIdx]]\n const headersTimeout = request.headersTimeout != null\n ? request.headersTimeout\n : client[kHeadersTimeout]\n socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS)\n }\n }\n }\n}\n\n// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2\nfunction shouldSendContentLength (method) {\n return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'\n}\n\nfunction writeH1 (client, request) {\n const { method, path, host, upgrade, blocking, reset } = request\n\n let { body, headers, contentLength } = request\n\n // https://tools.ietf.org/html/rfc7231#section-4.3.1\n // https://tools.ietf.org/html/rfc7231#section-4.3.2\n // https://tools.ietf.org/html/rfc7231#section-4.3.5\n\n // Sending a payload body on a request that does not\n // expect it can cause undefined behavior on some\n // servers and corrupt connection state. Do not\n // re-use the connection for further requests.\n\n const expectsPayload = (\n method === 'PUT' ||\n method === 'POST' ||\n method === 'PATCH' ||\n method === 'QUERY' ||\n method === 'PROPFIND' ||\n method === 'PROPPATCH'\n )\n\n if (util.isFormDataLike(body)) {\n if (!extractBody) {\n extractBody = require('../web/fetch/body.js').extractBody\n }\n\n const [bodyStream, contentType] = extractBody(body)\n if (request.contentType == null) {\n headers.push('content-type', contentType)\n }\n body = bodyStream.stream\n contentLength = bodyStream.length\n } else if (util.isBlobLike(body) && request.contentType == null && body.type) {\n headers.push('content-type', body.type)\n }\n\n if (body && typeof body.read === 'function') {\n // Try to read EOF in order to get length.\n body.read(0)\n }\n\n const bodyLength = util.bodyLength(body)\n\n contentLength = bodyLength ?? contentLength\n\n if (contentLength === null) {\n contentLength = request.contentLength\n }\n\n if (contentLength === 0 && !expectsPayload) {\n // https://tools.ietf.org/html/rfc7230#section-3.3.2\n // A user agent SHOULD NOT send a Content-Length header field when\n // the request message does not contain a payload body and the method\n // semantics do not anticipate such a body.\n\n contentLength = null\n }\n\n // https://github.com/nodejs/undici/issues/2046\n // A user agent may send a Content-Length header with 0 value, this should be allowed.\n if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) {\n if (client[kStrictContentLength]) {\n util.errorRequest(client, request, new RequestContentLengthMismatchError())\n return false\n }\n\n process.emitWarning(new RequestContentLengthMismatchError())\n }\n\n const socket = client[kSocket]\n\n const abort = (err) => {\n if (request.aborted || request.completed) {\n return\n }\n\n util.errorRequest(client, request, err || new RequestAbortedError())\n\n util.destroy(body)\n util.destroy(socket, new InformationalError('aborted'))\n }\n\n try {\n request.onConnect(abort)\n } catch (err) {\n util.errorRequest(client, request, err)\n }\n\n if (request.aborted) {\n return false\n }\n\n if (method === 'HEAD') {\n // https://github.com/mcollina/undici/issues/258\n // Close after a HEAD request to interop with misbehaving servers\n // that may send a body in the response.\n\n socket[kReset] = true\n }\n\n if (upgrade || method === 'CONNECT') {\n // On CONNECT or upgrade, block pipeline from dispatching further\n // requests on this connection.\n\n socket[kReset] = true\n }\n\n if (reset != null) {\n socket[kReset] = reset\n }\n\n if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {\n socket[kReset] = true\n }\n\n if (blocking) {\n socket[kBlocking] = true\n }\n\n let header = `${method} ${path} HTTP/1.1\\r\\n`\n\n if (typeof host === 'string') {\n header += `host: ${host}\\r\\n`\n } else {\n header += client[kHostHeader]\n }\n\n if (upgrade) {\n header += `connection: upgrade\\r\\nupgrade: ${upgrade}\\r\\n`\n } else if (client[kPipelining] && !socket[kReset]) {\n header += 'connection: keep-alive\\r\\n'\n } else {\n header += 'connection: close\\r\\n'\n }\n\n if (Array.isArray(headers)) {\n for (let n = 0; n < headers.length; n += 2) {\n const key = headers[n + 0]\n const val = headers[n + 1]\n\n if (Array.isArray(val)) {\n for (let i = 0; i < val.length; i++) {\n header += `${key}: ${val[i]}\\r\\n`\n }\n } else {\n header += `${key}: ${val}\\r\\n`\n }\n }\n }\n\n if (channels.sendHeaders.hasSubscribers) {\n channels.sendHeaders.publish({ request, headers: header, socket })\n }\n\n /* istanbul ignore else: assertion */\n if (!body || bodyLength === 0) {\n writeBuffer(abort, null, client, request, socket, contentLength, header, expectsPayload)\n } else if (util.isBuffer(body)) {\n writeBuffer(abort, body, client, request, socket, contentLength, header, expectsPayload)\n } else if (util.isBlobLike(body)) {\n if (typeof body.stream === 'function') {\n writeIterable(abort, body.stream(), client, request, socket, contentLength, header, expectsPayload)\n } else {\n writeBlob(abort, body, client, request, socket, contentLength, header, expectsPayload)\n }\n } else if (util.isStream(body)) {\n writeStream(abort, body, client, request, socket, contentLength, header, expectsPayload)\n } else if (util.isIterable(body)) {\n writeIterable(abort, body, client, request, socket, contentLength, header, expectsPayload)\n } else {\n assert(false)\n }\n\n return true\n}\n\nfunction writeStream (abort, body, client, request, socket, contentLength, header, expectsPayload) {\n assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')\n\n let finished = false\n\n const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header })\n\n const onData = function (chunk) {\n if (finished) {\n return\n }\n\n try {\n if (!writer.write(chunk) && this.pause) {\n this.pause()\n }\n } catch (err) {\n util.destroy(this, err)\n }\n }\n const onDrain = function () {\n if (finished) {\n return\n }\n\n if (body.resume) {\n body.resume()\n }\n }\n const onClose = function () {\n // 'close' might be emitted *before* 'error' for\n // broken streams. Wait a tick to avoid this case.\n queueMicrotask(() => {\n // It's only safe to remove 'error' listener after\n // 'close'.\n body.removeListener('error', onFinished)\n })\n\n if (!finished) {\n const err = new RequestAbortedError()\n queueMicrotask(() => onFinished(err))\n }\n }\n const onFinished = function (err) {\n if (finished) {\n return\n }\n\n finished = true\n\n assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))\n\n socket\n .off('drain', onDrain)\n .off('error', onFinished)\n\n body\n .removeListener('data', onData)\n .removeListener('end', onFinished)\n .removeListener('close', onClose)\n\n if (!err) {\n try {\n writer.end()\n } catch (er) {\n err = er\n }\n }\n\n writer.destroy(err)\n\n if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {\n util.destroy(body, err)\n } else {\n util.destroy(body)\n }\n }\n\n body\n .on('data', onData)\n .on('end', onFinished)\n .on('error', onFinished)\n .on('close', onClose)\n\n if (body.resume) {\n body.resume()\n }\n\n socket\n .on('drain', onDrain)\n .on('error', onFinished)\n\n if (body.errorEmitted ?? body.errored) {\n setImmediate(() => onFinished(body.errored))\n } else if (body.endEmitted ?? body.readableEnded) {\n setImmediate(() => onFinished(null))\n }\n\n if (body.closeEmitted ?? body.closed) {\n setImmediate(onClose)\n }\n}\n\nfunction writeBuffer (abort, body, client, request, socket, contentLength, header, expectsPayload) {\n try {\n if (!body) {\n if (contentLength === 0) {\n socket.write(`${header}content-length: 0\\r\\n\\r\\n`, 'latin1')\n } else {\n assert(contentLength === null, 'no body must not have content length')\n socket.write(`${header}\\r\\n`, 'latin1')\n }\n } else if (util.isBuffer(body)) {\n assert(contentLength === body.byteLength, 'buffer body must have content length')\n\n socket.cork()\n socket.write(`${header}content-length: ${contentLength}\\r\\n\\r\\n`, 'latin1')\n socket.write(body)\n socket.uncork()\n request.onBodySent(body)\n\n if (!expectsPayload && request.reset !== false) {\n socket[kReset] = true\n }\n }\n request.onRequestSent()\n\n client[kResume]()\n } catch (err) {\n abort(err)\n }\n}\n\nasync function writeBlob (abort, body, client, request, socket, contentLength, header, expectsPayload) {\n assert(contentLength === body.size, 'blob body must have content length')\n\n try {\n if (contentLength != null && contentLength !== body.size) {\n throw new RequestContentLengthMismatchError()\n }\n\n const buffer = Buffer.from(await body.arrayBuffer())\n\n socket.cork()\n socket.write(`${header}content-length: ${contentLength}\\r\\n\\r\\n`, 'latin1')\n socket.write(buffer)\n socket.uncork()\n\n request.onBodySent(buffer)\n request.onRequestSent()\n\n if (!expectsPayload && request.reset !== false) {\n socket[kReset] = true\n }\n\n client[kResume]()\n } catch (err) {\n abort(err)\n }\n}\n\nasync function writeIterable (abort, body, client, request, socket, contentLength, header, expectsPayload) {\n assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')\n\n let callback = null\n function onDrain () {\n if (callback) {\n const cb = callback\n callback = null\n cb()\n }\n }\n\n const waitForDrain = () => new Promise((resolve, reject) => {\n assert(callback === null)\n\n if (socket[kError]) {\n reject(socket[kError])\n } else {\n callback = resolve\n }\n })\n\n socket\n .on('close', onDrain)\n .on('drain', onDrain)\n\n const writer = new AsyncWriter({ abort, socket, request, contentLength, client, expectsPayload, header })\n try {\n // It's up to the user to somehow abort the async iterable.\n for await (const chunk of body) {\n if (socket[kError]) {\n throw socket[kError]\n }\n\n if (!writer.write(chunk)) {\n await waitForDrain()\n }\n }\n\n writer.end()\n } catch (err) {\n writer.destroy(err)\n } finally {\n socket\n .off('close', onDrain)\n .off('drain', onDrain)\n }\n}\n\nclass AsyncWriter {\n constructor ({ abort, socket, request, contentLength, client, expectsPayload, header }) {\n this.socket = socket\n this.request = request\n this.contentLength = contentLength\n this.client = client\n this.bytesWritten = 0\n this.expectsPayload = expectsPayload\n this.header = header\n this.abort = abort\n\n socket[kWriting] = true\n }\n\n write (chunk) {\n const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this\n\n if (socket[kError]) {\n throw socket[kError]\n }\n\n if (socket.destroyed) {\n return false\n }\n\n const len = Buffer.byteLength(chunk)\n if (!len) {\n return true\n }\n\n // We should defer writing chunks.\n if (contentLength !== null && bytesWritten + len > contentLength) {\n if (client[kStrictContentLength]) {\n throw new RequestContentLengthMismatchError()\n }\n\n process.emitWarning(new RequestContentLengthMismatchError())\n }\n\n socket.cork()\n\n if (bytesWritten === 0) {\n if (!expectsPayload && request.reset !== false) {\n socket[kReset] = true\n }\n\n if (contentLength === null) {\n socket.write(`${header}transfer-encoding: chunked\\r\\n`, 'latin1')\n } else {\n socket.write(`${header}content-length: ${contentLength}\\r\\n\\r\\n`, 'latin1')\n }\n }\n\n if (contentLength === null) {\n socket.write(`\\r\\n${len.toString(16)}\\r\\n`, 'latin1')\n }\n\n this.bytesWritten += len\n\n const ret = socket.write(chunk)\n\n socket.uncork()\n\n request.onBodySent(chunk)\n\n if (!ret) {\n if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {\n // istanbul ignore else: only for jest\n if (socket[kParser].timeout.refresh) {\n socket[kParser].timeout.refresh()\n }\n }\n }\n\n return ret\n }\n\n end () {\n const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this\n request.onRequestSent()\n\n socket[kWriting] = false\n\n if (socket[kError]) {\n throw socket[kError]\n }\n\n if (socket.destroyed) {\n return\n }\n\n if (bytesWritten === 0) {\n if (expectsPayload) {\n // https://tools.ietf.org/html/rfc7230#section-3.3.2\n // A user agent SHOULD send a Content-Length in a request message when\n // no Transfer-Encoding is sent and the request method defines a meaning\n // for an enclosed payload body.\n\n socket.write(`${header}content-length: 0\\r\\n\\r\\n`, 'latin1')\n } else {\n socket.write(`${header}\\r\\n`, 'latin1')\n }\n } else if (contentLength === null) {\n socket.write('\\r\\n0\\r\\n\\r\\n', 'latin1')\n }\n\n if (contentLength !== null && bytesWritten !== contentLength) {\n if (client[kStrictContentLength]) {\n throw new RequestContentLengthMismatchError()\n } else {\n process.emitWarning(new RequestContentLengthMismatchError())\n }\n }\n\n if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {\n // istanbul ignore else: only for jest\n if (socket[kParser].timeout.refresh) {\n socket[kParser].timeout.refresh()\n }\n }\n\n client[kResume]()\n }\n\n destroy (err) {\n const { socket, client, abort } = this\n\n socket[kWriting] = false\n\n if (err) {\n assert(client[kRunning] <= 1, 'pipeline should only contain this request')\n abort(err)\n }\n }\n}\n\nmodule.exports = connectH1\n","'use strict'\n\nconst assert = require('node:assert')\nconst { pipeline } = require('node:stream')\nconst util = require('../core/util.js')\nconst {\n RequestContentLengthMismatchError,\n RequestAbortedError,\n SocketError,\n InformationalError\n} = require('../core/errors.js')\nconst {\n kUrl,\n kReset,\n kClient,\n kRunning,\n kPending,\n kQueue,\n kPendingIdx,\n kRunningIdx,\n kError,\n kSocket,\n kStrictContentLength,\n kOnError,\n kMaxConcurrentStreams,\n kHTTP2Session,\n kResume,\n kSize,\n kHTTPContext\n} = require('../core/symbols.js')\n\nconst kOpenStreams = Symbol('open streams')\n\nlet extractBody\n\n// Experimental\nlet h2ExperimentalWarned = false\n\n/** @type {import('http2')} */\nlet http2\ntry {\n http2 = require('node:http2')\n} catch {\n // @ts-ignore\n http2 = { constants: {} }\n}\n\nconst {\n constants: {\n HTTP2_HEADER_AUTHORITY,\n HTTP2_HEADER_METHOD,\n HTTP2_HEADER_PATH,\n HTTP2_HEADER_SCHEME,\n HTTP2_HEADER_CONTENT_LENGTH,\n HTTP2_HEADER_EXPECT,\n HTTP2_HEADER_STATUS\n }\n} = http2\n\nfunction parseH2Headers (headers) {\n const result = []\n\n for (const [name, value] of Object.entries(headers)) {\n // h2 may concat the header value by array\n // e.g. Set-Cookie\n if (Array.isArray(value)) {\n for (const subvalue of value) {\n // we need to provide each header value of header name\n // because the headers handler expect name-value pair\n result.push(Buffer.from(name), Buffer.from(subvalue))\n }\n } else {\n result.push(Buffer.from(name), Buffer.from(value))\n }\n }\n\n return result\n}\n\nasync function connectH2 (client, socket) {\n client[kSocket] = socket\n\n if (!h2ExperimentalWarned) {\n h2ExperimentalWarned = true\n process.emitWarning('H2 support is experimental, expect them to change at any time.', {\n code: 'UNDICI-H2'\n })\n }\n\n const session = http2.connect(client[kUrl], {\n createConnection: () => socket,\n peerMaxConcurrentStreams: client[kMaxConcurrentStreams]\n })\n\n session[kOpenStreams] = 0\n session[kClient] = client\n session[kSocket] = socket\n\n util.addListener(session, 'error', onHttp2SessionError)\n util.addListener(session, 'frameError', onHttp2FrameError)\n util.addListener(session, 'end', onHttp2SessionEnd)\n util.addListener(session, 'goaway', onHTTP2GoAway)\n util.addListener(session, 'close', function () {\n const { [kClient]: client } = this\n const { [kSocket]: socket } = client\n\n const err = this[kSocket][kError] || this[kError] || new SocketError('closed', util.getSocketInfo(socket))\n\n client[kHTTP2Session] = null\n\n if (client.destroyed) {\n assert(client[kPending] === 0)\n\n // Fail entire queue.\n const requests = client[kQueue].splice(client[kRunningIdx])\n for (let i = 0; i < requests.length; i++) {\n const request = requests[i]\n util.errorRequest(client, request, err)\n }\n }\n })\n\n session.unref()\n\n client[kHTTP2Session] = session\n socket[kHTTP2Session] = session\n\n util.addListener(socket, 'error', function (err) {\n assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')\n\n this[kError] = err\n\n this[kClient][kOnError](err)\n })\n\n util.addListener(socket, 'end', function () {\n util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))\n })\n\n util.addListener(socket, 'close', function () {\n const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))\n\n client[kSocket] = null\n\n if (this[kHTTP2Session] != null) {\n this[kHTTP2Session].destroy(err)\n }\n\n client[kPendingIdx] = client[kRunningIdx]\n\n assert(client[kRunning] === 0)\n\n client.emit('disconnect', client[kUrl], [client], err)\n\n client[kResume]()\n })\n\n let closed = false\n socket.on('close', () => {\n closed = true\n })\n\n return {\n version: 'h2',\n defaultPipelining: Infinity,\n write (...args) {\n return writeH2(client, ...args)\n },\n resume () {\n resumeH2(client)\n },\n destroy (err, callback) {\n if (closed) {\n queueMicrotask(callback)\n } else {\n // Destroying the socket will trigger the session close\n socket.destroy(err).on('close', callback)\n }\n },\n get destroyed () {\n return socket.destroyed\n },\n busy () {\n return false\n }\n }\n}\n\nfunction resumeH2 (client) {\n const socket = client[kSocket]\n\n if (socket?.destroyed === false) {\n if (client[kSize] === 0 && client[kMaxConcurrentStreams] === 0) {\n socket.unref()\n client[kHTTP2Session].unref()\n } else {\n socket.ref()\n client[kHTTP2Session].ref()\n }\n }\n}\n\nfunction onHttp2SessionError (err) {\n assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')\n\n this[kSocket][kError] = err\n this[kClient][kOnError](err)\n}\n\nfunction onHttp2FrameError (type, code, id) {\n if (id === 0) {\n const err = new InformationalError(`HTTP/2: \"frameError\" received - type ${type}, code ${code}`)\n this[kSocket][kError] = err\n this[kClient][kOnError](err)\n }\n}\n\nfunction onHttp2SessionEnd () {\n const err = new SocketError('other side closed', util.getSocketInfo(this[kSocket]))\n this.destroy(err)\n util.destroy(this[kSocket], err)\n}\n\n/**\n * This is the root cause of #3011\n * We need to handle GOAWAY frames properly, and trigger the session close\n * along with the socket right away\n */\nfunction onHTTP2GoAway (code) {\n // We cannot recover, so best to close the session and the socket\n const err = this[kError] || new SocketError(`HTTP/2: \"GOAWAY\" frame received with code ${code}`, util.getSocketInfo(this))\n const client = this[kClient]\n\n client[kSocket] = null\n client[kHTTPContext] = null\n\n if (this[kHTTP2Session] != null) {\n this[kHTTP2Session].destroy(err)\n this[kHTTP2Session] = null\n }\n\n util.destroy(this[kSocket], err)\n\n // Fail head of pipeline.\n if (client[kRunningIdx] < client[kQueue].length) {\n const request = client[kQueue][client[kRunningIdx]]\n client[kQueue][client[kRunningIdx]++] = null\n util.errorRequest(client, request, err)\n client[kPendingIdx] = client[kRunningIdx]\n }\n\n assert(client[kRunning] === 0)\n\n client.emit('disconnect', client[kUrl], [client], err)\n\n client[kResume]()\n}\n\n// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2\nfunction shouldSendContentLength (method) {\n return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'\n}\n\nfunction writeH2 (client, request) {\n const session = client[kHTTP2Session]\n const { method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request\n let { body } = request\n\n if (upgrade) {\n util.errorRequest(client, request, new Error('Upgrade not supported for H2'))\n return false\n }\n\n const headers = {}\n for (let n = 0; n < reqHeaders.length; n += 2) {\n const key = reqHeaders[n + 0]\n const val = reqHeaders[n + 1]\n\n if (Array.isArray(val)) {\n for (let i = 0; i < val.length; i++) {\n if (headers[key]) {\n headers[key] += `,${val[i]}`\n } else {\n headers[key] = val[i]\n }\n }\n } else {\n headers[key] = val\n }\n }\n\n /** @type {import('node:http2').ClientHttp2Stream} */\n let stream\n\n const { hostname, port } = client[kUrl]\n\n headers[HTTP2_HEADER_AUTHORITY] = host || `${hostname}${port ? `:${port}` : ''}`\n headers[HTTP2_HEADER_METHOD] = method\n\n const abort = (err) => {\n if (request.aborted || request.completed) {\n return\n }\n\n err = err || new RequestAbortedError()\n\n util.errorRequest(client, request, err)\n\n if (stream != null) {\n util.destroy(stream, err)\n }\n\n // We do not destroy the socket as we can continue using the session\n // the stream get's destroyed and the session remains to create new streams\n util.destroy(body, err)\n client[kQueue][client[kRunningIdx]++] = null\n client[kResume]()\n }\n\n try {\n // We are already connected, streams are pending.\n // We can call on connect, and wait for abort\n request.onConnect(abort)\n } catch (err) {\n util.errorRequest(client, request, err)\n }\n\n if (request.aborted) {\n return false\n }\n\n if (method === 'CONNECT') {\n session.ref()\n // We are already connected, streams are pending, first request\n // will create a new stream. We trigger a request to create the stream and wait until\n // `ready` event is triggered\n // We disabled endStream to allow the user to write to the stream\n stream = session.request(headers, { endStream: false, signal })\n\n if (stream.id && !stream.pending) {\n request.onUpgrade(null, null, stream)\n ++session[kOpenStreams]\n client[kQueue][client[kRunningIdx]++] = null\n } else {\n stream.once('ready', () => {\n request.onUpgrade(null, null, stream)\n ++session[kOpenStreams]\n client[kQueue][client[kRunningIdx]++] = null\n })\n }\n\n stream.once('close', () => {\n session[kOpenStreams] -= 1\n if (session[kOpenStreams] === 0) session.unref()\n })\n\n return true\n }\n\n // https://tools.ietf.org/html/rfc7540#section-8.3\n // :path and :scheme headers must be omitted when sending CONNECT\n\n headers[HTTP2_HEADER_PATH] = path\n headers[HTTP2_HEADER_SCHEME] = 'https'\n\n // https://tools.ietf.org/html/rfc7231#section-4.3.1\n // https://tools.ietf.org/html/rfc7231#section-4.3.2\n // https://tools.ietf.org/html/rfc7231#section-4.3.5\n\n // Sending a payload body on a request that does not\n // expect it can cause undefined behavior on some\n // servers and corrupt connection state. Do not\n // re-use the connection for further requests.\n\n const expectsPayload = (\n method === 'PUT' ||\n method === 'POST' ||\n method === 'PATCH'\n )\n\n if (body && typeof body.read === 'function') {\n // Try to read EOF in order to get length.\n body.read(0)\n }\n\n let contentLength = util.bodyLength(body)\n\n if (util.isFormDataLike(body)) {\n extractBody ??= require('../web/fetch/body.js').extractBody\n\n const [bodyStream, contentType] = extractBody(body)\n headers['content-type'] = contentType\n\n body = bodyStream.stream\n contentLength = bodyStream.length\n }\n\n if (contentLength == null) {\n contentLength = request.contentLength\n }\n\n if (contentLength === 0 || !expectsPayload) {\n // https://tools.ietf.org/html/rfc7230#section-3.3.2\n // A user agent SHOULD NOT send a Content-Length header field when\n // the request message does not contain a payload body and the method\n // semantics do not anticipate such a body.\n\n contentLength = null\n }\n\n // https://github.com/nodejs/undici/issues/2046\n // A user agent may send a Content-Length header with 0 value, this should be allowed.\n if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) {\n if (client[kStrictContentLength]) {\n util.errorRequest(client, request, new RequestContentLengthMismatchError())\n return false\n }\n\n process.emitWarning(new RequestContentLengthMismatchError())\n }\n\n if (contentLength != null) {\n assert(body, 'no body must not have content length')\n headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`\n }\n\n session.ref()\n\n const shouldEndStream = method === 'GET' || method === 'HEAD' || body === null\n if (expectContinue) {\n headers[HTTP2_HEADER_EXPECT] = '100-continue'\n stream = session.request(headers, { endStream: shouldEndStream, signal })\n\n stream.once('continue', writeBodyH2)\n } else {\n stream = session.request(headers, {\n endStream: shouldEndStream,\n signal\n })\n writeBodyH2()\n }\n\n // Increment counter as we have new streams open\n ++session[kOpenStreams]\n\n stream.once('response', headers => {\n const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers\n request.onResponseStarted()\n\n // Due to the stream nature, it is possible we face a race condition\n // where the stream has been assigned, but the request has been aborted\n // the request remains in-flight and headers hasn't been received yet\n // for those scenarios, best effort is to destroy the stream immediately\n // as there's no value to keep it open.\n if (request.aborted) {\n const err = new RequestAbortedError()\n util.errorRequest(client, request, err)\n util.destroy(stream, err)\n return\n }\n\n if (request.onHeaders(Number(statusCode), parseH2Headers(realHeaders), stream.resume.bind(stream), '') === false) {\n stream.pause()\n }\n\n stream.on('data', (chunk) => {\n if (request.onData(chunk) === false) {\n stream.pause()\n }\n })\n })\n\n stream.once('end', () => {\n // When state is null, it means we haven't consumed body and the stream still do not have\n // a state.\n // Present specially when using pipeline or stream\n if (stream.state?.state == null || stream.state.state < 6) {\n request.onComplete([])\n }\n\n if (session[kOpenStreams] === 0) {\n // Stream is closed or half-closed-remote (6), decrement counter and cleanup\n // It does not have sense to continue working with the stream as we do not\n // have yet RST_STREAM support on client-side\n\n session.unref()\n }\n\n abort(new InformationalError('HTTP/2: stream half-closed (remote)'))\n client[kQueue][client[kRunningIdx]++] = null\n client[kPendingIdx] = client[kRunningIdx]\n client[kResume]()\n })\n\n stream.once('close', () => {\n session[kOpenStreams] -= 1\n if (session[kOpenStreams] === 0) {\n session.unref()\n }\n })\n\n stream.once('error', function (err) {\n abort(err)\n })\n\n stream.once('frameError', (type, code) => {\n abort(new InformationalError(`HTTP/2: \"frameError\" received - type ${type}, code ${code}`))\n })\n\n // stream.on('aborted', () => {\n // // TODO(HTTP/2): Support aborted\n // })\n\n // stream.on('timeout', () => {\n // // TODO(HTTP/2): Support timeout\n // })\n\n // stream.on('push', headers => {\n // // TODO(HTTP/2): Support push\n // })\n\n // stream.on('trailers', headers => {\n // // TODO(HTTP/2): Support trailers\n // })\n\n return true\n\n function writeBodyH2 () {\n /* istanbul ignore else: assertion */\n if (!body || contentLength === 0) {\n writeBuffer(\n abort,\n stream,\n null,\n client,\n request,\n client[kSocket],\n contentLength,\n expectsPayload\n )\n } else if (util.isBuffer(body)) {\n writeBuffer(\n abort,\n stream,\n body,\n client,\n request,\n client[kSocket],\n contentLength,\n expectsPayload\n )\n } else if (util.isBlobLike(body)) {\n if (typeof body.stream === 'function') {\n writeIterable(\n abort,\n stream,\n body.stream(),\n client,\n request,\n client[kSocket],\n contentLength,\n expectsPayload\n )\n } else {\n writeBlob(\n abort,\n stream,\n body,\n client,\n request,\n client[kSocket],\n contentLength,\n expectsPayload\n )\n }\n } else if (util.isStream(body)) {\n writeStream(\n abort,\n client[kSocket],\n expectsPayload,\n stream,\n body,\n client,\n request,\n contentLength\n )\n } else if (util.isIterable(body)) {\n writeIterable(\n abort,\n stream,\n body,\n client,\n request,\n client[kSocket],\n contentLength,\n expectsPayload\n )\n } else {\n assert(false)\n }\n }\n}\n\nfunction writeBuffer (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {\n try {\n if (body != null && util.isBuffer(body)) {\n assert(contentLength === body.byteLength, 'buffer body must have content length')\n h2stream.cork()\n h2stream.write(body)\n h2stream.uncork()\n h2stream.end()\n\n request.onBodySent(body)\n }\n\n if (!expectsPayload) {\n socket[kReset] = true\n }\n\n request.onRequestSent()\n client[kResume]()\n } catch (error) {\n abort(error)\n }\n}\n\nfunction writeStream (abort, socket, expectsPayload, h2stream, body, client, request, contentLength) {\n assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')\n\n // For HTTP/2, is enough to pipe the stream\n const pipe = pipeline(\n body,\n h2stream,\n (err) => {\n if (err) {\n util.destroy(pipe, err)\n abort(err)\n } else {\n util.removeAllListeners(pipe)\n request.onRequestSent()\n\n if (!expectsPayload) {\n socket[kReset] = true\n }\n\n client[kResume]()\n }\n }\n )\n\n util.addListener(pipe, 'data', onPipeData)\n\n function onPipeData (chunk) {\n request.onBodySent(chunk)\n }\n}\n\nasync function writeBlob (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {\n assert(contentLength === body.size, 'blob body must have content length')\n\n try {\n if (contentLength != null && contentLength !== body.size) {\n throw new RequestContentLengthMismatchError()\n }\n\n const buffer = Buffer.from(await body.arrayBuffer())\n\n h2stream.cork()\n h2stream.write(buffer)\n h2stream.uncork()\n h2stream.end()\n\n request.onBodySent(buffer)\n request.onRequestSent()\n\n if (!expectsPayload) {\n socket[kReset] = true\n }\n\n client[kResume]()\n } catch (err) {\n abort(err)\n }\n}\n\nasync function writeIterable (abort, h2stream, body, client, request, socket, contentLength, expectsPayload) {\n assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')\n\n let callback = null\n function onDrain () {\n if (callback) {\n const cb = callback\n callback = null\n cb()\n }\n }\n\n const waitForDrain = () => new Promise((resolve, reject) => {\n assert(callback === null)\n\n if (socket[kError]) {\n reject(socket[kError])\n } else {\n callback = resolve\n }\n })\n\n h2stream\n .on('close', onDrain)\n .on('drain', onDrain)\n\n try {\n // It's up to the user to somehow abort the async iterable.\n for await (const chunk of body) {\n if (socket[kError]) {\n throw socket[kError]\n }\n\n const res = h2stream.write(chunk)\n request.onBodySent(chunk)\n if (!res) {\n await waitForDrain()\n }\n }\n\n h2stream.end()\n\n request.onRequestSent()\n\n if (!expectsPayload) {\n socket[kReset] = true\n }\n\n client[kResume]()\n } catch (err) {\n abort(err)\n } finally {\n h2stream\n .off('close', onDrain)\n .off('drain', onDrain)\n }\n}\n\nmodule.exports = connectH2\n","'use strict'\n\nconst util = require('../core/util')\nconst { kBodyUsed } = require('../core/symbols')\nconst assert = require('node:assert')\nconst { InvalidArgumentError } = require('../core/errors')\nconst EE = require('node:events')\n\nconst redirectableStatusCodes = [300, 301, 302, 303, 307, 308]\n\nconst kBody = Symbol('body')\n\nclass BodyAsyncIterable {\n constructor (body) {\n this[kBody] = body\n this[kBodyUsed] = false\n }\n\n async * [Symbol.asyncIterator] () {\n assert(!this[kBodyUsed], 'disturbed')\n this[kBodyUsed] = true\n yield * this[kBody]\n }\n}\n\nclass RedirectHandler {\n constructor (dispatch, maxRedirections, opts, handler) {\n if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {\n throw new InvalidArgumentError('maxRedirections must be a positive number')\n }\n\n util.validateHandler(handler, opts.method, opts.upgrade)\n\n this.dispatch = dispatch\n this.location = null\n this.abort = null\n this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy\n this.maxRedirections = maxRedirections\n this.handler = handler\n this.history = []\n this.redirectionLimitReached = false\n\n if (util.isStream(this.opts.body)) {\n // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp\n // so that it can be dispatched again?\n // TODO (fix): Do we need 100-expect support to provide a way to do this properly?\n if (util.bodyLength(this.opts.body) === 0) {\n this.opts.body\n .on('data', function () {\n assert(false)\n })\n }\n\n if (typeof this.opts.body.readableDidRead !== 'boolean') {\n this.opts.body[kBodyUsed] = false\n EE.prototype.on.call(this.opts.body, 'data', function () {\n this[kBodyUsed] = true\n })\n }\n } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') {\n // TODO (fix): We can't access ReadableStream internal state\n // to determine whether or not it has been disturbed. This is just\n // a workaround.\n this.opts.body = new BodyAsyncIterable(this.opts.body)\n } else if (\n this.opts.body &&\n typeof this.opts.body !== 'string' &&\n !ArrayBuffer.isView(this.opts.body) &&\n util.isIterable(this.opts.body)\n ) {\n // TODO: Should we allow re-using iterable if !this.opts.idempotent\n // or through some other flag?\n this.opts.body = new BodyAsyncIterable(this.opts.body)\n }\n }\n\n onConnect (abort) {\n this.abort = abort\n this.handler.onConnect(abort, { history: this.history })\n }\n\n onUpgrade (statusCode, headers, socket) {\n this.handler.onUpgrade(statusCode, headers, socket)\n }\n\n onError (error) {\n this.handler.onError(error)\n }\n\n onHeaders (statusCode, headers, resume, statusText) {\n this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body)\n ? null\n : parseLocation(statusCode, headers)\n\n if (this.opts.throwOnMaxRedirect && this.history.length >= this.maxRedirections) {\n if (this.request) {\n this.request.abort(new Error('max redirects'))\n }\n\n this.redirectionLimitReached = true\n this.abort(new Error('max redirects'))\n return\n }\n\n if (this.opts.origin) {\n this.history.push(new URL(this.opts.path, this.opts.origin))\n }\n\n if (!this.location) {\n return this.handler.onHeaders(statusCode, headers, resume, statusText)\n }\n\n const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)))\n const path = search ? `${pathname}${search}` : pathname\n\n // Remove headers referring to the original URL.\n // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers.\n // https://tools.ietf.org/html/rfc7231#section-6.4\n this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin)\n this.opts.path = path\n this.opts.origin = origin\n this.opts.maxRedirections = 0\n this.opts.query = null\n\n // https://tools.ietf.org/html/rfc7231#section-6.4.4\n // In case of HTTP 303, always replace method to be either HEAD or GET\n if (statusCode === 303 && this.opts.method !== 'HEAD') {\n this.opts.method = 'GET'\n this.opts.body = null\n }\n }\n\n onData (chunk) {\n if (this.location) {\n /*\n https://tools.ietf.org/html/rfc7231#section-6.4\n\n TLDR: undici always ignores 3xx response bodies.\n\n Redirection is used to serve the requested resource from another URL, so it is assumes that\n no body is generated (and thus can be ignored). Even though generating a body is not prohibited.\n\n For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually\n (which means it's optional and not mandated) contain just an hyperlink to the value of\n the Location response header, so the body can be ignored safely.\n\n For status 300, which is \"Multiple Choices\", the spec mentions both generating a Location\n response header AND a response body with the other possible location to follow.\n Since the spec explicitly chooses not to specify a format for such body and leave it to\n servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it.\n */\n } else {\n return this.handler.onData(chunk)\n }\n }\n\n onComplete (trailers) {\n if (this.location) {\n /*\n https://tools.ietf.org/html/rfc7231#section-6.4\n\n TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections\n and neither are useful if present.\n\n See comment on onData method above for more detailed information.\n */\n\n this.location = null\n this.abort = null\n\n this.dispatch(this.opts, this)\n } else {\n this.handler.onComplete(trailers)\n }\n }\n\n onBodySent (chunk) {\n if (this.handler.onBodySent) {\n this.handler.onBodySent(chunk)\n }\n }\n}\n\nfunction parseLocation (statusCode, headers) {\n if (redirectableStatusCodes.indexOf(statusCode) === -1) {\n return null\n }\n\n for (let i = 0; i < headers.length; i += 2) {\n if (headers[i].length === 8 && util.headerNameToString(headers[i]) === 'location') {\n return headers[i + 1]\n }\n }\n}\n\n// https://tools.ietf.org/html/rfc7231#section-6.4.4\nfunction shouldRemoveHeader (header, removeContent, unknownOrigin) {\n if (header.length === 4) {\n return util.headerNameToString(header) === 'host'\n }\n if (removeContent && util.headerNameToString(header).startsWith('content-')) {\n return true\n }\n if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {\n const name = util.headerNameToString(header)\n return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization'\n }\n return false\n}\n\n// https://tools.ietf.org/html/rfc7231#section-6.4\nfunction cleanRequestHeaders (headers, removeContent, unknownOrigin) {\n const ret = []\n if (Array.isArray(headers)) {\n for (let i = 0; i < headers.length; i += 2) {\n if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) {\n ret.push(headers[i], headers[i + 1])\n }\n }\n } else if (headers && typeof headers === 'object') {\n for (const key of Object.keys(headers)) {\n if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {\n ret.push(key, headers[key])\n }\n }\n } else {\n assert(headers == null, 'headers must be an object or an array')\n }\n return ret\n}\n\nmodule.exports = RedirectHandler\n","'use strict'\n\nconst RedirectHandler = require('../handler/redirect-handler')\n\nfunction createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) {\n return (dispatch) => {\n return function Intercept (opts, handler) {\n const { maxRedirections = defaultMaxRedirections } = opts\n\n if (!maxRedirections) {\n return dispatch(opts, handler)\n }\n\n const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler)\n opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting.\n return dispatch(opts, redirectHandler)\n }\n }\n}\n\nmodule.exports = createRedirectInterceptor\n","// @ts-check\n\n'use strict'\n\nconst assert = require('node:assert')\nconst net = require('node:net')\nconst http = require('node:http')\nconst util = require('../core/util.js')\nconst { channels } = require('../core/diagnostics.js')\nconst Request = require('../core/request.js')\nconst DispatcherBase = require('./dispatcher-base')\nconst {\n InvalidArgumentError,\n InformationalError,\n ClientDestroyedError\n} = require('../core/errors.js')\nconst buildConnector = require('../core/connect.js')\nconst {\n kUrl,\n kServerName,\n kClient,\n kBusy,\n kConnect,\n kResuming,\n kRunning,\n kPending,\n kSize,\n kQueue,\n kConnected,\n kConnecting,\n kNeedDrain,\n kKeepAliveDefaultTimeout,\n kHostHeader,\n kPendingIdx,\n kRunningIdx,\n kError,\n kPipelining,\n kKeepAliveTimeoutValue,\n kMaxHeadersSize,\n kKeepAliveMaxTimeout,\n kKeepAliveTimeoutThreshold,\n kHeadersTimeout,\n kBodyTimeout,\n kStrictContentLength,\n kConnector,\n kMaxRedirections,\n kMaxRequests,\n kCounter,\n kClose,\n kDestroy,\n kDispatch,\n kInterceptors,\n kLocalAddress,\n kMaxResponseSize,\n kOnError,\n kHTTPContext,\n kMaxConcurrentStreams,\n kResume\n} = require('../core/symbols.js')\nconst connectH1 = require('./client-h1.js')\nconst connectH2 = require('./client-h2.js')\nlet deprecatedInterceptorWarned = false\n\nconst kClosedResolve = Symbol('kClosedResolve')\n\nconst noop = () => {}\n\nfunction getPipelining (client) {\n return client[kPipelining] ?? client[kHTTPContext]?.defaultPipelining ?? 1\n}\n\n/**\n * @type {import('../../types/client.js').default}\n */\nclass Client extends DispatcherBase {\n /**\n *\n * @param {string|URL} url\n * @param {import('../../types/client.js').Client.Options} options\n */\n constructor (url, {\n interceptors,\n maxHeaderSize,\n headersTimeout,\n socketTimeout,\n requestTimeout,\n connectTimeout,\n bodyTimeout,\n idleTimeout,\n keepAlive,\n keepAliveTimeout,\n maxKeepAliveTimeout,\n keepAliveMaxTimeout,\n keepAliveTimeoutThreshold,\n socketPath,\n pipelining,\n tls,\n strictContentLength,\n maxCachedSessions,\n maxRedirections,\n connect,\n maxRequestsPerClient,\n localAddress,\n maxResponseSize,\n autoSelectFamily,\n autoSelectFamilyAttemptTimeout,\n // h2\n maxConcurrentStreams,\n allowH2,\n webSocket\n } = {}) {\n super({ webSocket })\n\n if (keepAlive !== undefined) {\n throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead')\n }\n\n if (socketTimeout !== undefined) {\n throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead')\n }\n\n if (requestTimeout !== undefined) {\n throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead')\n }\n\n if (idleTimeout !== undefined) {\n throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead')\n }\n\n if (maxKeepAliveTimeout !== undefined) {\n throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead')\n }\n\n if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) {\n throw new InvalidArgumentError('invalid maxHeaderSize')\n }\n\n if (socketPath != null && typeof socketPath !== 'string') {\n throw new InvalidArgumentError('invalid socketPath')\n }\n\n if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {\n throw new InvalidArgumentError('invalid connectTimeout')\n }\n\n if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {\n throw new InvalidArgumentError('invalid keepAliveTimeout')\n }\n\n if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {\n throw new InvalidArgumentError('invalid keepAliveMaxTimeout')\n }\n\n if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {\n throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold')\n }\n\n if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {\n throw new InvalidArgumentError('headersTimeout must be a positive integer or zero')\n }\n\n if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {\n throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero')\n }\n\n if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {\n throw new InvalidArgumentError('connect must be a function or an object')\n }\n\n if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {\n throw new InvalidArgumentError('maxRedirections must be a positive number')\n }\n\n if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {\n throw new InvalidArgumentError('maxRequestsPerClient must be a positive number')\n }\n\n if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) {\n throw new InvalidArgumentError('localAddress must be valid string IP address')\n }\n\n if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {\n throw new InvalidArgumentError('maxResponseSize must be a positive number')\n }\n\n if (\n autoSelectFamilyAttemptTimeout != null &&\n (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)\n ) {\n throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number')\n }\n\n // h2\n if (allowH2 != null && typeof allowH2 !== 'boolean') {\n throw new InvalidArgumentError('allowH2 must be a valid boolean value')\n }\n\n if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) {\n throw new InvalidArgumentError('maxConcurrentStreams must be a positive integer, greater than 0')\n }\n\n if (typeof connect !== 'function') {\n connect = buildConnector({\n ...tls,\n maxCachedSessions,\n allowH2,\n socketPath,\n timeout: connectTimeout,\n ...(autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),\n ...connect\n })\n }\n\n if (interceptors?.Client && Array.isArray(interceptors.Client)) {\n this[kInterceptors] = interceptors.Client\n if (!deprecatedInterceptorWarned) {\n deprecatedInterceptorWarned = true\n process.emitWarning('Client.Options#interceptor is deprecated. Use Dispatcher#compose instead.', {\n code: 'UNDICI-CLIENT-INTERCEPTOR-DEPRECATED'\n })\n }\n } else {\n this[kInterceptors] = [createRedirectInterceptor({ maxRedirections })]\n }\n\n this[kUrl] = util.parseOrigin(url)\n this[kConnector] = connect\n this[kPipelining] = pipelining != null ? pipelining : 1\n this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize\n this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout\n this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout\n this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 2e3 : keepAliveTimeoutThreshold\n this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout]\n this[kServerName] = null\n this[kLocalAddress] = localAddress != null ? localAddress : null\n this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming\n this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming\n this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\\r\\n`\n this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3\n this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3\n this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength\n this[kMaxRedirections] = maxRedirections\n this[kMaxRequests] = maxRequestsPerClient\n this[kClosedResolve] = null\n this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1\n this[kMaxConcurrentStreams] = maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server\n this[kHTTPContext] = null\n\n // kQueue is built up of 3 sections separated by\n // the kRunningIdx and kPendingIdx indices.\n // | complete | running | pending |\n // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length\n // kRunningIdx points to the first running element.\n // kPendingIdx points to the first pending element.\n // This implements a fast queue with an amortized\n // time of O(1).\n\n this[kQueue] = []\n this[kRunningIdx] = 0\n this[kPendingIdx] = 0\n\n this[kResume] = (sync) => resume(this, sync)\n this[kOnError] = (err) => onError(this, err)\n }\n\n get pipelining () {\n return this[kPipelining]\n }\n\n set pipelining (value) {\n this[kPipelining] = value\n this[kResume](true)\n }\n\n get [kPending] () {\n return this[kQueue].length - this[kPendingIdx]\n }\n\n get [kRunning] () {\n return this[kPendingIdx] - this[kRunningIdx]\n }\n\n get [kSize] () {\n return this[kQueue].length - this[kRunningIdx]\n }\n\n get [kConnected] () {\n return !!this[kHTTPContext] && !this[kConnecting] && !this[kHTTPContext].destroyed\n }\n\n get [kBusy] () {\n return Boolean(\n this[kHTTPContext]?.busy(null) ||\n (this[kSize] >= (getPipelining(this) || 1)) ||\n this[kPending] > 0\n )\n }\n\n /* istanbul ignore: only used for test */\n [kConnect] (cb) {\n connect(this)\n this.once('connect', cb)\n }\n\n [kDispatch] (opts, handler) {\n const origin = opts.origin || this[kUrl].origin\n const request = new Request(origin, opts, handler)\n\n this[kQueue].push(request)\n if (this[kResuming]) {\n // Do nothing.\n } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {\n // Wait a tick in case stream/iterator is ended in the same tick.\n this[kResuming] = 1\n queueMicrotask(() => resume(this))\n } else {\n this[kResume](true)\n }\n\n if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {\n this[kNeedDrain] = 2\n }\n\n return this[kNeedDrain] < 2\n }\n\n async [kClose] () {\n // TODO: for H2 we need to gracefully flush the remaining enqueued\n // request and close each stream.\n return new Promise((resolve) => {\n if (this[kSize]) {\n this[kClosedResolve] = resolve\n } else {\n resolve(null)\n }\n })\n }\n\n async [kDestroy] (err) {\n return new Promise((resolve) => {\n const requests = this[kQueue].splice(this[kPendingIdx])\n for (let i = 0; i < requests.length; i++) {\n const request = requests[i]\n util.errorRequest(this, request, err)\n }\n\n const callback = () => {\n if (this[kClosedResolve]) {\n // TODO (fix): Should we error here with ClientDestroyedError?\n this[kClosedResolve]()\n this[kClosedResolve] = null\n }\n resolve(null)\n }\n\n if (this[kHTTPContext]) {\n this[kHTTPContext].destroy(err, callback)\n this[kHTTPContext] = null\n } else {\n queueMicrotask(callback)\n }\n\n this[kResume]()\n })\n }\n}\n\nconst createRedirectInterceptor = require('../interceptor/redirect-interceptor.js')\n\nfunction onError (client, err) {\n if (\n client[kRunning] === 0 &&\n err.code !== 'UND_ERR_INFO' &&\n err.code !== 'UND_ERR_SOCKET'\n ) {\n // Error is not caused by running request and not a recoverable\n // socket error.\n\n assert(client[kPendingIdx] === client[kRunningIdx])\n\n const requests = client[kQueue].splice(client[kRunningIdx])\n\n for (let i = 0; i < requests.length; i++) {\n const request = requests[i]\n util.errorRequest(client, request, err)\n }\n assert(client[kSize] === 0)\n }\n}\n\n/**\n * @param {Client} client\n * @returns\n */\nasync function connect (client) {\n assert(!client[kConnecting])\n assert(!client[kHTTPContext])\n\n let { host, hostname, protocol, port } = client[kUrl]\n\n // Resolve ipv6\n if (hostname[0] === '[') {\n const idx = hostname.indexOf(']')\n\n assert(idx !== -1)\n const ip = hostname.substring(1, idx)\n\n assert(net.isIP(ip))\n hostname = ip\n }\n\n client[kConnecting] = true\n\n if (channels.beforeConnect.hasSubscribers) {\n channels.beforeConnect.publish({\n connectParams: {\n host,\n hostname,\n protocol,\n port,\n version: client[kHTTPContext]?.version,\n servername: client[kServerName],\n localAddress: client[kLocalAddress]\n },\n connector: client[kConnector]\n })\n }\n\n try {\n const socket = await new Promise((resolve, reject) => {\n client[kConnector]({\n host,\n hostname,\n protocol,\n port,\n servername: client[kServerName],\n localAddress: client[kLocalAddress]\n }, (err, socket) => {\n if (err) {\n reject(err)\n } else {\n resolve(socket)\n }\n })\n })\n\n if (client.destroyed) {\n util.destroy(socket.on('error', noop), new ClientDestroyedError())\n return\n }\n\n assert(socket)\n\n try {\n client[kHTTPContext] = socket.alpnProtocol === 'h2'\n ? await connectH2(client, socket)\n : await connectH1(client, socket)\n } catch (err) {\n socket.destroy().on('error', noop)\n throw err\n }\n\n client[kConnecting] = false\n\n socket[kCounter] = 0\n socket[kMaxRequests] = client[kMaxRequests]\n socket[kClient] = client\n socket[kError] = null\n\n if (channels.connected.hasSubscribers) {\n channels.connected.publish({\n connectParams: {\n host,\n hostname,\n protocol,\n port,\n version: client[kHTTPContext]?.version,\n servername: client[kServerName],\n localAddress: client[kLocalAddress]\n },\n connector: client[kConnector],\n socket\n })\n }\n client.emit('connect', client[kUrl], [client])\n } catch (err) {\n if (client.destroyed) {\n return\n }\n\n client[kConnecting] = false\n\n if (channels.connectError.hasSubscribers) {\n channels.connectError.publish({\n connectParams: {\n host,\n hostname,\n protocol,\n port,\n version: client[kHTTPContext]?.version,\n servername: client[kServerName],\n localAddress: client[kLocalAddress]\n },\n connector: client[kConnector],\n error: err\n })\n }\n\n if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {\n assert(client[kRunning] === 0)\n while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {\n const request = client[kQueue][client[kPendingIdx]++]\n util.errorRequest(client, request, err)\n }\n } else {\n onError(client, err)\n }\n\n client.emit('connectionError', client[kUrl], [client], err)\n }\n\n client[kResume]()\n}\n\nfunction emitDrain (client) {\n client[kNeedDrain] = 0\n client.emit('drain', client[kUrl], [client])\n}\n\nfunction resume (client, sync) {\n if (client[kResuming] === 2) {\n return\n }\n\n client[kResuming] = 2\n\n _resume(client, sync)\n client[kResuming] = 0\n\n if (client[kRunningIdx] > 256) {\n client[kQueue].splice(0, client[kRunningIdx])\n client[kPendingIdx] -= client[kRunningIdx]\n client[kRunningIdx] = 0\n }\n}\n\nfunction _resume (client, sync) {\n while (true) {\n if (client.destroyed) {\n assert(client[kPending] === 0)\n return\n }\n\n if (client[kClosedResolve] && !client[kSize]) {\n client[kClosedResolve]()\n client[kClosedResolve] = null\n return\n }\n\n if (client[kHTTPContext]) {\n client[kHTTPContext].resume()\n }\n\n if (client[kBusy]) {\n client[kNeedDrain] = 2\n } else if (client[kNeedDrain] === 2) {\n if (sync) {\n client[kNeedDrain] = 1\n queueMicrotask(() => emitDrain(client))\n } else {\n emitDrain(client)\n }\n continue\n }\n\n if (client[kPending] === 0) {\n return\n }\n\n if (client[kRunning] >= (getPipelining(client) || 1)) {\n return\n }\n\n const request = client[kQueue][client[kPendingIdx]]\n\n if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {\n if (client[kRunning] > 0) {\n return\n }\n\n client[kServerName] = request.servername\n client[kHTTPContext]?.destroy(new InformationalError('servername changed'), () => {\n client[kHTTPContext] = null\n resume(client)\n })\n }\n\n if (client[kConnecting]) {\n return\n }\n\n if (!client[kHTTPContext]) {\n connect(client)\n return\n }\n\n if (client[kHTTPContext].destroyed) {\n return\n }\n\n if (client[kHTTPContext].busy(request)) {\n return\n }\n\n if (!request.aborted && client[kHTTPContext].write(request)) {\n client[kPendingIdx]++\n } else {\n client[kQueue].splice(client[kPendingIdx], 1)\n }\n }\n}\n\nmodule.exports = Client\n","/* eslint-disable */\n\n'use strict'\n\n// Extracted from node/lib/internal/fixed_queue.js\n\n// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two.\nconst kSize = 2048;\nconst kMask = kSize - 1;\n\n// The FixedQueue is implemented as a singly-linked list of fixed-size\n// circular buffers. It looks something like this:\n//\n// head tail\n// | |\n// v v\n// +-----------+ <-----\\ +-----------+ <------\\ +-----------+\n// | [null] | \\----- | next | \\------- | next |\n// +-----------+ +-----------+ +-----------+\n// | item | <-- bottom | item | <-- bottom | [empty] |\n// | item | | item | | [empty] |\n// | item | | item | | [empty] |\n// | item | | item | | [empty] |\n// | item | | item | bottom --> | item |\n// | item | | item | | item |\n// | ... | | ... | | ... |\n// | item | | item | | item |\n// | item | | item | | item |\n// | [empty] | <-- top | item | | item |\n// | [empty] | | item | | item |\n// | [empty] | | [empty] | <-- top top --> | [empty] |\n// +-----------+ +-----------+ +-----------+\n//\n// Or, if there is only one circular buffer, it looks something\n// like either of these:\n//\n// head tail head tail\n// | | | |\n// v v v v\n// +-----------+ +-----------+\n// | [null] | | [null] |\n// +-----------+ +-----------+\n// | [empty] | | item |\n// | [empty] | | item |\n// | item | <-- bottom top --> | [empty] |\n// | item | | [empty] |\n// | [empty] | <-- top bottom --> | item |\n// | [empty] | | item |\n// +-----------+ +-----------+\n//\n// Adding a value means moving `top` forward by one, removing means\n// moving `bottom` forward by one. After reaching the end, the queue\n// wraps around.\n//\n// When `top === bottom` the current queue is empty and when\n// `top + 1 === bottom` it's full. This wastes a single space of storage\n// but allows much quicker checks.\n\nclass FixedCircularBuffer {\n constructor() {\n this.bottom = 0;\n this.top = 0;\n this.list = new Array(kSize);\n this.next = null;\n }\n\n isEmpty() {\n return this.top === this.bottom;\n }\n\n isFull() {\n return ((this.top + 1) & kMask) === this.bottom;\n }\n\n push(data) {\n this.list[this.top] = data;\n this.top = (this.top + 1) & kMask;\n }\n\n shift() {\n const nextItem = this.list[this.bottom];\n if (nextItem === undefined)\n return null;\n this.list[this.bottom] = undefined;\n this.bottom = (this.bottom + 1) & kMask;\n return nextItem;\n }\n}\n\nmodule.exports = class FixedQueue {\n constructor() {\n this.head = this.tail = new FixedCircularBuffer();\n }\n\n isEmpty() {\n return this.head.isEmpty();\n }\n\n push(data) {\n if (this.head.isFull()) {\n // Head is full: Creates a new queue, sets the old queue's `.next` to it,\n // and sets it as the new main queue.\n this.head = this.head.next = new FixedCircularBuffer();\n }\n this.head.push(data);\n }\n\n shift() {\n const tail = this.tail;\n const next = tail.shift();\n if (tail.isEmpty() && tail.next !== null) {\n // If there is another queue, it forms the new tail.\n this.tail = tail.next;\n }\n return next;\n }\n};\n","const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = require('../core/symbols')\nconst kPool = Symbol('pool')\n\nclass PoolStats {\n constructor (pool) {\n this[kPool] = pool\n }\n\n get connected () {\n return this[kPool][kConnected]\n }\n\n get free () {\n return this[kPool][kFree]\n }\n\n get pending () {\n return this[kPool][kPending]\n }\n\n get queued () {\n return this[kPool][kQueued]\n }\n\n get running () {\n return this[kPool][kRunning]\n }\n\n get size () {\n return this[kPool][kSize]\n }\n}\n\nmodule.exports = PoolStats\n","'use strict'\n\nconst DispatcherBase = require('./dispatcher-base')\nconst FixedQueue = require('./fixed-queue')\nconst { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require('../core/symbols')\nconst PoolStats = require('./pool-stats')\n\nconst kClients = Symbol('clients')\nconst kNeedDrain = Symbol('needDrain')\nconst kQueue = Symbol('queue')\nconst kClosedResolve = Symbol('closed resolve')\nconst kOnDrain = Symbol('onDrain')\nconst kOnConnect = Symbol('onConnect')\nconst kOnDisconnect = Symbol('onDisconnect')\nconst kOnConnectionError = Symbol('onConnectionError')\nconst kGetDispatcher = Symbol('get dispatcher')\nconst kAddClient = Symbol('add client')\nconst kRemoveClient = Symbol('remove client')\nconst kStats = Symbol('stats')\n\nclass PoolBase extends DispatcherBase {\n constructor (opts) {\n super(opts)\n\n this[kQueue] = new FixedQueue()\n this[kClients] = []\n this[kQueued] = 0\n\n const pool = this\n\n this[kOnDrain] = function onDrain (origin, targets) {\n const queue = pool[kQueue]\n\n let needDrain = false\n\n while (!needDrain) {\n const item = queue.shift()\n if (!item) {\n break\n }\n pool[kQueued]--\n needDrain = !this.dispatch(item.opts, item.handler)\n }\n\n this[kNeedDrain] = needDrain\n\n if (!this[kNeedDrain] && pool[kNeedDrain]) {\n pool[kNeedDrain] = false\n pool.emit('drain', origin, [pool, ...targets])\n }\n\n if (pool[kClosedResolve] && queue.isEmpty()) {\n Promise\n .all(pool[kClients].map(c => c.close()))\n .then(pool[kClosedResolve])\n }\n }\n\n this[kOnConnect] = (origin, targets) => {\n pool.emit('connect', origin, [pool, ...targets])\n }\n\n this[kOnDisconnect] = (origin, targets, err) => {\n pool.emit('disconnect', origin, [pool, ...targets], err)\n }\n\n this[kOnConnectionError] = (origin, targets, err) => {\n pool.emit('connectionError', origin, [pool, ...targets], err)\n }\n\n this[kStats] = new PoolStats(this)\n }\n\n get [kBusy] () {\n return this[kNeedDrain]\n }\n\n get [kConnected] () {\n return this[kClients].filter(client => client[kConnected]).length\n }\n\n get [kFree] () {\n return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length\n }\n\n get [kPending] () {\n let ret = this[kQueued]\n for (const { [kPending]: pending } of this[kClients]) {\n ret += pending\n }\n return ret\n }\n\n get [kRunning] () {\n let ret = 0\n for (const { [kRunning]: running } of this[kClients]) {\n ret += running\n }\n return ret\n }\n\n get [kSize] () {\n let ret = this[kQueued]\n for (const { [kSize]: size } of this[kClients]) {\n ret += size\n }\n return ret\n }\n\n get stats () {\n return this[kStats]\n }\n\n async [kClose] () {\n if (this[kQueue].isEmpty()) {\n await Promise.all(this[kClients].map(c => c.close()))\n } else {\n await new Promise((resolve) => {\n this[kClosedResolve] = resolve\n })\n }\n }\n\n async [kDestroy] (err) {\n while (true) {\n const item = this[kQueue].shift()\n if (!item) {\n break\n }\n item.handler.onError(err)\n }\n\n await Promise.all(this[kClients].map(c => c.destroy(err)))\n }\n\n [kDispatch] (opts, handler) {\n const dispatcher = this[kGetDispatcher]()\n\n if (!dispatcher) {\n this[kNeedDrain] = true\n this[kQueue].push({ opts, handler })\n this[kQueued]++\n } else if (!dispatcher.dispatch(opts, handler)) {\n dispatcher[kNeedDrain] = true\n this[kNeedDrain] = !this[kGetDispatcher]()\n }\n\n return !this[kNeedDrain]\n }\n\n [kAddClient] (client) {\n client\n .on('drain', this[kOnDrain])\n .on('connect', this[kOnConnect])\n .on('disconnect', this[kOnDisconnect])\n .on('connectionError', this[kOnConnectionError])\n\n this[kClients].push(client)\n\n if (this[kNeedDrain]) {\n queueMicrotask(() => {\n if (this[kNeedDrain]) {\n this[kOnDrain](client[kUrl], [this, client])\n }\n })\n }\n\n return this\n }\n\n [kRemoveClient] (client) {\n client.close(() => {\n const idx = this[kClients].indexOf(client)\n if (idx !== -1) {\n this[kClients].splice(idx, 1)\n }\n })\n\n this[kNeedDrain] = this[kClients].some(dispatcher => (\n !dispatcher[kNeedDrain] &&\n dispatcher.closed !== true &&\n dispatcher.destroyed !== true\n ))\n }\n}\n\nmodule.exports = {\n PoolBase,\n kClients,\n kNeedDrain,\n kAddClient,\n kRemoveClient,\n kGetDispatcher\n}\n","'use strict'\n\nconst {\n PoolBase,\n kClients,\n kNeedDrain,\n kAddClient,\n kGetDispatcher\n} = require('./pool-base')\nconst Client = require('./client')\nconst {\n InvalidArgumentError\n} = require('../core/errors')\nconst util = require('../core/util')\nconst { kUrl, kInterceptors } = require('../core/symbols')\nconst buildConnector = require('../core/connect')\n\nconst kOptions = Symbol('options')\nconst kConnections = Symbol('connections')\nconst kFactory = Symbol('factory')\n\nfunction defaultFactory (origin, opts) {\n return new Client(origin, opts)\n}\n\nclass Pool extends PoolBase {\n constructor (origin, {\n connections,\n factory = defaultFactory,\n connect,\n connectTimeout,\n tls,\n maxCachedSessions,\n socketPath,\n autoSelectFamily,\n autoSelectFamilyAttemptTimeout,\n allowH2,\n ...options\n } = {}) {\n if (connections != null && (!Number.isFinite(connections) || connections < 0)) {\n throw new InvalidArgumentError('invalid connections')\n }\n\n if (typeof factory !== 'function') {\n throw new InvalidArgumentError('factory must be a function.')\n }\n\n if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {\n throw new InvalidArgumentError('connect must be a function or an object')\n }\n\n if (typeof connect !== 'function') {\n connect = buildConnector({\n ...tls,\n maxCachedSessions,\n allowH2,\n socketPath,\n timeout: connectTimeout,\n ...(autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),\n ...connect\n })\n }\n\n super(options)\n\n this[kInterceptors] = options.interceptors?.Pool && Array.isArray(options.interceptors.Pool)\n ? options.interceptors.Pool\n : []\n this[kConnections] = connections || null\n this[kUrl] = util.parseOrigin(origin)\n this[kOptions] = { ...util.deepClone(options), connect, allowH2 }\n this[kOptions].interceptors = options.interceptors\n ? { ...options.interceptors }\n : undefined\n this[kFactory] = factory\n\n this.on('connectionError', (origin, targets, error) => {\n // If a connection error occurs, we remove the client from the pool,\n // and emit a connectionError event. They will not be re-used.\n // Fixes https://github.com/nodejs/undici/issues/3895\n for (const target of targets) {\n // Do not use kRemoveClient here, as it will close the client,\n // but the client cannot be closed in this state.\n const idx = this[kClients].indexOf(target)\n if (idx !== -1) {\n this[kClients].splice(idx, 1)\n }\n }\n })\n }\n\n [kGetDispatcher] () {\n for (const client of this[kClients]) {\n if (!client[kNeedDrain]) {\n return client\n }\n }\n\n if (!this[kConnections] || this[kClients].length < this[kConnections]) {\n const dispatcher = this[kFactory](this[kUrl], this[kOptions])\n this[kAddClient](dispatcher)\n return dispatcher\n }\n }\n}\n\nmodule.exports = Pool\n","'use strict'\n\nconst {\n BalancedPoolMissingUpstreamError,\n InvalidArgumentError\n} = require('../core/errors')\nconst {\n PoolBase,\n kClients,\n kNeedDrain,\n kAddClient,\n kRemoveClient,\n kGetDispatcher\n} = require('./pool-base')\nconst Pool = require('./pool')\nconst { kUrl, kInterceptors } = require('../core/symbols')\nconst { parseOrigin } = require('../core/util')\nconst kFactory = Symbol('factory')\n\nconst kOptions = Symbol('options')\nconst kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor')\nconst kCurrentWeight = Symbol('kCurrentWeight')\nconst kIndex = Symbol('kIndex')\nconst kWeight = Symbol('kWeight')\nconst kMaxWeightPerServer = Symbol('kMaxWeightPerServer')\nconst kErrorPenalty = Symbol('kErrorPenalty')\n\n/**\n * Calculate the greatest common divisor of two numbers by\n * using the Euclidean algorithm.\n *\n * @param {number} a\n * @param {number} b\n * @returns {number}\n */\nfunction getGreatestCommonDivisor (a, b) {\n if (a === 0) return b\n\n while (b !== 0) {\n const t = b\n b = a % b\n a = t\n }\n return a\n}\n\nfunction defaultFactory (origin, opts) {\n return new Pool(origin, opts)\n}\n\nclass BalancedPool extends PoolBase {\n constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) {\n super()\n\n this[kOptions] = opts\n this[kIndex] = -1\n this[kCurrentWeight] = 0\n\n this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100\n this[kErrorPenalty] = this[kOptions].errorPenalty || 15\n\n if (!Array.isArray(upstreams)) {\n upstreams = [upstreams]\n }\n\n if (typeof factory !== 'function') {\n throw new InvalidArgumentError('factory must be a function.')\n }\n\n this[kInterceptors] = opts.interceptors?.BalancedPool && Array.isArray(opts.interceptors.BalancedPool)\n ? opts.interceptors.BalancedPool\n : []\n this[kFactory] = factory\n\n for (const upstream of upstreams) {\n this.addUpstream(upstream)\n }\n this._updateBalancedPoolStats()\n }\n\n addUpstream (upstream) {\n const upstreamOrigin = parseOrigin(upstream).origin\n\n if (this[kClients].find((pool) => (\n pool[kUrl].origin === upstreamOrigin &&\n pool.closed !== true &&\n pool.destroyed !== true\n ))) {\n return this\n }\n const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]))\n\n this[kAddClient](pool)\n pool.on('connect', () => {\n pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty])\n })\n\n pool.on('connectionError', () => {\n pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])\n this._updateBalancedPoolStats()\n })\n\n pool.on('disconnect', (...args) => {\n const err = args[2]\n if (err && err.code === 'UND_ERR_SOCKET') {\n // decrease the weight of the pool.\n pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])\n this._updateBalancedPoolStats()\n }\n })\n\n for (const client of this[kClients]) {\n client[kWeight] = this[kMaxWeightPerServer]\n }\n\n this._updateBalancedPoolStats()\n\n return this\n }\n\n _updateBalancedPoolStats () {\n let result = 0\n for (let i = 0; i < this[kClients].length; i++) {\n result = getGreatestCommonDivisor(this[kClients][i][kWeight], result)\n }\n\n this[kGreatestCommonDivisor] = result\n }\n\n removeUpstream (upstream) {\n const upstreamOrigin = parseOrigin(upstream).origin\n\n const pool = this[kClients].find((pool) => (\n pool[kUrl].origin === upstreamOrigin &&\n pool.closed !== true &&\n pool.destroyed !== true\n ))\n\n if (pool) {\n this[kRemoveClient](pool)\n }\n\n return this\n }\n\n get upstreams () {\n return this[kClients]\n .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true)\n .map((p) => p[kUrl].origin)\n }\n\n [kGetDispatcher] () {\n // We validate that pools is greater than 0,\n // otherwise we would have to wait until an upstream\n // is added, which might never happen.\n if (this[kClients].length === 0) {\n throw new BalancedPoolMissingUpstreamError()\n }\n\n const dispatcher = this[kClients].find(dispatcher => (\n !dispatcher[kNeedDrain] &&\n dispatcher.closed !== true &&\n dispatcher.destroyed !== true\n ))\n\n if (!dispatcher) {\n return\n }\n\n const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true)\n\n if (allClientsBusy) {\n return\n }\n\n let counter = 0\n\n let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain])\n\n while (counter++ < this[kClients].length) {\n this[kIndex] = (this[kIndex] + 1) % this[kClients].length\n const pool = this[kClients][this[kIndex]]\n\n // find pool index with the largest weight\n if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {\n maxWeightIndex = this[kIndex]\n }\n\n // decrease the current weight every `this[kClients].length`.\n if (this[kIndex] === 0) {\n // Set the current weight to the next lower weight.\n this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor]\n\n if (this[kCurrentWeight] <= 0) {\n this[kCurrentWeight] = this[kMaxWeightPerServer]\n }\n }\n if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) {\n return pool\n }\n }\n\n this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight]\n this[kIndex] = maxWeightIndex\n return this[kClients][maxWeightIndex]\n }\n}\n\nmodule.exports = BalancedPool\n","'use strict'\n\nconst { InvalidArgumentError } = require('../core/errors')\nconst { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = require('../core/symbols')\nconst DispatcherBase = require('./dispatcher-base')\nconst Pool = require('./pool')\nconst Client = require('./client')\nconst util = require('../core/util')\nconst createRedirectInterceptor = require('../interceptor/redirect-interceptor')\n\nconst kOnConnect = Symbol('onConnect')\nconst kOnDisconnect = Symbol('onDisconnect')\nconst kOnConnectionError = Symbol('onConnectionError')\nconst kMaxRedirections = Symbol('maxRedirections')\nconst kOnDrain = Symbol('onDrain')\nconst kFactory = Symbol('factory')\nconst kOptions = Symbol('options')\n\nfunction defaultFactory (origin, opts) {\n return opts && opts.connections === 1\n ? new Client(origin, opts)\n : new Pool(origin, opts)\n}\n\nclass Agent extends DispatcherBase {\n constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {\n\n if (typeof factory !== 'function') {\n throw new InvalidArgumentError('factory must be a function.')\n }\n\n if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {\n throw new InvalidArgumentError('connect must be a function or an object')\n }\n\n if (!Number.isInteger(maxRedirections) || maxRedirections < 0) {\n throw new InvalidArgumentError('maxRedirections must be a positive number')\n }\n\n super(options)\n\n if (connect && typeof connect !== 'function') {\n connect = { ...connect }\n }\n\n this[kInterceptors] = options.interceptors?.Agent && Array.isArray(options.interceptors.Agent)\n ? options.interceptors.Agent\n : [createRedirectInterceptor({ maxRedirections })]\n\n this[kOptions] = { ...util.deepClone(options), connect }\n this[kOptions].interceptors = options.interceptors\n ? { ...options.interceptors }\n : undefined\n this[kMaxRedirections] = maxRedirections\n this[kFactory] = factory\n this[kClients] = new Map()\n\n this[kOnDrain] = (origin, targets) => {\n this.emit('drain', origin, [this, ...targets])\n }\n\n this[kOnConnect] = (origin, targets) => {\n this.emit('connect', origin, [this, ...targets])\n }\n\n this[kOnDisconnect] = (origin, targets, err) => {\n this.emit('disconnect', origin, [this, ...targets], err)\n }\n\n this[kOnConnectionError] = (origin, targets, err) => {\n this.emit('connectionError', origin, [this, ...targets], err)\n }\n }\n\n get [kRunning] () {\n let ret = 0\n for (const client of this[kClients].values()) {\n ret += client[kRunning]\n }\n return ret\n }\n\n [kDispatch] (opts, handler) {\n let key\n if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) {\n key = String(opts.origin)\n } else {\n throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.')\n }\n\n let dispatcher = this[kClients].get(key)\n\n if (!dispatcher) {\n dispatcher = this[kFactory](opts.origin, this[kOptions])\n .on('drain', this[kOnDrain])\n .on('connect', this[kOnConnect])\n .on('disconnect', this[kOnDisconnect])\n .on('connectionError', this[kOnConnectionError])\n\n // This introduces a tiny memory leak, as dispatchers are never removed from the map.\n // TODO(mcollina): remove te timer when the client/pool do not have any more\n // active connections.\n this[kClients].set(key, dispatcher)\n }\n\n return dispatcher.dispatch(opts, handler)\n }\n\n async [kClose] () {\n const closePromises = []\n for (const client of this[kClients].values()) {\n closePromises.push(client.close())\n }\n this[kClients].clear()\n\n await Promise.all(closePromises)\n }\n\n async [kDestroy] (err) {\n const destroyPromises = []\n for (const client of this[kClients].values()) {\n destroyPromises.push(client.destroy(err))\n }\n this[kClients].clear()\n\n await Promise.all(destroyPromises)\n }\n}\n\nmodule.exports = Agent\n","'use strict'\n\nconst { kProxy, kClose, kDestroy, kDispatch, kInterceptors } = require('../core/symbols')\nconst { URL } = require('node:url')\nconst Agent = require('./agent')\nconst Pool = require('./pool')\nconst DispatcherBase = require('./dispatcher-base')\nconst { InvalidArgumentError, RequestAbortedError, SecureProxyConnectionError } = require('../core/errors')\nconst buildConnector = require('../core/connect')\nconst Client = require('./client')\n\nconst kAgent = Symbol('proxy agent')\nconst kClient = Symbol('proxy client')\nconst kProxyHeaders = Symbol('proxy headers')\nconst kRequestTls = Symbol('request tls settings')\nconst kProxyTls = Symbol('proxy tls settings')\nconst kConnectEndpoint = Symbol('connect endpoint function')\nconst kTunnelProxy = Symbol('tunnel proxy')\n\nfunction defaultProtocolPort (protocol) {\n return protocol === 'https:' ? 443 : 80\n}\n\nfunction defaultFactory (origin, opts) {\n return new Pool(origin, opts)\n}\n\nconst noop = () => {}\n\nfunction defaultAgentFactory (origin, opts) {\n if (opts.connections === 1) {\n return new Client(origin, opts)\n }\n return new Pool(origin, opts)\n}\n\nclass Http1ProxyWrapper extends DispatcherBase {\n #client\n\n constructor (proxyUrl, { headers = {}, connect, factory }) {\n super()\n if (!proxyUrl) {\n throw new InvalidArgumentError('Proxy URL is mandatory')\n }\n\n this[kProxyHeaders] = headers\n if (factory) {\n this.#client = factory(proxyUrl, { connect })\n } else {\n this.#client = new Client(proxyUrl, { connect })\n }\n }\n\n [kDispatch] (opts, handler) {\n const onHeaders = handler.onHeaders\n handler.onHeaders = function (statusCode, data, resume) {\n if (statusCode === 407) {\n if (typeof handler.onError === 'function') {\n handler.onError(new InvalidArgumentError('Proxy Authentication Required (407)'))\n }\n return\n }\n if (onHeaders) onHeaders.call(this, statusCode, data, resume)\n }\n\n // Rewrite request as an HTTP1 Proxy request, without tunneling.\n const {\n origin,\n path = '/',\n headers = {}\n } = opts\n\n opts.path = origin + path\n\n if (!('host' in headers) && !('Host' in headers)) {\n const { host } = new URL(origin)\n headers.host = host\n }\n opts.headers = { ...this[kProxyHeaders], ...headers }\n\n return this.#client[kDispatch](opts, handler)\n }\n\n async [kClose] () {\n return this.#client.close()\n }\n\n async [kDestroy] (err) {\n return this.#client.destroy(err)\n }\n}\n\nclass ProxyAgent extends DispatcherBase {\n constructor (opts) {\n super()\n\n if (!opts || (typeof opts === 'object' && !(opts instanceof URL) && !opts.uri)) {\n throw new InvalidArgumentError('Proxy uri is mandatory')\n }\n\n const { clientFactory = defaultFactory } = opts\n if (typeof clientFactory !== 'function') {\n throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.')\n }\n\n const { proxyTunnel = true } = opts\n\n const url = this.#getUrl(opts)\n const { href, origin, port, protocol, username, password, hostname: proxyHostname } = url\n\n this[kProxy] = { uri: href, protocol }\n this[kInterceptors] = opts.interceptors?.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent)\n ? opts.interceptors.ProxyAgent\n : []\n this[kRequestTls] = opts.requestTls\n this[kProxyTls] = opts.proxyTls\n this[kProxyHeaders] = opts.headers || {}\n this[kTunnelProxy] = proxyTunnel\n\n if (opts.auth && opts.token) {\n throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token')\n } else if (opts.auth) {\n /* @deprecated in favour of opts.token */\n this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}`\n } else if (opts.token) {\n this[kProxyHeaders]['proxy-authorization'] = opts.token\n } else if (username && password) {\n this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}`\n }\n\n const connect = buildConnector({ ...opts.proxyTls })\n this[kConnectEndpoint] = buildConnector({ ...opts.requestTls })\n\n const agentFactory = opts.factory || defaultAgentFactory\n const factory = (origin, options) => {\n const { protocol } = new URL(origin)\n if (!this[kTunnelProxy] && protocol === 'http:' && this[kProxy].protocol === 'http:') {\n return new Http1ProxyWrapper(this[kProxy].uri, {\n headers: this[kProxyHeaders],\n connect,\n factory: agentFactory\n })\n }\n return agentFactory(origin, options)\n }\n this[kClient] = clientFactory(url, { connect })\n this[kAgent] = new Agent({\n ...opts,\n factory,\n connect: async (opts, callback) => {\n let requestedPath = opts.host\n if (!opts.port) {\n requestedPath += `:${defaultProtocolPort(opts.protocol)}`\n }\n try {\n const { socket, statusCode } = await this[kClient].connect({\n origin,\n port,\n path: requestedPath,\n signal: opts.signal,\n headers: {\n ...this[kProxyHeaders],\n host: opts.host\n },\n servername: this[kProxyTls]?.servername || proxyHostname\n })\n if (statusCode !== 200) {\n socket.on('error', noop).destroy()\n callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`))\n }\n if (opts.protocol !== 'https:') {\n callback(null, socket)\n return\n }\n let servername\n if (this[kRequestTls]) {\n servername = this[kRequestTls].servername\n } else {\n servername = opts.servername\n }\n this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback)\n } catch (err) {\n if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {\n // Throw a custom error to avoid loop in client.js#connect\n callback(new SecureProxyConnectionError(err))\n } else {\n callback(err)\n }\n }\n }\n })\n }\n\n dispatch (opts, handler) {\n const headers = buildHeaders(opts.headers)\n throwIfProxyAuthIsSent(headers)\n\n if (headers && !('host' in headers) && !('Host' in headers)) {\n const { host } = new URL(opts.origin)\n headers.host = host\n }\n\n return this[kAgent].dispatch(\n {\n ...opts,\n headers\n },\n handler\n )\n }\n\n /**\n * @param {import('../types/proxy-agent').ProxyAgent.Options | string | URL} opts\n * @returns {URL}\n */\n #getUrl (opts) {\n if (typeof opts === 'string') {\n return new URL(opts)\n } else if (opts instanceof URL) {\n return opts\n } else {\n return new URL(opts.uri)\n }\n }\n\n async [kClose] () {\n await this[kAgent].close()\n await this[kClient].close()\n }\n\n async [kDestroy] () {\n await this[kAgent].destroy()\n await this[kClient].destroy()\n }\n}\n\n/**\n * @param {string[] | Record} headers\n * @returns {Record}\n */\nfunction buildHeaders (headers) {\n // When using undici.fetch, the headers list is stored\n // as an array.\n if (Array.isArray(headers)) {\n /** @type {Record} */\n const headersPair = {}\n\n for (let i = 0; i < headers.length; i += 2) {\n headersPair[headers[i]] = headers[i + 1]\n }\n\n return headersPair\n }\n\n return headers\n}\n\n/**\n * @param {Record} headers\n *\n * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers\n * Nevertheless, it was changed and to avoid a security vulnerability by end users\n * this check was created.\n * It should be removed in the next major version for performance reasons\n */\nfunction throwIfProxyAuthIsSent (headers) {\n const existProxyAuth = headers && Object.keys(headers)\n .find((key) => key.toLowerCase() === 'proxy-authorization')\n if (existProxyAuth) {\n throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor')\n }\n}\n\nmodule.exports = ProxyAgent\n","'use strict'\n\nconst DispatcherBase = require('./dispatcher-base')\nconst { kClose, kDestroy, kClosed, kDestroyed, kDispatch, kNoProxyAgent, kHttpProxyAgent, kHttpsProxyAgent } = require('../core/symbols')\nconst ProxyAgent = require('./proxy-agent')\nconst Agent = require('./agent')\n\nconst DEFAULT_PORTS = {\n 'http:': 80,\n 'https:': 443\n}\n\nlet experimentalWarned = false\n\nclass EnvHttpProxyAgent extends DispatcherBase {\n #noProxyValue = null\n #noProxyEntries = null\n #opts = null\n\n constructor (opts = {}) {\n super()\n this.#opts = opts\n\n if (!experimentalWarned) {\n experimentalWarned = true\n process.emitWarning('EnvHttpProxyAgent is experimental, expect them to change at any time.', {\n code: 'UNDICI-EHPA'\n })\n }\n\n const { httpProxy, httpsProxy, noProxy, ...agentOpts } = opts\n\n this[kNoProxyAgent] = new Agent(agentOpts)\n\n const HTTP_PROXY = httpProxy ?? process.env.http_proxy ?? process.env.HTTP_PROXY\n if (HTTP_PROXY) {\n this[kHttpProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTP_PROXY })\n } else {\n this[kHttpProxyAgent] = this[kNoProxyAgent]\n }\n\n const HTTPS_PROXY = httpsProxy ?? process.env.https_proxy ?? process.env.HTTPS_PROXY\n if (HTTPS_PROXY) {\n this[kHttpsProxyAgent] = new ProxyAgent({ ...agentOpts, uri: HTTPS_PROXY })\n } else {\n this[kHttpsProxyAgent] = this[kHttpProxyAgent]\n }\n\n this.#parseNoProxy()\n }\n\n [kDispatch] (opts, handler) {\n const url = new URL(opts.origin)\n const agent = this.#getProxyAgentForUrl(url)\n return agent.dispatch(opts, handler)\n }\n\n async [kClose] () {\n await this[kNoProxyAgent].close()\n if (!this[kHttpProxyAgent][kClosed]) {\n await this[kHttpProxyAgent].close()\n }\n if (!this[kHttpsProxyAgent][kClosed]) {\n await this[kHttpsProxyAgent].close()\n }\n }\n\n async [kDestroy] (err) {\n await this[kNoProxyAgent].destroy(err)\n if (!this[kHttpProxyAgent][kDestroyed]) {\n await this[kHttpProxyAgent].destroy(err)\n }\n if (!this[kHttpsProxyAgent][kDestroyed]) {\n await this[kHttpsProxyAgent].destroy(err)\n }\n }\n\n #getProxyAgentForUrl (url) {\n let { protocol, host: hostname, port } = url\n\n // Stripping ports in this way instead of using parsedUrl.hostname to make\n // sure that the brackets around IPv6 addresses are kept.\n hostname = hostname.replace(/:\\d*$/, '').toLowerCase()\n port = Number.parseInt(port, 10) || DEFAULT_PORTS[protocol] || 0\n if (!this.#shouldProxy(hostname, port)) {\n return this[kNoProxyAgent]\n }\n if (protocol === 'https:') {\n return this[kHttpsProxyAgent]\n }\n return this[kHttpProxyAgent]\n }\n\n #shouldProxy (hostname, port) {\n if (this.#noProxyChanged) {\n this.#parseNoProxy()\n }\n\n if (this.#noProxyEntries.length === 0) {\n return true // Always proxy if NO_PROXY is not set or empty.\n }\n if (this.#noProxyValue === '*') {\n return false // Never proxy if wildcard is set.\n }\n\n for (let i = 0; i < this.#noProxyEntries.length; i++) {\n const entry = this.#noProxyEntries[i]\n if (entry.port && entry.port !== port) {\n continue // Skip if ports don't match.\n }\n if (!/^[.*]/.test(entry.hostname)) {\n // No wildcards, so don't proxy only if there is not an exact match.\n if (hostname === entry.hostname) {\n return false\n }\n } else {\n // Don't proxy if the hostname ends with the no_proxy host.\n if (hostname.endsWith(entry.hostname.replace(/^\\*/, ''))) {\n return false\n }\n }\n }\n\n return true\n }\n\n #parseNoProxy () {\n const noProxyValue = this.#opts.noProxy ?? this.#noProxyEnv\n const noProxySplit = noProxyValue.split(/[,\\s]/)\n const noProxyEntries = []\n\n for (let i = 0; i < noProxySplit.length; i++) {\n const entry = noProxySplit[i]\n if (!entry) {\n continue\n }\n const parsed = entry.match(/^(.+):(\\d+)$/)\n noProxyEntries.push({\n hostname: (parsed ? parsed[1] : entry).toLowerCase(),\n port: parsed ? Number.parseInt(parsed[2], 10) : 0\n })\n }\n\n this.#noProxyValue = noProxyValue\n this.#noProxyEntries = noProxyEntries\n }\n\n get #noProxyChanged () {\n if (this.#opts.noProxy !== undefined) {\n return false\n }\n return this.#noProxyValue !== this.#noProxyEnv\n }\n\n get #noProxyEnv () {\n return process.env.no_proxy ?? process.env.NO_PROXY ?? ''\n }\n}\n\nmodule.exports = EnvHttpProxyAgent\n","'use strict'\nconst assert = require('node:assert')\n\nconst { kRetryHandlerDefaultRetry } = require('../core/symbols')\nconst { RequestRetryError } = require('../core/errors')\nconst {\n isDisturbed,\n parseHeaders,\n parseRangeHeader,\n wrapRequestBody\n} = require('../core/util')\n\nfunction calculateRetryAfterHeader (retryAfter) {\n const current = Date.now()\n return new Date(retryAfter).getTime() - current\n}\n\nclass RetryHandler {\n constructor (opts, handlers) {\n const { retryOptions, ...dispatchOpts } = opts\n const {\n // Retry scoped\n retry: retryFn,\n maxRetries,\n maxTimeout,\n minTimeout,\n timeoutFactor,\n // Response scoped\n methods,\n errorCodes,\n retryAfter,\n statusCodes\n } = retryOptions ?? {}\n\n this.dispatch = handlers.dispatch\n this.handler = handlers.handler\n this.opts = { ...dispatchOpts, body: wrapRequestBody(opts.body) }\n this.abort = null\n this.aborted = false\n this.retryOpts = {\n retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry],\n retryAfter: retryAfter ?? true,\n maxTimeout: maxTimeout ?? 30 * 1000, // 30s,\n minTimeout: minTimeout ?? 500, // .5s\n timeoutFactor: timeoutFactor ?? 2,\n maxRetries: maxRetries ?? 5,\n // What errors we should retry\n methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'],\n // Indicates which errors to retry\n statusCodes: statusCodes ?? [500, 502, 503, 504, 429],\n // List of errors to retry\n errorCodes: errorCodes ?? [\n 'ECONNRESET',\n 'ECONNREFUSED',\n 'ENOTFOUND',\n 'ENETDOWN',\n 'ENETUNREACH',\n 'EHOSTDOWN',\n 'EHOSTUNREACH',\n 'EPIPE',\n 'UND_ERR_SOCKET'\n ]\n }\n\n this.retryCount = 0\n this.retryCountCheckpoint = 0\n this.start = 0\n this.end = null\n this.etag = null\n this.resume = null\n\n // Handle possible onConnect duplication\n this.handler.onConnect(reason => {\n this.aborted = true\n if (this.abort) {\n this.abort(reason)\n } else {\n this.reason = reason\n }\n })\n }\n\n onRequestSent () {\n if (this.handler.onRequestSent) {\n this.handler.onRequestSent()\n }\n }\n\n onUpgrade (statusCode, headers, socket) {\n if (this.handler.onUpgrade) {\n this.handler.onUpgrade(statusCode, headers, socket)\n }\n }\n\n onConnect (abort) {\n if (this.aborted) {\n abort(this.reason)\n } else {\n this.abort = abort\n }\n }\n\n onBodySent (chunk) {\n if (this.handler.onBodySent) return this.handler.onBodySent(chunk)\n }\n\n static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) {\n const { statusCode, code, headers } = err\n const { method, retryOptions } = opts\n const {\n maxRetries,\n minTimeout,\n maxTimeout,\n timeoutFactor,\n statusCodes,\n errorCodes,\n methods\n } = retryOptions\n const { counter } = state\n\n // Any code that is not a Undici's originated and allowed to retry\n if (code && code !== 'UND_ERR_REQ_RETRY' && !errorCodes.includes(code)) {\n cb(err)\n return\n }\n\n // If a set of method are provided and the current method is not in the list\n if (Array.isArray(methods) && !methods.includes(method)) {\n cb(err)\n return\n }\n\n // If a set of status code are provided and the current status code is not in the list\n if (\n statusCode != null &&\n Array.isArray(statusCodes) &&\n !statusCodes.includes(statusCode)\n ) {\n cb(err)\n return\n }\n\n // If we reached the max number of retries\n if (counter > maxRetries) {\n cb(err)\n return\n }\n\n let retryAfterHeader = headers?.['retry-after']\n if (retryAfterHeader) {\n retryAfterHeader = Number(retryAfterHeader)\n retryAfterHeader = Number.isNaN(retryAfterHeader)\n ? calculateRetryAfterHeader(retryAfterHeader)\n : retryAfterHeader * 1e3 // Retry-After is in seconds\n }\n\n const retryTimeout =\n retryAfterHeader > 0\n ? Math.min(retryAfterHeader, maxTimeout)\n : Math.min(minTimeout * timeoutFactor ** (counter - 1), maxTimeout)\n\n setTimeout(() => cb(null), retryTimeout)\n }\n\n onHeaders (statusCode, rawHeaders, resume, statusMessage) {\n const headers = parseHeaders(rawHeaders)\n\n this.retryCount += 1\n\n if (statusCode >= 300) {\n if (this.retryOpts.statusCodes.includes(statusCode) === false) {\n return this.handler.onHeaders(\n statusCode,\n rawHeaders,\n resume,\n statusMessage\n )\n } else {\n this.abort(\n new RequestRetryError('Request failed', statusCode, {\n headers,\n data: {\n count: this.retryCount\n }\n })\n )\n return false\n }\n }\n\n // Checkpoint for resume from where we left it\n if (this.resume != null) {\n this.resume = null\n\n // Only Partial Content 206 supposed to provide Content-Range,\n // any other status code that partially consumed the payload\n // should not be retry because it would result in downstream\n // wrongly concatanete multiple responses.\n if (statusCode !== 206 && (this.start > 0 || statusCode !== 200)) {\n this.abort(\n new RequestRetryError('server does not support the range header and the payload was partially consumed', statusCode, {\n headers,\n data: { count: this.retryCount }\n })\n )\n return false\n }\n\n const contentRange = parseRangeHeader(headers['content-range'])\n // If no content range\n if (!contentRange) {\n this.abort(\n new RequestRetryError('Content-Range mismatch', statusCode, {\n headers,\n data: { count: this.retryCount }\n })\n )\n return false\n }\n\n // Let's start with a weak etag check\n if (this.etag != null && this.etag !== headers.etag) {\n this.abort(\n new RequestRetryError('ETag mismatch', statusCode, {\n headers,\n data: { count: this.retryCount }\n })\n )\n return false\n }\n\n const { start, size, end = size - 1 } = contentRange\n\n assert(this.start === start, 'content-range mismatch')\n assert(this.end == null || this.end === end, 'content-range mismatch')\n\n this.resume = resume\n return true\n }\n\n if (this.end == null) {\n if (statusCode === 206) {\n // First time we receive 206\n const range = parseRangeHeader(headers['content-range'])\n\n if (range == null) {\n return this.handler.onHeaders(\n statusCode,\n rawHeaders,\n resume,\n statusMessage\n )\n }\n\n const { start, size, end = size - 1 } = range\n assert(\n start != null && Number.isFinite(start),\n 'content-range mismatch'\n )\n assert(end != null && Number.isFinite(end), 'invalid content-length')\n\n this.start = start\n this.end = end\n }\n\n // We make our best to checkpoint the body for further range headers\n if (this.end == null) {\n const contentLength = headers['content-length']\n this.end = contentLength != null ? Number(contentLength) - 1 : null\n }\n\n assert(Number.isFinite(this.start))\n assert(\n this.end == null || Number.isFinite(this.end),\n 'invalid content-length'\n )\n\n this.resume = resume\n this.etag = headers.etag != null ? headers.etag : null\n\n // Weak etags are not useful for comparison nor cache\n // for instance not safe to assume if the response is byte-per-byte\n // equal\n if (this.etag != null && this.etag.startsWith('W/')) {\n this.etag = null\n }\n\n return this.handler.onHeaders(\n statusCode,\n rawHeaders,\n resume,\n statusMessage\n )\n }\n\n const err = new RequestRetryError('Request failed', statusCode, {\n headers,\n data: { count: this.retryCount }\n })\n\n this.abort(err)\n\n return false\n }\n\n onData (chunk) {\n this.start += chunk.length\n\n return this.handler.onData(chunk)\n }\n\n onComplete (rawTrailers) {\n this.retryCount = 0\n return this.handler.onComplete(rawTrailers)\n }\n\n onError (err) {\n if (this.aborted || isDisturbed(this.opts.body)) {\n return this.handler.onError(err)\n }\n\n // We reconcile in case of a mix between network errors\n // and server error response\n if (this.retryCount - this.retryCountCheckpoint > 0) {\n // We count the difference between the last checkpoint and the current retry count\n this.retryCount =\n this.retryCountCheckpoint +\n (this.retryCount - this.retryCountCheckpoint)\n } else {\n this.retryCount += 1\n }\n\n this.retryOpts.retry(\n err,\n {\n state: { counter: this.retryCount },\n opts: { retryOptions: this.retryOpts, ...this.opts }\n },\n onRetry.bind(this)\n )\n\n function onRetry (err) {\n if (err != null || this.aborted || isDisturbed(this.opts.body)) {\n return this.handler.onError(err)\n }\n\n if (this.start !== 0) {\n const headers = { range: `bytes=${this.start}-${this.end ?? ''}` }\n\n // Weak etag check - weak etags will make comparison algorithms never match\n if (this.etag != null) {\n headers['if-match'] = this.etag\n }\n\n this.opts = {\n ...this.opts,\n headers: {\n ...this.opts.headers,\n ...headers\n }\n }\n }\n\n try {\n this.retryCountCheckpoint = this.retryCount\n this.dispatch(this.opts, this)\n } catch (err) {\n this.handler.onError(err)\n }\n }\n }\n}\n\nmodule.exports = RetryHandler\n","'use strict'\n\nconst Dispatcher = require('./dispatcher')\nconst RetryHandler = require('../handler/retry-handler')\n\nclass RetryAgent extends Dispatcher {\n #agent = null\n #options = null\n constructor (agent, options = {}) {\n super(options)\n this.#agent = agent\n this.#options = options\n }\n\n dispatch (opts, handler) {\n const retry = new RetryHandler({\n ...opts,\n retryOptions: this.#options\n }, {\n dispatch: this.#agent.dispatch.bind(this.#agent),\n handler\n })\n return this.#agent.dispatch(opts, retry)\n }\n\n close () {\n return this.#agent.close()\n }\n\n destroy () {\n return this.#agent.destroy()\n }\n}\n\nmodule.exports = RetryAgent\n","// Ported from https://github.com/nodejs/undici/pull/907\n\n'use strict'\n\nconst assert = require('node:assert')\nconst { Readable } = require('node:stream')\nconst { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = require('../core/errors')\nconst util = require('../core/util')\nconst { ReadableStreamFrom } = require('../core/util')\n\nconst kConsume = Symbol('kConsume')\nconst kReading = Symbol('kReading')\nconst kBody = Symbol('kBody')\nconst kAbort = Symbol('kAbort')\nconst kContentType = Symbol('kContentType')\nconst kContentLength = Symbol('kContentLength')\n\nconst noop = () => {}\n\nclass BodyReadable extends Readable {\n constructor ({\n resume,\n abort,\n contentType = '',\n contentLength,\n highWaterMark = 64 * 1024 // Same as nodejs fs streams.\n }) {\n super({\n autoDestroy: true,\n read: resume,\n highWaterMark\n })\n\n this._readableState.dataEmitted = false\n\n this[kAbort] = abort\n this[kConsume] = null\n this[kBody] = null\n this[kContentType] = contentType\n this[kContentLength] = contentLength\n\n // Is stream being consumed through Readable API?\n // This is an optimization so that we avoid checking\n // for 'data' and 'readable' listeners in the hot path\n // inside push().\n this[kReading] = false\n }\n\n destroy (err) {\n if (!err && !this._readableState.endEmitted) {\n err = new RequestAbortedError()\n }\n\n if (err) {\n this[kAbort]()\n }\n\n return super.destroy(err)\n }\n\n _destroy (err, callback) {\n // Workaround for Node \"bug\". If the stream is destroyed in same\n // tick as it is created, then a user who is waiting for a\n // promise (i.e micro tick) for installing a 'error' listener will\n // never get a chance and will always encounter an unhandled exception.\n if (!this[kReading]) {\n setImmediate(() => {\n callback(err)\n })\n } else {\n callback(err)\n }\n }\n\n on (ev, ...args) {\n if (ev === 'data' || ev === 'readable') {\n this[kReading] = true\n }\n return super.on(ev, ...args)\n }\n\n addListener (ev, ...args) {\n return this.on(ev, ...args)\n }\n\n off (ev, ...args) {\n const ret = super.off(ev, ...args)\n if (ev === 'data' || ev === 'readable') {\n this[kReading] = (\n this.listenerCount('data') > 0 ||\n this.listenerCount('readable') > 0\n )\n }\n return ret\n }\n\n removeListener (ev, ...args) {\n return this.off(ev, ...args)\n }\n\n push (chunk) {\n if (this[kConsume] && chunk !== null) {\n consumePush(this[kConsume], chunk)\n return this[kReading] ? super.push(chunk) : true\n }\n return super.push(chunk)\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-text\n async text () {\n return consume(this, 'text')\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-json\n async json () {\n return consume(this, 'json')\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-blob\n async blob () {\n return consume(this, 'blob')\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-bytes\n async bytes () {\n return consume(this, 'bytes')\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-arraybuffer\n async arrayBuffer () {\n return consume(this, 'arrayBuffer')\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-formdata\n async formData () {\n // TODO: Implement.\n throw new NotSupportedError()\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-bodyused\n get bodyUsed () {\n return util.isDisturbed(this)\n }\n\n // https://fetch.spec.whatwg.org/#dom-body-body\n get body () {\n if (!this[kBody]) {\n this[kBody] = ReadableStreamFrom(this)\n if (this[kConsume]) {\n // TODO: Is this the best way to force a lock?\n this[kBody].getReader() // Ensure stream is locked.\n assert(this[kBody].locked)\n }\n }\n return this[kBody]\n }\n\n async dump (opts) {\n let limit = Number.isFinite(opts?.limit) ? opts.limit : 128 * 1024\n const signal = opts?.signal\n\n if (signal != null && (typeof signal !== 'object' || !('aborted' in signal))) {\n throw new InvalidArgumentError('signal must be an AbortSignal')\n }\n\n signal?.throwIfAborted()\n\n if (this._readableState.closeEmitted) {\n return null\n }\n\n return await new Promise((resolve, reject) => {\n if (this[kContentLength] > limit) {\n this.destroy(new AbortError())\n }\n\n const onAbort = () => {\n this.destroy(signal.reason ?? new AbortError())\n }\n signal?.addEventListener('abort', onAbort)\n\n this\n .on('close', function () {\n signal?.removeEventListener('abort', onAbort)\n if (signal?.aborted) {\n reject(signal.reason ?? new AbortError())\n } else {\n resolve(null)\n }\n })\n .on('error', noop)\n .on('data', function (chunk) {\n limit -= chunk.length\n if (limit <= 0) {\n this.destroy()\n }\n })\n .resume()\n })\n }\n}\n\n// https://streams.spec.whatwg.org/#readablestream-locked\nfunction isLocked (self) {\n // Consume is an implicit lock.\n return (self[kBody] && self[kBody].locked === true) || self[kConsume]\n}\n\n// https://fetch.spec.whatwg.org/#body-unusable\nfunction isUnusable (self) {\n return util.isDisturbed(self) || isLocked(self)\n}\n\nasync function consume (stream, type) {\n assert(!stream[kConsume])\n\n return new Promise((resolve, reject) => {\n if (isUnusable(stream)) {\n const rState = stream._readableState\n if (rState.destroyed && rState.closeEmitted === false) {\n stream\n .on('error', err => {\n reject(err)\n })\n .on('close', () => {\n reject(new TypeError('unusable'))\n })\n } else {\n reject(rState.errored ?? new TypeError('unusable'))\n }\n } else {\n queueMicrotask(() => {\n stream[kConsume] = {\n type,\n stream,\n resolve,\n reject,\n length: 0,\n body: []\n }\n\n stream\n .on('error', function (err) {\n consumeFinish(this[kConsume], err)\n })\n .on('close', function () {\n if (this[kConsume].body !== null) {\n consumeFinish(this[kConsume], new RequestAbortedError())\n }\n })\n\n consumeStart(stream[kConsume])\n })\n }\n })\n}\n\nfunction consumeStart (consume) {\n if (consume.body === null) {\n return\n }\n\n const { _readableState: state } = consume.stream\n\n if (state.bufferIndex) {\n const start = state.bufferIndex\n const end = state.buffer.length\n for (let n = start; n < end; n++) {\n consumePush(consume, state.buffer[n])\n }\n } else {\n for (const chunk of state.buffer) {\n consumePush(consume, chunk)\n }\n }\n\n if (state.endEmitted) {\n consumeEnd(this[kConsume])\n } else {\n consume.stream.on('end', function () {\n consumeEnd(this[kConsume])\n })\n }\n\n consume.stream.resume()\n\n while (consume.stream.read() != null) {\n // Loop\n }\n}\n\n/**\n * @param {Buffer[]} chunks\n * @param {number} length\n */\nfunction chunksDecode (chunks, length) {\n if (chunks.length === 0 || length === 0) {\n return ''\n }\n const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks, length)\n const bufferLength = buffer.length\n\n // Skip BOM.\n const start =\n bufferLength > 2 &&\n buffer[0] === 0xef &&\n buffer[1] === 0xbb &&\n buffer[2] === 0xbf\n ? 3\n : 0\n return buffer.utf8Slice(start, bufferLength)\n}\n\n/**\n * @param {Buffer[]} chunks\n * @param {number} length\n * @returns {Uint8Array}\n */\nfunction chunksConcat (chunks, length) {\n if (chunks.length === 0 || length === 0) {\n return new Uint8Array(0)\n }\n if (chunks.length === 1) {\n // fast-path\n return new Uint8Array(chunks[0])\n }\n const buffer = new Uint8Array(Buffer.allocUnsafeSlow(length).buffer)\n\n let offset = 0\n for (let i = 0; i < chunks.length; ++i) {\n const chunk = chunks[i]\n buffer.set(chunk, offset)\n offset += chunk.length\n }\n\n return buffer\n}\n\nfunction consumeEnd (consume) {\n const { type, body, resolve, stream, length } = consume\n\n try {\n if (type === 'text') {\n resolve(chunksDecode(body, length))\n } else if (type === 'json') {\n resolve(JSON.parse(chunksDecode(body, length)))\n } else if (type === 'arrayBuffer') {\n resolve(chunksConcat(body, length).buffer)\n } else if (type === 'blob') {\n resolve(new Blob(body, { type: stream[kContentType] }))\n } else if (type === 'bytes') {\n resolve(chunksConcat(body, length))\n }\n\n consumeFinish(consume)\n } catch (err) {\n stream.destroy(err)\n }\n}\n\nfunction consumePush (consume, chunk) {\n consume.length += chunk.length\n consume.body.push(chunk)\n}\n\nfunction consumeFinish (consume, err) {\n if (consume.body === null) {\n return\n }\n\n if (err) {\n consume.reject(err)\n } else {\n consume.resolve()\n }\n\n consume.type = null\n consume.stream = null\n consume.resolve = null\n consume.reject = null\n consume.length = 0\n consume.body = null\n}\n\nmodule.exports = { Readable: BodyReadable, chunksDecode }\n","const assert = require('node:assert')\nconst {\n ResponseStatusCodeError\n} = require('../core/errors')\n\nconst { chunksDecode } = require('./readable')\nconst CHUNK_LIMIT = 128 * 1024\n\nasync function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) {\n assert(body)\n\n let chunks = []\n let length = 0\n\n try {\n for await (const chunk of body) {\n chunks.push(chunk)\n length += chunk.length\n if (length > CHUNK_LIMIT) {\n chunks = []\n length = 0\n break\n }\n }\n } catch {\n chunks = []\n length = 0\n // Do nothing....\n }\n\n const message = `Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`\n\n if (statusCode === 204 || !contentType || !length) {\n queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers)))\n return\n }\n\n const stackTraceLimit = Error.stackTraceLimit\n Error.stackTraceLimit = 0\n let payload\n\n try {\n if (isContentTypeApplicationJson(contentType)) {\n payload = JSON.parse(chunksDecode(chunks, length))\n } else if (isContentTypeText(contentType)) {\n payload = chunksDecode(chunks, length)\n }\n } catch {\n // process in a callback to avoid throwing in the microtask queue\n } finally {\n Error.stackTraceLimit = stackTraceLimit\n }\n queueMicrotask(() => callback(new ResponseStatusCodeError(message, statusCode, headers, payload)))\n}\n\nconst isContentTypeApplicationJson = (contentType) => {\n return (\n contentType.length > 15 &&\n contentType[11] === '/' &&\n contentType[0] === 'a' &&\n contentType[1] === 'p' &&\n contentType[2] === 'p' &&\n contentType[3] === 'l' &&\n contentType[4] === 'i' &&\n contentType[5] === 'c' &&\n contentType[6] === 'a' &&\n contentType[7] === 't' &&\n contentType[8] === 'i' &&\n contentType[9] === 'o' &&\n contentType[10] === 'n' &&\n contentType[12] === 'j' &&\n contentType[13] === 's' &&\n contentType[14] === 'o' &&\n contentType[15] === 'n'\n )\n}\n\nconst isContentTypeText = (contentType) => {\n return (\n contentType.length > 4 &&\n contentType[4] === '/' &&\n contentType[0] === 't' &&\n contentType[1] === 'e' &&\n contentType[2] === 'x' &&\n contentType[3] === 't'\n )\n}\n\nmodule.exports = {\n getResolveErrorBodyCallback,\n isContentTypeApplicationJson,\n isContentTypeText\n}\n","'use strict'\n\nconst assert = require('node:assert')\nconst { Readable } = require('./readable')\nconst { InvalidArgumentError, RequestAbortedError } = require('../core/errors')\nconst util = require('../core/util')\nconst { getResolveErrorBodyCallback } = require('./util')\nconst { AsyncResource } = require('node:async_hooks')\n\nclass RequestHandler extends AsyncResource {\n constructor (opts, callback) {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts\n\n try {\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) {\n throw new InvalidArgumentError('invalid highWaterMark')\n }\n\n if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {\n throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')\n }\n\n if (method === 'CONNECT') {\n throw new InvalidArgumentError('invalid method')\n }\n\n if (onInfo && typeof onInfo !== 'function') {\n throw new InvalidArgumentError('invalid onInfo callback')\n }\n\n super('UNDICI_REQUEST')\n } catch (err) {\n if (util.isStream(body)) {\n util.destroy(body.on('error', util.nop), err)\n }\n throw err\n }\n\n this.method = method\n this.responseHeaders = responseHeaders || null\n this.opaque = opaque || null\n this.callback = callback\n this.res = null\n this.abort = null\n this.body = body\n this.trailers = {}\n this.context = null\n this.onInfo = onInfo || null\n this.throwOnError = throwOnError\n this.highWaterMark = highWaterMark\n this.signal = signal\n this.reason = null\n this.removeAbortListener = null\n\n if (util.isStream(body)) {\n body.on('error', (err) => {\n this.onError(err)\n })\n }\n\n if (this.signal) {\n if (this.signal.aborted) {\n this.reason = this.signal.reason ?? new RequestAbortedError()\n } else {\n this.removeAbortListener = util.addAbortListener(this.signal, () => {\n this.reason = this.signal.reason ?? new RequestAbortedError()\n if (this.res) {\n util.destroy(this.res.on('error', util.nop), this.reason)\n } else if (this.abort) {\n this.abort(this.reason)\n }\n\n if (this.removeAbortListener) {\n this.res?.off('close', this.removeAbortListener)\n this.removeAbortListener()\n this.removeAbortListener = null\n }\n })\n }\n }\n }\n\n onConnect (abort, context) {\n if (this.reason) {\n abort(this.reason)\n return\n }\n\n assert(this.callback)\n\n this.abort = abort\n this.context = context\n }\n\n onHeaders (statusCode, rawHeaders, resume, statusMessage) {\n const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this\n\n const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n\n if (statusCode < 200) {\n if (this.onInfo) {\n this.onInfo({ statusCode, headers })\n }\n return\n }\n\n const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers\n const contentType = parsedHeaders['content-type']\n const contentLength = parsedHeaders['content-length']\n const res = new Readable({\n resume,\n abort,\n contentType,\n contentLength: this.method !== 'HEAD' && contentLength\n ? Number(contentLength)\n : null,\n highWaterMark\n })\n\n if (this.removeAbortListener) {\n res.on('close', this.removeAbortListener)\n }\n\n this.callback = null\n this.res = res\n if (callback !== null) {\n if (this.throwOnError && statusCode >= 400) {\n this.runInAsyncScope(getResolveErrorBodyCallback, null,\n { callback, body: res, contentType, statusCode, statusMessage, headers }\n )\n } else {\n this.runInAsyncScope(callback, null, null, {\n statusCode,\n headers,\n trailers: this.trailers,\n opaque,\n body: res,\n context\n })\n }\n }\n }\n\n onData (chunk) {\n return this.res.push(chunk)\n }\n\n onComplete (trailers) {\n util.parseHeaders(trailers, this.trailers)\n this.res.push(null)\n }\n\n onError (err) {\n const { res, callback, body, opaque } = this\n\n if (callback) {\n // TODO: Does this need queueMicrotask?\n this.callback = null\n queueMicrotask(() => {\n this.runInAsyncScope(callback, null, err, { opaque })\n })\n }\n\n if (res) {\n this.res = null\n // Ensure all queued handlers are invoked before destroying res.\n queueMicrotask(() => {\n util.destroy(res, err)\n })\n }\n\n if (body) {\n this.body = null\n util.destroy(body, err)\n }\n\n if (this.removeAbortListener) {\n res?.off('close', this.removeAbortListener)\n this.removeAbortListener()\n this.removeAbortListener = null\n }\n }\n}\n\nfunction request (opts, callback) {\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n request.call(this, opts, (err, data) => {\n return err ? reject(err) : resolve(data)\n })\n })\n }\n\n try {\n this.dispatch(opts, new RequestHandler(opts, callback))\n } catch (err) {\n if (typeof callback !== 'function') {\n throw err\n }\n const opaque = opts?.opaque\n queueMicrotask(() => callback(err, { opaque }))\n }\n}\n\nmodule.exports = request\nmodule.exports.RequestHandler = RequestHandler\n","const { addAbortListener } = require('../core/util')\nconst { RequestAbortedError } = require('../core/errors')\n\nconst kListener = Symbol('kListener')\nconst kSignal = Symbol('kSignal')\n\nfunction abort (self) {\n if (self.abort) {\n self.abort(self[kSignal]?.reason)\n } else {\n self.reason = self[kSignal]?.reason ?? new RequestAbortedError()\n }\n removeSignal(self)\n}\n\nfunction addSignal (self, signal) {\n self.reason = null\n\n self[kSignal] = null\n self[kListener] = null\n\n if (!signal) {\n return\n }\n\n if (signal.aborted) {\n abort(self)\n return\n }\n\n self[kSignal] = signal\n self[kListener] = () => {\n abort(self)\n }\n\n addAbortListener(self[kSignal], self[kListener])\n}\n\nfunction removeSignal (self) {\n if (!self[kSignal]) {\n return\n }\n\n if ('removeEventListener' in self[kSignal]) {\n self[kSignal].removeEventListener('abort', self[kListener])\n } else {\n self[kSignal].removeListener('abort', self[kListener])\n }\n\n self[kSignal] = null\n self[kListener] = null\n}\n\nmodule.exports = {\n addSignal,\n removeSignal\n}\n","'use strict'\n\nconst assert = require('node:assert')\nconst { finished, PassThrough } = require('node:stream')\nconst { InvalidArgumentError, InvalidReturnValueError } = require('../core/errors')\nconst util = require('../core/util')\nconst { getResolveErrorBodyCallback } = require('./util')\nconst { AsyncResource } = require('node:async_hooks')\nconst { addSignal, removeSignal } = require('./abort-signal')\n\nclass StreamHandler extends AsyncResource {\n constructor (opts, factory, callback) {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts\n\n try {\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n if (typeof factory !== 'function') {\n throw new InvalidArgumentError('invalid factory')\n }\n\n if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {\n throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')\n }\n\n if (method === 'CONNECT') {\n throw new InvalidArgumentError('invalid method')\n }\n\n if (onInfo && typeof onInfo !== 'function') {\n throw new InvalidArgumentError('invalid onInfo callback')\n }\n\n super('UNDICI_STREAM')\n } catch (err) {\n if (util.isStream(body)) {\n util.destroy(body.on('error', util.nop), err)\n }\n throw err\n }\n\n this.responseHeaders = responseHeaders || null\n this.opaque = opaque || null\n this.factory = factory\n this.callback = callback\n this.res = null\n this.abort = null\n this.context = null\n this.trailers = null\n this.body = body\n this.onInfo = onInfo || null\n this.throwOnError = throwOnError || false\n\n if (util.isStream(body)) {\n body.on('error', (err) => {\n this.onError(err)\n })\n }\n\n addSignal(this, signal)\n }\n\n onConnect (abort, context) {\n if (this.reason) {\n abort(this.reason)\n return\n }\n\n assert(this.callback)\n\n this.abort = abort\n this.context = context\n }\n\n onHeaders (statusCode, rawHeaders, resume, statusMessage) {\n const { factory, opaque, context, callback, responseHeaders } = this\n\n const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n\n if (statusCode < 200) {\n if (this.onInfo) {\n this.onInfo({ statusCode, headers })\n }\n return\n }\n\n this.factory = null\n\n let res\n\n if (this.throwOnError && statusCode >= 400) {\n const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers\n const contentType = parsedHeaders['content-type']\n res = new PassThrough()\n\n this.callback = null\n this.runInAsyncScope(getResolveErrorBodyCallback, null,\n { callback, body: res, contentType, statusCode, statusMessage, headers }\n )\n } else {\n if (factory === null) {\n return\n }\n\n res = this.runInAsyncScope(factory, null, {\n statusCode,\n headers,\n opaque,\n context\n })\n\n if (\n !res ||\n typeof res.write !== 'function' ||\n typeof res.end !== 'function' ||\n typeof res.on !== 'function'\n ) {\n throw new InvalidReturnValueError('expected Writable')\n }\n\n // TODO: Avoid finished. It registers an unnecessary amount of listeners.\n finished(res, { readable: false }, (err) => {\n const { callback, res, opaque, trailers, abort } = this\n\n this.res = null\n if (err || !res.readable) {\n util.destroy(res, err)\n }\n\n this.callback = null\n this.runInAsyncScope(callback, null, err || null, { opaque, trailers })\n\n if (err) {\n abort()\n }\n })\n }\n\n res.on('drain', resume)\n\n this.res = res\n\n const needDrain = res.writableNeedDrain !== undefined\n ? res.writableNeedDrain\n : res._writableState?.needDrain\n\n return needDrain !== true\n }\n\n onData (chunk) {\n const { res } = this\n\n return res ? res.write(chunk) : true\n }\n\n onComplete (trailers) {\n const { res } = this\n\n removeSignal(this)\n\n if (!res) {\n return\n }\n\n this.trailers = util.parseHeaders(trailers)\n\n res.end()\n }\n\n onError (err) {\n const { res, callback, opaque, body } = this\n\n removeSignal(this)\n\n this.factory = null\n\n if (res) {\n this.res = null\n util.destroy(res, err)\n } else if (callback) {\n this.callback = null\n queueMicrotask(() => {\n this.runInAsyncScope(callback, null, err, { opaque })\n })\n }\n\n if (body) {\n this.body = null\n util.destroy(body, err)\n }\n }\n}\n\nfunction stream (opts, factory, callback) {\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n stream.call(this, opts, factory, (err, data) => {\n return err ? reject(err) : resolve(data)\n })\n })\n }\n\n try {\n this.dispatch(opts, new StreamHandler(opts, factory, callback))\n } catch (err) {\n if (typeof callback !== 'function') {\n throw err\n }\n const opaque = opts?.opaque\n queueMicrotask(() => callback(err, { opaque }))\n }\n}\n\nmodule.exports = stream\n","'use strict'\n\nconst {\n Readable,\n Duplex,\n PassThrough\n} = require('node:stream')\nconst {\n InvalidArgumentError,\n InvalidReturnValueError,\n RequestAbortedError\n} = require('../core/errors')\nconst util = require('../core/util')\nconst { AsyncResource } = require('node:async_hooks')\nconst { addSignal, removeSignal } = require('./abort-signal')\nconst assert = require('node:assert')\n\nconst kResume = Symbol('resume')\n\nclass PipelineRequest extends Readable {\n constructor () {\n super({ autoDestroy: true })\n\n this[kResume] = null\n }\n\n _read () {\n const { [kResume]: resume } = this\n\n if (resume) {\n this[kResume] = null\n resume()\n }\n }\n\n _destroy (err, callback) {\n this._read()\n\n callback(err)\n }\n}\n\nclass PipelineResponse extends Readable {\n constructor (resume) {\n super({ autoDestroy: true })\n this[kResume] = resume\n }\n\n _read () {\n this[kResume]()\n }\n\n _destroy (err, callback) {\n if (!err && !this._readableState.endEmitted) {\n err = new RequestAbortedError()\n }\n\n callback(err)\n }\n}\n\nclass PipelineHandler extends AsyncResource {\n constructor (opts, handler) {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n if (typeof handler !== 'function') {\n throw new InvalidArgumentError('invalid handler')\n }\n\n const { signal, method, opaque, onInfo, responseHeaders } = opts\n\n if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {\n throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')\n }\n\n if (method === 'CONNECT') {\n throw new InvalidArgumentError('invalid method')\n }\n\n if (onInfo && typeof onInfo !== 'function') {\n throw new InvalidArgumentError('invalid onInfo callback')\n }\n\n super('UNDICI_PIPELINE')\n\n this.opaque = opaque || null\n this.responseHeaders = responseHeaders || null\n this.handler = handler\n this.abort = null\n this.context = null\n this.onInfo = onInfo || null\n\n this.req = new PipelineRequest().on('error', util.nop)\n\n this.ret = new Duplex({\n readableObjectMode: opts.objectMode,\n autoDestroy: true,\n read: () => {\n const { body } = this\n\n if (body?.resume) {\n body.resume()\n }\n },\n write: (chunk, encoding, callback) => {\n const { req } = this\n\n if (req.push(chunk, encoding) || req._readableState.destroyed) {\n callback()\n } else {\n req[kResume] = callback\n }\n },\n destroy: (err, callback) => {\n const { body, req, res, ret, abort } = this\n\n if (!err && !ret._readableState.endEmitted) {\n err = new RequestAbortedError()\n }\n\n if (abort && err) {\n abort()\n }\n\n util.destroy(body, err)\n util.destroy(req, err)\n util.destroy(res, err)\n\n removeSignal(this)\n\n callback(err)\n }\n }).on('prefinish', () => {\n const { req } = this\n\n // Node < 15 does not call _final in same tick.\n req.push(null)\n })\n\n this.res = null\n\n addSignal(this, signal)\n }\n\n onConnect (abort, context) {\n const { ret, res } = this\n\n if (this.reason) {\n abort(this.reason)\n return\n }\n\n assert(!res, 'pipeline cannot be retried')\n assert(!ret.destroyed)\n\n this.abort = abort\n this.context = context\n }\n\n onHeaders (statusCode, rawHeaders, resume) {\n const { opaque, handler, context } = this\n\n if (statusCode < 200) {\n if (this.onInfo) {\n const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n this.onInfo({ statusCode, headers })\n }\n return\n }\n\n this.res = new PipelineResponse(resume)\n\n let body\n try {\n this.handler = null\n const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n body = this.runInAsyncScope(handler, null, {\n statusCode,\n headers,\n opaque,\n body: this.res,\n context\n })\n } catch (err) {\n this.res.on('error', util.nop)\n throw err\n }\n\n if (!body || typeof body.on !== 'function') {\n throw new InvalidReturnValueError('expected Readable')\n }\n\n body\n .on('data', (chunk) => {\n const { ret, body } = this\n\n if (!ret.push(chunk) && body.pause) {\n body.pause()\n }\n })\n .on('error', (err) => {\n const { ret } = this\n\n util.destroy(ret, err)\n })\n .on('end', () => {\n const { ret } = this\n\n ret.push(null)\n })\n .on('close', () => {\n const { ret } = this\n\n if (!ret._readableState.ended) {\n util.destroy(ret, new RequestAbortedError())\n }\n })\n\n this.body = body\n }\n\n onData (chunk) {\n const { res } = this\n return res.push(chunk)\n }\n\n onComplete (trailers) {\n const { res } = this\n res.push(null)\n }\n\n onError (err) {\n const { ret } = this\n this.handler = null\n util.destroy(ret, err)\n }\n}\n\nfunction pipeline (opts, handler) {\n try {\n const pipelineHandler = new PipelineHandler(opts, handler)\n this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler)\n return pipelineHandler.ret\n } catch (err) {\n return new PassThrough().destroy(err)\n }\n}\n\nmodule.exports = pipeline\n","'use strict'\n\nconst { InvalidArgumentError, SocketError } = require('../core/errors')\nconst { AsyncResource } = require('node:async_hooks')\nconst util = require('../core/util')\nconst { addSignal, removeSignal } = require('./abort-signal')\nconst assert = require('node:assert')\n\nclass UpgradeHandler extends AsyncResource {\n constructor (opts, callback) {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n const { signal, opaque, responseHeaders } = opts\n\n if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {\n throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')\n }\n\n super('UNDICI_UPGRADE')\n\n this.responseHeaders = responseHeaders || null\n this.opaque = opaque || null\n this.callback = callback\n this.abort = null\n this.context = null\n\n addSignal(this, signal)\n }\n\n onConnect (abort, context) {\n if (this.reason) {\n abort(this.reason)\n return\n }\n\n assert(this.callback)\n\n this.abort = abort\n this.context = null\n }\n\n onHeaders () {\n throw new SocketError('bad upgrade', null)\n }\n\n onUpgrade (statusCode, rawHeaders, socket) {\n assert(statusCode === 101)\n\n const { callback, opaque, context } = this\n\n removeSignal(this)\n\n this.callback = null\n const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n this.runInAsyncScope(callback, null, null, {\n headers,\n socket,\n opaque,\n context\n })\n }\n\n onError (err) {\n const { callback, opaque } = this\n\n removeSignal(this)\n\n if (callback) {\n this.callback = null\n queueMicrotask(() => {\n this.runInAsyncScope(callback, null, err, { opaque })\n })\n }\n }\n}\n\nfunction upgrade (opts, callback) {\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n upgrade.call(this, opts, (err, data) => {\n return err ? reject(err) : resolve(data)\n })\n })\n }\n\n try {\n const upgradeHandler = new UpgradeHandler(opts, callback)\n this.dispatch({\n ...opts,\n method: opts.method || 'GET',\n upgrade: opts.protocol || 'Websocket'\n }, upgradeHandler)\n } catch (err) {\n if (typeof callback !== 'function') {\n throw err\n }\n const opaque = opts?.opaque\n queueMicrotask(() => callback(err, { opaque }))\n }\n}\n\nmodule.exports = upgrade\n","'use strict'\n\nconst assert = require('node:assert')\nconst { AsyncResource } = require('node:async_hooks')\nconst { InvalidArgumentError, SocketError } = require('../core/errors')\nconst util = require('../core/util')\nconst { addSignal, removeSignal } = require('./abort-signal')\n\nclass ConnectHandler extends AsyncResource {\n constructor (opts, callback) {\n if (!opts || typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n if (typeof callback !== 'function') {\n throw new InvalidArgumentError('invalid callback')\n }\n\n const { signal, opaque, responseHeaders } = opts\n\n if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {\n throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')\n }\n\n super('UNDICI_CONNECT')\n\n this.opaque = opaque || null\n this.responseHeaders = responseHeaders || null\n this.callback = callback\n this.abort = null\n\n addSignal(this, signal)\n }\n\n onConnect (abort, context) {\n if (this.reason) {\n abort(this.reason)\n return\n }\n\n assert(this.callback)\n\n this.abort = abort\n this.context = context\n }\n\n onHeaders () {\n throw new SocketError('bad connect', null)\n }\n\n onUpgrade (statusCode, rawHeaders, socket) {\n const { callback, opaque, context } = this\n\n removeSignal(this)\n\n this.callback = null\n\n let headers = rawHeaders\n // Indicates is an HTTP2Session\n if (headers != null) {\n headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)\n }\n\n this.runInAsyncScope(callback, null, null, {\n statusCode,\n headers,\n socket,\n opaque,\n context\n })\n }\n\n onError (err) {\n const { callback, opaque } = this\n\n removeSignal(this)\n\n if (callback) {\n this.callback = null\n queueMicrotask(() => {\n this.runInAsyncScope(callback, null, err, { opaque })\n })\n }\n }\n}\n\nfunction connect (opts, callback) {\n if (callback === undefined) {\n return new Promise((resolve, reject) => {\n connect.call(this, opts, (err, data) => {\n return err ? reject(err) : resolve(data)\n })\n })\n }\n\n try {\n const connectHandler = new ConnectHandler(opts, callback)\n this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler)\n } catch (err) {\n if (typeof callback !== 'function') {\n throw err\n }\n const opaque = opts?.opaque\n queueMicrotask(() => callback(err, { opaque }))\n }\n}\n\nmodule.exports = connect\n","'use strict'\n\nmodule.exports.request = require('./api-request')\nmodule.exports.stream = require('./api-stream')\nmodule.exports.pipeline = require('./api-pipeline')\nmodule.exports.upgrade = require('./api-upgrade')\nmodule.exports.connect = require('./api-connect')\n","'use strict'\n\nconst { UndiciError } = require('../core/errors')\n\nconst kMockNotMatchedError = Symbol.for('undici.error.UND_MOCK_ERR_MOCK_NOT_MATCHED')\n\n/**\n * The request does not match any registered mock dispatches.\n */\nclass MockNotMatchedError extends UndiciError {\n constructor (message) {\n super(message)\n Error.captureStackTrace(this, MockNotMatchedError)\n this.name = 'MockNotMatchedError'\n this.message = message || 'The request does not match any registered mock dispatches'\n this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED'\n }\n\n static [Symbol.hasInstance] (instance) {\n return instance && instance[kMockNotMatchedError] === true\n }\n\n [kMockNotMatchedError] = true\n}\n\nmodule.exports = {\n MockNotMatchedError\n}\n","'use strict'\n\nmodule.exports = {\n kAgent: Symbol('agent'),\n kOptions: Symbol('options'),\n kFactory: Symbol('factory'),\n kDispatches: Symbol('dispatches'),\n kDispatchKey: Symbol('dispatch key'),\n kDefaultHeaders: Symbol('default headers'),\n kDefaultTrailers: Symbol('default trailers'),\n kContentLength: Symbol('content length'),\n kMockAgent: Symbol('mock agent'),\n kMockAgentSet: Symbol('mock agent set'),\n kMockAgentGet: Symbol('mock agent get'),\n kMockDispatch: Symbol('mock dispatch'),\n kClose: Symbol('close'),\n kOriginalClose: Symbol('original agent close'),\n kOrigin: Symbol('origin'),\n kIsMockActive: Symbol('is mock active'),\n kNetConnect: Symbol('net connect'),\n kGetNetConnect: Symbol('get net connect'),\n kConnected: Symbol('connected')\n}\n","'use strict'\n\nconst { MockNotMatchedError } = require('./mock-errors')\nconst {\n kDispatches,\n kMockAgent,\n kOriginalDispatch,\n kOrigin,\n kGetNetConnect\n} = require('./mock-symbols')\nconst { buildURL } = require('../core/util')\nconst { STATUS_CODES } = require('node:http')\nconst {\n types: {\n isPromise\n }\n} = require('node:util')\n\nfunction matchValue (match, value) {\n if (typeof match === 'string') {\n return match === value\n }\n if (match instanceof RegExp) {\n return match.test(value)\n }\n if (typeof match === 'function') {\n return match(value) === true\n }\n return false\n}\n\nfunction lowerCaseEntries (headers) {\n return Object.fromEntries(\n Object.entries(headers).map(([headerName, headerValue]) => {\n return [headerName.toLocaleLowerCase(), headerValue]\n })\n )\n}\n\n/**\n * @param {import('../../index').Headers|string[]|Record} headers\n * @param {string} key\n */\nfunction getHeaderByName (headers, key) {\n if (Array.isArray(headers)) {\n for (let i = 0; i < headers.length; i += 2) {\n if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) {\n return headers[i + 1]\n }\n }\n\n return undefined\n } else if (typeof headers.get === 'function') {\n return headers.get(key)\n } else {\n return lowerCaseEntries(headers)[key.toLocaleLowerCase()]\n }\n}\n\n/** @param {string[]} headers */\nfunction buildHeadersFromArray (headers) { // fetch HeadersList\n const clone = headers.slice()\n const entries = []\n for (let index = 0; index < clone.length; index += 2) {\n entries.push([clone[index], clone[index + 1]])\n }\n return Object.fromEntries(entries)\n}\n\nfunction matchHeaders (mockDispatch, headers) {\n if (typeof mockDispatch.headers === 'function') {\n if (Array.isArray(headers)) { // fetch HeadersList\n headers = buildHeadersFromArray(headers)\n }\n return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {})\n }\n if (typeof mockDispatch.headers === 'undefined') {\n return true\n }\n if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') {\n return false\n }\n\n for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) {\n const headerValue = getHeaderByName(headers, matchHeaderName)\n\n if (!matchValue(matchHeaderValue, headerValue)) {\n return false\n }\n }\n return true\n}\n\nfunction safeUrl (path) {\n if (typeof path !== 'string') {\n return path\n }\n\n const pathSegments = path.split('?')\n\n if (pathSegments.length !== 2) {\n return path\n }\n\n const qp = new URLSearchParams(pathSegments.pop())\n qp.sort()\n return [...pathSegments, qp.toString()].join('?')\n}\n\nfunction matchKey (mockDispatch, { path, method, body, headers }) {\n const pathMatch = matchValue(mockDispatch.path, path)\n const methodMatch = matchValue(mockDispatch.method, method)\n const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true\n const headersMatch = matchHeaders(mockDispatch, headers)\n return pathMatch && methodMatch && bodyMatch && headersMatch\n}\n\nfunction getResponseData (data) {\n if (Buffer.isBuffer(data)) {\n return data\n } else if (data instanceof Uint8Array) {\n return data\n } else if (data instanceof ArrayBuffer) {\n return data\n } else if (typeof data === 'object') {\n return JSON.stringify(data)\n } else {\n return data.toString()\n }\n}\n\nfunction getMockDispatch (mockDispatches, key) {\n const basePath = key.query ? buildURL(key.path, key.query) : key.path\n const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath\n\n // Match path\n let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath))\n if (matchedMockDispatches.length === 0) {\n throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`)\n }\n\n // Match method\n matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method))\n if (matchedMockDispatches.length === 0) {\n throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}' on path '${resolvedPath}'`)\n }\n\n // Match body\n matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true)\n if (matchedMockDispatches.length === 0) {\n throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}' on path '${resolvedPath}'`)\n }\n\n // Match headers\n matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers))\n if (matchedMockDispatches.length === 0) {\n const headers = typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers\n throw new MockNotMatchedError(`Mock dispatch not matched for headers '${headers}' on path '${resolvedPath}'`)\n }\n\n return matchedMockDispatches[0]\n}\n\nfunction addMockDispatch (mockDispatches, key, data) {\n const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false }\n const replyData = typeof data === 'function' ? { callback: data } : { ...data }\n const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } }\n mockDispatches.push(newMockDispatch)\n return newMockDispatch\n}\n\nfunction deleteMockDispatch (mockDispatches, key) {\n const index = mockDispatches.findIndex(dispatch => {\n if (!dispatch.consumed) {\n return false\n }\n return matchKey(dispatch, key)\n })\n if (index !== -1) {\n mockDispatches.splice(index, 1)\n }\n}\n\nfunction buildKey (opts) {\n const { path, method, body, headers, query } = opts\n return {\n path,\n method,\n body,\n headers,\n query\n }\n}\n\nfunction generateKeyValues (data) {\n const keys = Object.keys(data)\n const result = []\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n const value = data[key]\n const name = Buffer.from(`${key}`)\n if (Array.isArray(value)) {\n for (let j = 0; j < value.length; ++j) {\n result.push(name, Buffer.from(`${value[j]}`))\n }\n } else {\n result.push(name, Buffer.from(`${value}`))\n }\n }\n return result\n}\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status\n * @param {number} statusCode\n */\nfunction getStatusText (statusCode) {\n return STATUS_CODES[statusCode] || 'unknown'\n}\n\nasync function getResponse (body) {\n const buffers = []\n for await (const data of body) {\n buffers.push(data)\n }\n return Buffer.concat(buffers).toString('utf8')\n}\n\n/**\n * Mock dispatch function used to simulate undici dispatches\n */\nfunction mockDispatch (opts, handler) {\n // Get mock dispatch from built key\n const key = buildKey(opts)\n const mockDispatch = getMockDispatch(this[kDispatches], key)\n\n mockDispatch.timesInvoked++\n\n // Here's where we resolve a callback if a callback is present for the dispatch data.\n if (mockDispatch.data.callback) {\n mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) }\n }\n\n // Parse mockDispatch data\n const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch\n const { timesInvoked, times } = mockDispatch\n\n // If it's used up and not persistent, mark as consumed\n mockDispatch.consumed = !persist && timesInvoked >= times\n mockDispatch.pending = timesInvoked < times\n\n // If specified, trigger dispatch error\n if (error !== null) {\n deleteMockDispatch(this[kDispatches], key)\n handler.onError(error)\n return true\n }\n\n // Handle the request with a delay if necessary\n if (typeof delay === 'number' && delay > 0) {\n setTimeout(() => {\n handleReply(this[kDispatches])\n }, delay)\n } else {\n handleReply(this[kDispatches])\n }\n\n function handleReply (mockDispatches, _data = data) {\n // fetch's HeadersList is a 1D string array\n const optsHeaders = Array.isArray(opts.headers)\n ? buildHeadersFromArray(opts.headers)\n : opts.headers\n const body = typeof _data === 'function'\n ? _data({ ...opts, headers: optsHeaders })\n : _data\n\n // util.types.isPromise is likely needed for jest.\n if (isPromise(body)) {\n // If handleReply is asynchronous, throwing an error\n // in the callback will reject the promise, rather than\n // synchronously throw the error, which breaks some tests.\n // Rather, we wait for the callback to resolve if it is a\n // promise, and then re-run handleReply with the new body.\n body.then((newData) => handleReply(mockDispatches, newData))\n return\n }\n\n const responseData = getResponseData(body)\n const responseHeaders = generateKeyValues(headers)\n const responseTrailers = generateKeyValues(trailers)\n\n handler.onConnect?.(err => handler.onError(err), null)\n handler.onHeaders?.(statusCode, responseHeaders, resume, getStatusText(statusCode))\n handler.onData?.(Buffer.from(responseData))\n handler.onComplete?.(responseTrailers)\n deleteMockDispatch(mockDispatches, key)\n }\n\n function resume () {}\n\n return true\n}\n\nfunction buildMockDispatch () {\n const agent = this[kMockAgent]\n const origin = this[kOrigin]\n const originalDispatch = this[kOriginalDispatch]\n\n return function dispatch (opts, handler) {\n if (agent.isMockActive) {\n try {\n mockDispatch.call(this, opts, handler)\n } catch (error) {\n if (error instanceof MockNotMatchedError) {\n const netConnect = agent[kGetNetConnect]()\n if (netConnect === false) {\n throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`)\n }\n if (checkNetConnect(netConnect, origin)) {\n originalDispatch.call(this, opts, handler)\n } else {\n throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`)\n }\n } else {\n throw error\n }\n }\n } else {\n originalDispatch.call(this, opts, handler)\n }\n }\n}\n\nfunction checkNetConnect (netConnect, origin) {\n const url = new URL(origin)\n if (netConnect === true) {\n return true\n } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) {\n return true\n }\n return false\n}\n\nfunction buildMockOptions (opts) {\n if (opts) {\n const { agent, ...mockOptions } = opts\n return mockOptions\n }\n}\n\nmodule.exports = {\n getResponseData,\n getMockDispatch,\n addMockDispatch,\n deleteMockDispatch,\n buildKey,\n generateKeyValues,\n matchValue,\n getResponse,\n getStatusText,\n mockDispatch,\n buildMockDispatch,\n checkNetConnect,\n buildMockOptions,\n getHeaderByName,\n buildHeadersFromArray\n}\n","'use strict'\n\nconst { getResponseData, buildKey, addMockDispatch } = require('./mock-utils')\nconst {\n kDispatches,\n kDispatchKey,\n kDefaultHeaders,\n kDefaultTrailers,\n kContentLength,\n kMockDispatch\n} = require('./mock-symbols')\nconst { InvalidArgumentError } = require('../core/errors')\nconst { buildURL } = require('../core/util')\n\n/**\n * Defines the scope API for an interceptor reply\n */\nclass MockScope {\n constructor (mockDispatch) {\n this[kMockDispatch] = mockDispatch\n }\n\n /**\n * Delay a reply by a set amount in ms.\n */\n delay (waitInMs) {\n if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) {\n throw new InvalidArgumentError('waitInMs must be a valid integer > 0')\n }\n\n this[kMockDispatch].delay = waitInMs\n return this\n }\n\n /**\n * For a defined reply, never mark as consumed.\n */\n persist () {\n this[kMockDispatch].persist = true\n return this\n }\n\n /**\n * Allow one to define a reply for a set amount of matching requests.\n */\n times (repeatTimes) {\n if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) {\n throw new InvalidArgumentError('repeatTimes must be a valid integer > 0')\n }\n\n this[kMockDispatch].times = repeatTimes\n return this\n }\n}\n\n/**\n * Defines an interceptor for a Mock\n */\nclass MockInterceptor {\n constructor (opts, mockDispatches) {\n if (typeof opts !== 'object') {\n throw new InvalidArgumentError('opts must be an object')\n }\n if (typeof opts.path === 'undefined') {\n throw new InvalidArgumentError('opts.path must be defined')\n }\n if (typeof opts.method === 'undefined') {\n opts.method = 'GET'\n }\n // See https://github.com/nodejs/undici/issues/1245\n // As per RFC 3986, clients are not supposed to send URI\n // fragments to servers when they retrieve a document,\n if (typeof opts.path === 'string') {\n if (opts.query) {\n opts.path = buildURL(opts.path, opts.query)\n } else {\n // Matches https://github.com/nodejs/undici/blob/main/lib/web/fetch/index.js#L1811\n const parsedURL = new URL(opts.path, 'data://')\n opts.path = parsedURL.pathname + parsedURL.search\n }\n }\n if (typeof opts.method === 'string') {\n opts.method = opts.method.toUpperCase()\n }\n\n this[kDispatchKey] = buildKey(opts)\n this[kDispatches] = mockDispatches\n this[kDefaultHeaders] = {}\n this[kDefaultTrailers] = {}\n this[kContentLength] = false\n }\n\n createMockScopeDispatchData ({ statusCode, data, responseOptions }) {\n const responseData = getResponseData(data)\n const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {}\n const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers }\n const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers }\n\n return { statusCode, data, headers, trailers }\n }\n\n validateReplyParameters (replyParameters) {\n if (typeof replyParameters.statusCode === 'undefined') {\n throw new InvalidArgumentError('statusCode must be defined')\n }\n if (typeof replyParameters.responseOptions !== 'object' || replyParameters.responseOptions === null) {\n throw new InvalidArgumentError('responseOptions must be an object')\n }\n }\n\n /**\n * Mock an undici request with a defined reply.\n */\n reply (replyOptionsCallbackOrStatusCode) {\n // Values of reply aren't available right now as they\n // can only be available when the reply callback is invoked.\n if (typeof replyOptionsCallbackOrStatusCode === 'function') {\n // We'll first wrap the provided callback in another function,\n // this function will properly resolve the data from the callback\n // when invoked.\n const wrappedDefaultsCallback = (opts) => {\n // Our reply options callback contains the parameter for statusCode, data and options.\n const resolvedData = replyOptionsCallbackOrStatusCode(opts)\n\n // Check if it is in the right format\n if (typeof resolvedData !== 'object' || resolvedData === null) {\n throw new InvalidArgumentError('reply options callback must return an object')\n }\n\n const replyParameters = { data: '', responseOptions: {}, ...resolvedData }\n this.validateReplyParameters(replyParameters)\n // Since the values can be obtained immediately we return them\n // from this higher order function that will be resolved later.\n return {\n ...this.createMockScopeDispatchData(replyParameters)\n }\n }\n\n // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data.\n const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback)\n return new MockScope(newMockDispatch)\n }\n\n // We can have either one or three parameters, if we get here,\n // we should have 1-3 parameters. So we spread the arguments of\n // this function to obtain the parameters, since replyData will always\n // just be the statusCode.\n const replyParameters = {\n statusCode: replyOptionsCallbackOrStatusCode,\n data: arguments[1] === undefined ? '' : arguments[1],\n responseOptions: arguments[2] === undefined ? {} : arguments[2]\n }\n this.validateReplyParameters(replyParameters)\n\n // Send in-already provided data like usual\n const dispatchData = this.createMockScopeDispatchData(replyParameters)\n const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData)\n return new MockScope(newMockDispatch)\n }\n\n /**\n * Mock an undici request with a defined error.\n */\n replyWithError (error) {\n if (typeof error === 'undefined') {\n throw new InvalidArgumentError('error must be defined')\n }\n\n const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error })\n return new MockScope(newMockDispatch)\n }\n\n /**\n * Set default reply headers on the interceptor for subsequent replies\n */\n defaultReplyHeaders (headers) {\n if (typeof headers === 'undefined') {\n throw new InvalidArgumentError('headers must be defined')\n }\n\n this[kDefaultHeaders] = headers\n return this\n }\n\n /**\n * Set default reply trailers on the interceptor for subsequent replies\n */\n defaultReplyTrailers (trailers) {\n if (typeof trailers === 'undefined') {\n throw new InvalidArgumentError('trailers must be defined')\n }\n\n this[kDefaultTrailers] = trailers\n return this\n }\n\n /**\n * Set reply content length header for replies on the interceptor\n */\n replyContentLength () {\n this[kContentLength] = true\n return this\n }\n}\n\nmodule.exports.MockInterceptor = MockInterceptor\nmodule.exports.MockScope = MockScope\n","'use strict'\n\nconst { promisify } = require('node:util')\nconst Client = require('../dispatcher/client')\nconst { buildMockDispatch } = require('./mock-utils')\nconst {\n kDispatches,\n kMockAgent,\n kClose,\n kOriginalClose,\n kOrigin,\n kOriginalDispatch,\n kConnected\n} = require('./mock-symbols')\nconst { MockInterceptor } = require('./mock-interceptor')\nconst Symbols = require('../core/symbols')\nconst { InvalidArgumentError } = require('../core/errors')\n\n/**\n * MockClient provides an API that extends the Client to influence the mockDispatches.\n */\nclass MockClient extends Client {\n constructor (origin, opts) {\n super(origin, opts)\n\n if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {\n throw new InvalidArgumentError('Argument opts.agent must implement Agent')\n }\n\n this[kMockAgent] = opts.agent\n this[kOrigin] = origin\n this[kDispatches] = []\n this[kConnected] = 1\n this[kOriginalDispatch] = this.dispatch\n this[kOriginalClose] = this.close.bind(this)\n\n this.dispatch = buildMockDispatch.call(this)\n this.close = this[kClose]\n }\n\n get [Symbols.kConnected] () {\n return this[kConnected]\n }\n\n /**\n * Sets up the base interceptor for mocking replies from undici.\n */\n intercept (opts) {\n return new MockInterceptor(opts, this[kDispatches])\n }\n\n async [kClose] () {\n await promisify(this[kOriginalClose])()\n this[kConnected] = 0\n this[kMockAgent][Symbols.kClients].delete(this[kOrigin])\n }\n}\n\nmodule.exports = MockClient\n","'use strict'\n\nconst { promisify } = require('node:util')\nconst Pool = require('../dispatcher/pool')\nconst { buildMockDispatch } = require('./mock-utils')\nconst {\n kDispatches,\n kMockAgent,\n kClose,\n kOriginalClose,\n kOrigin,\n kOriginalDispatch,\n kConnected\n} = require('./mock-symbols')\nconst { MockInterceptor } = require('./mock-interceptor')\nconst Symbols = require('../core/symbols')\nconst { InvalidArgumentError } = require('../core/errors')\n\n/**\n * MockPool provides an API that extends the Pool to influence the mockDispatches.\n */\nclass MockPool extends Pool {\n constructor (origin, opts) {\n super(origin, opts)\n\n if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {\n throw new InvalidArgumentError('Argument opts.agent must implement Agent')\n }\n\n this[kMockAgent] = opts.agent\n this[kOrigin] = origin\n this[kDispatches] = []\n this[kConnected] = 1\n this[kOriginalDispatch] = this.dispatch\n this[kOriginalClose] = this.close.bind(this)\n\n this.dispatch = buildMockDispatch.call(this)\n this.close = this[kClose]\n }\n\n get [Symbols.kConnected] () {\n return this[kConnected]\n }\n\n /**\n * Sets up the base interceptor for mocking replies from undici.\n */\n intercept (opts) {\n return new MockInterceptor(opts, this[kDispatches])\n }\n\n async [kClose] () {\n await promisify(this[kOriginalClose])()\n this[kConnected] = 0\n this[kMockAgent][Symbols.kClients].delete(this[kOrigin])\n }\n}\n\nmodule.exports = MockPool\n","'use strict'\n\nconst singulars = {\n pronoun: 'it',\n is: 'is',\n was: 'was',\n this: 'this'\n}\n\nconst plurals = {\n pronoun: 'they',\n is: 'are',\n was: 'were',\n this: 'these'\n}\n\nmodule.exports = class Pluralizer {\n constructor (singular, plural) {\n this.singular = singular\n this.plural = plural\n }\n\n pluralize (count) {\n const one = count === 1\n const keys = one ? singulars : plurals\n const noun = one ? this.singular : this.plural\n return { ...keys, count, noun }\n }\n}\n","'use strict'\n\nconst { Transform } = require('node:stream')\nconst { Console } = require('node:console')\n\nconst PERSISTENT = process.versions.icu ? '✅' : 'Y '\nconst NOT_PERSISTENT = process.versions.icu ? '❌' : 'N '\n\n/**\n * Gets the output of `console.table(…)` as a string.\n */\nmodule.exports = class PendingInterceptorsFormatter {\n constructor ({ disableColors } = {}) {\n this.transform = new Transform({\n transform (chunk, _enc, cb) {\n cb(null, chunk)\n }\n })\n\n this.logger = new Console({\n stdout: this.transform,\n inspectOptions: {\n colors: !disableColors && !process.env.CI\n }\n })\n }\n\n format (pendingInterceptors) {\n const withPrettyHeaders = pendingInterceptors.map(\n ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({\n Method: method,\n Origin: origin,\n Path: path,\n 'Status code': statusCode,\n Persistent: persist ? PERSISTENT : NOT_PERSISTENT,\n Invocations: timesInvoked,\n Remaining: persist ? Infinity : times - timesInvoked\n }))\n\n this.logger.table(withPrettyHeaders)\n return this.transform.read().toString()\n }\n}\n","'use strict'\n\nconst { kClients } = require('../core/symbols')\nconst Agent = require('../dispatcher/agent')\nconst {\n kAgent,\n kMockAgentSet,\n kMockAgentGet,\n kDispatches,\n kIsMockActive,\n kNetConnect,\n kGetNetConnect,\n kOptions,\n kFactory\n} = require('./mock-symbols')\nconst MockClient = require('./mock-client')\nconst MockPool = require('./mock-pool')\nconst { matchValue, buildMockOptions } = require('./mock-utils')\nconst { InvalidArgumentError, UndiciError } = require('../core/errors')\nconst Dispatcher = require('../dispatcher/dispatcher')\nconst Pluralizer = require('./pluralizer')\nconst PendingInterceptorsFormatter = require('./pending-interceptors-formatter')\n\nclass MockAgent extends Dispatcher {\n constructor (opts) {\n super(opts)\n\n this[kNetConnect] = true\n this[kIsMockActive] = true\n\n // Instantiate Agent and encapsulate\n if ((opts?.agent && typeof opts.agent.dispatch !== 'function')) {\n throw new InvalidArgumentError('Argument opts.agent must implement Agent')\n }\n const agent = opts?.agent ? opts.agent : new Agent(opts)\n this[kAgent] = agent\n\n this[kClients] = agent[kClients]\n this[kOptions] = buildMockOptions(opts)\n }\n\n get (origin) {\n let dispatcher = this[kMockAgentGet](origin)\n\n if (!dispatcher) {\n dispatcher = this[kFactory](origin)\n this[kMockAgentSet](origin, dispatcher)\n }\n return dispatcher\n }\n\n dispatch (opts, handler) {\n // Call MockAgent.get to perform additional setup before dispatching as normal\n this.get(opts.origin)\n return this[kAgent].dispatch(opts, handler)\n }\n\n async close () {\n await this[kAgent].close()\n this[kClients].clear()\n }\n\n deactivate () {\n this[kIsMockActive] = false\n }\n\n activate () {\n this[kIsMockActive] = true\n }\n\n enableNetConnect (matcher) {\n if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) {\n if (Array.isArray(this[kNetConnect])) {\n this[kNetConnect].push(matcher)\n } else {\n this[kNetConnect] = [matcher]\n }\n } else if (typeof matcher === 'undefined') {\n this[kNetConnect] = true\n } else {\n throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.')\n }\n }\n\n disableNetConnect () {\n this[kNetConnect] = false\n }\n\n // This is required to bypass issues caused by using global symbols - see:\n // https://github.com/nodejs/undici/issues/1447\n get isMockActive () {\n return this[kIsMockActive]\n }\n\n [kMockAgentSet] (origin, dispatcher) {\n this[kClients].set(origin, dispatcher)\n }\n\n [kFactory] (origin) {\n const mockOptions = Object.assign({ agent: this }, this[kOptions])\n return this[kOptions] && this[kOptions].connections === 1\n ? new MockClient(origin, mockOptions)\n : new MockPool(origin, mockOptions)\n }\n\n [kMockAgentGet] (origin) {\n // First check if we can immediately find it\n const client = this[kClients].get(origin)\n if (client) {\n return client\n }\n\n // If the origin is not a string create a dummy parent pool and return to user\n if (typeof origin !== 'string') {\n const dispatcher = this[kFactory]('http://localhost:9999')\n this[kMockAgentSet](origin, dispatcher)\n return dispatcher\n }\n\n // If we match, create a pool and assign the same dispatches\n for (const [keyMatcher, nonExplicitDispatcher] of Array.from(this[kClients])) {\n if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) {\n const dispatcher = this[kFactory](origin)\n this[kMockAgentSet](origin, dispatcher)\n dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches]\n return dispatcher\n }\n }\n }\n\n [kGetNetConnect] () {\n return this[kNetConnect]\n }\n\n pendingInterceptors () {\n const mockAgentClients = this[kClients]\n\n return Array.from(mockAgentClients.entries())\n .flatMap(([origin, scope]) => scope[kDispatches].map(dispatch => ({ ...dispatch, origin })))\n .filter(({ pending }) => pending)\n }\n\n assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {\n const pending = this.pendingInterceptors()\n\n if (pending.length === 0) {\n return\n }\n\n const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length)\n\n throw new UndiciError(`\n${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending:\n\n${pendingInterceptorsFormatter.format(pending)}\n`.trim())\n }\n}\n\nmodule.exports = MockAgent\n","'use strict'\n\n// We include a version number for the Dispatcher API. In case of breaking changes,\n// this version number must be increased to avoid conflicts.\nconst globalDispatcher = Symbol.for('undici.globalDispatcher.1')\nconst { InvalidArgumentError } = require('./core/errors')\nconst Agent = require('./dispatcher/agent')\n\nif (getGlobalDispatcher() === undefined) {\n setGlobalDispatcher(new Agent())\n}\n\nfunction setGlobalDispatcher (agent) {\n if (!agent || typeof agent.dispatch !== 'function') {\n throw new InvalidArgumentError('Argument agent must implement Agent')\n }\n Object.defineProperty(globalThis, globalDispatcher, {\n value: agent,\n writable: true,\n enumerable: false,\n configurable: false\n })\n}\n\nfunction getGlobalDispatcher () {\n return globalThis[globalDispatcher]\n}\n\nmodule.exports = {\n setGlobalDispatcher,\n getGlobalDispatcher\n}\n","'use strict'\n\nmodule.exports = class DecoratorHandler {\n #handler\n\n constructor (handler) {\n if (typeof handler !== 'object' || handler === null) {\n throw new TypeError('handler must be an object')\n }\n this.#handler = handler\n }\n\n onConnect (...args) {\n return this.#handler.onConnect?.(...args)\n }\n\n onError (...args) {\n return this.#handler.onError?.(...args)\n }\n\n onUpgrade (...args) {\n return this.#handler.onUpgrade?.(...args)\n }\n\n onResponseStarted (...args) {\n return this.#handler.onResponseStarted?.(...args)\n }\n\n onHeaders (...args) {\n return this.#handler.onHeaders?.(...args)\n }\n\n onData (...args) {\n return this.#handler.onData?.(...args)\n }\n\n onComplete (...args) {\n return this.#handler.onComplete?.(...args)\n }\n\n onBodySent (...args) {\n return this.#handler.onBodySent?.(...args)\n }\n}\n","'use strict'\nconst RedirectHandler = require('../handler/redirect-handler')\n\nmodule.exports = opts => {\n const globalMaxRedirections = opts?.maxRedirections\n return dispatch => {\n return function redirectInterceptor (opts, handler) {\n const { maxRedirections = globalMaxRedirections, ...baseOpts } = opts\n\n if (!maxRedirections) {\n return dispatch(opts, handler)\n }\n\n const redirectHandler = new RedirectHandler(\n dispatch,\n maxRedirections,\n opts,\n handler\n )\n\n return dispatch(baseOpts, redirectHandler)\n }\n }\n}\n","'use strict'\nconst RetryHandler = require('../handler/retry-handler')\n\nmodule.exports = globalOpts => {\n return dispatch => {\n return function retryInterceptor (opts, handler) {\n return dispatch(\n opts,\n new RetryHandler(\n { ...opts, retryOptions: { ...globalOpts, ...opts.retryOptions } },\n {\n handler,\n dispatch\n }\n )\n )\n }\n }\n}\n","'use strict'\n\nconst util = require('../core/util')\nconst { InvalidArgumentError, RequestAbortedError } = require('../core/errors')\nconst DecoratorHandler = require('../handler/decorator-handler')\n\nclass DumpHandler extends DecoratorHandler {\n #maxSize = 1024 * 1024\n #abort = null\n #dumped = false\n #aborted = false\n #size = 0\n #reason = null\n #handler = null\n\n constructor ({ maxSize }, handler) {\n super(handler)\n\n if (maxSize != null && (!Number.isFinite(maxSize) || maxSize < 1)) {\n throw new InvalidArgumentError('maxSize must be a number greater than 0')\n }\n\n this.#maxSize = maxSize ?? this.#maxSize\n this.#handler = handler\n }\n\n onConnect (abort) {\n this.#abort = abort\n\n this.#handler.onConnect(this.#customAbort.bind(this))\n }\n\n #customAbort (reason) {\n this.#aborted = true\n this.#reason = reason\n }\n\n // TODO: will require adjustment after new hooks are out\n onHeaders (statusCode, rawHeaders, resume, statusMessage) {\n const headers = util.parseHeaders(rawHeaders)\n const contentLength = headers['content-length']\n\n if (contentLength != null && contentLength > this.#maxSize) {\n throw new RequestAbortedError(\n `Response size (${contentLength}) larger than maxSize (${\n this.#maxSize\n })`\n )\n }\n\n if (this.#aborted) {\n return true\n }\n\n return this.#handler.onHeaders(\n statusCode,\n rawHeaders,\n resume,\n statusMessage\n )\n }\n\n onError (err) {\n if (this.#dumped) {\n return\n }\n\n err = this.#reason ?? err\n\n this.#handler.onError(err)\n }\n\n onData (chunk) {\n this.#size = this.#size + chunk.length\n\n if (this.#size >= this.#maxSize) {\n this.#dumped = true\n\n if (this.#aborted) {\n this.#handler.onError(this.#reason)\n } else {\n this.#handler.onComplete([])\n }\n }\n\n return true\n }\n\n onComplete (trailers) {\n if (this.#dumped) {\n return\n }\n\n if (this.#aborted) {\n this.#handler.onError(this.reason)\n return\n }\n\n this.#handler.onComplete(trailers)\n }\n}\n\nfunction createDumpInterceptor (\n { maxSize: defaultMaxSize } = {\n maxSize: 1024 * 1024\n }\n) {\n return dispatch => {\n return function Intercept (opts, handler) {\n const { dumpMaxSize = defaultMaxSize } =\n opts\n\n const dumpHandler = new DumpHandler(\n { maxSize: dumpMaxSize },\n handler\n )\n\n return dispatch(opts, dumpHandler)\n }\n }\n}\n\nmodule.exports = createDumpInterceptor\n","'use strict'\nconst { isIP } = require('node:net')\nconst { lookup } = require('node:dns')\nconst DecoratorHandler = require('../handler/decorator-handler')\nconst { InvalidArgumentError, InformationalError } = require('../core/errors')\nconst maxInt = Math.pow(2, 31) - 1\n\nclass DNSInstance {\n #maxTTL = 0\n #maxItems = 0\n #records = new Map()\n dualStack = true\n affinity = null\n lookup = null\n pick = null\n\n constructor (opts) {\n this.#maxTTL = opts.maxTTL\n this.#maxItems = opts.maxItems\n this.dualStack = opts.dualStack\n this.affinity = opts.affinity\n this.lookup = opts.lookup ?? this.#defaultLookup\n this.pick = opts.pick ?? this.#defaultPick\n }\n\n get full () {\n return this.#records.size === this.#maxItems\n }\n\n runLookup (origin, opts, cb) {\n const ips = this.#records.get(origin.hostname)\n\n // If full, we just return the origin\n if (ips == null && this.full) {\n cb(null, origin.origin)\n return\n }\n\n const newOpts = {\n affinity: this.affinity,\n dualStack: this.dualStack,\n lookup: this.lookup,\n pick: this.pick,\n ...opts.dns,\n maxTTL: this.#maxTTL,\n maxItems: this.#maxItems\n }\n\n // If no IPs we lookup\n if (ips == null) {\n this.lookup(origin, newOpts, (err, addresses) => {\n if (err || addresses == null || addresses.length === 0) {\n cb(err ?? new InformationalError('No DNS entries found'))\n return\n }\n\n this.setRecords(origin, addresses)\n const records = this.#records.get(origin.hostname)\n\n const ip = this.pick(\n origin,\n records,\n newOpts.affinity\n )\n\n let port\n if (typeof ip.port === 'number') {\n port = `:${ip.port}`\n } else if (origin.port !== '') {\n port = `:${origin.port}`\n } else {\n port = ''\n }\n\n cb(\n null,\n `${origin.protocol}//${\n ip.family === 6 ? `[${ip.address}]` : ip.address\n }${port}`\n )\n })\n } else {\n // If there's IPs we pick\n const ip = this.pick(\n origin,\n ips,\n newOpts.affinity\n )\n\n // If no IPs we lookup - deleting old records\n if (ip == null) {\n this.#records.delete(origin.hostname)\n this.runLookup(origin, opts, cb)\n return\n }\n\n let port\n if (typeof ip.port === 'number') {\n port = `:${ip.port}`\n } else if (origin.port !== '') {\n port = `:${origin.port}`\n } else {\n port = ''\n }\n\n cb(\n null,\n `${origin.protocol}//${\n ip.family === 6 ? `[${ip.address}]` : ip.address\n }${port}`\n )\n }\n }\n\n #defaultLookup (origin, opts, cb) {\n lookup(\n origin.hostname,\n {\n all: true,\n family: this.dualStack === false ? this.affinity : 0,\n order: 'ipv4first'\n },\n (err, addresses) => {\n if (err) {\n return cb(err)\n }\n\n const results = new Map()\n\n for (const addr of addresses) {\n // On linux we found duplicates, we attempt to remove them with\n // the latest record\n results.set(`${addr.address}:${addr.family}`, addr)\n }\n\n cb(null, results.values())\n }\n )\n }\n\n #defaultPick (origin, hostnameRecords, affinity) {\n let ip = null\n const { records, offset } = hostnameRecords\n\n let family\n if (this.dualStack) {\n if (affinity == null) {\n // Balance between ip families\n if (offset == null || offset === maxInt) {\n hostnameRecords.offset = 0\n affinity = 4\n } else {\n hostnameRecords.offset++\n affinity = (hostnameRecords.offset & 1) === 1 ? 6 : 4\n }\n }\n\n if (records[affinity] != null && records[affinity].ips.length > 0) {\n family = records[affinity]\n } else {\n family = records[affinity === 4 ? 6 : 4]\n }\n } else {\n family = records[affinity]\n }\n\n // If no IPs we return null\n if (family == null || family.ips.length === 0) {\n return ip\n }\n\n if (family.offset == null || family.offset === maxInt) {\n family.offset = 0\n } else {\n family.offset++\n }\n\n const position = family.offset % family.ips.length\n ip = family.ips[position] ?? null\n\n if (ip == null) {\n return ip\n }\n\n if (Date.now() - ip.timestamp > ip.ttl) { // record TTL is already in ms\n // We delete expired records\n // It is possible that they have different TTL, so we manage them individually\n family.ips.splice(position, 1)\n return this.pick(origin, hostnameRecords, affinity)\n }\n\n return ip\n }\n\n setRecords (origin, addresses) {\n const timestamp = Date.now()\n const records = { records: { 4: null, 6: null } }\n for (const record of addresses) {\n record.timestamp = timestamp\n if (typeof record.ttl === 'number') {\n // The record TTL is expected to be in ms\n record.ttl = Math.min(record.ttl, this.#maxTTL)\n } else {\n record.ttl = this.#maxTTL\n }\n\n const familyRecords = records.records[record.family] ?? { ips: [] }\n\n familyRecords.ips.push(record)\n records.records[record.family] = familyRecords\n }\n\n this.#records.set(origin.hostname, records)\n }\n\n getHandler (meta, opts) {\n return new DNSDispatchHandler(this, meta, opts)\n }\n}\n\nclass DNSDispatchHandler extends DecoratorHandler {\n #state = null\n #opts = null\n #dispatch = null\n #handler = null\n #origin = null\n\n constructor (state, { origin, handler, dispatch }, opts) {\n super(handler)\n this.#origin = origin\n this.#handler = handler\n this.#opts = { ...opts }\n this.#state = state\n this.#dispatch = dispatch\n }\n\n onError (err) {\n switch (err.code) {\n case 'ETIMEDOUT':\n case 'ECONNREFUSED': {\n if (this.#state.dualStack) {\n // We delete the record and retry\n this.#state.runLookup(this.#origin, this.#opts, (err, newOrigin) => {\n if (err) {\n return this.#handler.onError(err)\n }\n\n const dispatchOpts = {\n ...this.#opts,\n origin: newOrigin\n }\n\n this.#dispatch(dispatchOpts, this)\n })\n\n // if dual-stack disabled, we error out\n return\n }\n\n this.#handler.onError(err)\n return\n }\n case 'ENOTFOUND':\n this.#state.deleteRecord(this.#origin)\n // eslint-disable-next-line no-fallthrough\n default:\n this.#handler.onError(err)\n break\n }\n }\n}\n\nmodule.exports = interceptorOpts => {\n if (\n interceptorOpts?.maxTTL != null &&\n (typeof interceptorOpts?.maxTTL !== 'number' || interceptorOpts?.maxTTL < 0)\n ) {\n throw new InvalidArgumentError('Invalid maxTTL. Must be a positive number')\n }\n\n if (\n interceptorOpts?.maxItems != null &&\n (typeof interceptorOpts?.maxItems !== 'number' ||\n interceptorOpts?.maxItems < 1)\n ) {\n throw new InvalidArgumentError(\n 'Invalid maxItems. Must be a positive number and greater than zero'\n )\n }\n\n if (\n interceptorOpts?.affinity != null &&\n interceptorOpts?.affinity !== 4 &&\n interceptorOpts?.affinity !== 6\n ) {\n throw new InvalidArgumentError('Invalid affinity. Must be either 4 or 6')\n }\n\n if (\n interceptorOpts?.dualStack != null &&\n typeof interceptorOpts?.dualStack !== 'boolean'\n ) {\n throw new InvalidArgumentError('Invalid dualStack. Must be a boolean')\n }\n\n if (\n interceptorOpts?.lookup != null &&\n typeof interceptorOpts?.lookup !== 'function'\n ) {\n throw new InvalidArgumentError('Invalid lookup. Must be a function')\n }\n\n if (\n interceptorOpts?.pick != null &&\n typeof interceptorOpts?.pick !== 'function'\n ) {\n throw new InvalidArgumentError('Invalid pick. Must be a function')\n }\n\n const dualStack = interceptorOpts?.dualStack ?? true\n let affinity\n if (dualStack) {\n affinity = interceptorOpts?.affinity ?? null\n } else {\n affinity = interceptorOpts?.affinity ?? 4\n }\n\n const opts = {\n maxTTL: interceptorOpts?.maxTTL ?? 10e3, // Expressed in ms\n lookup: interceptorOpts?.lookup ?? null,\n pick: interceptorOpts?.pick ?? null,\n dualStack,\n affinity,\n maxItems: interceptorOpts?.maxItems ?? Infinity\n }\n\n const instance = new DNSInstance(opts)\n\n return dispatch => {\n return function dnsInterceptor (origDispatchOpts, handler) {\n const origin =\n origDispatchOpts.origin.constructor === URL\n ? origDispatchOpts.origin\n : new URL(origDispatchOpts.origin)\n\n if (isIP(origin.hostname) !== 0) {\n return dispatch(origDispatchOpts, handler)\n }\n\n instance.runLookup(origin, origDispatchOpts, (err, newOrigin) => {\n if (err) {\n return handler.onError(err)\n }\n\n let dispatchOpts = null\n dispatchOpts = {\n ...origDispatchOpts,\n servername: origin.hostname, // For SNI on TLS\n origin: newOrigin,\n headers: {\n host: origin.hostname,\n ...origDispatchOpts.headers\n }\n }\n\n dispatch(\n dispatchOpts,\n instance.getHandler({ origin, dispatch, handler }, origDispatchOpts)\n )\n })\n\n return true\n }\n }\n}\n","// https://github.com/Ethan-Arrowood/undici-fetch\n\n'use strict'\n\nconst { kConstruct } = require('../../core/symbols')\nconst { kEnumerableProperty } = require('../../core/util')\nconst {\n iteratorMixin,\n isValidHeaderName,\n isValidHeaderValue\n} = require('./util')\nconst { webidl } = require('./webidl')\nconst assert = require('node:assert')\nconst util = require('node:util')\n\nconst kHeadersMap = Symbol('headers map')\nconst kHeadersSortedMap = Symbol('headers map sorted')\n\n/**\n * @param {number} code\n */\nfunction isHTTPWhiteSpaceCharCode (code) {\n return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize\n * @param {string} potentialValue\n */\nfunction headerValueNormalize (potentialValue) {\n // To normalize a byte sequence potentialValue, remove\n // any leading and trailing HTTP whitespace bytes from\n // potentialValue.\n let i = 0; let j = potentialValue.length\n\n while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j\n while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i\n\n return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j)\n}\n\nfunction fill (headers, object) {\n // To fill a Headers object headers with a given object object, run these steps:\n\n // 1. If object is a sequence, then for each header in object:\n // Note: webidl conversion to array has already been done.\n if (Array.isArray(object)) {\n for (let i = 0; i < object.length; ++i) {\n const header = object[i]\n // 1. If header does not contain exactly two items, then throw a TypeError.\n if (header.length !== 2) {\n throw webidl.errors.exception({\n header: 'Headers constructor',\n message: `expected name/value pair to be length 2, found ${header.length}.`\n })\n }\n\n // 2. Append (header’s first item, header’s second item) to headers.\n appendHeader(headers, header[0], header[1])\n }\n } else if (typeof object === 'object' && object !== null) {\n // Note: null should throw\n\n // 2. Otherwise, object is a record, then for each key → value in object,\n // append (key, value) to headers\n const keys = Object.keys(object)\n for (let i = 0; i < keys.length; ++i) {\n appendHeader(headers, keys[i], object[keys[i]])\n }\n } else {\n throw webidl.errors.conversionFailed({\n prefix: 'Headers constructor',\n argument: 'Argument 1',\n types: ['sequence>', 'record']\n })\n }\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#concept-headers-append\n */\nfunction appendHeader (headers, name, value) {\n // 1. Normalize value.\n value = headerValueNormalize(value)\n\n // 2. If name is not a header name or value is not a\n // header value, then throw a TypeError.\n if (!isValidHeaderName(name)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.append',\n value: name,\n type: 'header name'\n })\n } else if (!isValidHeaderValue(value)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.append',\n value,\n type: 'header value'\n })\n }\n\n // 3. If headers’s guard is \"immutable\", then throw a TypeError.\n // 4. Otherwise, if headers’s guard is \"request\" and name is a\n // forbidden header name, return.\n // 5. Otherwise, if headers’s guard is \"request-no-cors\":\n // TODO\n // Note: undici does not implement forbidden header names\n if (getHeadersGuard(headers) === 'immutable') {\n throw new TypeError('immutable')\n }\n\n // 6. Otherwise, if headers’s guard is \"response\" and name is a\n // forbidden response-header name, return.\n\n // 7. Append (name, value) to headers’s header list.\n return getHeadersList(headers).append(name, value, false)\n\n // 8. If headers’s guard is \"request-no-cors\", then remove\n // privileged no-CORS request headers from headers\n}\n\nfunction compareHeaderName (a, b) {\n return a[0] < b[0] ? -1 : 1\n}\n\nclass HeadersList {\n /** @type {[string, string][]|null} */\n cookies = null\n\n constructor (init) {\n if (init instanceof HeadersList) {\n this[kHeadersMap] = new Map(init[kHeadersMap])\n this[kHeadersSortedMap] = init[kHeadersSortedMap]\n this.cookies = init.cookies === null ? null : [...init.cookies]\n } else {\n this[kHeadersMap] = new Map(init)\n this[kHeadersSortedMap] = null\n }\n }\n\n /**\n * @see https://fetch.spec.whatwg.org/#header-list-contains\n * @param {string} name\n * @param {boolean} isLowerCase\n */\n contains (name, isLowerCase) {\n // A header list list contains a header name name if list\n // contains a header whose name is a byte-case-insensitive\n // match for name.\n\n return this[kHeadersMap].has(isLowerCase ? name : name.toLowerCase())\n }\n\n clear () {\n this[kHeadersMap].clear()\n this[kHeadersSortedMap] = null\n this.cookies = null\n }\n\n /**\n * @see https://fetch.spec.whatwg.org/#concept-header-list-append\n * @param {string} name\n * @param {string} value\n * @param {boolean} isLowerCase\n */\n append (name, value, isLowerCase) {\n this[kHeadersSortedMap] = null\n\n // 1. If list contains name, then set name to the first such\n // header’s name.\n const lowercaseName = isLowerCase ? name : name.toLowerCase()\n const exists = this[kHeadersMap].get(lowercaseName)\n\n // 2. Append (name, value) to list.\n if (exists) {\n const delimiter = lowercaseName === 'cookie' ? '; ' : ', '\n this[kHeadersMap].set(lowercaseName, {\n name: exists.name,\n value: `${exists.value}${delimiter}${value}`\n })\n } else {\n this[kHeadersMap].set(lowercaseName, { name, value })\n }\n\n if (lowercaseName === 'set-cookie') {\n (this.cookies ??= []).push(value)\n }\n }\n\n /**\n * @see https://fetch.spec.whatwg.org/#concept-header-list-set\n * @param {string} name\n * @param {string} value\n * @param {boolean} isLowerCase\n */\n set (name, value, isLowerCase) {\n this[kHeadersSortedMap] = null\n const lowercaseName = isLowerCase ? name : name.toLowerCase()\n\n if (lowercaseName === 'set-cookie') {\n this.cookies = [value]\n }\n\n // 1. If list contains name, then set the value of\n // the first such header to value and remove the\n // others.\n // 2. Otherwise, append header (name, value) to list.\n this[kHeadersMap].set(lowercaseName, { name, value })\n }\n\n /**\n * @see https://fetch.spec.whatwg.org/#concept-header-list-delete\n * @param {string} name\n * @param {boolean} isLowerCase\n */\n delete (name, isLowerCase) {\n this[kHeadersSortedMap] = null\n if (!isLowerCase) name = name.toLowerCase()\n\n if (name === 'set-cookie') {\n this.cookies = null\n }\n\n this[kHeadersMap].delete(name)\n }\n\n /**\n * @see https://fetch.spec.whatwg.org/#concept-header-list-get\n * @param {string} name\n * @param {boolean} isLowerCase\n * @returns {string | null}\n */\n get (name, isLowerCase) {\n // 1. If list does not contain name, then return null.\n // 2. Return the values of all headers in list whose name\n // is a byte-case-insensitive match for name,\n // separated from each other by 0x2C 0x20, in order.\n return this[kHeadersMap].get(isLowerCase ? name : name.toLowerCase())?.value ?? null\n }\n\n * [Symbol.iterator] () {\n // use the lowercased name\n for (const { 0: name, 1: { value } } of this[kHeadersMap]) {\n yield [name, value]\n }\n }\n\n get entries () {\n const headers = {}\n\n if (this[kHeadersMap].size !== 0) {\n for (const { name, value } of this[kHeadersMap].values()) {\n headers[name] = value\n }\n }\n\n return headers\n }\n\n rawValues () {\n return this[kHeadersMap].values()\n }\n\n get entriesList () {\n const headers = []\n\n if (this[kHeadersMap].size !== 0) {\n for (const { 0: lowerName, 1: { name, value } } of this[kHeadersMap]) {\n if (lowerName === 'set-cookie') {\n for (const cookie of this.cookies) {\n headers.push([name, cookie])\n }\n } else {\n headers.push([name, value])\n }\n }\n }\n\n return headers\n }\n\n // https://fetch.spec.whatwg.org/#convert-header-names-to-a-sorted-lowercase-set\n toSortedArray () {\n const size = this[kHeadersMap].size\n const array = new Array(size)\n // In most cases, you will use the fast-path.\n // fast-path: Use binary insertion sort for small arrays.\n if (size <= 32) {\n if (size === 0) {\n // If empty, it is an empty array. To avoid the first index assignment.\n return array\n }\n // Improve performance by unrolling loop and avoiding double-loop.\n // Double-loop-less version of the binary insertion sort.\n const iterator = this[kHeadersMap][Symbol.iterator]()\n const firstValue = iterator.next().value\n // set [name, value] to first index.\n array[0] = [firstValue[0], firstValue[1].value]\n // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine\n // 3.2.2. Assert: value is non-null.\n assert(firstValue[1].value !== null)\n for (\n let i = 1, j = 0, right = 0, left = 0, pivot = 0, x, value;\n i < size;\n ++i\n ) {\n // get next value\n value = iterator.next().value\n // set [name, value] to current index.\n x = array[i] = [value[0], value[1].value]\n // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine\n // 3.2.2. Assert: value is non-null.\n assert(x[1] !== null)\n left = 0\n right = i\n // binary search\n while (left < right) {\n // middle index\n pivot = left + ((right - left) >> 1)\n // compare header name\n if (array[pivot][0] <= x[0]) {\n left = pivot + 1\n } else {\n right = pivot\n }\n }\n if (i !== pivot) {\n j = i\n while (j > left) {\n array[j] = array[--j]\n }\n array[left] = x\n }\n }\n /* c8 ignore next 4 */\n if (!iterator.next().done) {\n // This is for debugging and will never be called.\n throw new TypeError('Unreachable')\n }\n return array\n } else {\n // This case would be a rare occurrence.\n // slow-path: fallback\n let i = 0\n for (const { 0: name, 1: { value } } of this[kHeadersMap]) {\n array[i++] = [name, value]\n // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine\n // 3.2.2. Assert: value is non-null.\n assert(value !== null)\n }\n return array.sort(compareHeaderName)\n }\n }\n}\n\n// https://fetch.spec.whatwg.org/#headers-class\nclass Headers {\n #guard\n #headersList\n\n constructor (init = undefined) {\n webidl.util.markAsUncloneable(this)\n\n if (init === kConstruct) {\n return\n }\n\n this.#headersList = new HeadersList()\n\n // The new Headers(init) constructor steps are:\n\n // 1. Set this’s guard to \"none\".\n this.#guard = 'none'\n\n // 2. If init is given, then fill this with init.\n if (init !== undefined) {\n init = webidl.converters.HeadersInit(init, 'Headers contructor', 'init')\n fill(this, init)\n }\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-append\n append (name, value) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 2, 'Headers.append')\n\n const prefix = 'Headers.append'\n name = webidl.converters.ByteString(name, prefix, 'name')\n value = webidl.converters.ByteString(value, prefix, 'value')\n\n return appendHeader(this, name, value)\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-delete\n delete (name) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 1, 'Headers.delete')\n\n const prefix = 'Headers.delete'\n name = webidl.converters.ByteString(name, prefix, 'name')\n\n // 1. If name is not a header name, then throw a TypeError.\n if (!isValidHeaderName(name)) {\n throw webidl.errors.invalidArgument({\n prefix: 'Headers.delete',\n value: name,\n type: 'header name'\n })\n }\n\n // 2. If this’s guard is \"immutable\", then throw a TypeError.\n // 3. Otherwise, if this’s guard is \"request\" and name is a\n // forbidden header name, return.\n // 4. Otherwise, if this’s guard is \"request-no-cors\", name\n // is not a no-CORS-safelisted request-header name, and\n // name is not a privileged no-CORS request-header name,\n // return.\n // 5. Otherwise, if this’s guard is \"response\" and name is\n // a forbidden response-header name, return.\n // Note: undici does not implement forbidden header names\n if (this.#guard === 'immutable') {\n throw new TypeError('immutable')\n }\n\n // 6. If this’s header list does not contain name, then\n // return.\n if (!this.#headersList.contains(name, false)) {\n return\n }\n\n // 7. Delete name from this’s header list.\n // 8. If this’s guard is \"request-no-cors\", then remove\n // privileged no-CORS request headers from this.\n this.#headersList.delete(name, false)\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-get\n get (name) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 1, 'Headers.get')\n\n const prefix = 'Headers.get'\n name = webidl.converters.ByteString(name, prefix, 'name')\n\n // 1. If name is not a header name, then throw a TypeError.\n if (!isValidHeaderName(name)) {\n throw webidl.errors.invalidArgument({\n prefix,\n value: name,\n type: 'header name'\n })\n }\n\n // 2. Return the result of getting name from this’s header\n // list.\n return this.#headersList.get(name, false)\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-has\n has (name) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 1, 'Headers.has')\n\n const prefix = 'Headers.has'\n name = webidl.converters.ByteString(name, prefix, 'name')\n\n // 1. If name is not a header name, then throw a TypeError.\n if (!isValidHeaderName(name)) {\n throw webidl.errors.invalidArgument({\n prefix,\n value: name,\n type: 'header name'\n })\n }\n\n // 2. Return true if this’s header list contains name;\n // otherwise false.\n return this.#headersList.contains(name, false)\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-set\n set (name, value) {\n webidl.brandCheck(this, Headers)\n\n webidl.argumentLengthCheck(arguments, 2, 'Headers.set')\n\n const prefix = 'Headers.set'\n name = webidl.converters.ByteString(name, prefix, 'name')\n value = webidl.converters.ByteString(value, prefix, 'value')\n\n // 1. Normalize value.\n value = headerValueNormalize(value)\n\n // 2. If name is not a header name or value is not a\n // header value, then throw a TypeError.\n if (!isValidHeaderName(name)) {\n throw webidl.errors.invalidArgument({\n prefix,\n value: name,\n type: 'header name'\n })\n } else if (!isValidHeaderValue(value)) {\n throw webidl.errors.invalidArgument({\n prefix,\n value,\n type: 'header value'\n })\n }\n\n // 3. If this’s guard is \"immutable\", then throw a TypeError.\n // 4. Otherwise, if this’s guard is \"request\" and name is a\n // forbidden header name, return.\n // 5. Otherwise, if this’s guard is \"request-no-cors\" and\n // name/value is not a no-CORS-safelisted request-header,\n // return.\n // 6. Otherwise, if this’s guard is \"response\" and name is a\n // forbidden response-header name, return.\n // Note: undici does not implement forbidden header names\n if (this.#guard === 'immutable') {\n throw new TypeError('immutable')\n }\n\n // 7. Set (name, value) in this’s header list.\n // 8. If this’s guard is \"request-no-cors\", then remove\n // privileged no-CORS request headers from this\n this.#headersList.set(name, value, false)\n }\n\n // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie\n getSetCookie () {\n webidl.brandCheck(this, Headers)\n\n // 1. If this’s header list does not contain `Set-Cookie`, then return « ».\n // 2. Return the values of all headers in this’s header list whose name is\n // a byte-case-insensitive match for `Set-Cookie`, in order.\n\n const list = this.#headersList.cookies\n\n if (list) {\n return [...list]\n }\n\n return []\n }\n\n // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine\n get [kHeadersSortedMap] () {\n if (this.#headersList[kHeadersSortedMap]) {\n return this.#headersList[kHeadersSortedMap]\n }\n\n // 1. Let headers be an empty list of headers with the key being the name\n // and value the value.\n const headers = []\n\n // 2. Let names be the result of convert header names to a sorted-lowercase\n // set with all the names of the headers in list.\n const names = this.#headersList.toSortedArray()\n\n const cookies = this.#headersList.cookies\n\n // fast-path\n if (cookies === null || cookies.length === 1) {\n // Note: The non-null assertion of value has already been done by `HeadersList#toSortedArray`\n return (this.#headersList[kHeadersSortedMap] = names)\n }\n\n // 3. For each name of names:\n for (let i = 0; i < names.length; ++i) {\n const { 0: name, 1: value } = names[i]\n // 1. If name is `set-cookie`, then:\n if (name === 'set-cookie') {\n // 1. Let values be a list of all values of headers in list whose name\n // is a byte-case-insensitive match for name, in order.\n\n // 2. For each value of values:\n // 1. Append (name, value) to headers.\n for (let j = 0; j < cookies.length; ++j) {\n headers.push([name, cookies[j]])\n }\n } else {\n // 2. Otherwise:\n\n // 1. Let value be the result of getting name from list.\n\n // 2. Assert: value is non-null.\n // Note: This operation was done by `HeadersList#toSortedArray`.\n\n // 3. Append (name, value) to headers.\n headers.push([name, value])\n }\n }\n\n // 4. Return headers.\n return (this.#headersList[kHeadersSortedMap] = headers)\n }\n\n [util.inspect.custom] (depth, options) {\n options.depth ??= depth\n\n return `Headers ${util.formatWithOptions(options, this.#headersList.entries)}`\n }\n\n static getHeadersGuard (o) {\n return o.#guard\n }\n\n static setHeadersGuard (o, guard) {\n o.#guard = guard\n }\n\n static getHeadersList (o) {\n return o.#headersList\n }\n\n static setHeadersList (o, list) {\n o.#headersList = list\n }\n}\n\nconst { getHeadersGuard, setHeadersGuard, getHeadersList, setHeadersList } = Headers\nReflect.deleteProperty(Headers, 'getHeadersGuard')\nReflect.deleteProperty(Headers, 'setHeadersGuard')\nReflect.deleteProperty(Headers, 'getHeadersList')\nReflect.deleteProperty(Headers, 'setHeadersList')\n\niteratorMixin('Headers', Headers, kHeadersSortedMap, 0, 1)\n\nObject.defineProperties(Headers.prototype, {\n append: kEnumerableProperty,\n delete: kEnumerableProperty,\n get: kEnumerableProperty,\n has: kEnumerableProperty,\n set: kEnumerableProperty,\n getSetCookie: kEnumerableProperty,\n [Symbol.toStringTag]: {\n value: 'Headers',\n configurable: true\n },\n [util.inspect.custom]: {\n enumerable: false\n }\n})\n\nwebidl.converters.HeadersInit = function (V, prefix, argument) {\n if (webidl.util.Type(V) === 'Object') {\n const iterator = Reflect.get(V, Symbol.iterator)\n\n // A work-around to ensure we send the properly-cased Headers when V is a Headers object.\n // Read https://github.com/nodejs/undici/pull/3159#issuecomment-2075537226 before touching, please.\n if (!util.types.isProxy(V) && iterator === Headers.prototype.entries) { // Headers object\n try {\n return getHeadersList(V).entriesList\n } catch {\n // fall-through\n }\n }\n\n if (typeof iterator === 'function') {\n return webidl.converters['sequence>'](V, prefix, argument, iterator.bind(V))\n }\n\n return webidl.converters['record'](V, prefix, argument)\n }\n\n throw webidl.errors.conversionFailed({\n prefix: 'Headers constructor',\n argument: 'Argument 1',\n types: ['sequence>', 'record']\n })\n}\n\nmodule.exports = {\n fill,\n // for test.\n compareHeaderName,\n Headers,\n HeadersList,\n getHeadersGuard,\n setHeadersGuard,\n setHeadersList,\n getHeadersList\n}\n","'use strict'\n\nconst { Headers, HeadersList, fill, getHeadersGuard, setHeadersGuard, setHeadersList } = require('./headers')\nconst { extractBody, cloneBody, mixinBody, hasFinalizationRegistry, streamRegistry, bodyUnusable } = require('./body')\nconst util = require('../../core/util')\nconst nodeUtil = require('node:util')\nconst { kEnumerableProperty } = util\nconst {\n isValidReasonPhrase,\n isCancelled,\n isAborted,\n isBlobLike,\n serializeJavascriptValueToJSONString,\n isErrorLike,\n isomorphicEncode,\n environmentSettingsObject: relevantRealm\n} = require('./util')\nconst {\n redirectStatusSet,\n nullBodyStatus\n} = require('./constants')\nconst { kState, kHeaders } = require('./symbols')\nconst { webidl } = require('./webidl')\nconst { FormData } = require('./formdata')\nconst { URLSerializer } = require('./data-url')\nconst { kConstruct } = require('../../core/symbols')\nconst assert = require('node:assert')\nconst { types } = require('node:util')\n\nconst textEncoder = new TextEncoder('utf-8')\n\n// https://fetch.spec.whatwg.org/#response-class\nclass Response {\n // Creates network error Response.\n static error () {\n // The static error() method steps are to return the result of creating a\n // Response object, given a new network error, \"immutable\", and this’s\n // relevant Realm.\n const responseObject = fromInnerResponse(makeNetworkError(), 'immutable')\n\n return responseObject\n }\n\n // https://fetch.spec.whatwg.org/#dom-response-json\n static json (data, init = {}) {\n webidl.argumentLengthCheck(arguments, 1, 'Response.json')\n\n if (init !== null) {\n init = webidl.converters.ResponseInit(init)\n }\n\n // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data.\n const bytes = textEncoder.encode(\n serializeJavascriptValueToJSONString(data)\n )\n\n // 2. Let body be the result of extracting bytes.\n const body = extractBody(bytes)\n\n // 3. Let responseObject be the result of creating a Response object, given a new response,\n // \"response\", and this’s relevant Realm.\n const responseObject = fromInnerResponse(makeResponse({}), 'response')\n\n // 4. Perform initialize a response given responseObject, init, and (body, \"application/json\").\n initializeResponse(responseObject, init, { body: body[0], type: 'application/json' })\n\n // 5. Return responseObject.\n return responseObject\n }\n\n // Creates a redirect Response that redirects to url with status status.\n static redirect (url, status = 302) {\n webidl.argumentLengthCheck(arguments, 1, 'Response.redirect')\n\n url = webidl.converters.USVString(url)\n status = webidl.converters['unsigned short'](status)\n\n // 1. Let parsedURL be the result of parsing url with current settings\n // object’s API base URL.\n // 2. If parsedURL is failure, then throw a TypeError.\n // TODO: base-URL?\n let parsedURL\n try {\n parsedURL = new URL(url, relevantRealm.settingsObject.baseUrl)\n } catch (err) {\n throw new TypeError(`Failed to parse URL from ${url}`, { cause: err })\n }\n\n // 3. If status is not a redirect status, then throw a RangeError.\n if (!redirectStatusSet.has(status)) {\n throw new RangeError(`Invalid status code ${status}`)\n }\n\n // 4. Let responseObject be the result of creating a Response object,\n // given a new response, \"immutable\", and this’s relevant Realm.\n const responseObject = fromInnerResponse(makeResponse({}), 'immutable')\n\n // 5. Set responseObject’s response’s status to status.\n responseObject[kState].status = status\n\n // 6. Let value be parsedURL, serialized and isomorphic encoded.\n const value = isomorphicEncode(URLSerializer(parsedURL))\n\n // 7. Append `Location`/value to responseObject’s response’s header list.\n responseObject[kState].headersList.append('location', value, true)\n\n // 8. Return responseObject.\n return responseObject\n }\n\n // https://fetch.spec.whatwg.org/#dom-response\n constructor (body = null, init = {}) {\n webidl.util.markAsUncloneable(this)\n if (body === kConstruct) {\n return\n }\n\n if (body !== null) {\n body = webidl.converters.BodyInit(body)\n }\n\n init = webidl.converters.ResponseInit(init)\n\n // 1. Set this’s response to a new response.\n this[kState] = makeResponse({})\n\n // 2. Set this’s headers to a new Headers object with this’s relevant\n // Realm, whose header list is this’s response’s header list and guard\n // is \"response\".\n this[kHeaders] = new Headers(kConstruct)\n setHeadersGuard(this[kHeaders], 'response')\n setHeadersList(this[kHeaders], this[kState].headersList)\n\n // 3. Let bodyWithType be null.\n let bodyWithType = null\n\n // 4. If body is non-null, then set bodyWithType to the result of extracting body.\n if (body != null) {\n const [extractedBody, type] = extractBody(body)\n bodyWithType = { body: extractedBody, type }\n }\n\n // 5. Perform initialize a response given this, init, and bodyWithType.\n initializeResponse(this, init, bodyWithType)\n }\n\n // Returns response’s type, e.g., \"cors\".\n get type () {\n webidl.brandCheck(this, Response)\n\n // The type getter steps are to return this’s response’s type.\n return this[kState].type\n }\n\n // Returns response’s URL, if it has one; otherwise the empty string.\n get url () {\n webidl.brandCheck(this, Response)\n\n const urlList = this[kState].urlList\n\n // The url getter steps are to return the empty string if this’s\n // response’s URL is null; otherwise this’s response’s URL,\n // serialized with exclude fragment set to true.\n const url = urlList[urlList.length - 1] ?? null\n\n if (url === null) {\n return ''\n }\n\n return URLSerializer(url, true)\n }\n\n // Returns whether response was obtained through a redirect.\n get redirected () {\n webidl.brandCheck(this, Response)\n\n // The redirected getter steps are to return true if this’s response’s URL\n // list has more than one item; otherwise false.\n return this[kState].urlList.length > 1\n }\n\n // Returns response’s status.\n get status () {\n webidl.brandCheck(this, Response)\n\n // The status getter steps are to return this’s response’s status.\n return this[kState].status\n }\n\n // Returns whether response’s status is an ok status.\n get ok () {\n webidl.brandCheck(this, Response)\n\n // The ok getter steps are to return true if this’s response’s status is an\n // ok status; otherwise false.\n return this[kState].status >= 200 && this[kState].status <= 299\n }\n\n // Returns response’s status message.\n get statusText () {\n webidl.brandCheck(this, Response)\n\n // The statusText getter steps are to return this’s response’s status\n // message.\n return this[kState].statusText\n }\n\n // Returns response’s headers as Headers.\n get headers () {\n webidl.brandCheck(this, Response)\n\n // The headers getter steps are to return this’s headers.\n return this[kHeaders]\n }\n\n get body () {\n webidl.brandCheck(this, Response)\n\n return this[kState].body ? this[kState].body.stream : null\n }\n\n get bodyUsed () {\n webidl.brandCheck(this, Response)\n\n return !!this[kState].body && util.isDisturbed(this[kState].body.stream)\n }\n\n // Returns a clone of response.\n clone () {\n webidl.brandCheck(this, Response)\n\n // 1. If this is unusable, then throw a TypeError.\n if (bodyUnusable(this)) {\n throw webidl.errors.exception({\n header: 'Response.clone',\n message: 'Body has already been consumed.'\n })\n }\n\n // 2. Let clonedResponse be the result of cloning this’s response.\n const clonedResponse = cloneResponse(this[kState])\n\n // Note: To re-register because of a new stream.\n if (hasFinalizationRegistry && this[kState].body?.stream) {\n streamRegistry.register(this, new WeakRef(this[kState].body.stream))\n }\n\n // 3. Return the result of creating a Response object, given\n // clonedResponse, this’s headers’s guard, and this’s relevant Realm.\n return fromInnerResponse(clonedResponse, getHeadersGuard(this[kHeaders]))\n }\n\n [nodeUtil.inspect.custom] (depth, options) {\n if (options.depth === null) {\n options.depth = 2\n }\n\n options.colors ??= true\n\n const properties = {\n status: this.status,\n statusText: this.statusText,\n headers: this.headers,\n body: this.body,\n bodyUsed: this.bodyUsed,\n ok: this.ok,\n redirected: this.redirected,\n type: this.type,\n url: this.url\n }\n\n return `Response ${nodeUtil.formatWithOptions(options, properties)}`\n }\n}\n\nmixinBody(Response)\n\nObject.defineProperties(Response.prototype, {\n type: kEnumerableProperty,\n url: kEnumerableProperty,\n status: kEnumerableProperty,\n ok: kEnumerableProperty,\n redirected: kEnumerableProperty,\n statusText: kEnumerableProperty,\n headers: kEnumerableProperty,\n clone: kEnumerableProperty,\n body: kEnumerableProperty,\n bodyUsed: kEnumerableProperty,\n [Symbol.toStringTag]: {\n value: 'Response',\n configurable: true\n }\n})\n\nObject.defineProperties(Response, {\n json: kEnumerableProperty,\n redirect: kEnumerableProperty,\n error: kEnumerableProperty\n})\n\n// https://fetch.spec.whatwg.org/#concept-response-clone\nfunction cloneResponse (response) {\n // To clone a response response, run these steps:\n\n // 1. If response is a filtered response, then return a new identical\n // filtered response whose internal response is a clone of response’s\n // internal response.\n if (response.internalResponse) {\n return filterResponse(\n cloneResponse(response.internalResponse),\n response.type\n )\n }\n\n // 2. Let newResponse be a copy of response, except for its body.\n const newResponse = makeResponse({ ...response, body: null })\n\n // 3. If response’s body is non-null, then set newResponse’s body to the\n // result of cloning response’s body.\n if (response.body != null) {\n newResponse.body = cloneBody(newResponse, response.body)\n }\n\n // 4. Return newResponse.\n return newResponse\n}\n\nfunction makeResponse (init) {\n return {\n aborted: false,\n rangeRequested: false,\n timingAllowPassed: false,\n requestIncludesCredentials: false,\n type: 'default',\n status: 200,\n timingInfo: null,\n cacheState: '',\n statusText: '',\n ...init,\n headersList: init?.headersList\n ? new HeadersList(init?.headersList)\n : new HeadersList(),\n urlList: init?.urlList ? [...init.urlList] : []\n }\n}\n\nfunction makeNetworkError (reason) {\n const isError = isErrorLike(reason)\n return makeResponse({\n type: 'error',\n status: 0,\n error: isError\n ? reason\n : new Error(reason ? String(reason) : reason),\n aborted: reason && reason.name === 'AbortError'\n })\n}\n\n// @see https://fetch.spec.whatwg.org/#concept-network-error\nfunction isNetworkError (response) {\n return (\n // A network error is a response whose type is \"error\",\n response.type === 'error' &&\n // status is 0\n response.status === 0\n )\n}\n\nfunction makeFilteredResponse (response, state) {\n state = {\n internalResponse: response,\n ...state\n }\n\n return new Proxy(response, {\n get (target, p) {\n return p in state ? state[p] : target[p]\n },\n set (target, p, value) {\n assert(!(p in state))\n target[p] = value\n return true\n }\n })\n}\n\n// https://fetch.spec.whatwg.org/#concept-filtered-response\nfunction filterResponse (response, type) {\n // Set response to the following filtered response with response as its\n // internal response, depending on request’s response tainting:\n if (type === 'basic') {\n // A basic filtered response is a filtered response whose type is \"basic\"\n // and header list excludes any headers in internal response’s header list\n // whose name is a forbidden response-header name.\n\n // Note: undici does not implement forbidden response-header names\n return makeFilteredResponse(response, {\n type: 'basic',\n headersList: response.headersList\n })\n } else if (type === 'cors') {\n // A CORS filtered response is a filtered response whose type is \"cors\"\n // and header list excludes any headers in internal response’s header\n // list whose name is not a CORS-safelisted response-header name, given\n // internal response’s CORS-exposed header-name list.\n\n // Note: undici does not implement CORS-safelisted response-header names\n return makeFilteredResponse(response, {\n type: 'cors',\n headersList: response.headersList\n })\n } else if (type === 'opaque') {\n // An opaque filtered response is a filtered response whose type is\n // \"opaque\", URL list is the empty list, status is 0, status message\n // is the empty byte sequence, header list is empty, and body is null.\n\n return makeFilteredResponse(response, {\n type: 'opaque',\n urlList: Object.freeze([]),\n status: 0,\n statusText: '',\n body: null\n })\n } else if (type === 'opaqueredirect') {\n // An opaque-redirect filtered response is a filtered response whose type\n // is \"opaqueredirect\", status is 0, status message is the empty byte\n // sequence, header list is empty, and body is null.\n\n return makeFilteredResponse(response, {\n type: 'opaqueredirect',\n status: 0,\n statusText: '',\n headersList: [],\n body: null\n })\n } else {\n assert(false)\n }\n}\n\n// https://fetch.spec.whatwg.org/#appropriate-network-error\nfunction makeAppropriateNetworkError (fetchParams, err = null) {\n // 1. Assert: fetchParams is canceled.\n assert(isCancelled(fetchParams))\n\n // 2. Return an aborted network error if fetchParams is aborted;\n // otherwise return a network error.\n return isAborted(fetchParams)\n ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err }))\n : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err }))\n}\n\n// https://whatpr.org/fetch/1392.html#initialize-a-response\nfunction initializeResponse (response, init, body) {\n // 1. If init[\"status\"] is not in the range 200 to 599, inclusive, then\n // throw a RangeError.\n if (init.status !== null && (init.status < 200 || init.status > 599)) {\n throw new RangeError('init[\"status\"] must be in the range of 200 to 599, inclusive.')\n }\n\n // 2. If init[\"statusText\"] does not match the reason-phrase token production,\n // then throw a TypeError.\n if ('statusText' in init && init.statusText != null) {\n // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2:\n // reason-phrase = *( HTAB / SP / VCHAR / obs-text )\n if (!isValidReasonPhrase(String(init.statusText))) {\n throw new TypeError('Invalid statusText')\n }\n }\n\n // 3. Set response’s response’s status to init[\"status\"].\n if ('status' in init && init.status != null) {\n response[kState].status = init.status\n }\n\n // 4. Set response’s response’s status message to init[\"statusText\"].\n if ('statusText' in init && init.statusText != null) {\n response[kState].statusText = init.statusText\n }\n\n // 5. If init[\"headers\"] exists, then fill response’s headers with init[\"headers\"].\n if ('headers' in init && init.headers != null) {\n fill(response[kHeaders], init.headers)\n }\n\n // 6. If body was given, then:\n if (body) {\n // 1. If response's status is a null body status, then throw a TypeError.\n if (nullBodyStatus.includes(response.status)) {\n throw webidl.errors.exception({\n header: 'Response constructor',\n message: `Invalid response status code ${response.status}`\n })\n }\n\n // 2. Set response's body to body's body.\n response[kState].body = body.body\n\n // 3. If body's type is non-null and response's header list does not contain\n // `Content-Type`, then append (`Content-Type`, body's type) to response's header list.\n if (body.type != null && !response[kState].headersList.contains('content-type', true)) {\n response[kState].headersList.append('content-type', body.type, true)\n }\n }\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#response-create\n * @param {any} innerResponse\n * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard\n * @returns {Response}\n */\nfunction fromInnerResponse (innerResponse, guard) {\n const response = new Response(kConstruct)\n response[kState] = innerResponse\n response[kHeaders] = new Headers(kConstruct)\n setHeadersList(response[kHeaders], innerResponse.headersList)\n setHeadersGuard(response[kHeaders], guard)\n\n if (hasFinalizationRegistry && innerResponse.body?.stream) {\n // If the target (response) is reclaimed, the cleanup callback may be called at some point with\n // the held value provided for it (innerResponse.body.stream). The held value can be any value:\n // a primitive or an object, even undefined. If the held value is an object, the registry keeps\n // a strong reference to it (so it can pass it to the cleanup callback later). Reworded from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry\n streamRegistry.register(response, new WeakRef(innerResponse.body.stream))\n }\n\n return response\n}\n\nwebidl.converters.ReadableStream = webidl.interfaceConverter(\n ReadableStream\n)\n\nwebidl.converters.FormData = webidl.interfaceConverter(\n FormData\n)\n\nwebidl.converters.URLSearchParams = webidl.interfaceConverter(\n URLSearchParams\n)\n\n// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit\nwebidl.converters.XMLHttpRequestBodyInit = function (V, prefix, name) {\n if (typeof V === 'string') {\n return webidl.converters.USVString(V, prefix, name)\n }\n\n if (isBlobLike(V)) {\n return webidl.converters.Blob(V, prefix, name, { strict: false })\n }\n\n if (ArrayBuffer.isView(V) || types.isArrayBuffer(V)) {\n return webidl.converters.BufferSource(V, prefix, name)\n }\n\n if (util.isFormDataLike(V)) {\n return webidl.converters.FormData(V, prefix, name, { strict: false })\n }\n\n if (V instanceof URLSearchParams) {\n return webidl.converters.URLSearchParams(V, prefix, name)\n }\n\n return webidl.converters.DOMString(V, prefix, name)\n}\n\n// https://fetch.spec.whatwg.org/#bodyinit\nwebidl.converters.BodyInit = function (V, prefix, argument) {\n if (V instanceof ReadableStream) {\n return webidl.converters.ReadableStream(V, prefix, argument)\n }\n\n // Note: the spec doesn't include async iterables,\n // this is an undici extension.\n if (V?.[Symbol.asyncIterator]) {\n return V\n }\n\n return webidl.converters.XMLHttpRequestBodyInit(V, prefix, argument)\n}\n\nwebidl.converters.ResponseInit = webidl.dictionaryConverter([\n {\n key: 'status',\n converter: webidl.converters['unsigned short'],\n defaultValue: () => 200\n },\n {\n key: 'statusText',\n converter: webidl.converters.ByteString,\n defaultValue: () => ''\n },\n {\n key: 'headers',\n converter: webidl.converters.HeadersInit\n }\n])\n\nmodule.exports = {\n isNetworkError,\n makeNetworkError,\n makeResponse,\n makeAppropriateNetworkError,\n filterResponse,\n Response,\n cloneResponse,\n fromInnerResponse\n}\n","'use strict'\n\nconst { kConnected, kSize } = require('../../core/symbols')\n\nclass CompatWeakRef {\n constructor (value) {\n this.value = value\n }\n\n deref () {\n return this.value[kConnected] === 0 && this.value[kSize] === 0\n ? undefined\n : this.value\n }\n}\n\nclass CompatFinalizer {\n constructor (finalizer) {\n this.finalizer = finalizer\n }\n\n register (dispatcher, key) {\n if (dispatcher.on) {\n dispatcher.on('disconnect', () => {\n if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {\n this.finalizer(key)\n }\n })\n }\n }\n\n unregister (key) {}\n}\n\nmodule.exports = function () {\n // FIXME: remove workaround when the Node bug is backported to v18\n // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308\n if (process.env.NODE_V8_COVERAGE && process.version.startsWith('v18')) {\n process._rawDebug('Using compatibility WeakRef and FinalizationRegistry')\n return {\n WeakRef: CompatWeakRef,\n FinalizationRegistry: CompatFinalizer\n }\n }\n return { WeakRef, FinalizationRegistry }\n}\n","/* globals AbortController */\n\n'use strict'\n\nconst { extractBody, mixinBody, cloneBody, bodyUnusable } = require('./body')\nconst { Headers, fill: fillHeaders, HeadersList, setHeadersGuard, getHeadersGuard, setHeadersList, getHeadersList } = require('./headers')\nconst { FinalizationRegistry } = require('./dispatcher-weakref')()\nconst util = require('../../core/util')\nconst nodeUtil = require('node:util')\nconst {\n isValidHTTPToken,\n sameOrigin,\n environmentSettingsObject\n} = require('./util')\nconst {\n forbiddenMethodsSet,\n corsSafeListedMethodsSet,\n referrerPolicy,\n requestRedirect,\n requestMode,\n requestCredentials,\n requestCache,\n requestDuplex\n} = require('./constants')\nconst { kEnumerableProperty, normalizedMethodRecordsBase, normalizedMethodRecords } = util\nconst { kHeaders, kSignal, kState, kDispatcher } = require('./symbols')\nconst { webidl } = require('./webidl')\nconst { URLSerializer } = require('./data-url')\nconst { kConstruct } = require('../../core/symbols')\nconst assert = require('node:assert')\nconst { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = require('node:events')\n\nconst kAbortController = Symbol('abortController')\n\nconst requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {\n signal.removeEventListener('abort', abort)\n})\n\nconst dependentControllerMap = new WeakMap()\n\nfunction buildAbort (acRef) {\n return abort\n\n function abort () {\n const ac = acRef.deref()\n if (ac !== undefined) {\n // Currently, there is a problem with FinalizationRegistry.\n // https://github.com/nodejs/node/issues/49344\n // https://github.com/nodejs/node/issues/47748\n // In the case of abort, the first step is to unregister from it.\n // If the controller can refer to it, it is still registered.\n // It will be removed in the future.\n requestFinalizer.unregister(abort)\n\n // Unsubscribe a listener.\n // FinalizationRegistry will no longer be called, so this must be done.\n this.removeEventListener('abort', abort)\n\n ac.abort(this.reason)\n\n const controllerList = dependentControllerMap.get(ac.signal)\n\n if (controllerList !== undefined) {\n if (controllerList.size !== 0) {\n for (const ref of controllerList) {\n const ctrl = ref.deref()\n if (ctrl !== undefined) {\n ctrl.abort(this.reason)\n }\n }\n controllerList.clear()\n }\n dependentControllerMap.delete(ac.signal)\n }\n }\n }\n}\n\nlet patchMethodWarning = false\n\n// https://fetch.spec.whatwg.org/#request-class\nclass Request {\n // https://fetch.spec.whatwg.org/#dom-request\n constructor (input, init = {}) {\n webidl.util.markAsUncloneable(this)\n if (input === kConstruct) {\n return\n }\n\n const prefix = 'Request constructor'\n webidl.argumentLengthCheck(arguments, 1, prefix)\n\n input = webidl.converters.RequestInfo(input, prefix, 'input')\n init = webidl.converters.RequestInit(init, prefix, 'init')\n\n // 1. Let request be null.\n let request = null\n\n // 2. Let fallbackMode be null.\n let fallbackMode = null\n\n // 3. Let baseURL be this’s relevant settings object’s API base URL.\n const baseUrl = environmentSettingsObject.settingsObject.baseUrl\n\n // 4. Let signal be null.\n let signal = null\n\n // 5. If input is a string, then:\n if (typeof input === 'string') {\n this[kDispatcher] = init.dispatcher\n\n // 1. Let parsedURL be the result of parsing input with baseURL.\n // 2. If parsedURL is failure, then throw a TypeError.\n let parsedURL\n try {\n parsedURL = new URL(input, baseUrl)\n } catch (err) {\n throw new TypeError('Failed to parse URL from ' + input, { cause: err })\n }\n\n // 3. If parsedURL includes credentials, then throw a TypeError.\n if (parsedURL.username || parsedURL.password) {\n throw new TypeError(\n 'Request cannot be constructed from a URL that includes credentials: ' +\n input\n )\n }\n\n // 4. Set request to a new request whose URL is parsedURL.\n request = makeRequest({ urlList: [parsedURL] })\n\n // 5. Set fallbackMode to \"cors\".\n fallbackMode = 'cors'\n } else {\n this[kDispatcher] = init.dispatcher || input[kDispatcher]\n\n // 6. Otherwise:\n\n // 7. Assert: input is a Request object.\n assert(input instanceof Request)\n\n // 8. Set request to input’s request.\n request = input[kState]\n\n // 9. Set signal to input’s signal.\n signal = input[kSignal]\n }\n\n // 7. Let origin be this’s relevant settings object’s origin.\n const origin = environmentSettingsObject.settingsObject.origin\n\n // 8. Let window be \"client\".\n let window = 'client'\n\n // 9. If request’s window is an environment settings object and its origin\n // is same origin with origin, then set window to request’s window.\n if (\n request.window?.constructor?.name === 'EnvironmentSettingsObject' &&\n sameOrigin(request.window, origin)\n ) {\n window = request.window\n }\n\n // 10. If init[\"window\"] exists and is non-null, then throw a TypeError.\n if (init.window != null) {\n throw new TypeError(`'window' option '${window}' must be null`)\n }\n\n // 11. If init[\"window\"] exists, then set window to \"no-window\".\n if ('window' in init) {\n window = 'no-window'\n }\n\n // 12. Set request to a new request with the following properties:\n request = makeRequest({\n // URL request’s URL.\n // undici implementation note: this is set as the first item in request's urlList in makeRequest\n // method request’s method.\n method: request.method,\n // header list A copy of request’s header list.\n // undici implementation note: headersList is cloned in makeRequest\n headersList: request.headersList,\n // unsafe-request flag Set.\n unsafeRequest: request.unsafeRequest,\n // client This’s relevant settings object.\n client: environmentSettingsObject.settingsObject,\n // window window.\n window,\n // priority request’s priority.\n priority: request.priority,\n // origin request’s origin. The propagation of the origin is only significant for navigation requests\n // being handled by a service worker. In this scenario a request can have an origin that is different\n // from the current client.\n origin: request.origin,\n // referrer request’s referrer.\n referrer: request.referrer,\n // referrer policy request’s referrer policy.\n referrerPolicy: request.referrerPolicy,\n // mode request’s mode.\n mode: request.mode,\n // credentials mode request’s credentials mode.\n credentials: request.credentials,\n // cache mode request’s cache mode.\n cache: request.cache,\n // redirect mode request’s redirect mode.\n redirect: request.redirect,\n // integrity metadata request’s integrity metadata.\n integrity: request.integrity,\n // keepalive request’s keepalive.\n keepalive: request.keepalive,\n // reload-navigation flag request’s reload-navigation flag.\n reloadNavigation: request.reloadNavigation,\n // history-navigation flag request’s history-navigation flag.\n historyNavigation: request.historyNavigation,\n // URL list A clone of request’s URL list.\n urlList: [...request.urlList]\n })\n\n const initHasKey = Object.keys(init).length !== 0\n\n // 13. If init is not empty, then:\n if (initHasKey) {\n // 1. If request’s mode is \"navigate\", then set it to \"same-origin\".\n if (request.mode === 'navigate') {\n request.mode = 'same-origin'\n }\n\n // 2. Unset request’s reload-navigation flag.\n request.reloadNavigation = false\n\n // 3. Unset request’s history-navigation flag.\n request.historyNavigation = false\n\n // 4. Set request’s origin to \"client\".\n request.origin = 'client'\n\n // 5. Set request’s referrer to \"client\"\n request.referrer = 'client'\n\n // 6. Set request’s referrer policy to the empty string.\n request.referrerPolicy = ''\n\n // 7. Set request’s URL to request’s current URL.\n request.url = request.urlList[request.urlList.length - 1]\n\n // 8. Set request’s URL list to « request’s URL ».\n request.urlList = [request.url]\n }\n\n // 14. If init[\"referrer\"] exists, then:\n if (init.referrer !== undefined) {\n // 1. Let referrer be init[\"referrer\"].\n const referrer = init.referrer\n\n // 2. If referrer is the empty string, then set request’s referrer to \"no-referrer\".\n if (referrer === '') {\n request.referrer = 'no-referrer'\n } else {\n // 1. Let parsedReferrer be the result of parsing referrer with\n // baseURL.\n // 2. If parsedReferrer is failure, then throw a TypeError.\n let parsedReferrer\n try {\n parsedReferrer = new URL(referrer, baseUrl)\n } catch (err) {\n throw new TypeError(`Referrer \"${referrer}\" is not a valid URL.`, { cause: err })\n }\n\n // 3. If one of the following is true\n // - parsedReferrer’s scheme is \"about\" and path is the string \"client\"\n // - parsedReferrer’s origin is not same origin with origin\n // then set request’s referrer to \"client\".\n if (\n (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') ||\n (origin && !sameOrigin(parsedReferrer, environmentSettingsObject.settingsObject.baseUrl))\n ) {\n request.referrer = 'client'\n } else {\n // 4. Otherwise, set request’s referrer to parsedReferrer.\n request.referrer = parsedReferrer\n }\n }\n }\n\n // 15. If init[\"referrerPolicy\"] exists, then set request’s referrer policy\n // to it.\n if (init.referrerPolicy !== undefined) {\n request.referrerPolicy = init.referrerPolicy\n }\n\n // 16. Let mode be init[\"mode\"] if it exists, and fallbackMode otherwise.\n let mode\n if (init.mode !== undefined) {\n mode = init.mode\n } else {\n mode = fallbackMode\n }\n\n // 17. If mode is \"navigate\", then throw a TypeError.\n if (mode === 'navigate') {\n throw webidl.errors.exception({\n header: 'Request constructor',\n message: 'invalid request mode navigate.'\n })\n }\n\n // 18. If mode is non-null, set request’s mode to mode.\n if (mode != null) {\n request.mode = mode\n }\n\n // 19. If init[\"credentials\"] exists, then set request’s credentials mode\n // to it.\n if (init.credentials !== undefined) {\n request.credentials = init.credentials\n }\n\n // 18. If init[\"cache\"] exists, then set request’s cache mode to it.\n if (init.cache !== undefined) {\n request.cache = init.cache\n }\n\n // 21. If request’s cache mode is \"only-if-cached\" and request’s mode is\n // not \"same-origin\", then throw a TypeError.\n if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {\n throw new TypeError(\n \"'only-if-cached' can be set only with 'same-origin' mode\"\n )\n }\n\n // 22. If init[\"redirect\"] exists, then set request’s redirect mode to it.\n if (init.redirect !== undefined) {\n request.redirect = init.redirect\n }\n\n // 23. If init[\"integrity\"] exists, then set request’s integrity metadata to it.\n if (init.integrity != null) {\n request.integrity = String(init.integrity)\n }\n\n // 24. If init[\"keepalive\"] exists, then set request’s keepalive to it.\n if (init.keepalive !== undefined) {\n request.keepalive = Boolean(init.keepalive)\n }\n\n // 25. If init[\"method\"] exists, then:\n if (init.method !== undefined) {\n // 1. Let method be init[\"method\"].\n let method = init.method\n\n const mayBeNormalized = normalizedMethodRecords[method]\n\n if (mayBeNormalized !== undefined) {\n // Note: Bypass validation DELETE, GET, HEAD, OPTIONS, POST, PUT, PATCH and these lowercase ones\n request.method = mayBeNormalized\n } else {\n // 2. If method is not a method or method is a forbidden method, then\n // throw a TypeError.\n if (!isValidHTTPToken(method)) {\n throw new TypeError(`'${method}' is not a valid HTTP method.`)\n }\n\n const upperCase = method.toUpperCase()\n\n if (forbiddenMethodsSet.has(upperCase)) {\n throw new TypeError(`'${method}' HTTP method is unsupported.`)\n }\n\n // 3. Normalize method.\n // https://fetch.spec.whatwg.org/#concept-method-normalize\n // Note: must be in uppercase\n method = normalizedMethodRecordsBase[upperCase] ?? method\n\n // 4. Set request’s method to method.\n request.method = method\n }\n\n if (!patchMethodWarning && request.method === 'patch') {\n process.emitWarning('Using `patch` is highly likely to result in a `405 Method Not Allowed`. `PATCH` is much more likely to succeed.', {\n code: 'UNDICI-FETCH-patch'\n })\n\n patchMethodWarning = true\n }\n }\n\n // 26. If init[\"signal\"] exists, then set signal to it.\n if (init.signal !== undefined) {\n signal = init.signal\n }\n\n // 27. Set this’s request to request.\n this[kState] = request\n\n // 28. Set this’s signal to a new AbortSignal object with this’s relevant\n // Realm.\n // TODO: could this be simplified with AbortSignal.any\n // (https://dom.spec.whatwg.org/#dom-abortsignal-any)\n const ac = new AbortController()\n this[kSignal] = ac.signal\n\n // 29. If signal is not null, then make this’s signal follow signal.\n if (signal != null) {\n if (\n !signal ||\n typeof signal.aborted !== 'boolean' ||\n typeof signal.addEventListener !== 'function'\n ) {\n throw new TypeError(\n \"Failed to construct 'Request': member signal is not of type AbortSignal.\"\n )\n }\n\n if (signal.aborted) {\n ac.abort(signal.reason)\n } else {\n // Keep a strong ref to ac while request object\n // is alive. This is needed to prevent AbortController\n // from being prematurely garbage collected.\n // See, https://github.com/nodejs/undici/issues/1926.\n this[kAbortController] = ac\n\n const acRef = new WeakRef(ac)\n const abort = buildAbort(acRef)\n\n // Third-party AbortControllers may not work with these.\n // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619.\n try {\n // If the max amount of listeners is equal to the default, increase it\n // This is only available in node >= v19.9.0\n if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) {\n setMaxListeners(1500, signal)\n } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) {\n setMaxListeners(1500, signal)\n }\n } catch {}\n\n util.addAbortListener(signal, abort)\n // The third argument must be a registry key to be unregistered.\n // Without it, you cannot unregister.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry\n // abort is used as the unregister key. (because it is unique)\n requestFinalizer.register(ac, { signal, abort }, abort)\n }\n }\n\n // 30. Set this’s headers to a new Headers object with this’s relevant\n // Realm, whose header list is request’s header list and guard is\n // \"request\".\n this[kHeaders] = new Headers(kConstruct)\n setHeadersList(this[kHeaders], request.headersList)\n setHeadersGuard(this[kHeaders], 'request')\n\n // 31. If this’s request’s mode is \"no-cors\", then:\n if (mode === 'no-cors') {\n // 1. If this’s request’s method is not a CORS-safelisted method,\n // then throw a TypeError.\n if (!corsSafeListedMethodsSet.has(request.method)) {\n throw new TypeError(\n `'${request.method} is unsupported in no-cors mode.`\n )\n }\n\n // 2. Set this’s headers’s guard to \"request-no-cors\".\n setHeadersGuard(this[kHeaders], 'request-no-cors')\n }\n\n // 32. If init is not empty, then:\n if (initHasKey) {\n /** @type {HeadersList} */\n const headersList = getHeadersList(this[kHeaders])\n // 1. Let headers be a copy of this’s headers and its associated header\n // list.\n // 2. If init[\"headers\"] exists, then set headers to init[\"headers\"].\n const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList)\n\n // 3. Empty this’s headers’s header list.\n headersList.clear()\n\n // 4. If headers is a Headers object, then for each header in its header\n // list, append header’s name/header’s value to this’s headers.\n if (headers instanceof HeadersList) {\n for (const { name, value } of headers.rawValues()) {\n headersList.append(name, value, false)\n }\n // Note: Copy the `set-cookie` meta-data.\n headersList.cookies = headers.cookies\n } else {\n // 5. Otherwise, fill this’s headers with headers.\n fillHeaders(this[kHeaders], headers)\n }\n }\n\n // 33. Let inputBody be input’s request’s body if input is a Request\n // object; otherwise null.\n const inputBody = input instanceof Request ? input[kState].body : null\n\n // 34. If either init[\"body\"] exists and is non-null or inputBody is\n // non-null, and request’s method is `GET` or `HEAD`, then throw a\n // TypeError.\n if (\n (init.body != null || inputBody != null) &&\n (request.method === 'GET' || request.method === 'HEAD')\n ) {\n throw new TypeError('Request with GET/HEAD method cannot have body.')\n }\n\n // 35. Let initBody be null.\n let initBody = null\n\n // 36. If init[\"body\"] exists and is non-null, then:\n if (init.body != null) {\n // 1. Let Content-Type be null.\n // 2. Set initBody and Content-Type to the result of extracting\n // init[\"body\"], with keepalive set to request’s keepalive.\n const [extractedBody, contentType] = extractBody(\n init.body,\n request.keepalive\n )\n initBody = extractedBody\n\n // 3, If Content-Type is non-null and this’s headers’s header list does\n // not contain `Content-Type`, then append `Content-Type`/Content-Type to\n // this’s headers.\n if (contentType && !getHeadersList(this[kHeaders]).contains('content-type', true)) {\n this[kHeaders].append('content-type', contentType)\n }\n }\n\n // 37. Let inputOrInitBody be initBody if it is non-null; otherwise\n // inputBody.\n const inputOrInitBody = initBody ?? inputBody\n\n // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is\n // null, then:\n if (inputOrInitBody != null && inputOrInitBody.source == null) {\n // 1. If initBody is non-null and init[\"duplex\"] does not exist,\n // then throw a TypeError.\n if (initBody != null && init.duplex == null) {\n throw new TypeError('RequestInit: duplex option is required when sending a body.')\n }\n\n // 2. If this’s request’s mode is neither \"same-origin\" nor \"cors\",\n // then throw a TypeError.\n if (request.mode !== 'same-origin' && request.mode !== 'cors') {\n throw new TypeError(\n 'If request is made from ReadableStream, mode should be \"same-origin\" or \"cors\"'\n )\n }\n\n // 3. Set this’s request’s use-CORS-preflight flag.\n request.useCORSPreflightFlag = true\n }\n\n // 39. Let finalBody be inputOrInitBody.\n let finalBody = inputOrInitBody\n\n // 40. If initBody is null and inputBody is non-null, then:\n if (initBody == null && inputBody != null) {\n // 1. If input is unusable, then throw a TypeError.\n if (bodyUnusable(input)) {\n throw new TypeError(\n 'Cannot construct a Request with a Request object that has already been used.'\n )\n }\n\n // 2. Set finalBody to the result of creating a proxy for inputBody.\n // https://streams.spec.whatwg.org/#readablestream-create-a-proxy\n const identityTransform = new TransformStream()\n inputBody.stream.pipeThrough(identityTransform)\n finalBody = {\n source: inputBody.source,\n length: inputBody.length,\n stream: identityTransform.readable\n }\n }\n\n // 41. Set this’s request’s body to finalBody.\n this[kState].body = finalBody\n }\n\n // Returns request’s HTTP method, which is \"GET\" by default.\n get method () {\n webidl.brandCheck(this, Request)\n\n // The method getter steps are to return this’s request’s method.\n return this[kState].method\n }\n\n // Returns the URL of request as a string.\n get url () {\n webidl.brandCheck(this, Request)\n\n // The url getter steps are to return this’s request’s URL, serialized.\n return URLSerializer(this[kState].url)\n }\n\n // Returns a Headers object consisting of the headers associated with request.\n // Note that headers added in the network layer by the user agent will not\n // be accounted for in this object, e.g., the \"Host\" header.\n get headers () {\n webidl.brandCheck(this, Request)\n\n // The headers getter steps are to return this’s headers.\n return this[kHeaders]\n }\n\n // Returns the kind of resource requested by request, e.g., \"document\"\n // or \"script\".\n get destination () {\n webidl.brandCheck(this, Request)\n\n // The destination getter are to return this’s request’s destination.\n return this[kState].destination\n }\n\n // Returns the referrer of request. Its value can be a same-origin URL if\n // explicitly set in init, the empty string to indicate no referrer, and\n // \"about:client\" when defaulting to the global’s default. This is used\n // during fetching to determine the value of the `Referer` header of the\n // request being made.\n get referrer () {\n webidl.brandCheck(this, Request)\n\n // 1. If this’s request’s referrer is \"no-referrer\", then return the\n // empty string.\n if (this[kState].referrer === 'no-referrer') {\n return ''\n }\n\n // 2. If this’s request’s referrer is \"client\", then return\n // \"about:client\".\n if (this[kState].referrer === 'client') {\n return 'about:client'\n }\n\n // Return this’s request’s referrer, serialized.\n return this[kState].referrer.toString()\n }\n\n // Returns the referrer policy associated with request.\n // This is used during fetching to compute the value of the request’s\n // referrer.\n get referrerPolicy () {\n webidl.brandCheck(this, Request)\n\n // The referrerPolicy getter steps are to return this’s request’s referrer policy.\n return this[kState].referrerPolicy\n }\n\n // Returns the mode associated with request, which is a string indicating\n // whether the request will use CORS, or will be restricted to same-origin\n // URLs.\n get mode () {\n webidl.brandCheck(this, Request)\n\n // The mode getter steps are to return this’s request’s mode.\n return this[kState].mode\n }\n\n // Returns the credentials mode associated with request,\n // which is a string indicating whether credentials will be sent with the\n // request always, never, or only when sent to a same-origin URL.\n get credentials () {\n // The credentials getter steps are to return this’s request’s credentials mode.\n return this[kState].credentials\n }\n\n // Returns the cache mode associated with request,\n // which is a string indicating how the request will\n // interact with the browser’s cache when fetching.\n get cache () {\n webidl.brandCheck(this, Request)\n\n // The cache getter steps are to return this’s request’s cache mode.\n return this[kState].cache\n }\n\n // Returns the redirect mode associated with request,\n // which is a string indicating how redirects for the\n // request will be handled during fetching. A request\n // will follow redirects by default.\n get redirect () {\n webidl.brandCheck(this, Request)\n\n // The redirect getter steps are to return this’s request’s redirect mode.\n return this[kState].redirect\n }\n\n // Returns request’s subresource integrity metadata, which is a\n // cryptographic hash of the resource being fetched. Its value\n // consists of multiple hashes separated by whitespace. [SRI]\n get integrity () {\n webidl.brandCheck(this, Request)\n\n // The integrity getter steps are to return this’s request’s integrity\n // metadata.\n return this[kState].integrity\n }\n\n // Returns a boolean indicating whether or not request can outlive the\n // global in which it was created.\n get keepalive () {\n webidl.brandCheck(this, Request)\n\n // The keepalive getter steps are to return this’s request’s keepalive.\n return this[kState].keepalive\n }\n\n // Returns a boolean indicating whether or not request is for a reload\n // navigation.\n get isReloadNavigation () {\n webidl.brandCheck(this, Request)\n\n // The isReloadNavigation getter steps are to return true if this’s\n // request’s reload-navigation flag is set; otherwise false.\n return this[kState].reloadNavigation\n }\n\n // Returns a boolean indicating whether or not request is for a history\n // navigation (a.k.a. back-forward navigation).\n get isHistoryNavigation () {\n webidl.brandCheck(this, Request)\n\n // The isHistoryNavigation getter steps are to return true if this’s request’s\n // history-navigation flag is set; otherwise false.\n return this[kState].historyNavigation\n }\n\n // Returns the signal associated with request, which is an AbortSignal\n // object indicating whether or not request has been aborted, and its\n // abort event handler.\n get signal () {\n webidl.brandCheck(this, Request)\n\n // The signal getter steps are to return this’s signal.\n return this[kSignal]\n }\n\n get body () {\n webidl.brandCheck(this, Request)\n\n return this[kState].body ? this[kState].body.stream : null\n }\n\n get bodyUsed () {\n webidl.brandCheck(this, Request)\n\n return !!this[kState].body && util.isDisturbed(this[kState].body.stream)\n }\n\n get duplex () {\n webidl.brandCheck(this, Request)\n\n return 'half'\n }\n\n // Returns a clone of request.\n clone () {\n webidl.brandCheck(this, Request)\n\n // 1. If this is unusable, then throw a TypeError.\n if (bodyUnusable(this)) {\n throw new TypeError('unusable')\n }\n\n // 2. Let clonedRequest be the result of cloning this’s request.\n const clonedRequest = cloneRequest(this[kState])\n\n // 3. Let clonedRequestObject be the result of creating a Request object,\n // given clonedRequest, this’s headers’s guard, and this’s relevant Realm.\n // 4. Make clonedRequestObject’s signal follow this’s signal.\n const ac = new AbortController()\n if (this.signal.aborted) {\n ac.abort(this.signal.reason)\n } else {\n let list = dependentControllerMap.get(this.signal)\n if (list === undefined) {\n list = new Set()\n dependentControllerMap.set(this.signal, list)\n }\n const acRef = new WeakRef(ac)\n list.add(acRef)\n util.addAbortListener(\n ac.signal,\n buildAbort(acRef)\n )\n }\n\n // 4. Return clonedRequestObject.\n return fromInnerRequest(clonedRequest, ac.signal, getHeadersGuard(this[kHeaders]))\n }\n\n [nodeUtil.inspect.custom] (depth, options) {\n if (options.depth === null) {\n options.depth = 2\n }\n\n options.colors ??= true\n\n const properties = {\n method: this.method,\n url: this.url,\n headers: this.headers,\n destination: this.destination,\n referrer: this.referrer,\n referrerPolicy: this.referrerPolicy,\n mode: this.mode,\n credentials: this.credentials,\n cache: this.cache,\n redirect: this.redirect,\n integrity: this.integrity,\n keepalive: this.keepalive,\n isReloadNavigation: this.isReloadNavigation,\n isHistoryNavigation: this.isHistoryNavigation,\n signal: this.signal\n }\n\n return `Request ${nodeUtil.formatWithOptions(options, properties)}`\n }\n}\n\nmixinBody(Request)\n\n// https://fetch.spec.whatwg.org/#requests\nfunction makeRequest (init) {\n return {\n method: init.method ?? 'GET',\n localURLsOnly: init.localURLsOnly ?? false,\n unsafeRequest: init.unsafeRequest ?? false,\n body: init.body ?? null,\n client: init.client ?? null,\n reservedClient: init.reservedClient ?? null,\n replacesClientId: init.replacesClientId ?? '',\n window: init.window ?? 'client',\n keepalive: init.keepalive ?? false,\n serviceWorkers: init.serviceWorkers ?? 'all',\n initiator: init.initiator ?? '',\n destination: init.destination ?? '',\n priority: init.priority ?? null,\n origin: init.origin ?? 'client',\n policyContainer: init.policyContainer ?? 'client',\n referrer: init.referrer ?? 'client',\n referrerPolicy: init.referrerPolicy ?? '',\n mode: init.mode ?? 'no-cors',\n useCORSPreflightFlag: init.useCORSPreflightFlag ?? false,\n credentials: init.credentials ?? 'same-origin',\n useCredentials: init.useCredentials ?? false,\n cache: init.cache ?? 'default',\n redirect: init.redirect ?? 'follow',\n integrity: init.integrity ?? '',\n cryptoGraphicsNonceMetadata: init.cryptoGraphicsNonceMetadata ?? '',\n parserMetadata: init.parserMetadata ?? '',\n reloadNavigation: init.reloadNavigation ?? false,\n historyNavigation: init.historyNavigation ?? false,\n userActivation: init.userActivation ?? false,\n taintedOrigin: init.taintedOrigin ?? false,\n redirectCount: init.redirectCount ?? 0,\n responseTainting: init.responseTainting ?? 'basic',\n preventNoCacheCacheControlHeaderModification: init.preventNoCacheCacheControlHeaderModification ?? false,\n done: init.done ?? false,\n timingAllowFailed: init.timingAllowFailed ?? false,\n urlList: init.urlList,\n url: init.urlList[0],\n headersList: init.headersList\n ? new HeadersList(init.headersList)\n : new HeadersList()\n }\n}\n\n// https://fetch.spec.whatwg.org/#concept-request-clone\nfunction cloneRequest (request) {\n // To clone a request request, run these steps:\n\n // 1. Let newRequest be a copy of request, except for its body.\n const newRequest = makeRequest({ ...request, body: null })\n\n // 2. If request’s body is non-null, set newRequest’s body to the\n // result of cloning request’s body.\n if (request.body != null) {\n newRequest.body = cloneBody(newRequest, request.body)\n }\n\n // 3. Return newRequest.\n return newRequest\n}\n\n/**\n * @see https://fetch.spec.whatwg.org/#request-create\n * @param {any} innerRequest\n * @param {AbortSignal} signal\n * @param {'request' | 'immutable' | 'request-no-cors' | 'response' | 'none'} guard\n * @returns {Request}\n */\nfunction fromInnerRequest (innerRequest, signal, guard) {\n const request = new Request(kConstruct)\n request[kState] = innerRequest\n request[kSignal] = signal\n request[kHeaders] = new Headers(kConstruct)\n setHeadersList(request[kHeaders], innerRequest.headersList)\n setHeadersGuard(request[kHeaders], guard)\n return request\n}\n\nObject.defineProperties(Request.prototype, {\n method: kEnumerableProperty,\n url: kEnumerableProperty,\n headers: kEnumerableProperty,\n redirect: kEnumerableProperty,\n clone: kEnumerableProperty,\n signal: kEnumerableProperty,\n duplex: kEnumerableProperty,\n destination: kEnumerableProperty,\n body: kEnumerableProperty,\n bodyUsed: kEnumerableProperty,\n isHistoryNavigation: kEnumerableProperty,\n isReloadNavigation: kEnumerableProperty,\n keepalive: kEnumerableProperty,\n integrity: kEnumerableProperty,\n cache: kEnumerableProperty,\n credentials: kEnumerableProperty,\n attribute: kEnumerableProperty,\n referrerPolicy: kEnumerableProperty,\n referrer: kEnumerableProperty,\n mode: kEnumerableProperty,\n [Symbol.toStringTag]: {\n value: 'Request',\n configurable: true\n }\n})\n\nwebidl.converters.Request = webidl.interfaceConverter(\n Request\n)\n\n// https://fetch.spec.whatwg.org/#requestinfo\nwebidl.converters.RequestInfo = function (V, prefix, argument) {\n if (typeof V === 'string') {\n return webidl.converters.USVString(V, prefix, argument)\n }\n\n if (V instanceof Request) {\n return webidl.converters.Request(V, prefix, argument)\n }\n\n return webidl.converters.USVString(V, prefix, argument)\n}\n\nwebidl.converters.AbortSignal = webidl.interfaceConverter(\n AbortSignal\n)\n\n// https://fetch.spec.whatwg.org/#requestinit\nwebidl.converters.RequestInit = webidl.dictionaryConverter([\n {\n key: 'method',\n converter: webidl.converters.ByteString\n },\n {\n key: 'headers',\n converter: webidl.converters.HeadersInit\n },\n {\n key: 'body',\n converter: webidl.nullableConverter(\n webidl.converters.BodyInit\n )\n },\n {\n key: 'referrer',\n converter: webidl.converters.USVString\n },\n {\n key: 'referrerPolicy',\n converter: webidl.converters.DOMString,\n // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy\n allowedValues: referrerPolicy\n },\n {\n key: 'mode',\n converter: webidl.converters.DOMString,\n // https://fetch.spec.whatwg.org/#concept-request-mode\n allowedValues: requestMode\n },\n {\n key: 'credentials',\n converter: webidl.converters.DOMString,\n // https://fetch.spec.whatwg.org/#requestcredentials\n allowedValues: requestCredentials\n },\n {\n key: 'cache',\n converter: webidl.converters.DOMString,\n // https://fetch.spec.whatwg.org/#requestcache\n allowedValues: requestCache\n },\n {\n key: 'redirect',\n converter: webidl.converters.DOMString,\n // https://fetch.spec.whatwg.org/#requestredirect\n allowedValues: requestRedirect\n },\n {\n key: 'integrity',\n converter: webidl.converters.DOMString\n },\n {\n key: 'keepalive',\n converter: webidl.converters.boolean\n },\n {\n key: 'signal',\n converter: webidl.nullableConverter(\n (signal) => webidl.converters.AbortSignal(\n signal,\n 'RequestInit',\n 'signal',\n { strict: false }\n )\n )\n },\n {\n key: 'window',\n converter: webidl.converters.any\n },\n {\n key: 'duplex',\n converter: webidl.converters.DOMString,\n allowedValues: requestDuplex\n },\n {\n key: 'dispatcher', // undici specific option\n converter: webidl.converters.any\n }\n])\n\nmodule.exports = { Request, makeRequest, fromInnerRequest, cloneRequest }\n","// https://github.com/Ethan-Arrowood/undici-fetch\n\n'use strict'\n\nconst {\n makeNetworkError,\n makeAppropriateNetworkError,\n filterResponse,\n makeResponse,\n fromInnerResponse\n} = require('./response')\nconst { HeadersList } = require('./headers')\nconst { Request, cloneRequest } = require('./request')\nconst zlib = require('node:zlib')\nconst {\n bytesMatch,\n makePolicyContainer,\n clonePolicyContainer,\n requestBadPort,\n TAOCheck,\n appendRequestOriginHeader,\n responseLocationURL,\n requestCurrentURL,\n setRequestReferrerPolicyOnRedirect,\n tryUpgradeRequestToAPotentiallyTrustworthyURL,\n createOpaqueTimingInfo,\n appendFetchMetadata,\n corsCheck,\n crossOriginResourcePolicyCheck,\n determineRequestsReferrer,\n coarsenedSharedCurrentTime,\n createDeferredPromise,\n isBlobLike,\n sameOrigin,\n isCancelled,\n isAborted,\n isErrorLike,\n fullyReadBody,\n readableStreamClose,\n isomorphicEncode,\n urlIsLocal,\n urlIsHttpHttpsScheme,\n urlHasHttpsScheme,\n clampAndCoarsenConnectionTimingInfo,\n simpleRangeHeaderValue,\n buildContentRange,\n createInflate,\n extractMimeType\n} = require('./util')\nconst { kState, kDispatcher } = require('./symbols')\nconst assert = require('node:assert')\nconst { safelyExtractBody, extractBody } = require('./body')\nconst {\n redirectStatusSet,\n nullBodyStatus,\n safeMethodsSet,\n requestBodyHeader,\n subresourceSet\n} = require('./constants')\nconst EE = require('node:events')\nconst { Readable, pipeline, finished } = require('node:stream')\nconst { addAbortListener, isErrored, isReadable, bufferToLowerCasedHeaderName } = require('../../core/util')\nconst { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require('./data-url')\nconst { getGlobalDispatcher } = require('../../global')\nconst { webidl } = require('./webidl')\nconst { STATUS_CODES } = require('node:http')\nconst GET_OR_HEAD = ['GET', 'HEAD']\n\nconst defaultUserAgent = typeof __UNDICI_IS_NODE__ !== 'undefined' || typeof esbuildDetection !== 'undefined'\n ? 'node'\n : 'undici'\n\n/** @type {import('buffer').resolveObjectURL} */\nlet resolveObjectURL\n\nclass Fetch extends EE {\n constructor (dispatcher) {\n super()\n\n this.dispatcher = dispatcher\n this.connection = null\n this.dump = false\n this.state = 'ongoing'\n }\n\n terminate (reason) {\n if (this.state !== 'ongoing') {\n return\n }\n\n this.state = 'terminated'\n this.connection?.destroy(reason)\n this.emit('terminated', reason)\n }\n\n // https://fetch.spec.whatwg.org/#fetch-controller-abort\n abort (error) {\n if (this.state !== 'ongoing') {\n return\n }\n\n // 1. Set controller’s state to \"aborted\".\n this.state = 'aborted'\n\n // 2. Let fallbackError be an \"AbortError\" DOMException.\n // 3. Set error to fallbackError if it is not given.\n if (!error) {\n error = new DOMException('The operation was aborted.', 'AbortError')\n }\n\n // 4. Let serializedError be StructuredSerialize(error).\n // If that threw an exception, catch it, and let\n // serializedError be StructuredSerialize(fallbackError).\n\n // 5. Set controller’s serialized abort reason to serializedError.\n this.serializedAbortReason = error\n\n this.connection?.destroy(error)\n this.emit('terminated', error)\n }\n}\n\nfunction handleFetchDone (response) {\n finalizeAndReportTiming(response, 'fetch')\n}\n\n// https://fetch.spec.whatwg.org/#fetch-method\nfunction fetch (input, init = undefined) {\n webidl.argumentLengthCheck(arguments, 1, 'globalThis.fetch')\n\n // 1. Let p be a new promise.\n let p = createDeferredPromise()\n\n // 2. Let requestObject be the result of invoking the initial value of\n // Request as constructor with input and init as arguments. If this throws\n // an exception, reject p with it and return p.\n let requestObject\n\n try {\n requestObject = new Request(input, init)\n } catch (e) {\n p.reject(e)\n return p.promise\n }\n\n // 3. Let request be requestObject’s request.\n const request = requestObject[kState]\n\n // 4. If requestObject’s signal’s aborted flag is set, then:\n if (requestObject.signal.aborted) {\n // 1. Abort the fetch() call with p, request, null, and\n // requestObject’s signal’s abort reason.\n abortFetch(p, request, null, requestObject.signal.reason)\n\n // 2. Return p.\n return p.promise\n }\n\n // 5. Let globalObject be request’s client’s global object.\n const globalObject = request.client.globalObject\n\n // 6. If globalObject is a ServiceWorkerGlobalScope object, then set\n // request’s service-workers mode to \"none\".\n if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') {\n request.serviceWorkers = 'none'\n }\n\n // 7. Let responseObject be null.\n let responseObject = null\n\n // 8. Let relevantRealm be this’s relevant Realm.\n\n // 9. Let locallyAborted be false.\n let locallyAborted = false\n\n // 10. Let controller be null.\n let controller = null\n\n // 11. Add the following abort steps to requestObject’s signal:\n addAbortListener(\n requestObject.signal,\n () => {\n // 1. Set locallyAborted to true.\n locallyAborted = true\n\n // 2. Assert: controller is non-null.\n assert(controller != null)\n\n // 3. Abort controller with requestObject’s signal’s abort reason.\n controller.abort(requestObject.signal.reason)\n\n const realResponse = responseObject?.deref()\n\n // 4. Abort the fetch() call with p, request, responseObject,\n // and requestObject’s signal’s abort reason.\n abortFetch(p, request, realResponse, requestObject.signal.reason)\n }\n )\n\n // 12. Let handleFetchDone given response response be to finalize and\n // report timing with response, globalObject, and \"fetch\".\n // see function handleFetchDone\n\n // 13. Set controller to the result of calling fetch given request,\n // with processResponseEndOfBody set to handleFetchDone, and processResponse\n // given response being these substeps:\n\n const processResponse = (response) => {\n // 1. If locallyAborted is true, terminate these substeps.\n if (locallyAborted) {\n return\n }\n\n // 2. If response’s aborted flag is set, then:\n if (response.aborted) {\n // 1. Let deserializedError be the result of deserialize a serialized\n // abort reason given controller’s serialized abort reason and\n // relevantRealm.\n\n // 2. Abort the fetch() call with p, request, responseObject, and\n // deserializedError.\n\n abortFetch(p, request, responseObject, controller.serializedAbortReason)\n return\n }\n\n // 3. If response is a network error, then reject p with a TypeError\n // and terminate these substeps.\n if (response.type === 'error') {\n p.reject(new TypeError('fetch failed', { cause: response.error }))\n return\n }\n\n // 4. Set responseObject to the result of creating a Response object,\n // given response, \"immutable\", and relevantRealm.\n responseObject = new WeakRef(fromInnerResponse(response, 'immutable'))\n\n // 5. Resolve p with responseObject.\n p.resolve(responseObject.deref())\n p = null\n }\n\n controller = fetching({\n request,\n processResponseEndOfBody: handleFetchDone,\n processResponse,\n dispatcher: requestObject[kDispatcher] // undici\n })\n\n // 14. Return p.\n return p.promise\n}\n\n// https://fetch.spec.whatwg.org/#finalize-and-report-timing\nfunction finalizeAndReportTiming (response, initiatorType = 'other') {\n // 1. If response is an aborted network error, then return.\n if (response.type === 'error' && response.aborted) {\n return\n }\n\n // 2. If response’s URL list is null or empty, then return.\n if (!response.urlList?.length) {\n return\n }\n\n // 3. Let originalURL be response’s URL list[0].\n const originalURL = response.urlList[0]\n\n // 4. Let timingInfo be response’s timing info.\n let timingInfo = response.timingInfo\n\n // 5. Let cacheState be response’s cache state.\n let cacheState = response.cacheState\n\n // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return.\n if (!urlIsHttpHttpsScheme(originalURL)) {\n return\n }\n\n // 7. If timingInfo is null, then return.\n if (timingInfo === null) {\n return\n }\n\n // 8. If response’s timing allow passed flag is not set, then:\n if (!response.timingAllowPassed) {\n // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo.\n timingInfo = createOpaqueTimingInfo({\n startTime: timingInfo.startTime\n })\n\n // 2. Set cacheState to the empty string.\n cacheState = ''\n }\n\n // 9. Set timingInfo’s end time to the coarsened shared current time\n // given global’s relevant settings object’s cross-origin isolated\n // capability.\n // TODO: given global’s relevant settings object’s cross-origin isolated\n // capability?\n timingInfo.endTime = coarsenedSharedCurrentTime()\n\n // 10. Set response’s timing info to timingInfo.\n response.timingInfo = timingInfo\n\n // 11. Mark resource timing for timingInfo, originalURL, initiatorType,\n // global, and cacheState.\n markResourceTiming(\n timingInfo,\n originalURL.href,\n initiatorType,\n globalThis,\n cacheState\n )\n}\n\n// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing\nconst markResourceTiming = performance.markResourceTiming\n\n// https://fetch.spec.whatwg.org/#abort-fetch\nfunction abortFetch (p, request, responseObject, error) {\n // 1. Reject promise with error.\n if (p) {\n // We might have already resolved the promise at this stage\n p.reject(error)\n }\n\n // 2. If request’s body is not null and is readable, then cancel request’s\n // body with error.\n if (request.body != null && isReadable(request.body?.stream)) {\n request.body.stream.cancel(error).catch((err) => {\n if (err.code === 'ERR_INVALID_STATE') {\n // Node bug?\n return\n }\n throw err\n })\n }\n\n // 3. If responseObject is null, then return.\n if (responseObject == null) {\n return\n }\n\n // 4. Let response be responseObject’s response.\n const response = responseObject[kState]\n\n // 5. If response’s body is not null and is readable, then error response’s\n // body with error.\n if (response.body != null && isReadable(response.body?.stream)) {\n response.body.stream.cancel(error).catch((err) => {\n if (err.code === 'ERR_INVALID_STATE') {\n // Node bug?\n return\n }\n throw err\n })\n }\n}\n\n// https://fetch.spec.whatwg.org/#fetching\nfunction fetching ({\n request,\n processRequestBodyChunkLength,\n processRequestEndOfBody,\n processResponse,\n processResponseEndOfBody,\n processResponseConsumeBody,\n useParallelQueue = false,\n dispatcher = getGlobalDispatcher() // undici\n}) {\n // Ensure that the dispatcher is set accordingly\n assert(dispatcher)\n\n // 1. Let taskDestination be null.\n let taskDestination = null\n\n // 2. Let crossOriginIsolatedCapability be false.\n let crossOriginIsolatedCapability = false\n\n // 3. If request’s client is non-null, then:\n if (request.client != null) {\n // 1. Set taskDestination to request’s client’s global object.\n taskDestination = request.client.globalObject\n\n // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin\n // isolated capability.\n crossOriginIsolatedCapability =\n request.client.crossOriginIsolatedCapability\n }\n\n // 4. If useParallelQueue is true, then set taskDestination to the result of\n // starting a new parallel queue.\n // TODO\n\n // 5. Let timingInfo be a new fetch timing info whose start time and\n // post-redirect start time are the coarsened shared current time given\n // crossOriginIsolatedCapability.\n const currentTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability)\n const timingInfo = createOpaqueTimingInfo({\n startTime: currentTime\n })\n\n // 6. Let fetchParams be a new fetch params whose\n // request is request,\n // timing info is timingInfo,\n // process request body chunk length is processRequestBodyChunkLength,\n // process request end-of-body is processRequestEndOfBody,\n // process response is processResponse,\n // process response consume body is processResponseConsumeBody,\n // process response end-of-body is processResponseEndOfBody,\n // task destination is taskDestination,\n // and cross-origin isolated capability is crossOriginIsolatedCapability.\n const fetchParams = {\n controller: new Fetch(dispatcher),\n request,\n timingInfo,\n processRequestBodyChunkLength,\n processRequestEndOfBody,\n processResponse,\n processResponseConsumeBody,\n processResponseEndOfBody,\n taskDestination,\n crossOriginIsolatedCapability\n }\n\n // 7. If request’s body is a byte sequence, then set request’s body to\n // request’s body as a body.\n // NOTE: Since fetching is only called from fetch, body should already be\n // extracted.\n assert(!request.body || request.body.stream)\n\n // 8. If request’s window is \"client\", then set request’s window to request’s\n // client, if request’s client’s global object is a Window object; otherwise\n // \"no-window\".\n if (request.window === 'client') {\n // TODO: What if request.client is null?\n request.window =\n request.client?.globalObject?.constructor?.name === 'Window'\n ? request.client\n : 'no-window'\n }\n\n // 9. If request’s origin is \"client\", then set request’s origin to request’s\n // client’s origin.\n if (request.origin === 'client') {\n request.origin = request.client.origin\n }\n\n // 10. If all of the following conditions are true:\n // TODO\n\n // 11. If request’s policy container is \"client\", then:\n if (request.policyContainer === 'client') {\n // 1. If request’s client is non-null, then set request’s policy\n // container to a clone of request’s client’s policy container. [HTML]\n if (request.client != null) {\n request.policyContainer = clonePolicyContainer(\n request.client.policyContainer\n )\n } else {\n // 2. Otherwise, set request’s policy container to a new policy\n // container.\n request.policyContainer = makePolicyContainer()\n }\n }\n\n // 12. If request’s header list does not contain `Accept`, then:\n if (!request.headersList.contains('accept', true)) {\n // 1. Let value be `*/*`.\n const value = '*/*'\n\n // 2. A user agent should set value to the first matching statement, if\n // any, switching on request’s destination:\n // \"document\"\n // \"frame\"\n // \"iframe\"\n // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`\n // \"image\"\n // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`\n // \"style\"\n // `text/css,*/*;q=0.1`\n // TODO\n\n // 3. Append `Accept`/value to request’s header list.\n request.headersList.append('accept', value, true)\n }\n\n // 13. If request’s header list does not contain `Accept-Language`, then\n // user agents should append `Accept-Language`/an appropriate value to\n // request’s header list.\n if (!request.headersList.contains('accept-language', true)) {\n request.headersList.append('accept-language', '*', true)\n }\n\n // 14. If request’s priority is null, then use request’s initiator and\n // destination appropriately in setting request’s priority to a\n // user-agent-defined object.\n if (request.priority === null) {\n // TODO\n }\n\n // 15. If request is a subresource request, then:\n if (subresourceSet.has(request.destination)) {\n // TODO\n }\n\n // 16. Run main fetch given fetchParams.\n mainFetch(fetchParams)\n .catch(err => {\n fetchParams.controller.terminate(err)\n })\n\n // 17. Return fetchParam's controller\n return fetchParams.controller\n}\n\n// https://fetch.spec.whatwg.org/#concept-main-fetch\nasync function mainFetch (fetchParams, recursive = false) {\n // 1. Let request be fetchParams’s request.\n const request = fetchParams.request\n\n // 2. Let response be null.\n let response = null\n\n // 3. If request’s local-URLs-only flag is set and request’s current URL is\n // not local, then set response to a network error.\n if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) {\n response = makeNetworkError('local URLs only')\n }\n\n // 4. Run report Content Security Policy violations for request.\n // TODO\n\n // 5. Upgrade request to a potentially trustworthy URL, if appropriate.\n tryUpgradeRequestToAPotentiallyTrustworthyURL(request)\n\n // 6. If should request be blocked due to a bad port, should fetching request\n // be blocked as mixed content, or should request be blocked by Content\n // Security Policy returns blocked, then set response to a network error.\n if (requestBadPort(request) === 'blocked') {\n response = makeNetworkError('bad port')\n }\n // TODO: should fetching request be blocked as mixed content?\n // TODO: should request be blocked by Content Security Policy?\n\n // 7. If request’s referrer policy is the empty string, then set request’s\n // referrer policy to request’s policy container’s referrer policy.\n if (request.referrerPolicy === '') {\n request.referrerPolicy = request.policyContainer.referrerPolicy\n }\n\n // 8. If request’s referrer is not \"no-referrer\", then set request’s\n // referrer to the result of invoking determine request’s referrer.\n if (request.referrer !== 'no-referrer') {\n request.referrer = determineRequestsReferrer(request)\n }\n\n // 9. Set request’s current URL’s scheme to \"https\" if all of the following\n // conditions are true:\n // - request’s current URL’s scheme is \"http\"\n // - request’s current URL’s host is a domain\n // - Matching request’s current URL’s host per Known HSTS Host Domain Name\n // Matching results in either a superdomain match with an asserted\n // includeSubDomains directive or a congruent match (with or without an\n // asserted includeSubDomains directive). [HSTS]\n // TODO\n\n // 10. If recursive is false, then run the remaining steps in parallel.\n // TODO\n\n // 11. If response is null, then set response to the result of running\n // the steps corresponding to the first matching statement:\n if (response === null) {\n response = await (async () => {\n const currentURL = requestCurrentURL(request)\n\n if (\n // - request’s current URL’s origin is same origin with request’s origin,\n // and request’s response tainting is \"basic\"\n (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') ||\n // request’s current URL’s scheme is \"data\"\n (currentURL.protocol === 'data:') ||\n // - request’s mode is \"navigate\" or \"websocket\"\n (request.mode === 'navigate' || request.mode === 'websocket')\n ) {\n // 1. Set request’s response tainting to \"basic\".\n request.responseTainting = 'basic'\n\n // 2. Return the result of running scheme fetch given fetchParams.\n return await schemeFetch(fetchParams)\n }\n\n // request’s mode is \"same-origin\"\n if (request.mode === 'same-origin') {\n // 1. Return a network error.\n return makeNetworkError('request mode cannot be \"same-origin\"')\n }\n\n // request’s mode is \"no-cors\"\n if (request.mode === 'no-cors') {\n // 1. If request’s redirect mode is not \"follow\", then return a network\n // error.\n if (request.redirect !== 'follow') {\n return makeNetworkError(\n 'redirect mode cannot be \"follow\" for \"no-cors\" request'\n )\n }\n\n // 2. Set request’s response tainting to \"opaque\".\n request.responseTainting = 'opaque'\n\n // 3. Return the result of running scheme fetch given fetchParams.\n return await schemeFetch(fetchParams)\n }\n\n // request’s current URL’s scheme is not an HTTP(S) scheme\n if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {\n // Return a network error.\n return makeNetworkError('URL scheme must be a HTTP(S) scheme')\n }\n\n // - request’s use-CORS-preflight flag is set\n // - request’s unsafe-request flag is set and either request’s method is\n // not a CORS-safelisted method or CORS-unsafe request-header names with\n // request’s header list is not empty\n // 1. Set request’s response tainting to \"cors\".\n // 2. Let corsWithPreflightResponse be the result of running HTTP fetch\n // given fetchParams and true.\n // 3. If corsWithPreflightResponse is a network error, then clear cache\n // entries using request.\n // 4. Return corsWithPreflightResponse.\n // TODO\n\n // Otherwise\n // 1. Set request’s response tainting to \"cors\".\n request.responseTainting = 'cors'\n\n // 2. Return the result of running HTTP fetch given fetchParams.\n return await httpFetch(fetchParams)\n })()\n }\n\n // 12. If recursive is true, then return response.\n if (recursive) {\n return response\n }\n\n // 13. If response is not a network error and response is not a filtered\n // response, then:\n if (response.status !== 0 && !response.internalResponse) {\n // If request’s response tainting is \"cors\", then:\n if (request.responseTainting === 'cors') {\n // 1. Let headerNames be the result of extracting header list values\n // given `Access-Control-Expose-Headers` and response’s header list.\n // TODO\n // 2. If request’s credentials mode is not \"include\" and headerNames\n // contains `*`, then set response’s CORS-exposed header-name list to\n // all unique header names in response’s header list.\n // TODO\n // 3. Otherwise, if headerNames is not null or failure, then set\n // response’s CORS-exposed header-name list to headerNames.\n // TODO\n }\n\n // Set response to the following filtered response with response as its\n // internal response, depending on request’s response tainting:\n if (request.responseTainting === 'basic') {\n response = filterResponse(response, 'basic')\n } else if (request.responseTainting === 'cors') {\n response = filterResponse(response, 'cors')\n } else if (request.responseTainting === 'opaque') {\n response = filterResponse(response, 'opaque')\n } else {\n assert(false)\n }\n }\n\n // 14. Let internalResponse be response, if response is a network error,\n // and response’s internal response otherwise.\n let internalResponse =\n response.status === 0 ? response : response.internalResponse\n\n // 15. If internalResponse’s URL list is empty, then set it to a clone of\n // request’s URL list.\n if (internalResponse.urlList.length === 0) {\n internalResponse.urlList.push(...request.urlList)\n }\n\n // 16. If request’s timing allow failed flag is unset, then set\n // internalResponse’s timing allow passed flag.\n if (!request.timingAllowFailed) {\n response.timingAllowPassed = true\n }\n\n // 17. If response is not a network error and any of the following returns\n // blocked\n // - should internalResponse to request be blocked as mixed content\n // - should internalResponse to request be blocked by Content Security Policy\n // - should internalResponse to request be blocked due to its MIME type\n // - should internalResponse to request be blocked due to nosniff\n // TODO\n\n // 18. If response’s type is \"opaque\", internalResponse’s status is 206,\n // internalResponse’s range-requested flag is set, and request’s header\n // list does not contain `Range`, then set response and internalResponse\n // to a network error.\n if (\n response.type === 'opaque' &&\n internalResponse.status === 206 &&\n internalResponse.rangeRequested &&\n !request.headers.contains('range', true)\n ) {\n response = internalResponse = makeNetworkError()\n }\n\n // 19. If response is not a network error and either request’s method is\n // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status,\n // set internalResponse’s body to null and disregard any enqueuing toward\n // it (if any).\n if (\n response.status !== 0 &&\n (request.method === 'HEAD' ||\n request.method === 'CONNECT' ||\n nullBodyStatus.includes(internalResponse.status))\n ) {\n internalResponse.body = null\n fetchParams.controller.dump = true\n }\n\n // 20. If request’s integrity metadata is not the empty string, then:\n if (request.integrity) {\n // 1. Let processBodyError be this step: run fetch finale given fetchParams\n // and a network error.\n const processBodyError = (reason) =>\n fetchFinale(fetchParams, makeNetworkError(reason))\n\n // 2. If request’s response tainting is \"opaque\", or response’s body is null,\n // then run processBodyError and abort these steps.\n if (request.responseTainting === 'opaque' || response.body == null) {\n processBodyError(response.error)\n return\n }\n\n // 3. Let processBody given bytes be these steps:\n const processBody = (bytes) => {\n // 1. If bytes do not match request’s integrity metadata,\n // then run processBodyError and abort these steps. [SRI]\n if (!bytesMatch(bytes, request.integrity)) {\n processBodyError('integrity mismatch')\n return\n }\n\n // 2. Set response’s body to bytes as a body.\n response.body = safelyExtractBody(bytes)[0]\n\n // 3. Run fetch finale given fetchParams and response.\n fetchFinale(fetchParams, response)\n }\n\n // 4. Fully read response’s body given processBody and processBodyError.\n await fullyReadBody(response.body, processBody, processBodyError)\n } else {\n // 21. Otherwise, run fetch finale given fetchParams and response.\n fetchFinale(fetchParams, response)\n }\n}\n\n// https://fetch.spec.whatwg.org/#concept-scheme-fetch\n// given a fetch params fetchParams\nfunction schemeFetch (fetchParams) {\n // Note: since the connection is destroyed on redirect, which sets fetchParams to a\n // cancelled state, we do not want this condition to trigger *unless* there have been\n // no redirects. See https://github.com/nodejs/undici/issues/1776\n // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.\n if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {\n return Promise.resolve(makeAppropriateNetworkError(fetchParams))\n }\n\n // 2. Let request be fetchParams’s request.\n const { request } = fetchParams\n\n const { protocol: scheme } = requestCurrentURL(request)\n\n // 3. Switch on request’s current URL’s scheme and run the associated steps:\n switch (scheme) {\n case 'about:': {\n // If request’s current URL’s path is the string \"blank\", then return a new response\n // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) »,\n // and body is the empty byte sequence as a body.\n\n // Otherwise, return a network error.\n return Promise.resolve(makeNetworkError('about scheme is not supported'))\n }\n case 'blob:': {\n if (!resolveObjectURL) {\n resolveObjectURL = require('node:buffer').resolveObjectURL\n }\n\n // 1. Let blobURLEntry be request’s current URL’s blob URL entry.\n const blobURLEntry = requestCurrentURL(request)\n\n // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56\n // Buffer.resolveObjectURL does not ignore URL queries.\n if (blobURLEntry.search.length !== 0) {\n return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.'))\n }\n\n const blob = resolveObjectURL(blobURLEntry.toString())\n\n // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s\n // object is not a Blob object, then return a network error.\n if (request.method !== 'GET' || !isBlobLike(blob)) {\n return Promise.resolve(makeNetworkError('invalid method'))\n }\n\n // 3. Let blob be blobURLEntry’s object.\n // Note: done above\n\n // 4. Let response be a new response.\n const response = makeResponse()\n\n // 5. Let fullLength be blob’s size.\n const fullLength = blob.size\n\n // 6. Let serializedFullLength be fullLength, serialized and isomorphic encoded.\n const serializedFullLength = isomorphicEncode(`${fullLength}`)\n\n // 7. Let type be blob’s type.\n const type = blob.type\n\n // 8. If request’s header list does not contain `Range`:\n // 9. Otherwise:\n if (!request.headersList.contains('range', true)) {\n // 1. Let bodyWithType be the result of safely extracting blob.\n // Note: in the FileAPI a blob \"object\" is a Blob *or* a MediaSource.\n // In node, this can only ever be a Blob. Therefore we can safely\n // use extractBody directly.\n const bodyWithType = extractBody(blob)\n\n // 2. Set response’s status message to `OK`.\n response.statusText = 'OK'\n\n // 3. Set response’s body to bodyWithType’s body.\n response.body = bodyWithType[0]\n\n // 4. Set response’s header list to « (`Content-Length`, serializedFullLength), (`Content-Type`, type) ».\n response.headersList.set('content-length', serializedFullLength, true)\n response.headersList.set('content-type', type, true)\n } else {\n // 1. Set response’s range-requested flag.\n response.rangeRequested = true\n\n // 2. Let rangeHeader be the result of getting `Range` from request’s header list.\n const rangeHeader = request.headersList.get('range', true)\n\n // 3. Let rangeValue be the result of parsing a single range header value given rangeHeader and true.\n const rangeValue = simpleRangeHeaderValue(rangeHeader, true)\n\n // 4. If rangeValue is failure, then return a network error.\n if (rangeValue === 'failure') {\n return Promise.resolve(makeNetworkError('failed to fetch the data URL'))\n }\n\n // 5. Let (rangeStart, rangeEnd) be rangeValue.\n let { rangeStartValue: rangeStart, rangeEndValue: rangeEnd } = rangeValue\n\n // 6. If rangeStart is null:\n // 7. Otherwise:\n if (rangeStart === null) {\n // 1. Set rangeStart to fullLength − rangeEnd.\n rangeStart = fullLength - rangeEnd\n\n // 2. Set rangeEnd to rangeStart + rangeEnd − 1.\n rangeEnd = rangeStart + rangeEnd - 1\n } else {\n // 1. If rangeStart is greater than or equal to fullLength, then return a network error.\n if (rangeStart >= fullLength) {\n return Promise.resolve(makeNetworkError('Range start is greater than the blob\\'s size.'))\n }\n\n // 2. If rangeEnd is null or rangeEnd is greater than or equal to fullLength, then set\n // rangeEnd to fullLength − 1.\n if (rangeEnd === null || rangeEnd >= fullLength) {\n rangeEnd = fullLength - 1\n }\n }\n\n // 8. Let slicedBlob be the result of invoking slice blob given blob, rangeStart,\n // rangeEnd + 1, and type.\n const slicedBlob = blob.slice(rangeStart, rangeEnd, type)\n\n // 9. Let slicedBodyWithType be the result of safely extracting slicedBlob.\n // Note: same reason as mentioned above as to why we use extractBody\n const slicedBodyWithType = extractBody(slicedBlob)\n\n // 10. Set response’s body to slicedBodyWithType’s body.\n response.body = slicedBodyWithType[0]\n\n // 11. Let serializedSlicedLength be slicedBlob’s size, serialized and isomorphic encoded.\n const serializedSlicedLength = isomorphicEncode(`${slicedBlob.size}`)\n\n // 12. Let contentRange be the result of invoking build a content range given rangeStart,\n // rangeEnd, and fullLength.\n const contentRange = buildContentRange(rangeStart, rangeEnd, fullLength)\n\n // 13. Set response’s status to 206.\n response.status = 206\n\n // 14. Set response’s status message to `Partial Content`.\n response.statusText = 'Partial Content'\n\n // 15. Set response’s header list to « (`Content-Length`, serializedSlicedLength),\n // (`Content-Type`, type), (`Content-Range`, contentRange) ».\n response.headersList.set('content-length', serializedSlicedLength, true)\n response.headersList.set('content-type', type, true)\n response.headersList.set('content-range', contentRange, true)\n }\n\n // 10. Return response.\n return Promise.resolve(response)\n }\n case 'data:': {\n // 1. Let dataURLStruct be the result of running the\n // data: URL processor on request’s current URL.\n const currentURL = requestCurrentURL(request)\n const dataURLStruct = dataURLProcessor(currentURL)\n\n // 2. If dataURLStruct is failure, then return a\n // network error.\n if (dataURLStruct === 'failure') {\n return Promise.resolve(makeNetworkError('failed to fetch the data URL'))\n }\n\n // 3. Let mimeType be dataURLStruct’s MIME type, serialized.\n const mimeType = serializeAMimeType(dataURLStruct.mimeType)\n\n // 4. Return a response whose status message is `OK`,\n // header list is « (`Content-Type`, mimeType) »,\n // and body is dataURLStruct’s body as a body.\n return Promise.resolve(makeResponse({\n statusText: 'OK',\n headersList: [\n ['content-type', { name: 'Content-Type', value: mimeType }]\n ],\n body: safelyExtractBody(dataURLStruct.body)[0]\n }))\n }\n case 'file:': {\n // For now, unfortunate as it is, file URLs are left as an exercise for the reader.\n // When in doubt, return a network error.\n return Promise.resolve(makeNetworkError('not implemented... yet...'))\n }\n case 'http:':\n case 'https:': {\n // Return the result of running HTTP fetch given fetchParams.\n\n return httpFetch(fetchParams)\n .catch((err) => makeNetworkError(err))\n }\n default: {\n return Promise.resolve(makeNetworkError('unknown scheme'))\n }\n }\n}\n\n// https://fetch.spec.whatwg.org/#finalize-response\nfunction finalizeResponse (fetchParams, response) {\n // 1. Set fetchParams’s request’s done flag.\n fetchParams.request.done = true\n\n // 2, If fetchParams’s process response done is not null, then queue a fetch\n // task to run fetchParams’s process response done given response, with\n // fetchParams’s task destination.\n if (fetchParams.processResponseDone != null) {\n queueMicrotask(() => fetchParams.processResponseDone(response))\n }\n}\n\n// https://fetch.spec.whatwg.org/#fetch-finale\nfunction fetchFinale (fetchParams, response) {\n // 1. Let timingInfo be fetchParams’s timing info.\n let timingInfo = fetchParams.timingInfo\n\n // 2. If response is not a network error and fetchParams’s request’s client is a secure context,\n // then set timingInfo’s server-timing headers to the result of getting, decoding, and splitting\n // `Server-Timing` from response’s internal response’s header list.\n // TODO\n\n // 3. Let processResponseEndOfBody be the following steps:\n const processResponseEndOfBody = () => {\n // 1. Let unsafeEndTime be the unsafe shared current time.\n const unsafeEndTime = Date.now() // ?\n\n // 2. If fetchParams’s request’s destination is \"document\", then set fetchParams’s controller’s\n // full timing info to fetchParams’s timing info.\n if (fetchParams.request.destination === 'document') {\n fetchParams.controller.fullTimingInfo = timingInfo\n }\n\n // 3. Set fetchParams’s controller’s report timing steps to the following steps given a global object global:\n fetchParams.controller.reportTimingSteps = () => {\n // 1. If fetchParams’s request’s URL’s scheme is not an HTTP(S) scheme, then return.\n if (fetchParams.request.url.protocol !== 'https:') {\n return\n }\n\n // 2. Set timingInfo’s end time to the relative high resolution time given unsafeEndTime and global.\n timingInfo.endTime = unsafeEndTime\n\n // 3. Let cacheState be response’s cache state.\n let cacheState = response.cacheState\n\n // 4. Let bodyInfo be response’s body info.\n const bodyInfo = response.bodyInfo\n\n // 5. If response’s timing allow passed flag is not set, then set timingInfo to the result of creating an\n // opaque timing info for timingInfo and set cacheState to the empty string.\n if (!response.timingAllowPassed) {\n timingInfo = createOpaqueTimingInfo(timingInfo)\n\n cacheState = ''\n }\n\n // 6. Let responseStatus be 0.\n let responseStatus = 0\n\n // 7. If fetchParams’s request’s mode is not \"navigate\" or response’s has-cross-origin-redirects is false:\n if (fetchParams.request.mode !== 'navigator' || !response.hasCrossOriginRedirects) {\n // 1. Set responseStatus to response’s status.\n responseStatus = response.status\n\n // 2. Let mimeType be the result of extracting a MIME type from response’s header list.\n const mimeType = extractMimeType(response.headersList)\n\n // 3. If mimeType is not failure, then set bodyInfo’s content type to the result of minimizing a supported MIME type given mimeType.\n if (mimeType !== 'failure') {\n bodyInfo.contentType = minimizeSupportedMimeType(mimeType)\n }\n }\n\n // 8. If fetchParams’s request’s initiator type is non-null, then mark resource timing given timingInfo,\n // fetchParams’s request’s URL, fetchParams’s request’s initiator type, global, cacheState, bodyInfo,\n // and responseStatus.\n if (fetchParams.request.initiatorType != null) {\n // TODO: update markresourcetiming\n markResourceTiming(timingInfo, fetchParams.request.url.href, fetchParams.request.initiatorType, globalThis, cacheState, bodyInfo, responseStatus)\n }\n }\n\n // 4. Let processResponseEndOfBodyTask be the following steps:\n const processResponseEndOfBodyTask = () => {\n // 1. Set fetchParams’s request’s done flag.\n fetchParams.request.done = true\n\n // 2. If fetchParams’s process response end-of-body is non-null, then run fetchParams’s process\n // response end-of-body given response.\n if (fetchParams.processResponseEndOfBody != null) {\n queueMicrotask(() => fetchParams.processResponseEndOfBody(response))\n }\n\n // 3. If fetchParams’s request’s initiator type is non-null and fetchParams’s request’s client’s\n // global object is fetchParams’s task destination, then run fetchParams’s controller’s report\n // timing steps given fetchParams’s request’s client’s global object.\n if (fetchParams.request.initiatorType != null) {\n fetchParams.controller.reportTimingSteps()\n }\n }\n\n // 5. Queue a fetch task to run processResponseEndOfBodyTask with fetchParams’s task destination\n queueMicrotask(() => processResponseEndOfBodyTask())\n }\n\n // 4. If fetchParams’s process response is non-null, then queue a fetch task to run fetchParams’s\n // process response given response, with fetchParams’s task destination.\n if (fetchParams.processResponse != null) {\n queueMicrotask(() => {\n fetchParams.processResponse(response)\n fetchParams.processResponse = null\n })\n }\n\n // 5. Let internalResponse be response, if response is a network error; otherwise response’s internal response.\n const internalResponse = response.type === 'error' ? response : (response.internalResponse ?? response)\n\n // 6. If internalResponse’s body is null, then run processResponseEndOfBody.\n // 7. Otherwise:\n if (internalResponse.body == null) {\n processResponseEndOfBody()\n } else {\n // mcollina: all the following steps of the specs are skipped.\n // The internal transform stream is not needed.\n // See https://github.com/nodejs/undici/pull/3093#issuecomment-2050198541\n\n // 1. Let transformStream be a new TransformStream.\n // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, enqueues chunk in transformStream.\n // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm and flushAlgorithm\n // set to processResponseEndOfBody.\n // 4. Set internalResponse’s body’s stream to the result of internalResponse’s body’s stream piped through transformStream.\n\n finished(internalResponse.body.stream, () => {\n processResponseEndOfBody()\n })\n }\n}\n\n// https://fetch.spec.whatwg.org/#http-fetch\nasync function httpFetch (fetchParams) {\n // 1. Let request be fetchParams’s request.\n const request = fetchParams.request\n\n // 2. Let response be null.\n let response = null\n\n // 3. Let actualResponse be null.\n let actualResponse = null\n\n // 4. Let timingInfo be fetchParams’s timing info.\n const timingInfo = fetchParams.timingInfo\n\n // 5. If request’s service-workers mode is \"all\", then:\n if (request.serviceWorkers === 'all') {\n // TODO\n }\n\n // 6. If response is null, then:\n if (response === null) {\n // 1. If makeCORSPreflight is true and one of these conditions is true:\n // TODO\n\n // 2. If request’s redirect mode is \"follow\", then set request’s\n // service-workers mode to \"none\".\n if (request.redirect === 'follow') {\n request.serviceWorkers = 'none'\n }\n\n // 3. Set response and actualResponse to the result of running\n // HTTP-network-or-cache fetch given fetchParams.\n actualResponse = response = await httpNetworkOrCacheFetch(fetchParams)\n\n // 4. If request’s response tainting is \"cors\" and a CORS check\n // for request and response returns failure, then return a network error.\n if (\n request.responseTainting === 'cors' &&\n corsCheck(request, response) === 'failure'\n ) {\n return makeNetworkError('cors failure')\n }\n\n // 5. If the TAO check for request and response returns failure, then set\n // request’s timing allow failed flag.\n if (TAOCheck(request, response) === 'failure') {\n request.timingAllowFailed = true\n }\n }\n\n // 7. If either request’s response tainting or response’s type\n // is \"opaque\", and the cross-origin resource policy check with\n // request’s origin, request’s client, request’s destination,\n // and actualResponse returns blocked, then return a network error.\n if (\n (request.responseTainting === 'opaque' || response.type === 'opaque') &&\n crossOriginResourcePolicyCheck(\n request.origin,\n request.client,\n request.destination,\n actualResponse\n ) === 'blocked'\n ) {\n return makeNetworkError('blocked')\n }\n\n // 8. If actualResponse’s status is a redirect status, then:\n if (redirectStatusSet.has(actualResponse.status)) {\n // 1. If actualResponse’s status is not 303, request’s body is not null,\n // and the connection uses HTTP/2, then user agents may, and are even\n // encouraged to, transmit an RST_STREAM frame.\n // See, https://github.com/whatwg/fetch/issues/1288\n if (request.redirect !== 'manual') {\n fetchParams.controller.connection.destroy(undefined, false)\n }\n\n // 2. Switch on request’s redirect mode:\n if (request.redirect === 'error') {\n // Set response to a network error.\n response = makeNetworkError('unexpected redirect')\n } else if (request.redirect === 'manual') {\n // Set response to an opaque-redirect filtered response whose internal\n // response is actualResponse.\n // NOTE(spec): On the web this would return an `opaqueredirect` response,\n // but that doesn't make sense server side.\n // See https://github.com/nodejs/undici/issues/1193.\n response = actualResponse\n } else if (request.redirect === 'follow') {\n // Set response to the result of running HTTP-redirect fetch given\n // fetchParams and response.\n response = await httpRedirectFetch(fetchParams, response)\n } else {\n assert(false)\n }\n }\n\n // 9. Set response’s timing info to timingInfo.\n response.timingInfo = timingInfo\n\n // 10. Return response.\n return response\n}\n\n// https://fetch.spec.whatwg.org/#http-redirect-fetch\nfunction httpRedirectFetch (fetchParams, response) {\n // 1. Let request be fetchParams’s request.\n const request = fetchParams.request\n\n // 2. Let actualResponse be response, if response is not a filtered response,\n // and response’s internal response otherwise.\n const actualResponse = response.internalResponse\n ? response.internalResponse\n : response\n\n // 3. Let locationURL be actualResponse’s location URL given request’s current\n // URL’s fragment.\n let locationURL\n\n try {\n locationURL = responseLocationURL(\n actualResponse,\n requestCurrentURL(request).hash\n )\n\n // 4. If locationURL is null, then return response.\n if (locationURL == null) {\n return response\n }\n } catch (err) {\n // 5. If locationURL is failure, then return a network error.\n return Promise.resolve(makeNetworkError(err))\n }\n\n // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network\n // error.\n if (!urlIsHttpHttpsScheme(locationURL)) {\n return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme'))\n }\n\n // 7. If request’s redirect count is 20, then return a network error.\n if (request.redirectCount === 20) {\n return Promise.resolve(makeNetworkError('redirect count exceeded'))\n }\n\n // 8. Increase request’s redirect count by 1.\n request.redirectCount += 1\n\n // 9. If request’s mode is \"cors\", locationURL includes credentials, and\n // request’s origin is not same origin with locationURL’s origin, then return\n // a network error.\n if (\n request.mode === 'cors' &&\n (locationURL.username || locationURL.password) &&\n !sameOrigin(request, locationURL)\n ) {\n return Promise.resolve(makeNetworkError('cross origin not allowed for request mode \"cors\"'))\n }\n\n // 10. If request’s response tainting is \"cors\" and locationURL includes\n // credentials, then return a network error.\n if (\n request.responseTainting === 'cors' &&\n (locationURL.username || locationURL.password)\n ) {\n return Promise.resolve(makeNetworkError(\n 'URL cannot contain credentials for request mode \"cors\"'\n ))\n }\n\n // 11. If actualResponse’s status is not 303, request’s body is non-null,\n // and request’s body’s source is null, then return a network error.\n if (\n actualResponse.status !== 303 &&\n request.body != null &&\n request.body.source == null\n ) {\n return Promise.resolve(makeNetworkError())\n }\n\n // 12. If one of the following is true\n // - actualResponse’s status is 301 or 302 and request’s method is `POST`\n // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD`\n if (\n ([301, 302].includes(actualResponse.status) && request.method === 'POST') ||\n (actualResponse.status === 303 &&\n !GET_OR_HEAD.includes(request.method))\n ) {\n // then:\n // 1. Set request’s method to `GET` and request’s body to null.\n request.method = 'GET'\n request.body = null\n\n // 2. For each headerName of request-body-header name, delete headerName from\n // request’s header list.\n for (const headerName of requestBodyHeader) {\n request.headersList.delete(headerName)\n }\n }\n\n // 13. If request’s current URL’s origin is not same origin with locationURL’s\n // origin, then for each headerName of CORS non-wildcard request-header name,\n // delete headerName from request’s header list.\n if (!sameOrigin(requestCurrentURL(request), locationURL)) {\n // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name\n request.headersList.delete('authorization', true)\n\n // https://fetch.spec.whatwg.org/#authentication-entries\n request.headersList.delete('proxy-authorization', true)\n\n // \"Cookie\" and \"Host\" are forbidden request-headers, which undici doesn't implement.\n request.headersList.delete('cookie', true)\n request.headersList.delete('host', true)\n }\n\n // 14. If request’s body is non-null, then set request’s body to the first return\n // value of safely extracting request’s body’s source.\n if (request.body != null) {\n assert(request.body.source != null)\n request.body = safelyExtractBody(request.body.source)[0]\n }\n\n // 15. Let timingInfo be fetchParams’s timing info.\n const timingInfo = fetchParams.timingInfo\n\n // 16. Set timingInfo’s redirect end time and post-redirect start time to the\n // coarsened shared current time given fetchParams’s cross-origin isolated\n // capability.\n timingInfo.redirectEndTime = timingInfo.postRedirectStartTime =\n coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)\n\n // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s\n // redirect start time to timingInfo’s start time.\n if (timingInfo.redirectStartTime === 0) {\n timingInfo.redirectStartTime = timingInfo.startTime\n }\n\n // 18. Append locationURL to request’s URL list.\n request.urlList.push(locationURL)\n\n // 19. Invoke set request’s referrer policy on redirect on request and\n // actualResponse.\n setRequestReferrerPolicyOnRedirect(request, actualResponse)\n\n // 20. Return the result of running main fetch given fetchParams and true.\n return mainFetch(fetchParams, true)\n}\n\n// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch\nasync function httpNetworkOrCacheFetch (\n fetchParams,\n isAuthenticationFetch = false,\n isNewConnectionFetch = false\n) {\n // 1. Let request be fetchParams’s request.\n const request = fetchParams.request\n\n // 2. Let httpFetchParams be null.\n let httpFetchParams = null\n\n // 3. Let httpRequest be null.\n let httpRequest = null\n\n // 4. Let response be null.\n let response = null\n\n // 5. Let storedResponse be null.\n // TODO: cache\n\n // 6. Let httpCache be null.\n const httpCache = null\n\n // 7. Let the revalidatingFlag be unset.\n const revalidatingFlag = false\n\n // 8. Run these steps, but abort when the ongoing fetch is terminated:\n\n // 1. If request’s window is \"no-window\" and request’s redirect mode is\n // \"error\", then set httpFetchParams to fetchParams and httpRequest to\n // request.\n if (request.window === 'no-window' && request.redirect === 'error') {\n httpFetchParams = fetchParams\n httpRequest = request\n } else {\n // Otherwise:\n\n // 1. Set httpRequest to a clone of request.\n httpRequest = cloneRequest(request)\n\n // 2. Set httpFetchParams to a copy of fetchParams.\n httpFetchParams = { ...fetchParams }\n\n // 3. Set httpFetchParams’s request to httpRequest.\n httpFetchParams.request = httpRequest\n }\n\n // 3. Let includeCredentials be true if one of\n const includeCredentials =\n request.credentials === 'include' ||\n (request.credentials === 'same-origin' &&\n request.responseTainting === 'basic')\n\n // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s\n // body is non-null; otherwise null.\n const contentLength = httpRequest.body ? httpRequest.body.length : null\n\n // 5. Let contentLengthHeaderValue be null.\n let contentLengthHeaderValue = null\n\n // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or\n // `PUT`, then set contentLengthHeaderValue to `0`.\n if (\n httpRequest.body == null &&\n ['POST', 'PUT'].includes(httpRequest.method)\n ) {\n contentLengthHeaderValue = '0'\n }\n\n // 7. If contentLength is non-null, then set contentLengthHeaderValue to\n // contentLength, serialized and isomorphic encoded.\n if (contentLength != null) {\n contentLengthHeaderValue = isomorphicEncode(`${contentLength}`)\n }\n\n // 8. If contentLengthHeaderValue is non-null, then append\n // `Content-Length`/contentLengthHeaderValue to httpRequest’s header\n // list.\n if (contentLengthHeaderValue != null) {\n httpRequest.headersList.append('content-length', contentLengthHeaderValue, true)\n }\n\n // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`,\n // contentLengthHeaderValue) to httpRequest’s header list.\n\n // 10. If contentLength is non-null and httpRequest’s keepalive is true,\n // then:\n if (contentLength != null && httpRequest.keepalive) {\n // NOTE: keepalive is a noop outside of browser context.\n }\n\n // 11. If httpRequest’s referrer is a URL, then append\n // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded,\n // to httpRequest’s header list.\n if (httpRequest.referrer instanceof URL) {\n httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href), true)\n }\n\n // 12. Append a request `Origin` header for httpRequest.\n appendRequestOriginHeader(httpRequest)\n\n // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA]\n appendFetchMetadata(httpRequest)\n\n // 14. If httpRequest’s header list does not contain `User-Agent`, then\n // user agents should append `User-Agent`/default `User-Agent` value to\n // httpRequest’s header list.\n if (!httpRequest.headersList.contains('user-agent', true)) {\n httpRequest.headersList.append('user-agent', defaultUserAgent)\n }\n\n // 15. If httpRequest’s cache mode is \"default\" and httpRequest’s header\n // list contains `If-Modified-Since`, `If-None-Match`,\n // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set\n // httpRequest’s cache mode to \"no-store\".\n if (\n httpRequest.cache === 'default' &&\n (httpRequest.headersList.contains('if-modified-since', true) ||\n httpRequest.headersList.contains('if-none-match', true) ||\n httpRequest.headersList.contains('if-unmodified-since', true) ||\n httpRequest.headersList.contains('if-match', true) ||\n httpRequest.headersList.contains('if-range', true))\n ) {\n httpRequest.cache = 'no-store'\n }\n\n // 16. If httpRequest’s cache mode is \"no-cache\", httpRequest’s prevent\n // no-cache cache-control header modification flag is unset, and\n // httpRequest’s header list does not contain `Cache-Control`, then append\n // `Cache-Control`/`max-age=0` to httpRequest’s header list.\n if (\n httpRequest.cache === 'no-cache' &&\n !httpRequest.preventNoCacheCacheControlHeaderModification &&\n !httpRequest.headersList.contains('cache-control', true)\n ) {\n httpRequest.headersList.append('cache-control', 'max-age=0', true)\n }\n\n // 17. If httpRequest’s cache mode is \"no-store\" or \"reload\", then:\n if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') {\n // 1. If httpRequest’s header list does not contain `Pragma`, then append\n // `Pragma`/`no-cache` to httpRequest’s header list.\n if (!httpRequest.headersList.contains('pragma', true)) {\n httpRequest.headersList.append('pragma', 'no-cache', true)\n }\n\n // 2. If httpRequest’s header list does not contain `Cache-Control`,\n // then append `Cache-Control`/`no-cache` to httpRequest’s header list.\n if (!httpRequest.headersList.contains('cache-control', true)) {\n httpRequest.headersList.append('cache-control', 'no-cache', true)\n }\n }\n\n // 18. If httpRequest’s header list contains `Range`, then append\n // `Accept-Encoding`/`identity` to httpRequest’s header list.\n if (httpRequest.headersList.contains('range', true)) {\n httpRequest.headersList.append('accept-encoding', 'identity', true)\n }\n\n // 19. Modify httpRequest’s header list per HTTP. Do not append a given\n // header if httpRequest’s header list contains that header’s name.\n // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129\n if (!httpRequest.headersList.contains('accept-encoding', true)) {\n if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {\n httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate', true)\n } else {\n httpRequest.headersList.append('accept-encoding', 'gzip, deflate', true)\n }\n }\n\n httpRequest.headersList.delete('host', true)\n\n // 20. If includeCredentials is true, then:\n if (includeCredentials) {\n // 1. If the user agent is not configured to block cookies for httpRequest\n // (see section 7 of [COOKIES]), then:\n // TODO: credentials\n // 2. If httpRequest’s header list does not contain `Authorization`, then:\n // TODO: credentials\n }\n\n // 21. If there’s a proxy-authentication entry, use it as appropriate.\n // TODO: proxy-authentication\n\n // 22. Set httpCache to the result of determining the HTTP cache\n // partition, given httpRequest.\n // TODO: cache\n\n // 23. If httpCache is null, then set httpRequest’s cache mode to\n // \"no-store\".\n if (httpCache == null) {\n httpRequest.cache = 'no-store'\n }\n\n // 24. If httpRequest’s cache mode is neither \"no-store\" nor \"reload\",\n // then:\n if (httpRequest.cache !== 'no-store' && httpRequest.cache !== 'reload') {\n // TODO: cache\n }\n\n // 9. If aborted, then return the appropriate network error for fetchParams.\n // TODO\n\n // 10. If response is null, then:\n if (response == null) {\n // 1. If httpRequest’s cache mode is \"only-if-cached\", then return a\n // network error.\n if (httpRequest.cache === 'only-if-cached') {\n return makeNetworkError('only if cached')\n }\n\n // 2. Let forwardResponse be the result of running HTTP-network fetch\n // given httpFetchParams, includeCredentials, and isNewConnectionFetch.\n const forwardResponse = await httpNetworkFetch(\n httpFetchParams,\n includeCredentials,\n isNewConnectionFetch\n )\n\n // 3. If httpRequest’s method is unsafe and forwardResponse’s status is\n // in the range 200 to 399, inclusive, invalidate appropriate stored\n // responses in httpCache, as per the \"Invalidation\" chapter of HTTP\n // Caching, and set storedResponse to null. [HTTP-CACHING]\n if (\n !safeMethodsSet.has(httpRequest.method) &&\n forwardResponse.status >= 200 &&\n forwardResponse.status <= 399\n ) {\n // TODO: cache\n }\n\n // 4. If the revalidatingFlag is set and forwardResponse’s status is 304,\n // then:\n if (revalidatingFlag && forwardResponse.status === 304) {\n // TODO: cache\n }\n\n // 5. If response is null, then:\n if (response == null) {\n // 1. Set response to forwardResponse.\n response = forwardResponse\n\n // 2. Store httpRequest and forwardResponse in httpCache, as per the\n // \"Storing Responses in Caches\" chapter of HTTP Caching. [HTTP-CACHING]\n // TODO: cache\n }\n }\n\n // 11. Set response’s URL list to a clone of httpRequest’s URL list.\n response.urlList = [...httpRequest.urlList]\n\n // 12. If httpRequest’s header list contains `Range`, then set response’s\n // range-requested flag.\n if (httpRequest.headersList.contains('range', true)) {\n response.rangeRequested = true\n }\n\n // 13. Set response’s request-includes-credentials to includeCredentials.\n response.requestIncludesCredentials = includeCredentials\n\n // 14. If response’s status is 401, httpRequest’s response tainting is not\n // \"cors\", includeCredentials is true, and request’s window is an environment\n // settings object, then:\n // TODO\n\n // 15. If response’s status is 407, then:\n if (response.status === 407) {\n // 1. If request’s window is \"no-window\", then return a network error.\n if (request.window === 'no-window') {\n return makeNetworkError()\n }\n\n // 2. ???\n\n // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.\n if (isCancelled(fetchParams)) {\n return makeAppropriateNetworkError(fetchParams)\n }\n\n // 4. Prompt the end user as appropriate in request’s window and store\n // the result as a proxy-authentication entry. [HTTP-AUTH]\n // TODO: Invoke some kind of callback?\n\n // 5. Set response to the result of running HTTP-network-or-cache fetch given\n // fetchParams.\n // TODO\n return makeNetworkError('proxy authentication required')\n }\n\n // 16. If all of the following are true\n if (\n // response’s status is 421\n response.status === 421 &&\n // isNewConnectionFetch is false\n !isNewConnectionFetch &&\n // request’s body is null, or request’s body is non-null and request’s body’s source is non-null\n (request.body == null || request.body.source != null)\n ) {\n // then:\n\n // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.\n if (isCancelled(fetchParams)) {\n return makeAppropriateNetworkError(fetchParams)\n }\n\n // 2. Set response to the result of running HTTP-network-or-cache\n // fetch given fetchParams, isAuthenticationFetch, and true.\n\n // TODO (spec): The spec doesn't specify this but we need to cancel\n // the active response before we can start a new one.\n // https://github.com/whatwg/fetch/issues/1293\n fetchParams.controller.connection.destroy()\n\n response = await httpNetworkOrCacheFetch(\n fetchParams,\n isAuthenticationFetch,\n true\n )\n }\n\n // 17. If isAuthenticationFetch is true, then create an authentication entry\n if (isAuthenticationFetch) {\n // TODO\n }\n\n // 18. Return response.\n return response\n}\n\n// https://fetch.spec.whatwg.org/#http-network-fetch\nasync function httpNetworkFetch (\n fetchParams,\n includeCredentials = false,\n forceNewConnection = false\n) {\n assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed)\n\n fetchParams.controller.connection = {\n abort: null,\n destroyed: false,\n destroy (err, abort = true) {\n if (!this.destroyed) {\n this.destroyed = true\n if (abort) {\n this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError'))\n }\n }\n }\n }\n\n // 1. Let request be fetchParams’s request.\n const request = fetchParams.request\n\n // 2. Let response be null.\n let response = null\n\n // 3. Let timingInfo be fetchParams’s timing info.\n const timingInfo = fetchParams.timingInfo\n\n // 4. Let httpCache be the result of determining the HTTP cache partition,\n // given request.\n // TODO: cache\n const httpCache = null\n\n // 5. If httpCache is null, then set request’s cache mode to \"no-store\".\n if (httpCache == null) {\n request.cache = 'no-store'\n }\n\n // 6. Let networkPartitionKey be the result of determining the network\n // partition key given request.\n // TODO\n\n // 7. Let newConnection be \"yes\" if forceNewConnection is true; otherwise\n // \"no\".\n const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars\n\n // 8. Switch on request’s mode:\n if (request.mode === 'websocket') {\n // Let connection be the result of obtaining a WebSocket connection,\n // given request’s current URL.\n // TODO\n } else {\n // Let connection be the result of obtaining a connection, given\n // networkPartitionKey, request’s current URL’s origin,\n // includeCredentials, and forceNewConnection.\n // TODO\n }\n\n // 9. Run these steps, but abort when the ongoing fetch is terminated:\n\n // 1. If connection is failure, then return a network error.\n\n // 2. Set timingInfo’s final connection timing info to the result of\n // calling clamp and coarsen connection timing info with connection’s\n // timing info, timingInfo’s post-redirect start time, and fetchParams’s\n // cross-origin isolated capability.\n\n // 3. If connection is not an HTTP/2 connection, request’s body is non-null,\n // and request’s body’s source is null, then append (`Transfer-Encoding`,\n // `chunked`) to request’s header list.\n\n // 4. Set timingInfo’s final network-request start time to the coarsened\n // shared current time given fetchParams’s cross-origin isolated\n // capability.\n\n // 5. Set response to the result of making an HTTP request over connection\n // using request with the following caveats:\n\n // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS]\n // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH]\n\n // - If request’s body is non-null, and request’s body’s source is null,\n // then the user agent may have a buffer of up to 64 kibibytes and store\n // a part of request’s body in that buffer. If the user agent reads from\n // request’s body beyond that buffer’s size and the user agent needs to\n // resend request, then instead return a network error.\n\n // - Set timingInfo’s final network-response start time to the coarsened\n // shared current time given fetchParams’s cross-origin isolated capability,\n // immediately after the user agent’s HTTP parser receives the first byte\n // of the response (e.g., frame header bytes for HTTP/2 or response status\n // line for HTTP/1.x).\n\n // - Wait until all the headers are transmitted.\n\n // - Any responses whose status is in the range 100 to 199, inclusive,\n // and is not 101, are to be ignored, except for the purposes of setting\n // timingInfo’s final network-response start time above.\n\n // - If request’s header list contains `Transfer-Encoding`/`chunked` and\n // response is transferred via HTTP/1.0 or older, then return a network\n // error.\n\n // - If the HTTP request results in a TLS client certificate dialog, then:\n\n // 1. If request’s window is an environment settings object, make the\n // dialog available in request’s window.\n\n // 2. Otherwise, return a network error.\n\n // To transmit request’s body body, run these steps:\n let requestBody = null\n // 1. If body is null and fetchParams’s process request end-of-body is\n // non-null, then queue a fetch task given fetchParams’s process request\n // end-of-body and fetchParams’s task destination.\n if (request.body == null && fetchParams.processRequestEndOfBody) {\n queueMicrotask(() => fetchParams.processRequestEndOfBody())\n } else if (request.body != null) {\n // 2. Otherwise, if body is non-null:\n\n // 1. Let processBodyChunk given bytes be these steps:\n const processBodyChunk = async function * (bytes) {\n // 1. If the ongoing fetch is terminated, then abort these steps.\n if (isCancelled(fetchParams)) {\n return\n }\n\n // 2. Run this step in parallel: transmit bytes.\n yield bytes\n\n // 3. If fetchParams’s process request body is non-null, then run\n // fetchParams’s process request body given bytes’s length.\n fetchParams.processRequestBodyChunkLength?.(bytes.byteLength)\n }\n\n // 2. Let processEndOfBody be these steps:\n const processEndOfBody = () => {\n // 1. If fetchParams is canceled, then abort these steps.\n if (isCancelled(fetchParams)) {\n return\n }\n\n // 2. If fetchParams’s process request end-of-body is non-null,\n // then run fetchParams’s process request end-of-body.\n if (fetchParams.processRequestEndOfBody) {\n fetchParams.processRequestEndOfBody()\n }\n }\n\n // 3. Let processBodyError given e be these steps:\n const processBodyError = (e) => {\n // 1. If fetchParams is canceled, then abort these steps.\n if (isCancelled(fetchParams)) {\n return\n }\n\n // 2. If e is an \"AbortError\" DOMException, then abort fetchParams’s controller.\n if (e.name === 'AbortError') {\n fetchParams.controller.abort()\n } else {\n fetchParams.controller.terminate(e)\n }\n }\n\n // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody,\n // processBodyError, and fetchParams’s task destination.\n requestBody = (async function * () {\n try {\n for await (const bytes of request.body.stream) {\n yield * processBodyChunk(bytes)\n }\n processEndOfBody()\n } catch (err) {\n processBodyError(err)\n }\n })()\n }\n\n try {\n // socket is only provided for websockets\n const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody })\n\n if (socket) {\n response = makeResponse({ status, statusText, headersList, socket })\n } else {\n const iterator = body[Symbol.asyncIterator]()\n fetchParams.controller.next = () => iterator.next()\n\n response = makeResponse({ status, statusText, headersList })\n }\n } catch (err) {\n // 10. If aborted, then:\n if (err.name === 'AbortError') {\n // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame.\n fetchParams.controller.connection.destroy()\n\n // 2. Return the appropriate network error for fetchParams.\n return makeAppropriateNetworkError(fetchParams, err)\n }\n\n return makeNetworkError(err)\n }\n\n // 11. Let pullAlgorithm be an action that resumes the ongoing fetch\n // if it is suspended.\n const pullAlgorithm = async () => {\n await fetchParams.controller.resume()\n }\n\n // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s\n // controller with reason, given reason.\n const cancelAlgorithm = (reason) => {\n // If the aborted fetch was already terminated, then we do not\n // need to do anything.\n if (!isCancelled(fetchParams)) {\n fetchParams.controller.abort(reason)\n }\n }\n\n // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by\n // the user agent.\n // TODO\n\n // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object\n // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent.\n // TODO\n\n // 15. Let stream be a new ReadableStream.\n // 16. Set up stream with byte reading support with pullAlgorithm set to pullAlgorithm,\n // cancelAlgorithm set to cancelAlgorithm.\n const stream = new ReadableStream(\n {\n async start (controller) {\n fetchParams.controller.controller = controller\n },\n async pull (controller) {\n await pullAlgorithm(controller)\n },\n async cancel (reason) {\n await cancelAlgorithm(reason)\n },\n type: 'bytes'\n }\n )\n\n // 17. Run these steps, but abort when the ongoing fetch is terminated:\n\n // 1. Set response’s body to a new body whose stream is stream.\n response.body = { stream, source: null, length: null }\n\n // 2. If response is not a network error and request’s cache mode is\n // not \"no-store\", then update response in httpCache for request.\n // TODO\n\n // 3. If includeCredentials is true and the user agent is not configured\n // to block cookies for request (see section 7 of [COOKIES]), then run the\n // \"set-cookie-string\" parsing algorithm (see section 5.2 of [COOKIES]) on\n // the value of each header whose name is a byte-case-insensitive match for\n // `Set-Cookie` in response’s header list, if any, and request’s current URL.\n // TODO\n\n // 18. If aborted, then:\n // TODO\n\n // 19. Run these steps in parallel:\n\n // 1. Run these steps, but abort when fetchParams is canceled:\n fetchParams.controller.onAborted = onAborted\n fetchParams.controller.on('terminated', onAborted)\n fetchParams.controller.resume = async () => {\n // 1. While true\n while (true) {\n // 1-3. See onData...\n\n // 4. Set bytes to the result of handling content codings given\n // codings and bytes.\n let bytes\n let isFailure\n try {\n const { done, value } = await fetchParams.controller.next()\n\n if (isAborted(fetchParams)) {\n break\n }\n\n bytes = done ? undefined : value\n } catch (err) {\n if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {\n // zlib doesn't like empty streams.\n bytes = undefined\n } else {\n bytes = err\n\n // err may be propagated from the result of calling readablestream.cancel,\n // which might not be an error. https://github.com/nodejs/undici/issues/2009\n isFailure = true\n }\n }\n\n if (bytes === undefined) {\n // 2. Otherwise, if the bytes transmission for response’s message\n // body is done normally and stream is readable, then close\n // stream, finalize response for fetchParams and response, and\n // abort these in-parallel steps.\n readableStreamClose(fetchParams.controller.controller)\n\n finalizeResponse(fetchParams, response)\n\n return\n }\n\n // 5. Increase timingInfo’s decoded body size by bytes’s length.\n timingInfo.decodedBodySize += bytes?.byteLength ?? 0\n\n // 6. If bytes is failure, then terminate fetchParams’s controller.\n if (isFailure) {\n fetchParams.controller.terminate(bytes)\n return\n }\n\n // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes\n // into stream.\n const buffer = new Uint8Array(bytes)\n if (buffer.byteLength) {\n fetchParams.controller.controller.enqueue(buffer)\n }\n\n // 8. If stream is errored, then terminate the ongoing fetch.\n if (isErrored(stream)) {\n fetchParams.controller.terminate()\n return\n }\n\n // 9. If stream doesn’t need more data ask the user agent to suspend\n // the ongoing fetch.\n if (fetchParams.controller.controller.desiredSize <= 0) {\n return\n }\n }\n }\n\n // 2. If aborted, then:\n function onAborted (reason) {\n // 2. If fetchParams is aborted, then:\n if (isAborted(fetchParams)) {\n // 1. Set response’s aborted flag.\n response.aborted = true\n\n // 2. If stream is readable, then error stream with the result of\n // deserialize a serialized abort reason given fetchParams’s\n // controller’s serialized abort reason and an\n // implementation-defined realm.\n if (isReadable(stream)) {\n fetchParams.controller.controller.error(\n fetchParams.controller.serializedAbortReason\n )\n }\n } else {\n // 3. Otherwise, if stream is readable, error stream with a TypeError.\n if (isReadable(stream)) {\n fetchParams.controller.controller.error(new TypeError('terminated', {\n cause: isErrorLike(reason) ? reason : undefined\n }))\n }\n }\n\n // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame.\n // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so.\n fetchParams.controller.connection.destroy()\n }\n\n // 20. Return response.\n return response\n\n function dispatch ({ body }) {\n const url = requestCurrentURL(request)\n /** @type {import('../..').Agent} */\n const agent = fetchParams.controller.dispatcher\n\n return new Promise((resolve, reject) => agent.dispatch(\n {\n path: url.pathname + url.search,\n origin: url.origin,\n method: request.method,\n body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body,\n headers: request.headersList.entries,\n maxRedirections: 0,\n upgrade: request.mode === 'websocket' ? 'websocket' : undefined\n },\n {\n body: null,\n abort: null,\n\n onConnect (abort) {\n // TODO (fix): Do we need connection here?\n const { connection } = fetchParams.controller\n\n // Set timingInfo’s final connection timing info to the result of calling clamp and coarsen\n // connection timing info with connection’s timing info, timingInfo’s post-redirect start\n // time, and fetchParams’s cross-origin isolated capability.\n // TODO: implement connection timing\n timingInfo.finalConnectionTimingInfo = clampAndCoarsenConnectionTimingInfo(undefined, timingInfo.postRedirectStartTime, fetchParams.crossOriginIsolatedCapability)\n\n if (connection.destroyed) {\n abort(new DOMException('The operation was aborted.', 'AbortError'))\n } else {\n fetchParams.controller.on('terminated', abort)\n this.abort = connection.abort = abort\n }\n\n // Set timingInfo’s final network-request start time to the coarsened shared current time given\n // fetchParams’s cross-origin isolated capability.\n timingInfo.finalNetworkRequestStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)\n },\n\n onResponseStarted () {\n // Set timingInfo’s final network-response start time to the coarsened shared current\n // time given fetchParams’s cross-origin isolated capability, immediately after the\n // user agent’s HTTP parser receives the first byte of the response (e.g., frame header\n // bytes for HTTP/2 or response status line for HTTP/1.x).\n timingInfo.finalNetworkResponseStartTime = coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)\n },\n\n onHeaders (status, rawHeaders, resume, statusText) {\n if (status < 200) {\n return\n }\n\n let location = ''\n\n const headersList = new HeadersList()\n\n for (let i = 0; i < rawHeaders.length; i += 2) {\n headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true)\n }\n location = headersList.get('location', true)\n\n this.body = new Readable({ read: resume })\n\n const decoders = []\n\n const willFollow = location && request.redirect === 'follow' &&\n redirectStatusSet.has(status)\n\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding\n if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {\n // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1\n const contentEncoding = headersList.get('content-encoding', true)\n // \"All content-coding values are case-insensitive...\"\n /** @type {string[]} */\n const codings = contentEncoding ? contentEncoding.toLowerCase().split(',') : []\n\n // Limit the number of content-encodings to prevent resource exhaustion.\n // CVE fix similar to urllib3 (GHSA-gm62-xv2j-4w53) and curl (CVE-2022-32206).\n const maxContentEncodings = 5\n if (codings.length > maxContentEncodings) {\n reject(new Error(`too many content-encodings in response: ${codings.length}, maximum allowed is ${maxContentEncodings}`))\n return true\n }\n\n for (let i = codings.length - 1; i >= 0; --i) {\n const coding = codings[i].trim()\n // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2\n if (coding === 'x-gzip' || coding === 'gzip') {\n decoders.push(zlib.createGunzip({\n // Be less strict when decoding compressed responses, since sometimes\n // servers send slightly invalid responses that are still accepted\n // by common browsers.\n // Always using Z_SYNC_FLUSH is what cURL does.\n flush: zlib.constants.Z_SYNC_FLUSH,\n finishFlush: zlib.constants.Z_SYNC_FLUSH\n }))\n } else if (coding === 'deflate') {\n decoders.push(createInflate({\n flush: zlib.constants.Z_SYNC_FLUSH,\n finishFlush: zlib.constants.Z_SYNC_FLUSH\n }))\n } else if (coding === 'br') {\n decoders.push(zlib.createBrotliDecompress({\n flush: zlib.constants.BROTLI_OPERATION_FLUSH,\n finishFlush: zlib.constants.BROTLI_OPERATION_FLUSH\n }))\n } else {\n decoders.length = 0\n break\n }\n }\n }\n\n const onError = this.onError.bind(this)\n\n resolve({\n status,\n statusText,\n headersList,\n body: decoders.length\n ? pipeline(this.body, ...decoders, (err) => {\n if (err) {\n this.onError(err)\n }\n }).on('error', onError)\n : this.body.on('error', onError)\n })\n\n return true\n },\n\n onData (chunk) {\n if (fetchParams.controller.dump) {\n return\n }\n\n // 1. If one or more bytes have been transmitted from response’s\n // message body, then:\n\n // 1. Let bytes be the transmitted bytes.\n const bytes = chunk\n\n // 2. Let codings be the result of extracting header list values\n // given `Content-Encoding` and response’s header list.\n // See pullAlgorithm.\n\n // 3. Increase timingInfo’s encoded body size by bytes’s length.\n timingInfo.encodedBodySize += bytes.byteLength\n\n // 4. See pullAlgorithm...\n\n return this.body.push(bytes)\n },\n\n onComplete () {\n if (this.abort) {\n fetchParams.controller.off('terminated', this.abort)\n }\n\n if (fetchParams.controller.onAborted) {\n fetchParams.controller.off('terminated', fetchParams.controller.onAborted)\n }\n\n fetchParams.controller.ended = true\n\n this.body.push(null)\n },\n\n onError (error) {\n if (this.abort) {\n fetchParams.controller.off('terminated', this.abort)\n }\n\n this.body?.destroy(error)\n\n fetchParams.controller.terminate(error)\n\n reject(error)\n },\n\n onUpgrade (status, rawHeaders, socket) {\n if (status !== 101) {\n return\n }\n\n const headersList = new HeadersList()\n\n for (let i = 0; i < rawHeaders.length; i += 2) {\n headersList.append(bufferToLowerCasedHeaderName(rawHeaders[i]), rawHeaders[i + 1].toString('latin1'), true)\n }\n\n resolve({\n status,\n statusText: STATUS_CODES[status],\n headersList,\n socket\n })\n\n return true\n }\n }\n ))\n }\n}\n\nmodule.exports = {\n fetch,\n Fetch,\n fetching,\n finalizeAndReportTiming\n}\n","'use strict'\n\nmodule.exports = {\n kState: Symbol('FileReader state'),\n kResult: Symbol('FileReader result'),\n kError: Symbol('FileReader error'),\n kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'),\n kEvents: Symbol('FileReader events'),\n kAborted: Symbol('FileReader aborted')\n}\n","'use strict'\n\nconst { webidl } = require('../fetch/webidl')\n\nconst kState = Symbol('ProgressEvent state')\n\n/**\n * @see https://xhr.spec.whatwg.org/#progressevent\n */\nclass ProgressEvent extends Event {\n constructor (type, eventInitDict = {}) {\n type = webidl.converters.DOMString(type, 'ProgressEvent constructor', 'type')\n eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {})\n\n super(type, eventInitDict)\n\n this[kState] = {\n lengthComputable: eventInitDict.lengthComputable,\n loaded: eventInitDict.loaded,\n total: eventInitDict.total\n }\n }\n\n get lengthComputable () {\n webidl.brandCheck(this, ProgressEvent)\n\n return this[kState].lengthComputable\n }\n\n get loaded () {\n webidl.brandCheck(this, ProgressEvent)\n\n return this[kState].loaded\n }\n\n get total () {\n webidl.brandCheck(this, ProgressEvent)\n\n return this[kState].total\n }\n}\n\nwebidl.converters.ProgressEventInit = webidl.dictionaryConverter([\n {\n key: 'lengthComputable',\n converter: webidl.converters.boolean,\n defaultValue: () => false\n },\n {\n key: 'loaded',\n converter: webidl.converters['unsigned long long'],\n defaultValue: () => 0\n },\n {\n key: 'total',\n converter: webidl.converters['unsigned long long'],\n defaultValue: () => 0\n },\n {\n key: 'bubbles',\n converter: webidl.converters.boolean,\n defaultValue: () => false\n },\n {\n key: 'cancelable',\n converter: webidl.converters.boolean,\n defaultValue: () => false\n },\n {\n key: 'composed',\n converter: webidl.converters.boolean,\n defaultValue: () => false\n }\n])\n\nmodule.exports = {\n ProgressEvent\n}\n","'use strict'\n\n/**\n * @see https://encoding.spec.whatwg.org/#concept-encoding-get\n * @param {string|undefined} label\n */\nfunction getEncoding (label) {\n if (!label) {\n return 'failure'\n }\n\n // 1. Remove any leading and trailing ASCII whitespace from label.\n // 2. If label is an ASCII case-insensitive match for any of the\n // labels listed in the table below, then return the\n // corresponding encoding; otherwise return failure.\n switch (label.trim().toLowerCase()) {\n case 'unicode-1-1-utf-8':\n case 'unicode11utf8':\n case 'unicode20utf8':\n case 'utf-8':\n case 'utf8':\n case 'x-unicode20utf8':\n return 'UTF-8'\n case '866':\n case 'cp866':\n case 'csibm866':\n case 'ibm866':\n return 'IBM866'\n case 'csisolatin2':\n case 'iso-8859-2':\n case 'iso-ir-101':\n case 'iso8859-2':\n case 'iso88592':\n case 'iso_8859-2':\n case 'iso_8859-2:1987':\n case 'l2':\n case 'latin2':\n return 'ISO-8859-2'\n case 'csisolatin3':\n case 'iso-8859-3':\n case 'iso-ir-109':\n case 'iso8859-3':\n case 'iso88593':\n case 'iso_8859-3':\n case 'iso_8859-3:1988':\n case 'l3':\n case 'latin3':\n return 'ISO-8859-3'\n case 'csisolatin4':\n case 'iso-8859-4':\n case 'iso-ir-110':\n case 'iso8859-4':\n case 'iso88594':\n case 'iso_8859-4':\n case 'iso_8859-4:1988':\n case 'l4':\n case 'latin4':\n return 'ISO-8859-4'\n case 'csisolatincyrillic':\n case 'cyrillic':\n case 'iso-8859-5':\n case 'iso-ir-144':\n case 'iso8859-5':\n case 'iso88595':\n case 'iso_8859-5':\n case 'iso_8859-5:1988':\n return 'ISO-8859-5'\n case 'arabic':\n case 'asmo-708':\n case 'csiso88596e':\n case 'csiso88596i':\n case 'csisolatinarabic':\n case 'ecma-114':\n case 'iso-8859-6':\n case 'iso-8859-6-e':\n case 'iso-8859-6-i':\n case 'iso-ir-127':\n case 'iso8859-6':\n case 'iso88596':\n case 'iso_8859-6':\n case 'iso_8859-6:1987':\n return 'ISO-8859-6'\n case 'csisolatingreek':\n case 'ecma-118':\n case 'elot_928':\n case 'greek':\n case 'greek8':\n case 'iso-8859-7':\n case 'iso-ir-126':\n case 'iso8859-7':\n case 'iso88597':\n case 'iso_8859-7':\n case 'iso_8859-7:1987':\n case 'sun_eu_greek':\n return 'ISO-8859-7'\n case 'csiso88598e':\n case 'csisolatinhebrew':\n case 'hebrew':\n case 'iso-8859-8':\n case 'iso-8859-8-e':\n case 'iso-ir-138':\n case 'iso8859-8':\n case 'iso88598':\n case 'iso_8859-8':\n case 'iso_8859-8:1988':\n case 'visual':\n return 'ISO-8859-8'\n case 'csiso88598i':\n case 'iso-8859-8-i':\n case 'logical':\n return 'ISO-8859-8-I'\n case 'csisolatin6':\n case 'iso-8859-10':\n case 'iso-ir-157':\n case 'iso8859-10':\n case 'iso885910':\n case 'l6':\n case 'latin6':\n return 'ISO-8859-10'\n case 'iso-8859-13':\n case 'iso8859-13':\n case 'iso885913':\n return 'ISO-8859-13'\n case 'iso-8859-14':\n case 'iso8859-14':\n case 'iso885914':\n return 'ISO-8859-14'\n case 'csisolatin9':\n case 'iso-8859-15':\n case 'iso8859-15':\n case 'iso885915':\n case 'iso_8859-15':\n case 'l9':\n return 'ISO-8859-15'\n case 'iso-8859-16':\n return 'ISO-8859-16'\n case 'cskoi8r':\n case 'koi':\n case 'koi8':\n case 'koi8-r':\n case 'koi8_r':\n return 'KOI8-R'\n case 'koi8-ru':\n case 'koi8-u':\n return 'KOI8-U'\n case 'csmacintosh':\n case 'mac':\n case 'macintosh':\n case 'x-mac-roman':\n return 'macintosh'\n case 'iso-8859-11':\n case 'iso8859-11':\n case 'iso885911':\n case 'tis-620':\n case 'windows-874':\n return 'windows-874'\n case 'cp1250':\n case 'windows-1250':\n case 'x-cp1250':\n return 'windows-1250'\n case 'cp1251':\n case 'windows-1251':\n case 'x-cp1251':\n return 'windows-1251'\n case 'ansi_x3.4-1968':\n case 'ascii':\n case 'cp1252':\n case 'cp819':\n case 'csisolatin1':\n case 'ibm819':\n case 'iso-8859-1':\n case 'iso-ir-100':\n case 'iso8859-1':\n case 'iso88591':\n case 'iso_8859-1':\n case 'iso_8859-1:1987':\n case 'l1':\n case 'latin1':\n case 'us-ascii':\n case 'windows-1252':\n case 'x-cp1252':\n return 'windows-1252'\n case 'cp1253':\n case 'windows-1253':\n case 'x-cp1253':\n return 'windows-1253'\n case 'cp1254':\n case 'csisolatin5':\n case 'iso-8859-9':\n case 'iso-ir-148':\n case 'iso8859-9':\n case 'iso88599':\n case 'iso_8859-9':\n case 'iso_8859-9:1989':\n case 'l5':\n case 'latin5':\n case 'windows-1254':\n case 'x-cp1254':\n return 'windows-1254'\n case 'cp1255':\n case 'windows-1255':\n case 'x-cp1255':\n return 'windows-1255'\n case 'cp1256':\n case 'windows-1256':\n case 'x-cp1256':\n return 'windows-1256'\n case 'cp1257':\n case 'windows-1257':\n case 'x-cp1257':\n return 'windows-1257'\n case 'cp1258':\n case 'windows-1258':\n case 'x-cp1258':\n return 'windows-1258'\n case 'x-mac-cyrillic':\n case 'x-mac-ukrainian':\n return 'x-mac-cyrillic'\n case 'chinese':\n case 'csgb2312':\n case 'csiso58gb231280':\n case 'gb2312':\n case 'gb_2312':\n case 'gb_2312-80':\n case 'gbk':\n case 'iso-ir-58':\n case 'x-gbk':\n return 'GBK'\n case 'gb18030':\n return 'gb18030'\n case 'big5':\n case 'big5-hkscs':\n case 'cn-big5':\n case 'csbig5':\n case 'x-x-big5':\n return 'Big5'\n case 'cseucpkdfmtjapanese':\n case 'euc-jp':\n case 'x-euc-jp':\n return 'EUC-JP'\n case 'csiso2022jp':\n case 'iso-2022-jp':\n return 'ISO-2022-JP'\n case 'csshiftjis':\n case 'ms932':\n case 'ms_kanji':\n case 'shift-jis':\n case 'shift_jis':\n case 'sjis':\n case 'windows-31j':\n case 'x-sjis':\n return 'Shift_JIS'\n case 'cseuckr':\n case 'csksc56011987':\n case 'euc-kr':\n case 'iso-ir-149':\n case 'korean':\n case 'ks_c_5601-1987':\n case 'ks_c_5601-1989':\n case 'ksc5601':\n case 'ksc_5601':\n case 'windows-949':\n return 'EUC-KR'\n case 'csiso2022kr':\n case 'hz-gb-2312':\n case 'iso-2022-cn':\n case 'iso-2022-cn-ext':\n case 'iso-2022-kr':\n case 'replacement':\n return 'replacement'\n case 'unicodefffe':\n case 'utf-16be':\n return 'UTF-16BE'\n case 'csunicode':\n case 'iso-10646-ucs-2':\n case 'ucs-2':\n case 'unicode':\n case 'unicodefeff':\n case 'utf-16':\n case 'utf-16le':\n return 'UTF-16LE'\n case 'x-user-defined':\n return 'x-user-defined'\n default: return 'failure'\n }\n}\n\nmodule.exports = {\n getEncoding\n}\n","'use strict'\n\nconst {\n kState,\n kError,\n kResult,\n kAborted,\n kLastProgressEventFired\n} = require('./symbols')\nconst { ProgressEvent } = require('./progressevent')\nconst { getEncoding } = require('./encoding')\nconst { serializeAMimeType, parseMIMEType } = require('../fetch/data-url')\nconst { types } = require('node:util')\nconst { StringDecoder } = require('string_decoder')\nconst { btoa } = require('node:buffer')\n\n/** @type {PropertyDescriptor} */\nconst staticPropertyDescriptors = {\n enumerable: true,\n writable: false,\n configurable: false\n}\n\n/**\n * @see https://w3c.github.io/FileAPI/#readOperation\n * @param {import('./filereader').FileReader} fr\n * @param {import('buffer').Blob} blob\n * @param {string} type\n * @param {string?} encodingName\n */\nfunction readOperation (fr, blob, type, encodingName) {\n // 1. If fr’s state is \"loading\", throw an InvalidStateError\n // DOMException.\n if (fr[kState] === 'loading') {\n throw new DOMException('Invalid state', 'InvalidStateError')\n }\n\n // 2. Set fr’s state to \"loading\".\n fr[kState] = 'loading'\n\n // 3. Set fr’s result to null.\n fr[kResult] = null\n\n // 4. Set fr’s error to null.\n fr[kError] = null\n\n // 5. Let stream be the result of calling get stream on blob.\n /** @type {import('stream/web').ReadableStream} */\n const stream = blob.stream()\n\n // 6. Let reader be the result of getting a reader from stream.\n const reader = stream.getReader()\n\n // 7. Let bytes be an empty byte sequence.\n /** @type {Uint8Array[]} */\n const bytes = []\n\n // 8. Let chunkPromise be the result of reading a chunk from\n // stream with reader.\n let chunkPromise = reader.read()\n\n // 9. Let isFirstChunk be true.\n let isFirstChunk = true\n\n // 10. In parallel, while true:\n // Note: \"In parallel\" just means non-blocking\n // Note 2: readOperation itself cannot be async as double\n // reading the body would then reject the promise, instead\n // of throwing an error.\n ;(async () => {\n while (!fr[kAborted]) {\n // 1. Wait for chunkPromise to be fulfilled or rejected.\n try {\n const { done, value } = await chunkPromise\n\n // 2. If chunkPromise is fulfilled, and isFirstChunk is\n // true, queue a task to fire a progress event called\n // loadstart at fr.\n if (isFirstChunk && !fr[kAborted]) {\n queueMicrotask(() => {\n fireAProgressEvent('loadstart', fr)\n })\n }\n\n // 3. Set isFirstChunk to false.\n isFirstChunk = false\n\n // 4. If chunkPromise is fulfilled with an object whose\n // done property is false and whose value property is\n // a Uint8Array object, run these steps:\n if (!done && types.isUint8Array(value)) {\n // 1. Let bs be the byte sequence represented by the\n // Uint8Array object.\n\n // 2. Append bs to bytes.\n bytes.push(value)\n\n // 3. If roughly 50ms have passed since these steps\n // were last invoked, queue a task to fire a\n // progress event called progress at fr.\n if (\n (\n fr[kLastProgressEventFired] === undefined ||\n Date.now() - fr[kLastProgressEventFired] >= 50\n ) &&\n !fr[kAborted]\n ) {\n fr[kLastProgressEventFired] = Date.now()\n queueMicrotask(() => {\n fireAProgressEvent('progress', fr)\n })\n }\n\n // 4. Set chunkPromise to the result of reading a\n // chunk from stream with reader.\n chunkPromise = reader.read()\n } else if (done) {\n // 5. Otherwise, if chunkPromise is fulfilled with an\n // object whose done property is true, queue a task\n // to run the following steps and abort this algorithm:\n queueMicrotask(() => {\n // 1. Set fr’s state to \"done\".\n fr[kState] = 'done'\n\n // 2. Let result be the result of package data given\n // bytes, type, blob’s type, and encodingName.\n try {\n const result = packageData(bytes, type, blob.type, encodingName)\n\n // 4. Else:\n\n if (fr[kAborted]) {\n return\n }\n\n // 1. Set fr’s result to result.\n fr[kResult] = result\n\n // 2. Fire a progress event called load at the fr.\n fireAProgressEvent('load', fr)\n } catch (error) {\n // 3. If package data threw an exception error:\n\n // 1. Set fr’s error to error.\n fr[kError] = error\n\n // 2. Fire a progress event called error at fr.\n fireAProgressEvent('error', fr)\n }\n\n // 5. If fr’s state is not \"loading\", fire a progress\n // event called loadend at the fr.\n if (fr[kState] !== 'loading') {\n fireAProgressEvent('loadend', fr)\n }\n })\n\n break\n }\n } catch (error) {\n if (fr[kAborted]) {\n return\n }\n\n // 6. Otherwise, if chunkPromise is rejected with an\n // error error, queue a task to run the following\n // steps and abort this algorithm:\n queueMicrotask(() => {\n // 1. Set fr’s state to \"done\".\n fr[kState] = 'done'\n\n // 2. Set fr’s error to error.\n fr[kError] = error\n\n // 3. Fire a progress event called error at fr.\n fireAProgressEvent('error', fr)\n\n // 4. If fr’s state is not \"loading\", fire a progress\n // event called loadend at fr.\n if (fr[kState] !== 'loading') {\n fireAProgressEvent('loadend', fr)\n }\n })\n\n break\n }\n }\n })()\n}\n\n/**\n * @see https://w3c.github.io/FileAPI/#fire-a-progress-event\n * @see https://dom.spec.whatwg.org/#concept-event-fire\n * @param {string} e The name of the event\n * @param {import('./filereader').FileReader} reader\n */\nfunction fireAProgressEvent (e, reader) {\n // The progress event e does not bubble. e.bubbles must be false\n // The progress event e is NOT cancelable. e.cancelable must be false\n const event = new ProgressEvent(e, {\n bubbles: false,\n cancelable: false\n })\n\n reader.dispatchEvent(event)\n}\n\n/**\n * @see https://w3c.github.io/FileAPI/#blob-package-data\n * @param {Uint8Array[]} bytes\n * @param {string} type\n * @param {string?} mimeType\n * @param {string?} encodingName\n */\nfunction packageData (bytes, type, mimeType, encodingName) {\n // 1. A Blob has an associated package data algorithm, given\n // bytes, a type, a optional mimeType, and a optional\n // encodingName, which switches on type and runs the\n // associated steps:\n\n switch (type) {\n case 'DataURL': {\n // 1. Return bytes as a DataURL [RFC2397] subject to\n // the considerations below:\n // * Use mimeType as part of the Data URL if it is\n // available in keeping with the Data URL\n // specification [RFC2397].\n // * If mimeType is not available return a Data URL\n // without a media-type. [RFC2397].\n\n // https://datatracker.ietf.org/doc/html/rfc2397#section-3\n // dataurl := \"data:\" [ mediatype ] [ \";base64\" ] \",\" data\n // mediatype := [ type \"/\" subtype ] *( \";\" parameter )\n // data := *urlchar\n // parameter := attribute \"=\" value\n let dataURL = 'data:'\n\n const parsed = parseMIMEType(mimeType || 'application/octet-stream')\n\n if (parsed !== 'failure') {\n dataURL += serializeAMimeType(parsed)\n }\n\n dataURL += ';base64,'\n\n const decoder = new StringDecoder('latin1')\n\n for (const chunk of bytes) {\n dataURL += btoa(decoder.write(chunk))\n }\n\n dataURL += btoa(decoder.end())\n\n return dataURL\n }\n case 'Text': {\n // 1. Let encoding be failure\n let encoding = 'failure'\n\n // 2. If the encodingName is present, set encoding to the\n // result of getting an encoding from encodingName.\n if (encodingName) {\n encoding = getEncoding(encodingName)\n }\n\n // 3. If encoding is failure, and mimeType is present:\n if (encoding === 'failure' && mimeType) {\n // 1. Let type be the result of parse a MIME type\n // given mimeType.\n const type = parseMIMEType(mimeType)\n\n // 2. If type is not failure, set encoding to the result\n // of getting an encoding from type’s parameters[\"charset\"].\n if (type !== 'failure') {\n encoding = getEncoding(type.parameters.get('charset'))\n }\n }\n\n // 4. If encoding is failure, then set encoding to UTF-8.\n if (encoding === 'failure') {\n encoding = 'UTF-8'\n }\n\n // 5. Decode bytes using fallback encoding encoding, and\n // return the result.\n return decode(bytes, encoding)\n }\n case 'ArrayBuffer': {\n // Return a new ArrayBuffer whose contents are bytes.\n const sequence = combineByteSequences(bytes)\n\n return sequence.buffer\n }\n case 'BinaryString': {\n // Return bytes as a binary string, in which every byte\n // is represented by a code unit of equal value [0..255].\n let binaryString = ''\n\n const decoder = new StringDecoder('latin1')\n\n for (const chunk of bytes) {\n binaryString += decoder.write(chunk)\n }\n\n binaryString += decoder.end()\n\n return binaryString\n }\n }\n}\n\n/**\n * @see https://encoding.spec.whatwg.org/#decode\n * @param {Uint8Array[]} ioQueue\n * @param {string} encoding\n */\nfunction decode (ioQueue, encoding) {\n const bytes = combineByteSequences(ioQueue)\n\n // 1. Let BOMEncoding be the result of BOM sniffing ioQueue.\n const BOMEncoding = BOMSniffing(bytes)\n\n let slice = 0\n\n // 2. If BOMEncoding is non-null:\n if (BOMEncoding !== null) {\n // 1. Set encoding to BOMEncoding.\n encoding = BOMEncoding\n\n // 2. Read three bytes from ioQueue, if BOMEncoding is\n // UTF-8; otherwise read two bytes.\n // (Do nothing with those bytes.)\n slice = BOMEncoding === 'UTF-8' ? 3 : 2\n }\n\n // 3. Process a queue with an instance of encoding’s\n // decoder, ioQueue, output, and \"replacement\".\n\n // 4. Return output.\n\n const sliced = bytes.slice(slice)\n return new TextDecoder(encoding).decode(sliced)\n}\n\n/**\n * @see https://encoding.spec.whatwg.org/#bom-sniff\n * @param {Uint8Array} ioQueue\n */\nfunction BOMSniffing (ioQueue) {\n // 1. Let BOM be the result of peeking 3 bytes from ioQueue,\n // converted to a byte sequence.\n const [a, b, c] = ioQueue\n\n // 2. For each of the rows in the table below, starting with\n // the first one and going down, if BOM starts with the\n // bytes given in the first column, then return the\n // encoding given in the cell in the second column of that\n // row. Otherwise, return null.\n if (a === 0xEF && b === 0xBB && c === 0xBF) {\n return 'UTF-8'\n } else if (a === 0xFE && b === 0xFF) {\n return 'UTF-16BE'\n } else if (a === 0xFF && b === 0xFE) {\n return 'UTF-16LE'\n }\n\n return null\n}\n\n/**\n * @param {Uint8Array[]} sequences\n */\nfunction combineByteSequences (sequences) {\n const size = sequences.reduce((a, b) => {\n return a + b.byteLength\n }, 0)\n\n let offset = 0\n\n return sequences.reduce((a, b) => {\n a.set(b, offset)\n offset += b.byteLength\n return a\n }, new Uint8Array(size))\n}\n\nmodule.exports = {\n staticPropertyDescriptors,\n readOperation,\n fireAProgressEvent\n}\n","'use strict'\n\nconst {\n staticPropertyDescriptors,\n readOperation,\n fireAProgressEvent\n} = require('./util')\nconst {\n kState,\n kError,\n kResult,\n kEvents,\n kAborted\n} = require('./symbols')\nconst { webidl } = require('../fetch/webidl')\nconst { kEnumerableProperty } = require('../../core/util')\n\nclass FileReader extends EventTarget {\n constructor () {\n super()\n\n this[kState] = 'empty'\n this[kResult] = null\n this[kError] = null\n this[kEvents] = {\n loadend: null,\n error: null,\n abort: null,\n load: null,\n progress: null,\n loadstart: null\n }\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer\n * @param {import('buffer').Blob} blob\n */\n readAsArrayBuffer (blob) {\n webidl.brandCheck(this, FileReader)\n\n webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsArrayBuffer')\n\n blob = webidl.converters.Blob(blob, { strict: false })\n\n // The readAsArrayBuffer(blob) method, when invoked,\n // must initiate a read operation for blob with ArrayBuffer.\n readOperation(this, blob, 'ArrayBuffer')\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#readAsBinaryString\n * @param {import('buffer').Blob} blob\n */\n readAsBinaryString (blob) {\n webidl.brandCheck(this, FileReader)\n\n webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsBinaryString')\n\n blob = webidl.converters.Blob(blob, { strict: false })\n\n // The readAsBinaryString(blob) method, when invoked,\n // must initiate a read operation for blob with BinaryString.\n readOperation(this, blob, 'BinaryString')\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#readAsDataText\n * @param {import('buffer').Blob} blob\n * @param {string?} encoding\n */\n readAsText (blob, encoding = undefined) {\n webidl.brandCheck(this, FileReader)\n\n webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsText')\n\n blob = webidl.converters.Blob(blob, { strict: false })\n\n if (encoding !== undefined) {\n encoding = webidl.converters.DOMString(encoding, 'FileReader.readAsText', 'encoding')\n }\n\n // The readAsText(blob, encoding) method, when invoked,\n // must initiate a read operation for blob with Text and encoding.\n readOperation(this, blob, 'Text', encoding)\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL\n * @param {import('buffer').Blob} blob\n */\n readAsDataURL (blob) {\n webidl.brandCheck(this, FileReader)\n\n webidl.argumentLengthCheck(arguments, 1, 'FileReader.readAsDataURL')\n\n blob = webidl.converters.Blob(blob, { strict: false })\n\n // The readAsDataURL(blob) method, when invoked, must\n // initiate a read operation for blob with DataURL.\n readOperation(this, blob, 'DataURL')\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dfn-abort\n */\n abort () {\n // 1. If this's state is \"empty\" or if this's state is\n // \"done\" set this's result to null and terminate\n // this algorithm.\n if (this[kState] === 'empty' || this[kState] === 'done') {\n this[kResult] = null\n return\n }\n\n // 2. If this's state is \"loading\" set this's state to\n // \"done\" and set this's result to null.\n if (this[kState] === 'loading') {\n this[kState] = 'done'\n this[kResult] = null\n }\n\n // 3. If there are any tasks from this on the file reading\n // task source in an affiliated task queue, then remove\n // those tasks from that task queue.\n this[kAborted] = true\n\n // 4. Terminate the algorithm for the read method being processed.\n // TODO\n\n // 5. Fire a progress event called abort at this.\n fireAProgressEvent('abort', this)\n\n // 6. If this's state is not \"loading\", fire a progress\n // event called loadend at this.\n if (this[kState] !== 'loading') {\n fireAProgressEvent('loadend', this)\n }\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate\n */\n get readyState () {\n webidl.brandCheck(this, FileReader)\n\n switch (this[kState]) {\n case 'empty': return this.EMPTY\n case 'loading': return this.LOADING\n case 'done': return this.DONE\n }\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dom-filereader-result\n */\n get result () {\n webidl.brandCheck(this, FileReader)\n\n // The result attribute’s getter, when invoked, must return\n // this's result.\n return this[kResult]\n }\n\n /**\n * @see https://w3c.github.io/FileAPI/#dom-filereader-error\n */\n get error () {\n webidl.brandCheck(this, FileReader)\n\n // The error attribute’s getter, when invoked, must return\n // this's error.\n return this[kError]\n }\n\n get onloadend () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].loadend\n }\n\n set onloadend (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].loadend) {\n this.removeEventListener('loadend', this[kEvents].loadend)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].loadend = fn\n this.addEventListener('loadend', fn)\n } else {\n this[kEvents].loadend = null\n }\n }\n\n get onerror () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].error\n }\n\n set onerror (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].error) {\n this.removeEventListener('error', this[kEvents].error)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].error = fn\n this.addEventListener('error', fn)\n } else {\n this[kEvents].error = null\n }\n }\n\n get onloadstart () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].loadstart\n }\n\n set onloadstart (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].loadstart) {\n this.removeEventListener('loadstart', this[kEvents].loadstart)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].loadstart = fn\n this.addEventListener('loadstart', fn)\n } else {\n this[kEvents].loadstart = null\n }\n }\n\n get onprogress () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].progress\n }\n\n set onprogress (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].progress) {\n this.removeEventListener('progress', this[kEvents].progress)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].progress = fn\n this.addEventListener('progress', fn)\n } else {\n this[kEvents].progress = null\n }\n }\n\n get onload () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].load\n }\n\n set onload (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].load) {\n this.removeEventListener('load', this[kEvents].load)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].load = fn\n this.addEventListener('load', fn)\n } else {\n this[kEvents].load = null\n }\n }\n\n get onabort () {\n webidl.brandCheck(this, FileReader)\n\n return this[kEvents].abort\n }\n\n set onabort (fn) {\n webidl.brandCheck(this, FileReader)\n\n if (this[kEvents].abort) {\n this.removeEventListener('abort', this[kEvents].abort)\n }\n\n if (typeof fn === 'function') {\n this[kEvents].abort = fn\n this.addEventListener('abort', fn)\n } else {\n this[kEvents].abort = null\n }\n }\n}\n\n// https://w3c.github.io/FileAPI/#dom-filereader-empty\nFileReader.EMPTY = FileReader.prototype.EMPTY = 0\n// https://w3c.github.io/FileAPI/#dom-filereader-loading\nFileReader.LOADING = FileReader.prototype.LOADING = 1\n// https://w3c.github.io/FileAPI/#dom-filereader-done\nFileReader.DONE = FileReader.prototype.DONE = 2\n\nObject.defineProperties(FileReader.prototype, {\n EMPTY: staticPropertyDescriptors,\n LOADING: staticPropertyDescriptors,\n DONE: staticPropertyDescriptors,\n readAsArrayBuffer: kEnumerableProperty,\n readAsBinaryString: kEnumerableProperty,\n readAsText: kEnumerableProperty,\n readAsDataURL: kEnumerableProperty,\n abort: kEnumerableProperty,\n readyState: kEnumerableProperty,\n result: kEnumerableProperty,\n error: kEnumerableProperty,\n onloadstart: kEnumerableProperty,\n onprogress: kEnumerableProperty,\n onload: kEnumerableProperty,\n onabort: kEnumerableProperty,\n onerror: kEnumerableProperty,\n onloadend: kEnumerableProperty,\n [Symbol.toStringTag]: {\n value: 'FileReader',\n writable: false,\n enumerable: false,\n configurable: true\n }\n})\n\nObject.defineProperties(FileReader, {\n EMPTY: staticPropertyDescriptors,\n LOADING: staticPropertyDescriptors,\n DONE: staticPropertyDescriptors\n})\n\nmodule.exports = {\n FileReader\n}\n","'use strict'\n\nmodule.exports = {\n kConstruct: require('../../core/symbols').kConstruct\n}\n","'use strict'\n\nconst assert = require('node:assert')\nconst { URLSerializer } = require('../fetch/data-url')\nconst { isValidHeaderName } = require('../fetch/util')\n\n/**\n * @see https://url.spec.whatwg.org/#concept-url-equals\n * @param {URL} A\n * @param {URL} B\n * @param {boolean | undefined} excludeFragment\n * @returns {boolean}\n */\nfunction urlEquals (A, B, excludeFragment = false) {\n const serializedA = URLSerializer(A, excludeFragment)\n\n const serializedB = URLSerializer(B, excludeFragment)\n\n return serializedA === serializedB\n}\n\n/**\n * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262\n * @param {string} header\n */\nfunction getFieldValues (header) {\n assert(header !== null)\n\n const values = []\n\n for (let value of header.split(',')) {\n value = value.trim()\n\n if (isValidHeaderName(value)) {\n values.push(value)\n }\n }\n\n return values\n}\n\nmodule.exports = {\n urlEquals,\n getFieldValues\n}\n","'use strict'\n\nconst { kConstruct } = require('./symbols')\nconst { urlEquals, getFieldValues } = require('./util')\nconst { kEnumerableProperty, isDisturbed } = require('../../core/util')\nconst { webidl } = require('../fetch/webidl')\nconst { Response, cloneResponse, fromInnerResponse } = require('../fetch/response')\nconst { Request, fromInnerRequest } = require('../fetch/request')\nconst { kState } = require('../fetch/symbols')\nconst { fetching } = require('../fetch/index')\nconst { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = require('../fetch/util')\nconst assert = require('node:assert')\n\n/**\n * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation\n * @typedef {Object} CacheBatchOperation\n * @property {'delete' | 'put'} type\n * @property {any} request\n * @property {any} response\n * @property {import('../../types/cache').CacheQueryOptions} options\n */\n\n/**\n * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list\n * @typedef {[any, any][]} requestResponseList\n */\n\nclass Cache {\n /**\n * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list\n * @type {requestResponseList}\n */\n #relevantRequestResponseList\n\n constructor () {\n if (arguments[0] !== kConstruct) {\n webidl.illegalConstructor()\n }\n\n webidl.util.markAsUncloneable(this)\n this.#relevantRequestResponseList = arguments[1]\n }\n\n async match (request, options = {}) {\n webidl.brandCheck(this, Cache)\n\n const prefix = 'Cache.match'\n webidl.argumentLengthCheck(arguments, 1, prefix)\n\n request = webidl.converters.RequestInfo(request, prefix, 'request')\n options = webidl.converters.CacheQueryOptions(options, prefix, 'options')\n\n const p = this.#internalMatchAll(request, options, 1)\n\n if (p.length === 0) {\n return\n }\n\n return p[0]\n }\n\n async matchAll (request = undefined, options = {}) {\n webidl.brandCheck(this, Cache)\n\n const prefix = 'Cache.matchAll'\n if (request !== undefined) request = webidl.converters.RequestInfo(request, prefix, 'request')\n options = webidl.converters.CacheQueryOptions(options, prefix, 'options')\n\n return this.#internalMatchAll(request, options)\n }\n\n async add (request) {\n webidl.brandCheck(this, Cache)\n\n const prefix = 'Cache.add'\n webidl.argumentLengthCheck(arguments, 1, prefix)\n\n request = webidl.converters.RequestInfo(request, prefix, 'request')\n\n // 1.\n const requests = [request]\n\n // 2.\n const responseArrayPromise = this.addAll(requests)\n\n // 3.\n return await responseArrayPromise\n }\n\n async addAll (requests) {\n webidl.brandCheck(this, Cache)\n\n const prefix = 'Cache.addAll'\n webidl.argumentLengthCheck(arguments, 1, prefix)\n\n // 1.\n const responsePromises = []\n\n // 2.\n const requestList = []\n\n // 3.\n for (let request of requests) {\n if (request === undefined) {\n throw webidl.errors.conversionFailed({\n prefix,\n argument: 'Argument 1',\n types: ['undefined is not allowed']\n })\n }\n\n request = webidl.converters.RequestInfo(request)\n\n if (typeof request === 'string') {\n continue\n }\n\n // 3.1\n const r = request[kState]\n\n // 3.2\n if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') {\n throw webidl.errors.exception({\n header: prefix,\n message: 'Expected http/s scheme when method is not GET.'\n })\n }\n }\n\n // 4.\n /** @type {ReturnType[]} */\n const fetchControllers = []\n\n // 5.\n for (const request of requests) {\n // 5.1\n const r = new Request(request)[kState]\n\n // 5.2\n if (!urlIsHttpHttpsScheme(r.url)) {\n throw webidl.errors.exception({\n header: prefix,\n message: 'Expected http/s scheme.'\n })\n }\n\n // 5.4\n r.initiator = 'fetch'\n r.destination = 'subresource'\n\n // 5.5\n requestList.push(r)\n\n // 5.6\n const responsePromise = createDeferredPromise()\n\n // 5.7\n fetchControllers.push(fetching({\n request: r,\n processResponse (response) {\n // 1.\n if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) {\n responsePromise.reject(webidl.errors.exception({\n header: 'Cache.addAll',\n message: 'Received an invalid status code or the request failed.'\n }))\n } else if (response.headersList.contains('vary')) { // 2.\n // 2.1\n const fieldValues = getFieldValues(response.headersList.get('vary'))\n\n // 2.2\n for (const fieldValue of fieldValues) {\n // 2.2.1\n if (fieldValue === '*') {\n responsePromise.reject(webidl.errors.exception({\n header: 'Cache.addAll',\n message: 'invalid vary field value'\n }))\n\n for (const controller of fetchControllers) {\n controller.abort()\n }\n\n return\n }\n }\n }\n },\n processResponseEndOfBody (response) {\n // 1.\n if (response.aborted) {\n responsePromise.reject(new DOMException('aborted', 'AbortError'))\n return\n }\n\n // 2.\n responsePromise.resolve(response)\n }\n }))\n\n // 5.8\n responsePromises.push(responsePromise.promise)\n }\n\n // 6.\n const p = Promise.all(responsePromises)\n\n // 7.\n const responses = await p\n\n // 7.1\n const operations = []\n\n // 7.2\n let index = 0\n\n // 7.3\n for (const response of responses) {\n // 7.3.1\n /** @type {CacheBatchOperation} */\n const operation = {\n type: 'put', // 7.3.2\n request: requestList[index], // 7.3.3\n response // 7.3.4\n }\n\n operations.push(operation) // 7.3.5\n\n index++ // 7.3.6\n }\n\n // 7.5\n const cacheJobPromise = createDeferredPromise()\n\n // 7.6.1\n let errorData = null\n\n // 7.6.2\n try {\n this.#batchCacheOperations(operations)\n } catch (e) {\n errorData = e\n }\n\n // 7.6.3\n queueMicrotask(() => {\n // 7.6.3.1\n if (errorData === null) {\n cacheJobPromise.resolve(undefined)\n } else {\n // 7.6.3.2\n cacheJobPromise.reject(errorData)\n }\n })\n\n // 7.7\n return cacheJobPromise.promise\n }\n\n async put (request, response) {\n webidl.brandCheck(this, Cache)\n\n const prefix = 'Cache.put'\n webidl.argumentLengthCheck(arguments, 2, prefix)\n\n request = webidl.converters.RequestInfo(request, prefix, 'request')\n response = webidl.converters.Response(response, prefix, 'response')\n\n // 1.\n let innerRequest = null\n\n // 2.\n if (request instanceof Request) {\n innerRequest = request[kState]\n } else { // 3.\n innerRequest = new Request(request)[kState]\n }\n\n // 4.\n if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') {\n throw webidl.errors.exception({\n header: prefix,\n message: 'Expected an http/s scheme when method is not GET'\n })\n }\n\n // 5.\n const innerResponse = response[kState]\n\n // 6.\n if (innerResponse.status === 206) {\n throw webidl.errors.exception({\n header: prefix,\n message: 'Got 206 status'\n })\n }\n\n // 7.\n if (innerResponse.headersList.contains('vary')) {\n // 7.1.\n const fieldValues = getFieldValues(innerResponse.headersList.get('vary'))\n\n // 7.2.\n for (const fieldValue of fieldValues) {\n // 7.2.1\n if (fieldValue === '*') {\n throw webidl.errors.exception({\n header: prefix,\n message: 'Got * vary field value'\n })\n }\n }\n }\n\n // 8.\n if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) {\n throw webidl.errors.exception({\n header: prefix,\n message: 'Response body is locked or disturbed'\n })\n }\n\n // 9.\n const clonedResponse = cloneResponse(innerResponse)\n\n // 10.\n const bodyReadPromise = createDeferredPromise()\n\n // 11.\n if (innerResponse.body != null) {\n // 11.1\n const stream = innerResponse.body.stream\n\n // 11.2\n const reader = stream.getReader()\n\n // 11.3\n readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject)\n } else {\n bodyReadPromise.resolve(undefined)\n }\n\n // 12.\n /** @type {CacheBatchOperation[]} */\n const operations = []\n\n // 13.\n /** @type {CacheBatchOperation} */\n const operation = {\n type: 'put', // 14.\n request: innerRequest, // 15.\n response: clonedResponse // 16.\n }\n\n // 17.\n operations.push(operation)\n\n // 19.\n const bytes = await bodyReadPromise.promise\n\n if (clonedResponse.body != null) {\n clonedResponse.body.source = bytes\n }\n\n // 19.1\n const cacheJobPromise = createDeferredPromise()\n\n // 19.2.1\n let errorData = null\n\n // 19.2.2\n try {\n this.#batchCacheOperations(operations)\n } catch (e) {\n errorData = e\n }\n\n // 19.2.3\n queueMicrotask(() => {\n // 19.2.3.1\n if (errorData === null) {\n cacheJobPromise.resolve()\n } else { // 19.2.3.2\n cacheJobPromise.reject(errorData)\n }\n })\n\n return cacheJobPromise.promise\n }\n\n async delete (request, options = {}) {\n webidl.brandCheck(this, Cache)\n\n const prefix = 'Cache.delete'\n webidl.argumentLengthCheck(arguments, 1, prefix)\n\n request = webidl.converters.RequestInfo(request, prefix, 'request')\n options = webidl.converters.CacheQueryOptions(options, prefix, 'options')\n\n /**\n * @type {Request}\n */\n let r = null\n\n if (request instanceof Request) {\n r = request[kState]\n\n if (r.method !== 'GET' && !options.ignoreMethod) {\n return false\n }\n } else {\n assert(typeof request === 'string')\n\n r = new Request(request)[kState]\n }\n\n /** @type {CacheBatchOperation[]} */\n const operations = []\n\n /** @type {CacheBatchOperation} */\n const operation = {\n type: 'delete',\n request: r,\n options\n }\n\n operations.push(operation)\n\n const cacheJobPromise = createDeferredPromise()\n\n let errorData = null\n let requestResponses\n\n try {\n requestResponses = this.#batchCacheOperations(operations)\n } catch (e) {\n errorData = e\n }\n\n queueMicrotask(() => {\n if (errorData === null) {\n cacheJobPromise.resolve(!!requestResponses?.length)\n } else {\n cacheJobPromise.reject(errorData)\n }\n })\n\n return cacheJobPromise.promise\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys\n * @param {any} request\n * @param {import('../../types/cache').CacheQueryOptions} options\n * @returns {Promise}\n */\n async keys (request = undefined, options = {}) {\n webidl.brandCheck(this, Cache)\n\n const prefix = 'Cache.keys'\n\n if (request !== undefined) request = webidl.converters.RequestInfo(request, prefix, 'request')\n options = webidl.converters.CacheQueryOptions(options, prefix, 'options')\n\n // 1.\n let r = null\n\n // 2.\n if (request !== undefined) {\n // 2.1\n if (request instanceof Request) {\n // 2.1.1\n r = request[kState]\n\n // 2.1.2\n if (r.method !== 'GET' && !options.ignoreMethod) {\n return []\n }\n } else if (typeof request === 'string') { // 2.2\n r = new Request(request)[kState]\n }\n }\n\n // 4.\n const promise = createDeferredPromise()\n\n // 5.\n // 5.1\n const requests = []\n\n // 5.2\n if (request === undefined) {\n // 5.2.1\n for (const requestResponse of this.#relevantRequestResponseList) {\n // 5.2.1.1\n requests.push(requestResponse[0])\n }\n } else { // 5.3\n // 5.3.1\n const requestResponses = this.#queryCache(r, options)\n\n // 5.3.2\n for (const requestResponse of requestResponses) {\n // 5.3.2.1\n requests.push(requestResponse[0])\n }\n }\n\n // 5.4\n queueMicrotask(() => {\n // 5.4.1\n const requestList = []\n\n // 5.4.2\n for (const request of requests) {\n const requestObject = fromInnerRequest(\n request,\n new AbortController().signal,\n 'immutable'\n )\n // 5.4.2.1\n requestList.push(requestObject)\n }\n\n // 5.4.3\n promise.resolve(Object.freeze(requestList))\n })\n\n return promise.promise\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm\n * @param {CacheBatchOperation[]} operations\n * @returns {requestResponseList}\n */\n #batchCacheOperations (operations) {\n // 1.\n const cache = this.#relevantRequestResponseList\n\n // 2.\n const backupCache = [...cache]\n\n // 3.\n const addedItems = []\n\n // 4.1\n const resultList = []\n\n try {\n // 4.2\n for (const operation of operations) {\n // 4.2.1\n if (operation.type !== 'delete' && operation.type !== 'put') {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'operation type does not match \"delete\" or \"put\"'\n })\n }\n\n // 4.2.2\n if (operation.type === 'delete' && operation.response != null) {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'delete operation should not have an associated response'\n })\n }\n\n // 4.2.3\n if (this.#queryCache(operation.request, operation.options, addedItems).length) {\n throw new DOMException('???', 'InvalidStateError')\n }\n\n // 4.2.4\n let requestResponses\n\n // 4.2.5\n if (operation.type === 'delete') {\n // 4.2.5.1\n requestResponses = this.#queryCache(operation.request, operation.options)\n\n // TODO: the spec is wrong, this is needed to pass WPTs\n if (requestResponses.length === 0) {\n return []\n }\n\n // 4.2.5.2\n for (const requestResponse of requestResponses) {\n const idx = cache.indexOf(requestResponse)\n assert(idx !== -1)\n\n // 4.2.5.2.1\n cache.splice(idx, 1)\n }\n } else if (operation.type === 'put') { // 4.2.6\n // 4.2.6.1\n if (operation.response == null) {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'put operation should have an associated response'\n })\n }\n\n // 4.2.6.2\n const r = operation.request\n\n // 4.2.6.3\n if (!urlIsHttpHttpsScheme(r.url)) {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'expected http or https scheme'\n })\n }\n\n // 4.2.6.4\n if (r.method !== 'GET') {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'not get method'\n })\n }\n\n // 4.2.6.5\n if (operation.options != null) {\n throw webidl.errors.exception({\n header: 'Cache.#batchCacheOperations',\n message: 'options must not be defined'\n })\n }\n\n // 4.2.6.6\n requestResponses = this.#queryCache(operation.request)\n\n // 4.2.6.7\n for (const requestResponse of requestResponses) {\n const idx = cache.indexOf(requestResponse)\n assert(idx !== -1)\n\n // 4.2.6.7.1\n cache.splice(idx, 1)\n }\n\n // 4.2.6.8\n cache.push([operation.request, operation.response])\n\n // 4.2.6.10\n addedItems.push([operation.request, operation.response])\n }\n\n // 4.2.7\n resultList.push([operation.request, operation.response])\n }\n\n // 4.3\n return resultList\n } catch (e) { // 5.\n // 5.1\n this.#relevantRequestResponseList.length = 0\n\n // 5.2\n this.#relevantRequestResponseList = backupCache\n\n // 5.3\n throw e\n }\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#query-cache\n * @param {any} requestQuery\n * @param {import('../../types/cache').CacheQueryOptions} options\n * @param {requestResponseList} targetStorage\n * @returns {requestResponseList}\n */\n #queryCache (requestQuery, options, targetStorage) {\n /** @type {requestResponseList} */\n const resultList = []\n\n const storage = targetStorage ?? this.#relevantRequestResponseList\n\n for (const requestResponse of storage) {\n const [cachedRequest, cachedResponse] = requestResponse\n if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) {\n resultList.push(requestResponse)\n }\n }\n\n return resultList\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm\n * @param {any} requestQuery\n * @param {any} request\n * @param {any | null} response\n * @param {import('../../types/cache').CacheQueryOptions | undefined} options\n * @returns {boolean}\n */\n #requestMatchesCachedItem (requestQuery, request, response = null, options) {\n // if (options?.ignoreMethod === false && request.method === 'GET') {\n // return false\n // }\n\n const queryURL = new URL(requestQuery.url)\n\n const cachedURL = new URL(request.url)\n\n if (options?.ignoreSearch) {\n cachedURL.search = ''\n\n queryURL.search = ''\n }\n\n if (!urlEquals(queryURL, cachedURL, true)) {\n return false\n }\n\n if (\n response == null ||\n options?.ignoreVary ||\n !response.headersList.contains('vary')\n ) {\n return true\n }\n\n const fieldValues = getFieldValues(response.headersList.get('vary'))\n\n for (const fieldValue of fieldValues) {\n if (fieldValue === '*') {\n return false\n }\n\n const requestValue = request.headersList.get(fieldValue)\n const queryValue = requestQuery.headersList.get(fieldValue)\n\n // If one has the header and the other doesn't, or one has\n // a different value than the other, return false\n if (requestValue !== queryValue) {\n return false\n }\n }\n\n return true\n }\n\n #internalMatchAll (request, options, maxResponses = Infinity) {\n // 1.\n let r = null\n\n // 2.\n if (request !== undefined) {\n if (request instanceof Request) {\n // 2.1.1\n r = request[kState]\n\n // 2.1.2\n if (r.method !== 'GET' && !options.ignoreMethod) {\n return []\n }\n } else if (typeof request === 'string') {\n // 2.2.1\n r = new Request(request)[kState]\n }\n }\n\n // 5.\n // 5.1\n const responses = []\n\n // 5.2\n if (request === undefined) {\n // 5.2.1\n for (const requestResponse of this.#relevantRequestResponseList) {\n responses.push(requestResponse[1])\n }\n } else { // 5.3\n // 5.3.1\n const requestResponses = this.#queryCache(r, options)\n\n // 5.3.2\n for (const requestResponse of requestResponses) {\n responses.push(requestResponse[1])\n }\n }\n\n // 5.4\n // We don't implement CORs so we don't need to loop over the responses, yay!\n\n // 5.5.1\n const responseList = []\n\n // 5.5.2\n for (const response of responses) {\n // 5.5.2.1\n const responseObject = fromInnerResponse(response, 'immutable')\n\n responseList.push(responseObject.clone())\n\n if (responseList.length >= maxResponses) {\n break\n }\n }\n\n // 6.\n return Object.freeze(responseList)\n }\n}\n\nObject.defineProperties(Cache.prototype, {\n [Symbol.toStringTag]: {\n value: 'Cache',\n configurable: true\n },\n match: kEnumerableProperty,\n matchAll: kEnumerableProperty,\n add: kEnumerableProperty,\n addAll: kEnumerableProperty,\n put: kEnumerableProperty,\n delete: kEnumerableProperty,\n keys: kEnumerableProperty\n})\n\nconst cacheQueryOptionConverters = [\n {\n key: 'ignoreSearch',\n converter: webidl.converters.boolean,\n defaultValue: () => false\n },\n {\n key: 'ignoreMethod',\n converter: webidl.converters.boolean,\n defaultValue: () => false\n },\n {\n key: 'ignoreVary',\n converter: webidl.converters.boolean,\n defaultValue: () => false\n }\n]\n\nwebidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters)\n\nwebidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([\n ...cacheQueryOptionConverters,\n {\n key: 'cacheName',\n converter: webidl.converters.DOMString\n }\n])\n\nwebidl.converters.Response = webidl.interfaceConverter(Response)\n\nwebidl.converters['sequence'] = webidl.sequenceConverter(\n webidl.converters.RequestInfo\n)\n\nmodule.exports = {\n Cache\n}\n","'use strict'\n\nconst { kConstruct } = require('./symbols')\nconst { Cache } = require('./cache')\nconst { webidl } = require('../fetch/webidl')\nconst { kEnumerableProperty } = require('../../core/util')\n\nclass CacheStorage {\n /**\n * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map\n * @type {Map}\n */\n async has (cacheName) {\n webidl.brandCheck(this, CacheStorage)\n\n const prefix = 'CacheStorage.has'\n webidl.argumentLengthCheck(arguments, 1, prefix)\n\n cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName')\n\n // 2.1.1\n // 2.2\n return this.#caches.has(cacheName)\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open\n * @param {string} cacheName\n * @returns {Promise}\n */\n async open (cacheName) {\n webidl.brandCheck(this, CacheStorage)\n\n const prefix = 'CacheStorage.open'\n webidl.argumentLengthCheck(arguments, 1, prefix)\n\n cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName')\n\n // 2.1\n if (this.#caches.has(cacheName)) {\n // await caches.open('v1') !== await caches.open('v1')\n\n // 2.1.1\n const cache = this.#caches.get(cacheName)\n\n // 2.1.1.1\n return new Cache(kConstruct, cache)\n }\n\n // 2.2\n const cache = []\n\n // 2.3\n this.#caches.set(cacheName, cache)\n\n // 2.4\n return new Cache(kConstruct, cache)\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete\n * @param {string} cacheName\n * @returns {Promise}\n */\n async delete (cacheName) {\n webidl.brandCheck(this, CacheStorage)\n\n const prefix = 'CacheStorage.delete'\n webidl.argumentLengthCheck(arguments, 1, prefix)\n\n cacheName = webidl.converters.DOMString(cacheName, prefix, 'cacheName')\n\n return this.#caches.delete(cacheName)\n }\n\n /**\n * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys\n * @returns {Promise}\n */\n async keys () {\n webidl.brandCheck(this, CacheStorage)\n\n // 2.1\n const keys = this.#caches.keys()\n\n // 2.2\n return [...keys]\n }\n}\n\nObject.defineProperties(CacheStorage.prototype, {\n [Symbol.toStringTag]: {\n value: 'CacheStorage',\n configurable: true\n },\n match: kEnumerableProperty,\n has: kEnumerableProperty,\n open: kEnumerableProperty,\n delete: kEnumerableProperty,\n keys: kEnumerableProperty\n})\n\nmodule.exports = {\n CacheStorage\n}\n","'use strict'\n\n// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size\nconst maxAttributeValueSize = 1024\n\n// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size\nconst maxNameValuePairSize = 4096\n\nmodule.exports = {\n maxAttributeValueSize,\n maxNameValuePairSize\n}\n","'use strict'\n\n/**\n * @param {string} value\n * @returns {boolean}\n */\nfunction isCTLExcludingHtab (value) {\n for (let i = 0; i < value.length; ++i) {\n const code = value.charCodeAt(i)\n\n if (\n (code >= 0x00 && code <= 0x08) ||\n (code >= 0x0A && code <= 0x1F) ||\n code === 0x7F\n ) {\n return true\n }\n }\n return false\n}\n\n/**\n CHAR = \n token = 1*\n separators = \"(\" | \")\" | \"<\" | \">\" | \"@\"\n | \",\" | \";\" | \":\" | \"\\\" | <\">\n | \"/\" | \"[\" | \"]\" | \"?\" | \"=\"\n | \"{\" | \"}\" | SP | HT\n * @param {string} name\n */\nfunction validateCookieName (name) {\n for (let i = 0; i < name.length; ++i) {\n const code = name.charCodeAt(i)\n\n if (\n code < 0x21 || // exclude CTLs (0-31), SP and HT\n code > 0x7E || // exclude non-ascii and DEL\n code === 0x22 || // \"\n code === 0x28 || // (\n code === 0x29 || // )\n code === 0x3C || // <\n code === 0x3E || // >\n code === 0x40 || // @\n code === 0x2C || // ,\n code === 0x3B || // ;\n code === 0x3A || // :\n code === 0x5C || // \\\n code === 0x2F || // /\n code === 0x5B || // [\n code === 0x5D || // ]\n code === 0x3F || // ?\n code === 0x3D || // =\n code === 0x7B || // {\n code === 0x7D // }\n ) {\n throw new Error('Invalid cookie name')\n }\n }\n}\n\n/**\n cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )\n cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E\n ; US-ASCII characters excluding CTLs,\n ; whitespace DQUOTE, comma, semicolon,\n ; and backslash\n * @param {string} value\n */\nfunction validateCookieValue (value) {\n let len = value.length\n let i = 0\n\n // if the value is wrapped in DQUOTE\n if (value[0] === '\"') {\n if (len === 1 || value[len - 1] !== '\"') {\n throw new Error('Invalid cookie value')\n }\n --len\n ++i\n }\n\n while (i < len) {\n const code = value.charCodeAt(i++)\n\n if (\n code < 0x21 || // exclude CTLs (0-31)\n code > 0x7E || // non-ascii and DEL (127)\n code === 0x22 || // \"\n code === 0x2C || // ,\n code === 0x3B || // ;\n code === 0x5C // \\\n ) {\n throw new Error('Invalid cookie value')\n }\n }\n}\n\n/**\n * path-value = \n * @param {string} path\n */\nfunction validateCookiePath (path) {\n for (let i = 0; i < path.length; ++i) {\n const code = path.charCodeAt(i)\n\n if (\n code < 0x20 || // exclude CTLs (0-31)\n code === 0x7F || // DEL\n code === 0x3B // ;\n ) {\n throw new Error('Invalid cookie path')\n }\n }\n}\n\n/**\n * I have no idea why these values aren't allowed to be honest,\n * but Deno tests these. - Khafra\n * @param {string} domain\n */\nfunction validateCookieDomain (domain) {\n if (\n domain.startsWith('-') ||\n domain.endsWith('.') ||\n domain.endsWith('-')\n ) {\n throw new Error('Invalid cookie domain')\n }\n}\n\nconst IMFDays = [\n 'Sun', 'Mon', 'Tue', 'Wed',\n 'Thu', 'Fri', 'Sat'\n]\n\nconst IMFMonths = [\n 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',\n 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'\n]\n\nconst IMFPaddedNumbers = Array(61).fill(0).map((_, i) => i.toString().padStart(2, '0'))\n\n/**\n * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1\n * @param {number|Date} date\n IMF-fixdate = day-name \",\" SP date1 SP time-of-day SP GMT\n ; fixed length/zone/capitalization subset of the format\n ; see Section 3.3 of [RFC5322]\n\n day-name = %x4D.6F.6E ; \"Mon\", case-sensitive\n / %x54.75.65 ; \"Tue\", case-sensitive\n / %x57.65.64 ; \"Wed\", case-sensitive\n / %x54.68.75 ; \"Thu\", case-sensitive\n / %x46.72.69 ; \"Fri\", case-sensitive\n / %x53.61.74 ; \"Sat\", case-sensitive\n / %x53.75.6E ; \"Sun\", case-sensitive\n date1 = day SP month SP year\n ; e.g., 02 Jun 1982\n\n day = 2DIGIT\n month = %x4A.61.6E ; \"Jan\", case-sensitive\n / %x46.65.62 ; \"Feb\", case-sensitive\n / %x4D.61.72 ; \"Mar\", case-sensitive\n / %x41.70.72 ; \"Apr\", case-sensitive\n / %x4D.61.79 ; \"May\", case-sensitive\n / %x4A.75.6E ; \"Jun\", case-sensitive\n / %x4A.75.6C ; \"Jul\", case-sensitive\n / %x41.75.67 ; \"Aug\", case-sensitive\n / %x53.65.70 ; \"Sep\", case-sensitive\n / %x4F.63.74 ; \"Oct\", case-sensitive\n / %x4E.6F.76 ; \"Nov\", case-sensitive\n / %x44.65.63 ; \"Dec\", case-sensitive\n year = 4DIGIT\n\n GMT = %x47.4D.54 ; \"GMT\", case-sensitive\n\n time-of-day = hour \":\" minute \":\" second\n ; 00:00:00 - 23:59:60 (leap second)\n\n hour = 2DIGIT\n minute = 2DIGIT\n second = 2DIGIT\n */\nfunction toIMFDate (date) {\n if (typeof date === 'number') {\n date = new Date(date)\n }\n\n return `${IMFDays[date.getUTCDay()]}, ${IMFPaddedNumbers[date.getUTCDate()]} ${IMFMonths[date.getUTCMonth()]} ${date.getUTCFullYear()} ${IMFPaddedNumbers[date.getUTCHours()]}:${IMFPaddedNumbers[date.getUTCMinutes()]}:${IMFPaddedNumbers[date.getUTCSeconds()]} GMT`\n}\n\n/**\n max-age-av = \"Max-Age=\" non-zero-digit *DIGIT\n ; In practice, both expires-av and max-age-av\n ; are limited to dates representable by the\n ; user agent.\n * @param {number} maxAge\n */\nfunction validateCookieMaxAge (maxAge) {\n if (maxAge < 0) {\n throw new Error('Invalid cookie max-age')\n }\n}\n\n/**\n * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1\n * @param {import('./index').Cookie} cookie\n */\nfunction stringify (cookie) {\n if (cookie.name.length === 0) {\n return null\n }\n\n validateCookieName(cookie.name)\n validateCookieValue(cookie.value)\n\n const out = [`${cookie.name}=${cookie.value}`]\n\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2\n if (cookie.name.startsWith('__Secure-')) {\n cookie.secure = true\n }\n\n if (cookie.name.startsWith('__Host-')) {\n cookie.secure = true\n cookie.domain = null\n cookie.path = '/'\n }\n\n if (cookie.secure) {\n out.push('Secure')\n }\n\n if (cookie.httpOnly) {\n out.push('HttpOnly')\n }\n\n if (typeof cookie.maxAge === 'number') {\n validateCookieMaxAge(cookie.maxAge)\n out.push(`Max-Age=${cookie.maxAge}`)\n }\n\n if (cookie.domain) {\n validateCookieDomain(cookie.domain)\n out.push(`Domain=${cookie.domain}`)\n }\n\n if (cookie.path) {\n validateCookiePath(cookie.path)\n out.push(`Path=${cookie.path}`)\n }\n\n if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') {\n out.push(`Expires=${toIMFDate(cookie.expires)}`)\n }\n\n if (cookie.sameSite) {\n out.push(`SameSite=${cookie.sameSite}`)\n }\n\n for (const part of cookie.unparsed) {\n if (!part.includes('=')) {\n throw new Error('Invalid unparsed')\n }\n\n const [key, ...value] = part.split('=')\n\n out.push(`${key.trim()}=${value.join('=')}`)\n }\n\n return out.join('; ')\n}\n\nmodule.exports = {\n isCTLExcludingHtab,\n validateCookieName,\n validateCookiePath,\n validateCookieValue,\n toIMFDate,\n stringify\n}\n","'use strict'\n\nconst { maxNameValuePairSize, maxAttributeValueSize } = require('./constants')\nconst { isCTLExcludingHtab } = require('./util')\nconst { collectASequenceOfCodePointsFast } = require('../fetch/data-url')\nconst assert = require('node:assert')\n\n/**\n * @description Parses the field-value attributes of a set-cookie header string.\n * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4\n * @param {string} header\n * @returns if the header is invalid, null will be returned\n */\nfunction parseSetCookie (header) {\n // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F\n // character (CTL characters excluding HTAB): Abort these steps and\n // ignore the set-cookie-string entirely.\n if (isCTLExcludingHtab(header)) {\n return null\n }\n\n let nameValuePair = ''\n let unparsedAttributes = ''\n let name = ''\n let value = ''\n\n // 2. If the set-cookie-string contains a %x3B (\";\") character:\n if (header.includes(';')) {\n // 1. The name-value-pair string consists of the characters up to,\n // but not including, the first %x3B (\";\"), and the unparsed-\n // attributes consist of the remainder of the set-cookie-string\n // (including the %x3B (\";\") in question).\n const position = { position: 0 }\n\n nameValuePair = collectASequenceOfCodePointsFast(';', header, position)\n unparsedAttributes = header.slice(position.position)\n } else {\n // Otherwise:\n\n // 1. The name-value-pair string consists of all the characters\n // contained in the set-cookie-string, and the unparsed-\n // attributes is the empty string.\n nameValuePair = header\n }\n\n // 3. If the name-value-pair string lacks a %x3D (\"=\") character, then\n // the name string is empty, and the value string is the value of\n // name-value-pair.\n if (!nameValuePair.includes('=')) {\n value = nameValuePair\n } else {\n // Otherwise, the name string consists of the characters up to, but\n // not including, the first %x3D (\"=\") character, and the (possibly\n // empty) value string consists of the characters after the first\n // %x3D (\"=\") character.\n const position = { position: 0 }\n name = collectASequenceOfCodePointsFast(\n '=',\n nameValuePair,\n position\n )\n value = nameValuePair.slice(position.position + 1)\n }\n\n // 4. Remove any leading or trailing WSP characters from the name\n // string and the value string.\n name = name.trim()\n value = value.trim()\n\n // 5. If the sum of the lengths of the name string and the value string\n // is more than 4096 octets, abort these steps and ignore the set-\n // cookie-string entirely.\n if (name.length + value.length > maxNameValuePairSize) {\n return null\n }\n\n // 6. The cookie-name is the name string, and the cookie-value is the\n // value string.\n return {\n name, value, ...parseUnparsedAttributes(unparsedAttributes)\n }\n}\n\n/**\n * Parses the remaining attributes of a set-cookie header\n * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4\n * @param {string} unparsedAttributes\n * @param {[Object.]={}} cookieAttributeList\n */\nfunction parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) {\n // 1. If the unparsed-attributes string is empty, skip the rest of\n // these steps.\n if (unparsedAttributes.length === 0) {\n return cookieAttributeList\n }\n\n // 2. Discard the first character of the unparsed-attributes (which\n // will be a %x3B (\";\") character).\n assert(unparsedAttributes[0] === ';')\n unparsedAttributes = unparsedAttributes.slice(1)\n\n let cookieAv = ''\n\n // 3. If the remaining unparsed-attributes contains a %x3B (\";\")\n // character:\n if (unparsedAttributes.includes(';')) {\n // 1. Consume the characters of the unparsed-attributes up to, but\n // not including, the first %x3B (\";\") character.\n cookieAv = collectASequenceOfCodePointsFast(\n ';',\n unparsedAttributes,\n { position: 0 }\n )\n unparsedAttributes = unparsedAttributes.slice(cookieAv.length)\n } else {\n // Otherwise:\n\n // 1. Consume the remainder of the unparsed-attributes.\n cookieAv = unparsedAttributes\n unparsedAttributes = ''\n }\n\n // Let the cookie-av string be the characters consumed in this step.\n\n let attributeName = ''\n let attributeValue = ''\n\n // 4. If the cookie-av string contains a %x3D (\"=\") character:\n if (cookieAv.includes('=')) {\n // 1. The (possibly empty) attribute-name string consists of the\n // characters up to, but not including, the first %x3D (\"=\")\n // character, and the (possibly empty) attribute-value string\n // consists of the characters after the first %x3D (\"=\")\n // character.\n const position = { position: 0 }\n\n attributeName = collectASequenceOfCodePointsFast(\n '=',\n cookieAv,\n position\n )\n attributeValue = cookieAv.slice(position.position + 1)\n } else {\n // Otherwise:\n\n // 1. The attribute-name string consists of the entire cookie-av\n // string, and the attribute-value string is empty.\n attributeName = cookieAv\n }\n\n // 5. Remove any leading or trailing WSP characters from the attribute-\n // name string and the attribute-value string.\n attributeName = attributeName.trim()\n attributeValue = attributeValue.trim()\n\n // 6. If the attribute-value is longer than 1024 octets, ignore the\n // cookie-av string and return to Step 1 of this algorithm.\n if (attributeValue.length > maxAttributeValueSize) {\n return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)\n }\n\n // 7. Process the attribute-name and attribute-value according to the\n // requirements in the following subsections. (Notice that\n // attributes with unrecognized attribute-names are ignored.)\n const attributeNameLowercase = attributeName.toLowerCase()\n\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1\n // If the attribute-name case-insensitively matches the string\n // \"Expires\", the user agent MUST process the cookie-av as follows.\n if (attributeNameLowercase === 'expires') {\n // 1. Let the expiry-time be the result of parsing the attribute-value\n // as cookie-date (see Section 5.1.1).\n const expiryTime = new Date(attributeValue)\n\n // 2. If the attribute-value failed to parse as a cookie date, ignore\n // the cookie-av.\n\n cookieAttributeList.expires = expiryTime\n } else if (attributeNameLowercase === 'max-age') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2\n // If the attribute-name case-insensitively matches the string \"Max-\n // Age\", the user agent MUST process the cookie-av as follows.\n\n // 1. If the first character of the attribute-value is not a DIGIT or a\n // \"-\" character, ignore the cookie-av.\n const charCode = attributeValue.charCodeAt(0)\n\n if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') {\n return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)\n }\n\n // 2. If the remainder of attribute-value contains a non-DIGIT\n // character, ignore the cookie-av.\n if (!/^\\d+$/.test(attributeValue)) {\n return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)\n }\n\n // 3. Let delta-seconds be the attribute-value converted to an integer.\n const deltaSeconds = Number(attributeValue)\n\n // 4. Let cookie-age-limit be the maximum age of the cookie (which\n // SHOULD be 400 days or less, see Section 4.1.2.2).\n\n // 5. Set delta-seconds to the smaller of its present value and cookie-\n // age-limit.\n // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs)\n\n // 6. If delta-seconds is less than or equal to zero (0), let expiry-\n // time be the earliest representable date and time. Otherwise, let\n // the expiry-time be the current date and time plus delta-seconds\n // seconds.\n // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds\n\n // 7. Append an attribute to the cookie-attribute-list with an\n // attribute-name of Max-Age and an attribute-value of expiry-time.\n cookieAttributeList.maxAge = deltaSeconds\n } else if (attributeNameLowercase === 'domain') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3\n // If the attribute-name case-insensitively matches the string \"Domain\",\n // the user agent MUST process the cookie-av as follows.\n\n // 1. Let cookie-domain be the attribute-value.\n let cookieDomain = attributeValue\n\n // 2. If cookie-domain starts with %x2E (\".\"), let cookie-domain be\n // cookie-domain without its leading %x2E (\".\").\n if (cookieDomain[0] === '.') {\n cookieDomain = cookieDomain.slice(1)\n }\n\n // 3. Convert the cookie-domain to lower case.\n cookieDomain = cookieDomain.toLowerCase()\n\n // 4. Append an attribute to the cookie-attribute-list with an\n // attribute-name of Domain and an attribute-value of cookie-domain.\n cookieAttributeList.domain = cookieDomain\n } else if (attributeNameLowercase === 'path') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4\n // If the attribute-name case-insensitively matches the string \"Path\",\n // the user agent MUST process the cookie-av as follows.\n\n // 1. If the attribute-value is empty or if the first character of the\n // attribute-value is not %x2F (\"/\"):\n let cookiePath = ''\n if (attributeValue.length === 0 || attributeValue[0] !== '/') {\n // 1. Let cookie-path be the default-path.\n cookiePath = '/'\n } else {\n // Otherwise:\n\n // 1. Let cookie-path be the attribute-value.\n cookiePath = attributeValue\n }\n\n // 2. Append an attribute to the cookie-attribute-list with an\n // attribute-name of Path and an attribute-value of cookie-path.\n cookieAttributeList.path = cookiePath\n } else if (attributeNameLowercase === 'secure') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5\n // If the attribute-name case-insensitively matches the string \"Secure\",\n // the user agent MUST append an attribute to the cookie-attribute-list\n // with an attribute-name of Secure and an empty attribute-value.\n\n cookieAttributeList.secure = true\n } else if (attributeNameLowercase === 'httponly') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6\n // If the attribute-name case-insensitively matches the string\n // \"HttpOnly\", the user agent MUST append an attribute to the cookie-\n // attribute-list with an attribute-name of HttpOnly and an empty\n // attribute-value.\n\n cookieAttributeList.httpOnly = true\n } else if (attributeNameLowercase === 'samesite') {\n // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7\n // If the attribute-name case-insensitively matches the string\n // \"SameSite\", the user agent MUST process the cookie-av as follows:\n\n // 1. Let enforcement be \"Default\".\n let enforcement = 'Default'\n\n const attributeValueLowercase = attributeValue.toLowerCase()\n // 2. If cookie-av's attribute-value is a case-insensitive match for\n // \"None\", set enforcement to \"None\".\n if (attributeValueLowercase.includes('none')) {\n enforcement = 'None'\n }\n\n // 3. If cookie-av's attribute-value is a case-insensitive match for\n // \"Strict\", set enforcement to \"Strict\".\n if (attributeValueLowercase.includes('strict')) {\n enforcement = 'Strict'\n }\n\n // 4. If cookie-av's attribute-value is a case-insensitive match for\n // \"Lax\", set enforcement to \"Lax\".\n if (attributeValueLowercase.includes('lax')) {\n enforcement = 'Lax'\n }\n\n // 5. Append an attribute to the cookie-attribute-list with an\n // attribute-name of \"SameSite\" and an attribute-value of\n // enforcement.\n cookieAttributeList.sameSite = enforcement\n } else {\n cookieAttributeList.unparsed ??= []\n\n cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`)\n }\n\n // 8. Return to Step 1 of this algorithm.\n return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)\n}\n\nmodule.exports = {\n parseSetCookie,\n parseUnparsedAttributes\n}\n","'use strict'\n\nconst { parseSetCookie } = require('./parse')\nconst { stringify } = require('./util')\nconst { webidl } = require('../fetch/webidl')\nconst { Headers } = require('../fetch/headers')\n\n/**\n * @typedef {Object} Cookie\n * @property {string} name\n * @property {string} value\n * @property {Date|number|undefined} expires\n * @property {number|undefined} maxAge\n * @property {string|undefined} domain\n * @property {string|undefined} path\n * @property {boolean|undefined} secure\n * @property {boolean|undefined} httpOnly\n * @property {'Strict'|'Lax'|'None'} sameSite\n * @property {string[]} unparsed\n */\n\n/**\n * @param {Headers} headers\n * @returns {Record}\n */\nfunction getCookies (headers) {\n webidl.argumentLengthCheck(arguments, 1, 'getCookies')\n\n webidl.brandCheck(headers, Headers, { strict: false })\n\n const cookie = headers.get('cookie')\n const out = {}\n\n if (!cookie) {\n return out\n }\n\n for (const piece of cookie.split(';')) {\n const [name, ...value] = piece.split('=')\n\n out[name.trim()] = value.join('=')\n }\n\n return out\n}\n\n/**\n * @param {Headers} headers\n * @param {string} name\n * @param {{ path?: string, domain?: string }|undefined} attributes\n * @returns {void}\n */\nfunction deleteCookie (headers, name, attributes) {\n webidl.brandCheck(headers, Headers, { strict: false })\n\n const prefix = 'deleteCookie'\n webidl.argumentLengthCheck(arguments, 2, prefix)\n\n name = webidl.converters.DOMString(name, prefix, 'name')\n attributes = webidl.converters.DeleteCookieAttributes(attributes)\n\n // Matches behavior of\n // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278\n setCookie(headers, {\n name,\n value: '',\n expires: new Date(0),\n ...attributes\n })\n}\n\n/**\n * @param {Headers} headers\n * @returns {Cookie[]}\n */\nfunction getSetCookies (headers) {\n webidl.argumentLengthCheck(arguments, 1, 'getSetCookies')\n\n webidl.brandCheck(headers, Headers, { strict: false })\n\n const cookies = headers.getSetCookie()\n\n if (!cookies) {\n return []\n }\n\n return cookies.map((pair) => parseSetCookie(pair))\n}\n\n/**\n * @param {Headers} headers\n * @param {Cookie} cookie\n * @returns {void}\n */\nfunction setCookie (headers, cookie) {\n webidl.argumentLengthCheck(arguments, 2, 'setCookie')\n\n webidl.brandCheck(headers, Headers, { strict: false })\n\n cookie = webidl.converters.Cookie(cookie)\n\n const str = stringify(cookie)\n\n if (str) {\n headers.append('Set-Cookie', str)\n }\n}\n\nwebidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([\n {\n converter: webidl.nullableConverter(webidl.converters.DOMString),\n key: 'path',\n defaultValue: () => null\n },\n {\n converter: webidl.nullableConverter(webidl.converters.DOMString),\n key: 'domain',\n defaultValue: () => null\n }\n])\n\nwebidl.converters.Cookie = webidl.dictionaryConverter([\n {\n converter: webidl.converters.DOMString,\n key: 'name'\n },\n {\n converter: webidl.converters.DOMString,\n key: 'value'\n },\n {\n converter: webidl.nullableConverter((value) => {\n if (typeof value === 'number') {\n return webidl.converters['unsigned long long'](value)\n }\n\n return new Date(value)\n }),\n key: 'expires',\n defaultValue: () => null\n },\n {\n converter: webidl.nullableConverter(webidl.converters['long long']),\n key: 'maxAge',\n defaultValue: () => null\n },\n {\n converter: webidl.nullableConverter(webidl.converters.DOMString),\n key: 'domain',\n defaultValue: () => null\n },\n {\n converter: webidl.nullableConverter(webidl.converters.DOMString),\n key: 'path',\n defaultValue: () => null\n },\n {\n converter: webidl.nullableConverter(webidl.converters.boolean),\n key: 'secure',\n defaultValue: () => null\n },\n {\n converter: webidl.nullableConverter(webidl.converters.boolean),\n key: 'httpOnly',\n defaultValue: () => null\n },\n {\n converter: webidl.converters.USVString,\n key: 'sameSite',\n allowedValues: ['Strict', 'Lax', 'None']\n },\n {\n converter: webidl.sequenceConverter(webidl.converters.DOMString),\n key: 'unparsed',\n defaultValue: () => new Array(0)\n }\n])\n\nmodule.exports = {\n getCookies,\n deleteCookie,\n getSetCookies,\n setCookie\n}\n","'use strict'\n\nconst { webidl } = require('../fetch/webidl')\nconst { kEnumerableProperty } = require('../../core/util')\nconst { kConstruct } = require('../../core/symbols')\nconst { MessagePort } = require('node:worker_threads')\n\n/**\n * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent\n */\nclass MessageEvent extends Event {\n #eventInit\n\n constructor (type, eventInitDict = {}) {\n if (type === kConstruct) {\n super(arguments[1], arguments[2])\n webidl.util.markAsUncloneable(this)\n return\n }\n\n const prefix = 'MessageEvent constructor'\n webidl.argumentLengthCheck(arguments, 1, prefix)\n\n type = webidl.converters.DOMString(type, prefix, 'type')\n eventInitDict = webidl.converters.MessageEventInit(eventInitDict, prefix, 'eventInitDict')\n\n super(type, eventInitDict)\n\n this.#eventInit = eventInitDict\n webidl.util.markAsUncloneable(this)\n }\n\n get data () {\n webidl.brandCheck(this, MessageEvent)\n\n return this.#eventInit.data\n }\n\n get origin () {\n webidl.brandCheck(this, MessageEvent)\n\n return this.#eventInit.origin\n }\n\n get lastEventId () {\n webidl.brandCheck(this, MessageEvent)\n\n return this.#eventInit.lastEventId\n }\n\n get source () {\n webidl.brandCheck(this, MessageEvent)\n\n return this.#eventInit.source\n }\n\n get ports () {\n webidl.brandCheck(this, MessageEvent)\n\n if (!Object.isFrozen(this.#eventInit.ports)) {\n Object.freeze(this.#eventInit.ports)\n }\n\n return this.#eventInit.ports\n }\n\n initMessageEvent (\n type,\n bubbles = false,\n cancelable = false,\n data = null,\n origin = '',\n lastEventId = '',\n source = null,\n ports = []\n ) {\n webidl.brandCheck(this, MessageEvent)\n\n webidl.argumentLengthCheck(arguments, 1, 'MessageEvent.initMessageEvent')\n\n return new MessageEvent(type, {\n bubbles, cancelable, data, origin, lastEventId, source, ports\n })\n }\n\n static createFastMessageEvent (type, init) {\n const messageEvent = new MessageEvent(kConstruct, type, init)\n messageEvent.#eventInit = init\n messageEvent.#eventInit.data ??= null\n messageEvent.#eventInit.origin ??= ''\n messageEvent.#eventInit.lastEventId ??= ''\n messageEvent.#eventInit.source ??= null\n messageEvent.#eventInit.ports ??= []\n return messageEvent\n }\n}\n\nconst { createFastMessageEvent } = MessageEvent\ndelete MessageEvent.createFastMessageEvent\n\n/**\n * @see https://websockets.spec.whatwg.org/#the-closeevent-interface\n */\nclass CloseEvent extends Event {\n #eventInit\n\n constructor (type, eventInitDict = {}) {\n const prefix = 'CloseEvent constructor'\n webidl.argumentLengthCheck(arguments, 1, prefix)\n\n type = webidl.converters.DOMString(type, prefix, 'type')\n eventInitDict = webidl.converters.CloseEventInit(eventInitDict)\n\n super(type, eventInitDict)\n\n this.#eventInit = eventInitDict\n webidl.util.markAsUncloneable(this)\n }\n\n get wasClean () {\n webidl.brandCheck(this, CloseEvent)\n\n return this.#eventInit.wasClean\n }\n\n get code () {\n webidl.brandCheck(this, CloseEvent)\n\n return this.#eventInit.code\n }\n\n get reason () {\n webidl.brandCheck(this, CloseEvent)\n\n return this.#eventInit.reason\n }\n}\n\n// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface\nclass ErrorEvent extends Event {\n #eventInit\n\n constructor (type, eventInitDict) {\n const prefix = 'ErrorEvent constructor'\n webidl.argumentLengthCheck(arguments, 1, prefix)\n\n super(type, eventInitDict)\n webidl.util.markAsUncloneable(this)\n\n type = webidl.converters.DOMString(type, prefix, 'type')\n eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {})\n\n this.#eventInit = eventInitDict\n }\n\n get message () {\n webidl.brandCheck(this, ErrorEvent)\n\n return this.#eventInit.message\n }\n\n get filename () {\n webidl.brandCheck(this, ErrorEvent)\n\n return this.#eventInit.filename\n }\n\n get lineno () {\n webidl.brandCheck(this, ErrorEvent)\n\n return this.#eventInit.lineno\n }\n\n get colno () {\n webidl.brandCheck(this, ErrorEvent)\n\n return this.#eventInit.colno\n }\n\n get error () {\n webidl.brandCheck(this, ErrorEvent)\n\n return this.#eventInit.error\n }\n}\n\nObject.defineProperties(MessageEvent.prototype, {\n [Symbol.toStringTag]: {\n value: 'MessageEvent',\n configurable: true\n },\n data: kEnumerableProperty,\n origin: kEnumerableProperty,\n lastEventId: kEnumerableProperty,\n source: kEnumerableProperty,\n ports: kEnumerableProperty,\n initMessageEvent: kEnumerableProperty\n})\n\nObject.defineProperties(CloseEvent.prototype, {\n [Symbol.toStringTag]: {\n value: 'CloseEvent',\n configurable: true\n },\n reason: kEnumerableProperty,\n code: kEnumerableProperty,\n wasClean: kEnumerableProperty\n})\n\nObject.defineProperties(ErrorEvent.prototype, {\n [Symbol.toStringTag]: {\n value: 'ErrorEvent',\n configurable: true\n },\n message: kEnumerableProperty,\n filename: kEnumerableProperty,\n lineno: kEnumerableProperty,\n colno: kEnumerableProperty,\n error: kEnumerableProperty\n})\n\nwebidl.converters.MessagePort = webidl.interfaceConverter(MessagePort)\n\nwebidl.converters['sequence'] = webidl.sequenceConverter(\n webidl.converters.MessagePort\n)\n\nconst eventInit = [\n {\n key: 'bubbles',\n converter: webidl.converters.boolean,\n defaultValue: () => false\n },\n {\n key: 'cancelable',\n converter: webidl.converters.boolean,\n defaultValue: () => false\n },\n {\n key: 'composed',\n converter: webidl.converters.boolean,\n defaultValue: () => false\n }\n]\n\nwebidl.converters.MessageEventInit = webidl.dictionaryConverter([\n ...eventInit,\n {\n key: 'data',\n converter: webidl.converters.any,\n defaultValue: () => null\n },\n {\n key: 'origin',\n converter: webidl.converters.USVString,\n defaultValue: () => ''\n },\n {\n key: 'lastEventId',\n converter: webidl.converters.DOMString,\n defaultValue: () => ''\n },\n {\n key: 'source',\n // Node doesn't implement WindowProxy or ServiceWorker, so the only\n // valid value for source is a MessagePort.\n converter: webidl.nullableConverter(webidl.converters.MessagePort),\n defaultValue: () => null\n },\n {\n key: 'ports',\n converter: webidl.converters['sequence'],\n defaultValue: () => new Array(0)\n }\n])\n\nwebidl.converters.CloseEventInit = webidl.dictionaryConverter([\n ...eventInit,\n {\n key: 'wasClean',\n converter: webidl.converters.boolean,\n defaultValue: () => false\n },\n {\n key: 'code',\n converter: webidl.converters['unsigned short'],\n defaultValue: () => 0\n },\n {\n key: 'reason',\n converter: webidl.converters.USVString,\n defaultValue: () => ''\n }\n])\n\nwebidl.converters.ErrorEventInit = webidl.dictionaryConverter([\n ...eventInit,\n {\n key: 'message',\n converter: webidl.converters.DOMString,\n defaultValue: () => ''\n },\n {\n key: 'filename',\n converter: webidl.converters.USVString,\n defaultValue: () => ''\n },\n {\n key: 'lineno',\n converter: webidl.converters['unsigned long'],\n defaultValue: () => 0\n },\n {\n key: 'colno',\n converter: webidl.converters['unsigned long'],\n defaultValue: () => 0\n },\n {\n key: 'error',\n converter: webidl.converters.any\n }\n])\n\nmodule.exports = {\n MessageEvent,\n CloseEvent,\n ErrorEvent,\n createFastMessageEvent\n}\n","'use strict'\n\n// This is a Globally Unique Identifier unique used\n// to validate that the endpoint accepts websocket\n// connections.\n// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3\nconst uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'\n\n/** @type {PropertyDescriptor} */\nconst staticPropertyDescriptors = {\n enumerable: true,\n writable: false,\n configurable: false\n}\n\nconst states = {\n CONNECTING: 0,\n OPEN: 1,\n CLOSING: 2,\n CLOSED: 3\n}\n\nconst sentCloseFrameState = {\n NOT_SENT: 0,\n PROCESSING: 1,\n SENT: 2\n}\n\nconst opcodes = {\n CONTINUATION: 0x0,\n TEXT: 0x1,\n BINARY: 0x2,\n CLOSE: 0x8,\n PING: 0x9,\n PONG: 0xA\n}\n\nconst maxUnsigned16Bit = 2 ** 16 - 1 // 65535\n\nconst parserStates = {\n INFO: 0,\n PAYLOADLENGTH_16: 2,\n PAYLOADLENGTH_64: 3,\n READ_DATA: 4\n}\n\nconst emptyBuffer = Buffer.allocUnsafe(0)\n\nconst sendHints = {\n string: 1,\n typedArray: 2,\n arrayBuffer: 3,\n blob: 4\n}\n\nmodule.exports = {\n uid,\n sentCloseFrameState,\n staticPropertyDescriptors,\n states,\n opcodes,\n maxUnsigned16Bit,\n parserStates,\n emptyBuffer,\n sendHints\n}\n","'use strict'\n\nmodule.exports = {\n kWebSocketURL: Symbol('url'),\n kReadyState: Symbol('ready state'),\n kController: Symbol('controller'),\n kResponse: Symbol('response'),\n kBinaryType: Symbol('binary type'),\n kSentClose: Symbol('sent close'),\n kReceivedClose: Symbol('received close'),\n kByteParser: Symbol('byte parser')\n}\n","'use strict'\n\nconst { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = require('./symbols')\nconst { states, opcodes } = require('./constants')\nconst { ErrorEvent, createFastMessageEvent } = require('./events')\nconst { isUtf8 } = require('node:buffer')\nconst { collectASequenceOfCodePointsFast, removeHTTPWhitespace } = require('../fetch/data-url')\n\n/* globals Blob */\n\n/**\n * @param {import('./websocket').WebSocket} ws\n * @returns {boolean}\n */\nfunction isConnecting (ws) {\n // If the WebSocket connection is not yet established, and the connection\n // is not yet closed, then the WebSocket connection is in the CONNECTING state.\n return ws[kReadyState] === states.CONNECTING\n}\n\n/**\n * @param {import('./websocket').WebSocket} ws\n * @returns {boolean}\n */\nfunction isEstablished (ws) {\n // If the server's response is validated as provided for above, it is\n // said that _The WebSocket Connection is Established_ and that the\n // WebSocket Connection is in the OPEN state.\n return ws[kReadyState] === states.OPEN\n}\n\n/**\n * @param {import('./websocket').WebSocket} ws\n * @returns {boolean}\n */\nfunction isClosing (ws) {\n // Upon either sending or receiving a Close control frame, it is said\n // that _The WebSocket Closing Handshake is Started_ and that the\n // WebSocket connection is in the CLOSING state.\n return ws[kReadyState] === states.CLOSING\n}\n\n/**\n * @param {import('./websocket').WebSocket} ws\n * @returns {boolean}\n */\nfunction isClosed (ws) {\n return ws[kReadyState] === states.CLOSED\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#concept-event-fire\n * @param {string} e\n * @param {EventTarget} target\n * @param {(...args: ConstructorParameters) => Event} eventFactory\n * @param {EventInit | undefined} eventInitDict\n */\nfunction fireEvent (e, target, eventFactory = (type, init) => new Event(type, init), eventInitDict = {}) {\n // 1. If eventConstructor is not given, then let eventConstructor be Event.\n\n // 2. Let event be the result of creating an event given eventConstructor,\n // in the relevant realm of target.\n // 3. Initialize event’s type attribute to e.\n const event = eventFactory(e, eventInitDict)\n\n // 4. Initialize any other IDL attributes of event as described in the\n // invocation of this algorithm.\n\n // 5. Return the result of dispatching event at target, with legacy target\n // override flag set if set.\n target.dispatchEvent(event)\n}\n\n/**\n * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol\n * @param {import('./websocket').WebSocket} ws\n * @param {number} type Opcode\n * @param {Buffer} data application data\n */\nfunction websocketMessageReceived (ws, type, data) {\n // 1. If ready state is not OPEN (1), then return.\n if (ws[kReadyState] !== states.OPEN) {\n return\n }\n\n // 2. Let dataForEvent be determined by switching on type and binary type:\n let dataForEvent\n\n if (type === opcodes.TEXT) {\n // -> type indicates that the data is Text\n // a new DOMString containing data\n try {\n dataForEvent = utf8Decode(data)\n } catch {\n failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.')\n return\n }\n } else if (type === opcodes.BINARY) {\n if (ws[kBinaryType] === 'blob') {\n // -> type indicates that the data is Binary and binary type is \"blob\"\n // a new Blob object, created in the relevant Realm of the WebSocket\n // object, that represents data as its raw data\n dataForEvent = new Blob([data])\n } else {\n // -> type indicates that the data is Binary and binary type is \"arraybuffer\"\n // a new ArrayBuffer object, created in the relevant Realm of the\n // WebSocket object, whose contents are data\n dataForEvent = toArrayBuffer(data)\n }\n }\n\n // 3. Fire an event named message at the WebSocket object, using MessageEvent,\n // with the origin attribute initialized to the serialization of the WebSocket\n // object’s url's origin, and the data attribute initialized to dataForEvent.\n fireEvent('message', ws, createFastMessageEvent, {\n origin: ws[kWebSocketURL].origin,\n data: dataForEvent\n })\n}\n\nfunction toArrayBuffer (buffer) {\n if (buffer.byteLength === buffer.buffer.byteLength) {\n return buffer.buffer\n }\n return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength)\n}\n\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc6455\n * @see https://datatracker.ietf.org/doc/html/rfc2616\n * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407\n * @param {string} protocol\n */\nfunction isValidSubprotocol (protocol) {\n // If present, this value indicates one\n // or more comma-separated subprotocol the client wishes to speak,\n // ordered by preference. The elements that comprise this value\n // MUST be non-empty strings with characters in the range U+0021 to\n // U+007E not including separator characters as defined in\n // [RFC2616] and MUST all be unique strings.\n if (protocol.length === 0) {\n return false\n }\n\n for (let i = 0; i < protocol.length; ++i) {\n const code = protocol.charCodeAt(i)\n\n if (\n code < 0x21 || // CTL, contains SP (0x20) and HT (0x09)\n code > 0x7E ||\n code === 0x22 || // \"\n code === 0x28 || // (\n code === 0x29 || // )\n code === 0x2C || // ,\n code === 0x2F || // /\n code === 0x3A || // :\n code === 0x3B || // ;\n code === 0x3C || // <\n code === 0x3D || // =\n code === 0x3E || // >\n code === 0x3F || // ?\n code === 0x40 || // @\n code === 0x5B || // [\n code === 0x5C || // \\\n code === 0x5D || // ]\n code === 0x7B || // {\n code === 0x7D // }\n ) {\n return false\n }\n }\n\n return true\n}\n\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4\n * @param {number} code\n */\nfunction isValidStatusCode (code) {\n if (code >= 1000 && code < 1015) {\n return (\n code !== 1004 && // reserved\n code !== 1005 && // \"MUST NOT be set as a status code\"\n code !== 1006 // \"MUST NOT be set as a status code\"\n )\n }\n\n return code >= 3000 && code <= 4999\n}\n\n/**\n * @param {import('./websocket').WebSocket} ws\n * @param {string|undefined} reason\n */\nfunction failWebsocketConnection (ws, reason) {\n const { [kController]: controller, [kResponse]: response } = ws\n\n controller.abort()\n\n if (response?.socket && !response.socket.destroyed) {\n response.socket.destroy()\n }\n\n if (reason) {\n // TODO: process.nextTick\n fireEvent('error', ws, (type, init) => new ErrorEvent(type, init), {\n error: new Error(reason),\n message: reason\n })\n }\n}\n\n/**\n * @see https://datatracker.ietf.org/doc/html/rfc6455#section-5.5\n * @param {number} opcode\n */\nfunction isControlFrame (opcode) {\n return (\n opcode === opcodes.CLOSE ||\n opcode === opcodes.PING ||\n opcode === opcodes.PONG\n )\n}\n\nfunction isContinuationFrame (opcode) {\n return opcode === opcodes.CONTINUATION\n}\n\nfunction isTextBinaryFrame (opcode) {\n return opcode === opcodes.TEXT || opcode === opcodes.BINARY\n}\n\nfunction isValidOpcode (opcode) {\n return isTextBinaryFrame(opcode) || isContinuationFrame(opcode) || isControlFrame(opcode)\n}\n\n/**\n * Parses a Sec-WebSocket-Extensions header value.\n * @param {string} extensions\n * @returns {Map}\n */\n// TODO(@Uzlopak, @KhafraDev): make compliant https://datatracker.ietf.org/doc/html/rfc6455#section-9.1\nfunction parseExtensions (extensions) {\n const position = { position: 0 }\n const extensionList = new Map()\n\n while (position.position < extensions.length) {\n const pair = collectASequenceOfCodePointsFast(';', extensions, position)\n const [name, value = ''] = pair.split('=')\n\n extensionList.set(\n removeHTTPWhitespace(name, true, false),\n removeHTTPWhitespace(value, false, true)\n )\n\n position.position++\n }\n\n return extensionList\n}\n\n/**\n * @see https://www.rfc-editor.org/rfc/rfc7692#section-7.1.2.2\n * @description \"client-max-window-bits = 1*DIGIT\"\n * @param {string} value\n */\nfunction isValidClientWindowBits (value) {\n // Must have at least one character\n if (value.length === 0) {\n return false\n }\n\n // Check all characters are ASCII digits\n for (let i = 0; i < value.length; i++) {\n const byte = value.charCodeAt(i)\n\n if (byte < 0x30 || byte > 0x39) {\n return false\n }\n }\n\n // Check numeric range: zlib requires windowBits in range 8-15\n const num = Number.parseInt(value, 10)\n return num >= 8 && num <= 15\n}\n\n// https://nodejs.org/api/intl.html#detecting-internationalization-support\nconst hasIntl = typeof process.versions.icu === 'string'\nconst fatalDecoder = hasIntl ? new TextDecoder('utf-8', { fatal: true }) : undefined\n\n/**\n * Converts a Buffer to utf-8, even on platforms without icu.\n * @param {Buffer} buffer\n */\nconst utf8Decode = hasIntl\n ? fatalDecoder.decode.bind(fatalDecoder)\n : function (buffer) {\n if (isUtf8(buffer)) {\n return buffer.toString('utf-8')\n }\n throw new TypeError('Invalid utf-8 received.')\n }\n\nmodule.exports = {\n isConnecting,\n isEstablished,\n isClosing,\n isClosed,\n fireEvent,\n isValidSubprotocol,\n isValidStatusCode,\n failWebsocketConnection,\n websocketMessageReceived,\n utf8Decode,\n isControlFrame,\n isContinuationFrame,\n isTextBinaryFrame,\n isValidOpcode,\n parseExtensions,\n isValidClientWindowBits\n}\n","'use strict'\n\nconst { maxUnsigned16Bit } = require('./constants')\n\nconst BUFFER_SIZE = 16386\n\n/** @type {import('crypto')} */\nlet crypto\nlet buffer = null\nlet bufIdx = BUFFER_SIZE\n\ntry {\n crypto = require('node:crypto')\n/* c8 ignore next 3 */\n} catch {\n crypto = {\n // not full compatibility, but minimum.\n randomFillSync: function randomFillSync (buffer, _offset, _size) {\n for (let i = 0; i < buffer.length; ++i) {\n buffer[i] = Math.random() * 255 | 0\n }\n return buffer\n }\n }\n}\n\nfunction generateMask () {\n if (bufIdx === BUFFER_SIZE) {\n bufIdx = 0\n crypto.randomFillSync((buffer ??= Buffer.allocUnsafe(BUFFER_SIZE)), 0, BUFFER_SIZE)\n }\n return [buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++], buffer[bufIdx++]]\n}\n\nclass WebsocketFrameSend {\n /**\n * @param {Buffer|undefined} data\n */\n constructor (data) {\n this.frameData = data\n }\n\n createFrame (opcode) {\n const frameData = this.frameData\n const maskKey = generateMask()\n const bodyLength = frameData?.byteLength ?? 0\n\n /** @type {number} */\n let payloadLength = bodyLength // 0-125\n let offset = 6\n\n if (bodyLength > maxUnsigned16Bit) {\n offset += 8 // payload length is next 8 bytes\n payloadLength = 127\n } else if (bodyLength > 125) {\n offset += 2 // payload length is next 2 bytes\n payloadLength = 126\n }\n\n const buffer = Buffer.allocUnsafe(bodyLength + offset)\n\n // Clear first 2 bytes, everything else is overwritten\n buffer[0] = buffer[1] = 0\n buffer[0] |= 0x80 // FIN\n buffer[0] = (buffer[0] & 0xF0) + opcode // opcode\n\n /*! ws. MIT License. Einar Otto Stangvik */\n buffer[offset - 4] = maskKey[0]\n buffer[offset - 3] = maskKey[1]\n buffer[offset - 2] = maskKey[2]\n buffer[offset - 1] = maskKey[3]\n\n buffer[1] = payloadLength\n\n if (payloadLength === 126) {\n buffer.writeUInt16BE(bodyLength, 2)\n } else if (payloadLength === 127) {\n // Clear extended payload length\n buffer[2] = buffer[3] = 0\n buffer.writeUIntBE(bodyLength, 4, 6)\n }\n\n buffer[1] |= 0x80 // MASK\n\n // mask body\n for (let i = 0; i < bodyLength; ++i) {\n buffer[offset + i] = frameData[i] ^ maskKey[i & 3]\n }\n\n return buffer\n }\n}\n\nmodule.exports = {\n WebsocketFrameSend\n}\n","'use strict'\n\nconst { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = require('./constants')\nconst {\n kReadyState,\n kSentClose,\n kByteParser,\n kReceivedClose,\n kResponse\n} = require('./symbols')\nconst { fireEvent, failWebsocketConnection, isClosing, isClosed, isEstablished, parseExtensions } = require('./util')\nconst { channels } = require('../../core/diagnostics')\nconst { CloseEvent } = require('./events')\nconst { makeRequest } = require('../fetch/request')\nconst { fetching } = require('../fetch/index')\nconst { Headers, getHeadersList } = require('../fetch/headers')\nconst { getDecodeSplit } = require('../fetch/util')\nconst { WebsocketFrameSend } = require('./frame')\n\n/** @type {import('crypto')} */\nlet crypto\ntry {\n crypto = require('node:crypto')\n/* c8 ignore next 3 */\n} catch {\n\n}\n\n/**\n * @see https://websockets.spec.whatwg.org/#concept-websocket-establish\n * @param {URL} url\n * @param {string|string[]} protocols\n * @param {import('./websocket').WebSocket} ws\n * @param {(response: any, extensions: string[] | undefined) => void} onEstablish\n * @param {Partial} options\n */\nfunction establishWebSocketConnection (url, protocols, client, ws, onEstablish, options) {\n // 1. Let requestURL be a copy of url, with its scheme set to \"http\", if url’s\n // scheme is \"ws\", and to \"https\" otherwise.\n const requestURL = url\n\n requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:'\n\n // 2. Let request be a new request, whose URL is requestURL, client is client,\n // service-workers mode is \"none\", referrer is \"no-referrer\", mode is\n // \"websocket\", credentials mode is \"include\", cache mode is \"no-store\" ,\n // and redirect mode is \"error\".\n const request = makeRequest({\n urlList: [requestURL],\n client,\n serviceWorkers: 'none',\n referrer: 'no-referrer',\n mode: 'websocket',\n credentials: 'include',\n cache: 'no-store',\n redirect: 'error'\n })\n\n // Note: undici extension, allow setting custom headers.\n if (options.headers) {\n const headersList = getHeadersList(new Headers(options.headers))\n\n request.headersList = headersList\n }\n\n // 3. Append (`Upgrade`, `websocket`) to request’s header list.\n // 4. Append (`Connection`, `Upgrade`) to request’s header list.\n // Note: both of these are handled by undici currently.\n // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397\n\n // 5. Let keyValue be a nonce consisting of a randomly selected\n // 16-byte value that has been forgiving-base64-encoded and\n // isomorphic encoded.\n const keyValue = crypto.randomBytes(16).toString('base64')\n\n // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s\n // header list.\n request.headersList.append('sec-websocket-key', keyValue)\n\n // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s\n // header list.\n request.headersList.append('sec-websocket-version', '13')\n\n // 8. For each protocol in protocols, combine\n // (`Sec-WebSocket-Protocol`, protocol) in request’s header\n // list.\n for (const protocol of protocols) {\n request.headersList.append('sec-websocket-protocol', protocol)\n }\n\n // 9. Let permessageDeflate be a user-agent defined\n // \"permessage-deflate\" extension header value.\n // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673\n const permessageDeflate = 'permessage-deflate; client_max_window_bits'\n\n // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to\n // request’s header list.\n request.headersList.append('sec-websocket-extensions', permessageDeflate)\n\n // 11. Fetch request with useParallelQueue set to true, and\n // processResponse given response being these steps:\n const controller = fetching({\n request,\n useParallelQueue: true,\n dispatcher: options.dispatcher,\n processResponse (response) {\n // 1. If response is a network error or its status is not 101,\n // fail the WebSocket connection.\n if (response.type === 'error' || response.status !== 101) {\n failWebsocketConnection(ws, 'Received network error or non-101 status code.')\n return\n }\n\n // 2. If protocols is not the empty list and extracting header\n // list values given `Sec-WebSocket-Protocol` and response’s\n // header list results in null, failure, or the empty byte\n // sequence, then fail the WebSocket connection.\n if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) {\n failWebsocketConnection(ws, 'Server did not respond with sent protocols.')\n return\n }\n\n // 3. Follow the requirements stated step 2 to step 6, inclusive,\n // of the last set of steps in section 4.1 of The WebSocket\n // Protocol to validate response. This either results in fail\n // the WebSocket connection or the WebSocket connection is\n // established.\n\n // 2. If the response lacks an |Upgrade| header field or the |Upgrade|\n // header field contains a value that is not an ASCII case-\n // insensitive match for the value \"websocket\", the client MUST\n // _Fail the WebSocket Connection_.\n if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') {\n failWebsocketConnection(ws, 'Server did not set Upgrade header to \"websocket\".')\n return\n }\n\n // 3. If the response lacks a |Connection| header field or the\n // |Connection| header field doesn't contain a token that is an\n // ASCII case-insensitive match for the value \"Upgrade\", the client\n // MUST _Fail the WebSocket Connection_.\n if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') {\n failWebsocketConnection(ws, 'Server did not set Connection header to \"upgrade\".')\n return\n }\n\n // 4. If the response lacks a |Sec-WebSocket-Accept| header field or\n // the |Sec-WebSocket-Accept| contains a value other than the\n // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket-\n // Key| (as a string, not base64-decoded) with the string \"258EAFA5-\n // E914-47DA-95CA-C5AB0DC85B11\" but ignoring any leading and\n // trailing whitespace, the client MUST _Fail the WebSocket\n // Connection_.\n const secWSAccept = response.headersList.get('Sec-WebSocket-Accept')\n const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64')\n if (secWSAccept !== digest) {\n failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.')\n return\n }\n\n // 5. If the response includes a |Sec-WebSocket-Extensions| header\n // field and this header field indicates the use of an extension\n // that was not present in the client's handshake (the server has\n // indicated an extension not requested by the client), the client\n // MUST _Fail the WebSocket Connection_. (The parsing of this\n // header field to determine which extensions are requested is\n // discussed in Section 9.1.)\n const secExtension = response.headersList.get('Sec-WebSocket-Extensions')\n let extensions\n\n if (secExtension !== null) {\n extensions = parseExtensions(secExtension)\n\n if (!extensions.has('permessage-deflate')) {\n failWebsocketConnection(ws, 'Sec-WebSocket-Extensions header does not match.')\n return\n }\n }\n\n // 6. If the response includes a |Sec-WebSocket-Protocol| header field\n // and this header field indicates the use of a subprotocol that was\n // not present in the client's handshake (the server has indicated a\n // subprotocol not requested by the client), the client MUST _Fail\n // the WebSocket Connection_.\n const secProtocol = response.headersList.get('Sec-WebSocket-Protocol')\n\n if (secProtocol !== null) {\n const requestProtocols = getDecodeSplit('sec-websocket-protocol', request.headersList)\n\n // The client can request that the server use a specific subprotocol by\n // including the |Sec-WebSocket-Protocol| field in its handshake. If it\n // is specified, the server needs to include the same field and one of\n // the selected subprotocol values in its response for the connection to\n // be established.\n if (!requestProtocols.includes(secProtocol)) {\n failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.')\n return\n }\n }\n\n response.socket.on('data', onSocketData)\n response.socket.on('close', onSocketClose)\n response.socket.on('error', onSocketError)\n\n if (channels.open.hasSubscribers) {\n channels.open.publish({\n address: response.socket.address(),\n protocol: secProtocol,\n extensions: secExtension\n })\n }\n\n onEstablish(response, extensions)\n }\n })\n\n return controller\n}\n\nfunction closeWebSocketConnection (ws, code, reason, reasonByteLength) {\n if (isClosing(ws) || isClosed(ws)) {\n // If this's ready state is CLOSING (2) or CLOSED (3)\n // Do nothing.\n } else if (!isEstablished(ws)) {\n // If the WebSocket connection is not yet established\n // Fail the WebSocket connection and set this's ready state\n // to CLOSING (2).\n failWebsocketConnection(ws, 'Connection was closed before it was established.')\n ws[kReadyState] = states.CLOSING\n } else if (ws[kSentClose] === sentCloseFrameState.NOT_SENT) {\n // If the WebSocket closing handshake has not yet been started\n // Start the WebSocket closing handshake and set this's ready\n // state to CLOSING (2).\n // - If neither code nor reason is present, the WebSocket Close\n // message must not have a body.\n // - If code is present, then the status code to use in the\n // WebSocket Close message must be the integer given by code.\n // - If reason is also present, then reasonBytes must be\n // provided in the Close message after the status code.\n\n ws[kSentClose] = sentCloseFrameState.PROCESSING\n\n const frame = new WebsocketFrameSend()\n\n // If neither code nor reason is present, the WebSocket Close\n // message must not have a body.\n\n // If code is present, then the status code to use in the\n // WebSocket Close message must be the integer given by code.\n if (code !== undefined && reason === undefined) {\n frame.frameData = Buffer.allocUnsafe(2)\n frame.frameData.writeUInt16BE(code, 0)\n } else if (code !== undefined && reason !== undefined) {\n // If reason is also present, then reasonBytes must be\n // provided in the Close message after the status code.\n frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength)\n frame.frameData.writeUInt16BE(code, 0)\n // the body MAY contain UTF-8-encoded data with value /reason/\n frame.frameData.write(reason, 2, 'utf-8')\n } else {\n frame.frameData = emptyBuffer\n }\n\n /** @type {import('stream').Duplex} */\n const socket = ws[kResponse].socket\n\n socket.write(frame.createFrame(opcodes.CLOSE))\n\n ws[kSentClose] = sentCloseFrameState.SENT\n\n // Upon either sending or receiving a Close control frame, it is said\n // that _The WebSocket Closing Handshake is Started_ and that the\n // WebSocket connection is in the CLOSING state.\n ws[kReadyState] = states.CLOSING\n } else {\n // Otherwise\n // Set this's ready state to CLOSING (2).\n ws[kReadyState] = states.CLOSING\n }\n}\n\n/**\n * @param {Buffer} chunk\n */\nfunction onSocketData (chunk) {\n if (!this.ws[kByteParser].write(chunk)) {\n this.pause()\n }\n}\n\n/**\n * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol\n * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4\n */\nfunction onSocketClose () {\n const { ws } = this\n const { [kResponse]: response } = ws\n\n response.socket.off('data', onSocketData)\n response.socket.off('close', onSocketClose)\n response.socket.off('error', onSocketError)\n\n // If the TCP connection was closed after the\n // WebSocket closing handshake was completed, the WebSocket connection\n // is said to have been closed _cleanly_.\n const wasClean = ws[kSentClose] === sentCloseFrameState.SENT && ws[kReceivedClose]\n\n let code = 1005\n let reason = ''\n\n const result = ws[kByteParser].closingInfo\n\n if (result && !result.error) {\n code = result.code ?? 1005\n reason = result.reason\n } else if (!ws[kReceivedClose]) {\n // If _The WebSocket\n // Connection is Closed_ and no Close control frame was received by the\n // endpoint (such as could occur if the underlying transport connection\n // is lost), _The WebSocket Connection Close Code_ is considered to be\n // 1006.\n code = 1006\n }\n\n // 1. Change the ready state to CLOSED (3).\n ws[kReadyState] = states.CLOSED\n\n // 2. If the user agent was required to fail the WebSocket\n // connection, or if the WebSocket connection was closed\n // after being flagged as full, fire an event named error\n // at the WebSocket object.\n // TODO\n\n // 3. Fire an event named close at the WebSocket object,\n // using CloseEvent, with the wasClean attribute\n // initialized to true if the connection closed cleanly\n // and false otherwise, the code attribute initialized to\n // the WebSocket connection close code, and the reason\n // attribute initialized to the result of applying UTF-8\n // decode without BOM to the WebSocket connection close\n // reason.\n // TODO: process.nextTick\n fireEvent('close', ws, (type, init) => new CloseEvent(type, init), {\n wasClean, code, reason\n })\n\n if (channels.close.hasSubscribers) {\n channels.close.publish({\n websocket: ws,\n code,\n reason\n })\n }\n}\n\nfunction onSocketError (error) {\n const { ws } = this\n\n ws[kReadyState] = states.CLOSING\n\n if (channels.socketError.hasSubscribers) {\n channels.socketError.publish(error)\n }\n\n this.destroy()\n}\n\nmodule.exports = {\n establishWebSocketConnection,\n closeWebSocketConnection\n}\n","'use strict'\n\nconst { createInflateRaw, Z_DEFAULT_WINDOWBITS } = require('node:zlib')\nconst { isValidClientWindowBits } = require('./util')\nconst { MessageSizeExceededError } = require('../../core/errors')\n\nconst tail = Buffer.from([0x00, 0x00, 0xff, 0xff])\nconst kBuffer = Symbol('kBuffer')\nconst kLength = Symbol('kLength')\n\nclass PerMessageDeflate {\n /** @type {import('node:zlib').InflateRaw} */\n #inflate\n\n #options = {}\n\n #maxPayloadSize = 0\n\n /**\n * @param {Map} extensions\n */\n constructor (extensions, options) {\n this.#options.serverNoContextTakeover = extensions.has('server_no_context_takeover')\n this.#options.serverMaxWindowBits = extensions.get('server_max_window_bits')\n\n this.#maxPayloadSize = options.maxPayloadSize\n }\n\n /**\n * Decompress a compressed payload.\n * @param {Buffer} chunk Compressed data\n * @param {boolean} fin Final fragment flag\n * @param {Function} callback Callback function\n */\n decompress (chunk, fin, callback) {\n // An endpoint uses the following algorithm to decompress a message.\n // 1. Append 4 octets of 0x00 0x00 0xff 0xff to the tail end of the\n // payload of the message.\n // 2. Decompress the resulting data using DEFLATE.\n if (!this.#inflate) {\n let windowBits = Z_DEFAULT_WINDOWBITS\n\n if (this.#options.serverMaxWindowBits) { // empty values default to Z_DEFAULT_WINDOWBITS\n if (!isValidClientWindowBits(this.#options.serverMaxWindowBits)) {\n callback(new Error('Invalid server_max_window_bits'))\n return\n }\n\n windowBits = Number.parseInt(this.#options.serverMaxWindowBits)\n }\n\n try {\n this.#inflate = createInflateRaw({ windowBits })\n } catch (err) {\n callback(err)\n return\n }\n this.#inflate[kBuffer] = []\n this.#inflate[kLength] = 0\n\n this.#inflate.on('data', (data) => {\n this.#inflate[kLength] += data.length\n\n if (this.#maxPayloadSize > 0 && this.#inflate[kLength] > this.#maxPayloadSize) {\n callback(new MessageSizeExceededError())\n this.#inflate.removeAllListeners()\n this.#inflate = null\n return\n }\n\n this.#inflate[kBuffer].push(data)\n })\n\n this.#inflate.on('error', (err) => {\n this.#inflate = null\n callback(err)\n })\n }\n\n this.#inflate.write(chunk)\n if (fin) {\n this.#inflate.write(tail)\n }\n\n this.#inflate.flush(() => {\n if (!this.#inflate) {\n return\n }\n\n const full = Buffer.concat(this.#inflate[kBuffer], this.#inflate[kLength])\n\n this.#inflate[kBuffer].length = 0\n this.#inflate[kLength] = 0\n\n callback(null, full)\n })\n }\n}\n\nmodule.exports = { PerMessageDeflate }\n","'use strict'\n\nconst { Writable } = require('node:stream')\nconst assert = require('node:assert')\nconst { parserStates, opcodes, states, emptyBuffer, sentCloseFrameState } = require('./constants')\nconst { kReadyState, kSentClose, kResponse, kReceivedClose } = require('./symbols')\nconst { channels } = require('../../core/diagnostics')\nconst {\n isValidStatusCode,\n isValidOpcode,\n failWebsocketConnection,\n websocketMessageReceived,\n utf8Decode,\n isControlFrame,\n isTextBinaryFrame,\n isContinuationFrame\n} = require('./util')\nconst { WebsocketFrameSend } = require('./frame')\nconst { closeWebSocketConnection } = require('./connection')\nconst { PerMessageDeflate } = require('./permessage-deflate')\nconst { MessageSizeExceededError } = require('../../core/errors')\n\n// This code was influenced by ws released under the MIT license.\n// Copyright (c) 2011 Einar Otto Stangvik \n// Copyright (c) 2013 Arnout Kazemier and contributors\n// Copyright (c) 2016 Luigi Pinca and contributors\n\nclass ByteParser extends Writable {\n #buffers = []\n #fragmentsBytes = 0\n #byteOffset = 0\n #loop = false\n\n #state = parserStates.INFO\n\n #info = {}\n #fragments = []\n\n /** @type {Map} */\n #extensions\n\n /** @type {number} */\n #maxPayloadSize\n\n /**\n * @param {import('./websocket').WebSocket} ws\n * @param {Map|null} extensions\n * @param {{ maxPayloadSize?: number }} [options]\n */\n constructor (ws, extensions, options = {}) {\n super()\n\n this.ws = ws\n this.#extensions = extensions == null ? new Map() : extensions\n this.#maxPayloadSize = options.maxPayloadSize ?? 0\n\n if (this.#extensions.has('permessage-deflate')) {\n this.#extensions.set('permessage-deflate', new PerMessageDeflate(extensions, options))\n }\n }\n\n /**\n * @param {Buffer} chunk\n * @param {() => void} callback\n */\n _write (chunk, _, callback) {\n this.#buffers.push(chunk)\n this.#byteOffset += chunk.length\n this.#loop = true\n\n this.run(callback)\n }\n\n #validatePayloadLength () {\n if (\n this.#maxPayloadSize > 0 &&\n !isControlFrame(this.#info.opcode) &&\n this.#info.payloadLength > this.#maxPayloadSize\n ) {\n failWebsocketConnection(this.ws, 'Payload size exceeds maximum allowed size')\n return false\n }\n\n return true\n }\n\n /**\n * Runs whenever a new chunk is received.\n * Callback is called whenever there are no more chunks buffering,\n * or not enough bytes are buffered to parse.\n */\n run (callback) {\n while (this.#loop) {\n if (this.#state === parserStates.INFO) {\n // If there aren't enough bytes to parse the payload length, etc.\n if (this.#byteOffset < 2) {\n return callback()\n }\n\n const buffer = this.consume(2)\n const fin = (buffer[0] & 0x80) !== 0\n const opcode = buffer[0] & 0x0F\n const masked = (buffer[1] & 0x80) === 0x80\n\n const fragmented = !fin && opcode !== opcodes.CONTINUATION\n const payloadLength = buffer[1] & 0x7F\n\n const rsv1 = buffer[0] & 0x40\n const rsv2 = buffer[0] & 0x20\n const rsv3 = buffer[0] & 0x10\n\n if (!isValidOpcode(opcode)) {\n failWebsocketConnection(this.ws, 'Invalid opcode received')\n return callback()\n }\n\n if (masked) {\n failWebsocketConnection(this.ws, 'Frame cannot be masked')\n return callback()\n }\n\n // MUST be 0 unless an extension is negotiated that defines meanings\n // for non-zero values. If a nonzero value is received and none of\n // the negotiated extensions defines the meaning of such a nonzero\n // value, the receiving endpoint MUST _Fail the WebSocket\n // Connection_.\n // This document allocates the RSV1 bit of the WebSocket header for\n // PMCEs and calls the bit the \"Per-Message Compressed\" bit. On a\n // WebSocket connection where a PMCE is in use, this bit indicates\n // whether a message is compressed or not.\n if (rsv1 !== 0 && !this.#extensions.has('permessage-deflate')) {\n failWebsocketConnection(this.ws, 'Expected RSV1 to be clear.')\n return\n }\n\n if (rsv2 !== 0 || rsv3 !== 0) {\n failWebsocketConnection(this.ws, 'RSV1, RSV2, RSV3 must be clear')\n return\n }\n\n if (fragmented && !isTextBinaryFrame(opcode)) {\n // Only text and binary frames can be fragmented\n failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.')\n return\n }\n\n // If we are already parsing a text/binary frame and do not receive either\n // a continuation frame or close frame, fail the connection.\n if (isTextBinaryFrame(opcode) && this.#fragments.length > 0) {\n failWebsocketConnection(this.ws, 'Expected continuation frame')\n return\n }\n\n if (this.#info.fragmented && fragmented) {\n // A fragmented frame can't be fragmented itself\n failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.')\n return\n }\n\n // \"All control frames MUST have a payload length of 125 bytes or less\n // and MUST NOT be fragmented.\"\n if ((payloadLength > 125 || fragmented) && isControlFrame(opcode)) {\n failWebsocketConnection(this.ws, 'Control frame either too large or fragmented')\n return\n }\n\n if (isContinuationFrame(opcode) && this.#fragments.length === 0 && !this.#info.compressed) {\n failWebsocketConnection(this.ws, 'Unexpected continuation frame')\n return\n }\n\n if (payloadLength <= 125) {\n this.#info.payloadLength = payloadLength\n this.#state = parserStates.READ_DATA\n\n if (!this.#validatePayloadLength()) {\n return\n }\n } else if (payloadLength === 126) {\n this.#state = parserStates.PAYLOADLENGTH_16\n } else if (payloadLength === 127) {\n this.#state = parserStates.PAYLOADLENGTH_64\n }\n\n if (isTextBinaryFrame(opcode)) {\n this.#info.binaryType = opcode\n this.#info.compressed = rsv1 !== 0\n }\n\n this.#info.opcode = opcode\n this.#info.masked = masked\n this.#info.fin = fin\n this.#info.fragmented = fragmented\n } else if (this.#state === parserStates.PAYLOADLENGTH_16) {\n if (this.#byteOffset < 2) {\n return callback()\n }\n\n const buffer = this.consume(2)\n\n this.#info.payloadLength = buffer.readUInt16BE(0)\n this.#state = parserStates.READ_DATA\n\n if (!this.#validatePayloadLength()) {\n return\n }\n } else if (this.#state === parserStates.PAYLOADLENGTH_64) {\n if (this.#byteOffset < 8) {\n return callback()\n }\n\n const buffer = this.consume(8)\n const upper = buffer.readUInt32BE(0)\n const lower = buffer.readUInt32BE(4)\n\n // 2^31 is the maximum bytes an arraybuffer can contain\n // on 32-bit systems. Although, on 64-bit systems, this is\n // 2^53-1 bytes.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length\n // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275\n // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e\n if (upper !== 0 || lower > 2 ** 31 - 1) {\n failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.')\n return\n }\n\n this.#info.payloadLength = lower\n this.#state = parserStates.READ_DATA\n\n if (!this.#validatePayloadLength()) {\n return\n }\n } else if (this.#state === parserStates.READ_DATA) {\n if (this.#byteOffset < this.#info.payloadLength) {\n return callback()\n }\n\n const body = this.consume(this.#info.payloadLength)\n\n if (isControlFrame(this.#info.opcode)) {\n this.#loop = this.parseControlFrame(body)\n this.#state = parserStates.INFO\n } else {\n if (!this.#info.compressed) {\n this.writeFragments(body)\n\n if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) {\n failWebsocketConnection(this.ws, new MessageSizeExceededError().message)\n return\n }\n\n // If the frame is not fragmented, a message has been received.\n // If the frame is fragmented, it will terminate with a fin bit set\n // and an opcode of 0 (continuation), therefore we handle that when\n // parsing continuation frames, not here.\n if (!this.#info.fragmented && this.#info.fin) {\n websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments())\n }\n\n this.#state = parserStates.INFO\n } else {\n this.#extensions.get('permessage-deflate').decompress(\n body,\n this.#info.fin,\n (error, data) => {\n if (error) {\n failWebsocketConnection(this.ws, error.message)\n return\n }\n\n this.writeFragments(data)\n\n if (this.#maxPayloadSize > 0 && this.#fragmentsBytes > this.#maxPayloadSize) {\n failWebsocketConnection(this.ws, new MessageSizeExceededError().message)\n return\n }\n\n if (!this.#info.fin) {\n this.#state = parserStates.INFO\n this.#loop = true\n this.run(callback)\n return\n }\n\n websocketMessageReceived(this.ws, this.#info.binaryType, this.consumeFragments())\n\n this.#loop = true\n this.#state = parserStates.INFO\n this.run(callback)\n }\n )\n\n this.#loop = false\n break\n }\n }\n }\n }\n }\n\n /**\n * Take n bytes from the buffered Buffers\n * @param {number} n\n * @returns {Buffer}\n */\n consume (n) {\n if (n > this.#byteOffset) {\n throw new Error('Called consume() before buffers satiated.')\n } else if (n === 0) {\n return emptyBuffer\n }\n\n if (this.#buffers[0].length === n) {\n this.#byteOffset -= this.#buffers[0].length\n return this.#buffers.shift()\n }\n\n const buffer = Buffer.allocUnsafe(n)\n let offset = 0\n\n while (offset !== n) {\n const next = this.#buffers[0]\n const { length } = next\n\n if (length + offset === n) {\n buffer.set(this.#buffers.shift(), offset)\n break\n } else if (length + offset > n) {\n buffer.set(next.subarray(0, n - offset), offset)\n this.#buffers[0] = next.subarray(n - offset)\n break\n } else {\n buffer.set(this.#buffers.shift(), offset)\n offset += next.length\n }\n }\n\n this.#byteOffset -= n\n\n return buffer\n }\n\n writeFragments (fragment) {\n this.#fragmentsBytes += fragment.length\n this.#fragments.push(fragment)\n }\n\n consumeFragments () {\n const fragments = this.#fragments\n\n if (fragments.length === 1) {\n this.#fragmentsBytes = 0\n return fragments.shift()\n }\n\n const output = Buffer.concat(fragments, this.#fragmentsBytes)\n this.#fragments = []\n this.#fragmentsBytes = 0\n\n return output\n }\n\n parseCloseBody (data) {\n assert(data.length !== 1)\n\n // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5\n /** @type {number|undefined} */\n let code\n\n if (data.length >= 2) {\n // _The WebSocket Connection Close Code_ is\n // defined as the status code (Section 7.4) contained in the first Close\n // control frame received by the application\n code = data.readUInt16BE(0)\n }\n\n if (code !== undefined && !isValidStatusCode(code)) {\n return { code: 1002, reason: 'Invalid status code', error: true }\n }\n\n // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6\n /** @type {Buffer} */\n let reason = data.subarray(2)\n\n // Remove BOM\n if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) {\n reason = reason.subarray(3)\n }\n\n try {\n reason = utf8Decode(reason)\n } catch {\n return { code: 1007, reason: 'Invalid UTF-8', error: true }\n }\n\n return { code, reason, error: false }\n }\n\n /**\n * Parses control frames.\n * @param {Buffer} body\n */\n parseControlFrame (body) {\n const { opcode, payloadLength } = this.#info\n\n if (opcode === opcodes.CLOSE) {\n if (payloadLength === 1) {\n failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.')\n return false\n }\n\n this.#info.closeInfo = this.parseCloseBody(body)\n\n if (this.#info.closeInfo.error) {\n const { code, reason } = this.#info.closeInfo\n\n closeWebSocketConnection(this.ws, code, reason, reason.length)\n failWebsocketConnection(this.ws, reason)\n return false\n }\n\n if (this.ws[kSentClose] !== sentCloseFrameState.SENT) {\n // If an endpoint receives a Close frame and did not previously send a\n // Close frame, the endpoint MUST send a Close frame in response. (When\n // sending a Close frame in response, the endpoint typically echos the\n // status code it received.)\n let body = emptyBuffer\n if (this.#info.closeInfo.code) {\n body = Buffer.allocUnsafe(2)\n body.writeUInt16BE(this.#info.closeInfo.code, 0)\n }\n const closeFrame = new WebsocketFrameSend(body)\n\n this.ws[kResponse].socket.write(\n closeFrame.createFrame(opcodes.CLOSE),\n (err) => {\n if (!err) {\n this.ws[kSentClose] = sentCloseFrameState.SENT\n }\n }\n )\n }\n\n // Upon either sending or receiving a Close control frame, it is said\n // that _The WebSocket Closing Handshake is Started_ and that the\n // WebSocket connection is in the CLOSING state.\n this.ws[kReadyState] = states.CLOSING\n this.ws[kReceivedClose] = true\n\n return false\n } else if (opcode === opcodes.PING) {\n // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in\n // response, unless it already received a Close frame.\n // A Pong frame sent in response to a Ping frame must have identical\n // \"Application data\"\n\n if (!this.ws[kReceivedClose]) {\n const frame = new WebsocketFrameSend(body)\n\n this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG))\n\n if (channels.ping.hasSubscribers) {\n channels.ping.publish({\n payload: body\n })\n }\n }\n } else if (opcode === opcodes.PONG) {\n // A Pong frame MAY be sent unsolicited. This serves as a\n // unidirectional heartbeat. A response to an unsolicited Pong frame is\n // not expected.\n\n if (channels.pong.hasSubscribers) {\n channels.pong.publish({\n payload: body\n })\n }\n }\n\n return true\n }\n\n get closingInfo () {\n return this.#info.closeInfo\n }\n}\n\nmodule.exports = {\n ByteParser\n}\n","'use strict'\n\nconst { WebsocketFrameSend } = require('./frame')\nconst { opcodes, sendHints } = require('./constants')\nconst FixedQueue = require('../../dispatcher/fixed-queue')\n\n/** @type {typeof Uint8Array} */\nconst FastBuffer = Buffer[Symbol.species]\n\n/**\n * @typedef {object} SendQueueNode\n * @property {Promise | null} promise\n * @property {((...args: any[]) => any)} callback\n * @property {Buffer | null} frame\n */\n\nclass SendQueue {\n /**\n * @type {FixedQueue}\n */\n #queue = new FixedQueue()\n\n /**\n * @type {boolean}\n */\n #running = false\n\n /** @type {import('node:net').Socket} */\n #socket\n\n constructor (socket) {\n this.#socket = socket\n }\n\n add (item, cb, hint) {\n if (hint !== sendHints.blob) {\n const frame = createFrame(item, hint)\n if (!this.#running) {\n // fast-path\n this.#socket.write(frame, cb)\n } else {\n /** @type {SendQueueNode} */\n const node = {\n promise: null,\n callback: cb,\n frame\n }\n this.#queue.push(node)\n }\n return\n }\n\n /** @type {SendQueueNode} */\n const node = {\n promise: item.arrayBuffer().then((ab) => {\n node.promise = null\n node.frame = createFrame(ab, hint)\n }),\n callback: cb,\n frame: null\n }\n\n this.#queue.push(node)\n\n if (!this.#running) {\n this.#run()\n }\n }\n\n async #run () {\n this.#running = true\n const queue = this.#queue\n while (!queue.isEmpty()) {\n const node = queue.shift()\n // wait pending promise\n if (node.promise !== null) {\n await node.promise\n }\n // write\n this.#socket.write(node.frame, node.callback)\n // cleanup\n node.callback = node.frame = null\n }\n this.#running = false\n }\n}\n\nfunction createFrame (data, hint) {\n return new WebsocketFrameSend(toBuffer(data, hint)).createFrame(hint === sendHints.string ? opcodes.TEXT : opcodes.BINARY)\n}\n\nfunction toBuffer (data, hint) {\n switch (hint) {\n case sendHints.string:\n return Buffer.from(data)\n case sendHints.arrayBuffer:\n case sendHints.blob:\n return new FastBuffer(data)\n case sendHints.typedArray:\n return new FastBuffer(data.buffer, data.byteOffset, data.byteLength)\n }\n}\n\nmodule.exports = { SendQueue }\n","'use strict'\n\nconst { webidl } = require('../fetch/webidl')\nconst { URLSerializer } = require('../fetch/data-url')\nconst { environmentSettingsObject } = require('../fetch/util')\nconst { staticPropertyDescriptors, states, sentCloseFrameState, sendHints } = require('./constants')\nconst {\n kWebSocketURL,\n kReadyState,\n kController,\n kBinaryType,\n kResponse,\n kSentClose,\n kByteParser\n} = require('./symbols')\nconst {\n isConnecting,\n isEstablished,\n isClosing,\n isValidSubprotocol,\n fireEvent\n} = require('./util')\nconst { establishWebSocketConnection, closeWebSocketConnection } = require('./connection')\nconst { ByteParser } = require('./receiver')\nconst { kEnumerableProperty, isBlobLike } = require('../../core/util')\nconst { getGlobalDispatcher } = require('../../global')\nconst { types } = require('node:util')\nconst { ErrorEvent, CloseEvent } = require('./events')\nconst { SendQueue } = require('./sender')\n\n// https://websockets.spec.whatwg.org/#interface-definition\nclass WebSocket extends EventTarget {\n #events = {\n open: null,\n error: null,\n close: null,\n message: null\n }\n\n #bufferedAmount = 0\n #protocol = ''\n #extensions = ''\n\n /** @type {SendQueue} */\n #sendQueue\n\n /**\n * @param {string} url\n * @param {string|string[]} protocols\n */\n constructor (url, protocols = []) {\n super()\n\n webidl.util.markAsUncloneable(this)\n\n const prefix = 'WebSocket constructor'\n webidl.argumentLengthCheck(arguments, 1, prefix)\n\n const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols, prefix, 'options')\n\n url = webidl.converters.USVString(url, prefix, 'url')\n protocols = options.protocols\n\n // 1. Let baseURL be this's relevant settings object's API base URL.\n const baseURL = environmentSettingsObject.settingsObject.baseUrl\n\n // 1. Let urlRecord be the result of applying the URL parser to url with baseURL.\n let urlRecord\n\n try {\n urlRecord = new URL(url, baseURL)\n } catch (e) {\n // 3. If urlRecord is failure, then throw a \"SyntaxError\" DOMException.\n throw new DOMException(e, 'SyntaxError')\n }\n\n // 4. If urlRecord’s scheme is \"http\", then set urlRecord’s scheme to \"ws\".\n if (urlRecord.protocol === 'http:') {\n urlRecord.protocol = 'ws:'\n } else if (urlRecord.protocol === 'https:') {\n // 5. Otherwise, if urlRecord’s scheme is \"https\", set urlRecord’s scheme to \"wss\".\n urlRecord.protocol = 'wss:'\n }\n\n // 6. If urlRecord’s scheme is not \"ws\" or \"wss\", then throw a \"SyntaxError\" DOMException.\n if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') {\n throw new DOMException(\n `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`,\n 'SyntaxError'\n )\n }\n\n // 7. If urlRecord’s fragment is non-null, then throw a \"SyntaxError\"\n // DOMException.\n if (urlRecord.hash || urlRecord.href.endsWith('#')) {\n throw new DOMException('Got fragment', 'SyntaxError')\n }\n\n // 8. If protocols is a string, set protocols to a sequence consisting\n // of just that string.\n if (typeof protocols === 'string') {\n protocols = [protocols]\n }\n\n // 9. If any of the values in protocols occur more than once or otherwise\n // fail to match the requirements for elements that comprise the value\n // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket\n // protocol, then throw a \"SyntaxError\" DOMException.\n if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) {\n throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')\n }\n\n if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) {\n throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')\n }\n\n // 10. Set this's url to urlRecord.\n this[kWebSocketURL] = new URL(urlRecord.href)\n\n // 11. Let client be this's relevant settings object.\n const client = environmentSettingsObject.settingsObject\n\n // 12. Run this step in parallel:\n\n // 1. Establish a WebSocket connection given urlRecord, protocols,\n // and client.\n this[kController] = establishWebSocketConnection(\n urlRecord,\n protocols,\n client,\n this,\n (response, extensions) => this.#onConnectionEstablished(response, extensions),\n options\n )\n\n // Each WebSocket object has an associated ready state, which is a\n // number representing the state of the connection. Initially it must\n // be CONNECTING (0).\n this[kReadyState] = WebSocket.CONNECTING\n\n this[kSentClose] = sentCloseFrameState.NOT_SENT\n\n // The extensions attribute must initially return the empty string.\n\n // The protocol attribute must initially return the empty string.\n\n // Each WebSocket object has an associated binary type, which is a\n // BinaryType. Initially it must be \"blob\".\n this[kBinaryType] = 'blob'\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#dom-websocket-close\n * @param {number|undefined} code\n * @param {string|undefined} reason\n */\n close (code = undefined, reason = undefined) {\n webidl.brandCheck(this, WebSocket)\n\n const prefix = 'WebSocket.close'\n\n if (code !== undefined) {\n code = webidl.converters['unsigned short'](code, prefix, 'code', { clamp: true })\n }\n\n if (reason !== undefined) {\n reason = webidl.converters.USVString(reason, prefix, 'reason')\n }\n\n // 1. If code is present, but is neither an integer equal to 1000 nor an\n // integer in the range 3000 to 4999, inclusive, throw an\n // \"InvalidAccessError\" DOMException.\n if (code !== undefined) {\n if (code !== 1000 && (code < 3000 || code > 4999)) {\n throw new DOMException('invalid code', 'InvalidAccessError')\n }\n }\n\n let reasonByteLength = 0\n\n // 2. If reason is present, then run these substeps:\n if (reason !== undefined) {\n // 1. Let reasonBytes be the result of encoding reason.\n // 2. If reasonBytes is longer than 123 bytes, then throw a\n // \"SyntaxError\" DOMException.\n reasonByteLength = Buffer.byteLength(reason)\n\n if (reasonByteLength > 123) {\n throw new DOMException(\n `Reason must be less than 123 bytes; received ${reasonByteLength}`,\n 'SyntaxError'\n )\n }\n }\n\n // 3. Run the first matching steps from the following list:\n closeWebSocketConnection(this, code, reason, reasonByteLength)\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#dom-websocket-send\n * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data\n */\n send (data) {\n webidl.brandCheck(this, WebSocket)\n\n const prefix = 'WebSocket.send'\n webidl.argumentLengthCheck(arguments, 1, prefix)\n\n data = webidl.converters.WebSocketSendData(data, prefix, 'data')\n\n // 1. If this's ready state is CONNECTING, then throw an\n // \"InvalidStateError\" DOMException.\n if (isConnecting(this)) {\n throw new DOMException('Sent before connected.', 'InvalidStateError')\n }\n\n // 2. Run the appropriate set of steps from the following list:\n // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1\n // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2\n\n if (!isEstablished(this) || isClosing(this)) {\n return\n }\n\n // If data is a string\n if (typeof data === 'string') {\n // If the WebSocket connection is established and the WebSocket\n // closing handshake has not yet started, then the user agent\n // must send a WebSocket Message comprised of the data argument\n // using a text frame opcode; if the data cannot be sent, e.g.\n // because it would need to be buffered but the buffer is full,\n // the user agent must flag the WebSocket as full and then close\n // the WebSocket connection. Any invocation of this method with a\n // string argument that does not throw an exception must increase\n // the bufferedAmount attribute by the number of bytes needed to\n // express the argument as UTF-8.\n\n const length = Buffer.byteLength(data)\n\n this.#bufferedAmount += length\n this.#sendQueue.add(data, () => {\n this.#bufferedAmount -= length\n }, sendHints.string)\n } else if (types.isArrayBuffer(data)) {\n // If the WebSocket connection is established, and the WebSocket\n // closing handshake has not yet started, then the user agent must\n // send a WebSocket Message comprised of data using a binary frame\n // opcode; if the data cannot be sent, e.g. because it would need\n // to be buffered but the buffer is full, the user agent must flag\n // the WebSocket as full and then close the WebSocket connection.\n // The data to be sent is the data stored in the buffer described\n // by the ArrayBuffer object. Any invocation of this method with an\n // ArrayBuffer argument that does not throw an exception must\n // increase the bufferedAmount attribute by the length of the\n // ArrayBuffer in bytes.\n\n this.#bufferedAmount += data.byteLength\n this.#sendQueue.add(data, () => {\n this.#bufferedAmount -= data.byteLength\n }, sendHints.arrayBuffer)\n } else if (ArrayBuffer.isView(data)) {\n // If the WebSocket connection is established, and the WebSocket\n // closing handshake has not yet started, then the user agent must\n // send a WebSocket Message comprised of data using a binary frame\n // opcode; if the data cannot be sent, e.g. because it would need to\n // be buffered but the buffer is full, the user agent must flag the\n // WebSocket as full and then close the WebSocket connection. The\n // data to be sent is the data stored in the section of the buffer\n // described by the ArrayBuffer object that data references. Any\n // invocation of this method with this kind of argument that does\n // not throw an exception must increase the bufferedAmount attribute\n // by the length of data’s buffer in bytes.\n\n this.#bufferedAmount += data.byteLength\n this.#sendQueue.add(data, () => {\n this.#bufferedAmount -= data.byteLength\n }, sendHints.typedArray)\n } else if (isBlobLike(data)) {\n // If the WebSocket connection is established, and the WebSocket\n // closing handshake has not yet started, then the user agent must\n // send a WebSocket Message comprised of data using a binary frame\n // opcode; if the data cannot be sent, e.g. because it would need to\n // be buffered but the buffer is full, the user agent must flag the\n // WebSocket as full and then close the WebSocket connection. The data\n // to be sent is the raw data represented by the Blob object. Any\n // invocation of this method with a Blob argument that does not throw\n // an exception must increase the bufferedAmount attribute by the size\n // of the Blob object’s raw data, in bytes.\n\n this.#bufferedAmount += data.size\n this.#sendQueue.add(data, () => {\n this.#bufferedAmount -= data.size\n }, sendHints.blob)\n }\n }\n\n get readyState () {\n webidl.brandCheck(this, WebSocket)\n\n // The readyState getter steps are to return this's ready state.\n return this[kReadyState]\n }\n\n get bufferedAmount () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#bufferedAmount\n }\n\n get url () {\n webidl.brandCheck(this, WebSocket)\n\n // The url getter steps are to return this's url, serialized.\n return URLSerializer(this[kWebSocketURL])\n }\n\n get extensions () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#extensions\n }\n\n get protocol () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#protocol\n }\n\n get onopen () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#events.open\n }\n\n set onopen (fn) {\n webidl.brandCheck(this, WebSocket)\n\n if (this.#events.open) {\n this.removeEventListener('open', this.#events.open)\n }\n\n if (typeof fn === 'function') {\n this.#events.open = fn\n this.addEventListener('open', fn)\n } else {\n this.#events.open = null\n }\n }\n\n get onerror () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#events.error\n }\n\n set onerror (fn) {\n webidl.brandCheck(this, WebSocket)\n\n if (this.#events.error) {\n this.removeEventListener('error', this.#events.error)\n }\n\n if (typeof fn === 'function') {\n this.#events.error = fn\n this.addEventListener('error', fn)\n } else {\n this.#events.error = null\n }\n }\n\n get onclose () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#events.close\n }\n\n set onclose (fn) {\n webidl.brandCheck(this, WebSocket)\n\n if (this.#events.close) {\n this.removeEventListener('close', this.#events.close)\n }\n\n if (typeof fn === 'function') {\n this.#events.close = fn\n this.addEventListener('close', fn)\n } else {\n this.#events.close = null\n }\n }\n\n get onmessage () {\n webidl.brandCheck(this, WebSocket)\n\n return this.#events.message\n }\n\n set onmessage (fn) {\n webidl.brandCheck(this, WebSocket)\n\n if (this.#events.message) {\n this.removeEventListener('message', this.#events.message)\n }\n\n if (typeof fn === 'function') {\n this.#events.message = fn\n this.addEventListener('message', fn)\n } else {\n this.#events.message = null\n }\n }\n\n get binaryType () {\n webidl.brandCheck(this, WebSocket)\n\n return this[kBinaryType]\n }\n\n set binaryType (type) {\n webidl.brandCheck(this, WebSocket)\n\n if (type !== 'blob' && type !== 'arraybuffer') {\n this[kBinaryType] = 'blob'\n } else {\n this[kBinaryType] = type\n }\n }\n\n /**\n * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol\n */\n #onConnectionEstablished (response, parsedExtensions) {\n // processResponse is called when the \"response's header list has been received and initialized.\"\n // once this happens, the connection is open\n this[kResponse] = response\n\n const maxPayloadSize = this[kController]?.dispatcher?.webSocketOptions?.maxPayloadSize\n\n const parser = new ByteParser(this, parsedExtensions, {\n maxPayloadSize\n })\n parser.on('drain', onParserDrain)\n parser.on('error', onParserError.bind(this))\n\n response.socket.ws = this\n this[kByteParser] = parser\n\n this.#sendQueue = new SendQueue(response.socket)\n\n // 1. Change the ready state to OPEN (1).\n this[kReadyState] = states.OPEN\n\n // 2. Change the extensions attribute’s value to the extensions in use, if\n // it is not the null value.\n // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1\n const extensions = response.headersList.get('sec-websocket-extensions')\n\n if (extensions !== null) {\n this.#extensions = extensions\n }\n\n // 3. Change the protocol attribute’s value to the subprotocol in use, if\n // it is not the null value.\n // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9\n const protocol = response.headersList.get('sec-websocket-protocol')\n\n if (protocol !== null) {\n this.#protocol = protocol\n }\n\n // 4. Fire an event named open at the WebSocket object.\n fireEvent('open', this)\n }\n}\n\n// https://websockets.spec.whatwg.org/#dom-websocket-connecting\nWebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING\n// https://websockets.spec.whatwg.org/#dom-websocket-open\nWebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN\n// https://websockets.spec.whatwg.org/#dom-websocket-closing\nWebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING\n// https://websockets.spec.whatwg.org/#dom-websocket-closed\nWebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED\n\nObject.defineProperties(WebSocket.prototype, {\n CONNECTING: staticPropertyDescriptors,\n OPEN: staticPropertyDescriptors,\n CLOSING: staticPropertyDescriptors,\n CLOSED: staticPropertyDescriptors,\n url: kEnumerableProperty,\n readyState: kEnumerableProperty,\n bufferedAmount: kEnumerableProperty,\n onopen: kEnumerableProperty,\n onerror: kEnumerableProperty,\n onclose: kEnumerableProperty,\n close: kEnumerableProperty,\n onmessage: kEnumerableProperty,\n binaryType: kEnumerableProperty,\n send: kEnumerableProperty,\n extensions: kEnumerableProperty,\n protocol: kEnumerableProperty,\n [Symbol.toStringTag]: {\n value: 'WebSocket',\n writable: false,\n enumerable: false,\n configurable: true\n }\n})\n\nObject.defineProperties(WebSocket, {\n CONNECTING: staticPropertyDescriptors,\n OPEN: staticPropertyDescriptors,\n CLOSING: staticPropertyDescriptors,\n CLOSED: staticPropertyDescriptors\n})\n\nwebidl.converters['sequence'] = webidl.sequenceConverter(\n webidl.converters.DOMString\n)\n\nwebidl.converters['DOMString or sequence'] = function (V, prefix, argument) {\n if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) {\n return webidl.converters['sequence'](V)\n }\n\n return webidl.converters.DOMString(V, prefix, argument)\n}\n\n// This implements the proposal made in https://github.com/whatwg/websockets/issues/42\nwebidl.converters.WebSocketInit = webidl.dictionaryConverter([\n {\n key: 'protocols',\n converter: webidl.converters['DOMString or sequence'],\n defaultValue: () => new Array(0)\n },\n {\n key: 'dispatcher',\n converter: webidl.converters.any,\n defaultValue: () => getGlobalDispatcher()\n },\n {\n key: 'headers',\n converter: webidl.nullableConverter(webidl.converters.HeadersInit)\n }\n])\n\nwebidl.converters['DOMString or sequence or WebSocketInit'] = function (V) {\n if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) {\n return webidl.converters.WebSocketInit(V)\n }\n\n return { protocols: webidl.converters['DOMString or sequence'](V) }\n}\n\nwebidl.converters.WebSocketSendData = function (V) {\n if (webidl.util.Type(V) === 'Object') {\n if (isBlobLike(V)) {\n return webidl.converters.Blob(V, { strict: false })\n }\n\n if (ArrayBuffer.isView(V) || types.isArrayBuffer(V)) {\n return webidl.converters.BufferSource(V)\n }\n }\n\n return webidl.converters.USVString(V)\n}\n\nfunction onParserDrain () {\n this.ws[kResponse].socket.resume()\n}\n\nfunction onParserError (err) {\n let message\n let code\n\n if (err instanceof CloseEvent) {\n message = err.reason\n code = err.code\n } else {\n message = err.message\n }\n\n fireEvent('error', this, () => new ErrorEvent('error', { error: err, message }))\n\n closeWebSocketConnection(this, code)\n}\n\nmodule.exports = {\n WebSocket\n}\n","'use strict'\n\n/**\n * Checks if the given value is a valid LastEventId.\n * @param {string} value\n * @returns {boolean}\n */\nfunction isValidLastEventId (value) {\n // LastEventId should not contain U+0000 NULL\n return value.indexOf('\\u0000') === -1\n}\n\n/**\n * Checks if the given value is a base 10 digit.\n * @param {string} value\n * @returns {boolean}\n */\nfunction isASCIINumber (value) {\n if (value.length === 0) return false\n for (let i = 0; i < value.length; i++) {\n if (value.charCodeAt(i) < 0x30 || value.charCodeAt(i) > 0x39) return false\n }\n return true\n}\n\n// https://github.com/nodejs/undici/issues/2664\nfunction delay (ms) {\n return new Promise((resolve) => {\n setTimeout(resolve, ms).unref()\n })\n}\n\nmodule.exports = {\n isValidLastEventId,\n isASCIINumber,\n delay\n}\n","'use strict'\nconst { Transform } = require('node:stream')\nconst { isASCIINumber, isValidLastEventId } = require('./util')\n\n/**\n * @type {number[]} BOM\n */\nconst BOM = [0xEF, 0xBB, 0xBF]\n/**\n * @type {10} LF\n */\nconst LF = 0x0A\n/**\n * @type {13} CR\n */\nconst CR = 0x0D\n/**\n * @type {58} COLON\n */\nconst COLON = 0x3A\n/**\n * @type {32} SPACE\n */\nconst SPACE = 0x20\n\n/**\n * @typedef {object} EventSourceStreamEvent\n * @type {object}\n * @property {string} [event] The event type.\n * @property {string} [data] The data of the message.\n * @property {string} [id] A unique ID for the event.\n * @property {string} [retry] The reconnection time, in milliseconds.\n */\n\n/**\n * @typedef eventSourceSettings\n * @type {object}\n * @property {string} lastEventId The last event ID received from the server.\n * @property {string} origin The origin of the event source.\n * @property {number} reconnectionTime The reconnection time, in milliseconds.\n */\n\nclass EventSourceStream extends Transform {\n /**\n * @type {eventSourceSettings}\n */\n state = null\n\n /**\n * Leading byte-order-mark check.\n * @type {boolean}\n */\n checkBOM = true\n\n /**\n * @type {boolean}\n */\n crlfCheck = false\n\n /**\n * @type {boolean}\n */\n eventEndCheck = false\n\n /**\n * @type {Buffer}\n */\n buffer = null\n\n pos = 0\n\n event = {\n data: undefined,\n event: undefined,\n id: undefined,\n retry: undefined\n }\n\n /**\n * @param {object} options\n * @param {eventSourceSettings} options.eventSourceSettings\n * @param {Function} [options.push]\n */\n constructor (options = {}) {\n // Enable object mode as EventSourceStream emits objects of shape\n // EventSourceStreamEvent\n options.readableObjectMode = true\n\n super(options)\n\n this.state = options.eventSourceSettings || {}\n if (options.push) {\n this.push = options.push\n }\n }\n\n /**\n * @param {Buffer} chunk\n * @param {string} _encoding\n * @param {Function} callback\n * @returns {void}\n */\n _transform (chunk, _encoding, callback) {\n if (chunk.length === 0) {\n callback()\n return\n }\n\n // Cache the chunk in the buffer, as the data might not be complete while\n // processing it\n // TODO: Investigate if there is a more performant way to handle\n // incoming chunks\n // see: https://github.com/nodejs/undici/issues/2630\n if (this.buffer) {\n this.buffer = Buffer.concat([this.buffer, chunk])\n } else {\n this.buffer = chunk\n }\n\n // Strip leading byte-order-mark if we opened the stream and started\n // the processing of the incoming data\n if (this.checkBOM) {\n switch (this.buffer.length) {\n case 1:\n // Check if the first byte is the same as the first byte of the BOM\n if (this.buffer[0] === BOM[0]) {\n // If it is, we need to wait for more data\n callback()\n return\n }\n // Set the checkBOM flag to false as we don't need to check for the\n // BOM anymore\n this.checkBOM = false\n\n // The buffer only contains one byte so we need to wait for more data\n callback()\n return\n case 2:\n // Check if the first two bytes are the same as the first two bytes\n // of the BOM\n if (\n this.buffer[0] === BOM[0] &&\n this.buffer[1] === BOM[1]\n ) {\n // If it is, we need to wait for more data, because the third byte\n // is needed to determine if it is the BOM or not\n callback()\n return\n }\n\n // Set the checkBOM flag to false as we don't need to check for the\n // BOM anymore\n this.checkBOM = false\n break\n case 3:\n // Check if the first three bytes are the same as the first three\n // bytes of the BOM\n if (\n this.buffer[0] === BOM[0] &&\n this.buffer[1] === BOM[1] &&\n this.buffer[2] === BOM[2]\n ) {\n // If it is, we can drop the buffered data, as it is only the BOM\n this.buffer = Buffer.alloc(0)\n // Set the checkBOM flag to false as we don't need to check for the\n // BOM anymore\n this.checkBOM = false\n\n // Await more data\n callback()\n return\n }\n // If it is not the BOM, we can start processing the data\n this.checkBOM = false\n break\n default:\n // The buffer is longer than 3 bytes, so we can drop the BOM if it is\n // present\n if (\n this.buffer[0] === BOM[0] &&\n this.buffer[1] === BOM[1] &&\n this.buffer[2] === BOM[2]\n ) {\n // Remove the BOM from the buffer\n this.buffer = this.buffer.subarray(3)\n }\n\n // Set the checkBOM flag to false as we don't need to check for the\n this.checkBOM = false\n break\n }\n }\n\n while (this.pos < this.buffer.length) {\n // If the previous line ended with an end-of-line, we need to check\n // if the next character is also an end-of-line.\n if (this.eventEndCheck) {\n // If the the current character is an end-of-line, then the event\n // is finished and we can process it\n\n // If the previous line ended with a carriage return, we need to\n // check if the current character is a line feed and remove it\n // from the buffer.\n if (this.crlfCheck) {\n // If the current character is a line feed, we can remove it\n // from the buffer and reset the crlfCheck flag\n if (this.buffer[this.pos] === LF) {\n this.buffer = this.buffer.subarray(this.pos + 1)\n this.pos = 0\n this.crlfCheck = false\n\n // It is possible that the line feed is not the end of the\n // event. We need to check if the next character is an\n // end-of-line character to determine if the event is\n // finished. We simply continue the loop to check the next\n // character.\n\n // As we removed the line feed from the buffer and set the\n // crlfCheck flag to false, we basically don't make any\n // distinction between a line feed and a carriage return.\n continue\n }\n this.crlfCheck = false\n }\n\n if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {\n // If the current character is a carriage return, we need to\n // set the crlfCheck flag to true, as we need to check if the\n // next character is a line feed so we can remove it from the\n // buffer\n if (this.buffer[this.pos] === CR) {\n this.crlfCheck = true\n }\n\n this.buffer = this.buffer.subarray(this.pos + 1)\n this.pos = 0\n if (\n this.event.data !== undefined || this.event.event || this.event.id || this.event.retry) {\n this.processEvent(this.event)\n }\n this.clearEvent()\n continue\n }\n // If the current character is not an end-of-line, then the event\n // is not finished and we have to reset the eventEndCheck flag\n this.eventEndCheck = false\n continue\n }\n\n // If the current character is an end-of-line, we can process the\n // line\n if (this.buffer[this.pos] === LF || this.buffer[this.pos] === CR) {\n // If the current character is a carriage return, we need to\n // set the crlfCheck flag to true, as we need to check if the\n // next character is a line feed\n if (this.buffer[this.pos] === CR) {\n this.crlfCheck = true\n }\n\n // In any case, we can process the line as we reached an\n // end-of-line character\n this.parseLine(this.buffer.subarray(0, this.pos), this.event)\n\n // Remove the processed line from the buffer\n this.buffer = this.buffer.subarray(this.pos + 1)\n // Reset the position as we removed the processed line from the buffer\n this.pos = 0\n // A line was processed and this could be the end of the event. We need\n // to check if the next line is empty to determine if the event is\n // finished.\n this.eventEndCheck = true\n continue\n }\n\n this.pos++\n }\n\n callback()\n }\n\n /**\n * @param {Buffer} line\n * @param {EventStreamEvent} event\n */\n parseLine (line, event) {\n // If the line is empty (a blank line)\n // Dispatch the event, as defined below.\n // This will be handled in the _transform method\n if (line.length === 0) {\n return\n }\n\n // If the line starts with a U+003A COLON character (:)\n // Ignore the line.\n const colonPosition = line.indexOf(COLON)\n if (colonPosition === 0) {\n return\n }\n\n let field = ''\n let value = ''\n\n // If the line contains a U+003A COLON character (:)\n if (colonPosition !== -1) {\n // Collect the characters on the line before the first U+003A COLON\n // character (:), and let field be that string.\n // TODO: Investigate if there is a more performant way to extract the\n // field\n // see: https://github.com/nodejs/undici/issues/2630\n field = line.subarray(0, colonPosition).toString('utf8')\n\n // Collect the characters on the line after the first U+003A COLON\n // character (:), and let value be that string.\n // If value starts with a U+0020 SPACE character, remove it from value.\n let valueStart = colonPosition + 1\n if (line[valueStart] === SPACE) {\n ++valueStart\n }\n // TODO: Investigate if there is a more performant way to extract the\n // value\n // see: https://github.com/nodejs/undici/issues/2630\n value = line.subarray(valueStart).toString('utf8')\n\n // Otherwise, the string is not empty but does not contain a U+003A COLON\n // character (:)\n } else {\n // Process the field using the steps described below, using the whole\n // line as the field name, and the empty string as the field value.\n field = line.toString('utf8')\n value = ''\n }\n\n // Modify the event with the field name and value. The value is also\n // decoded as UTF-8\n switch (field) {\n case 'data':\n if (event[field] === undefined) {\n event[field] = value\n } else {\n event[field] += `\\n${value}`\n }\n break\n case 'retry':\n if (isASCIINumber(value)) {\n event[field] = value\n }\n break\n case 'id':\n if (isValidLastEventId(value)) {\n event[field] = value\n }\n break\n case 'event':\n if (value.length > 0) {\n event[field] = value\n }\n break\n }\n }\n\n /**\n * @param {EventSourceStreamEvent} event\n */\n processEvent (event) {\n if (event.retry && isASCIINumber(event.retry)) {\n this.state.reconnectionTime = parseInt(event.retry, 10)\n }\n\n if (event.id && isValidLastEventId(event.id)) {\n this.state.lastEventId = event.id\n }\n\n // only dispatch event, when data is provided\n if (event.data !== undefined) {\n this.push({\n type: event.event || 'message',\n options: {\n data: event.data,\n lastEventId: this.state.lastEventId,\n origin: this.state.origin\n }\n })\n }\n }\n\n clearEvent () {\n this.event = {\n data: undefined,\n event: undefined,\n id: undefined,\n retry: undefined\n }\n }\n}\n\nmodule.exports = {\n EventSourceStream\n}\n","'use strict'\n\nconst { pipeline } = require('node:stream')\nconst { fetching } = require('../fetch')\nconst { makeRequest } = require('../fetch/request')\nconst { webidl } = require('../fetch/webidl')\nconst { EventSourceStream } = require('./eventsource-stream')\nconst { parseMIMEType } = require('../fetch/data-url')\nconst { createFastMessageEvent } = require('../websocket/events')\nconst { isNetworkError } = require('../fetch/response')\nconst { delay } = require('./util')\nconst { kEnumerableProperty } = require('../../core/util')\nconst { environmentSettingsObject } = require('../fetch/util')\n\nlet experimentalWarned = false\n\n/**\n * A reconnection time, in milliseconds. This must initially be an implementation-defined value,\n * probably in the region of a few seconds.\n *\n * In Comparison:\n * - Chrome uses 3000ms.\n * - Deno uses 5000ms.\n *\n * @type {3000}\n */\nconst defaultReconnectionTime = 3000\n\n/**\n * The readyState attribute represents the state of the connection.\n * @enum\n * @readonly\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-readystate-dev\n */\n\n/**\n * The connection has not yet been established, or it was closed and the user\n * agent is reconnecting.\n * @type {0}\n */\nconst CONNECTING = 0\n\n/**\n * The user agent has an open connection and is dispatching events as it\n * receives them.\n * @type {1}\n */\nconst OPEN = 1\n\n/**\n * The connection is not open, and the user agent is not trying to reconnect.\n * @type {2}\n */\nconst CLOSED = 2\n\n/**\n * Requests for the element will have their mode set to \"cors\" and their credentials mode set to \"same-origin\".\n * @type {'anonymous'}\n */\nconst ANONYMOUS = 'anonymous'\n\n/**\n * Requests for the element will have their mode set to \"cors\" and their credentials mode set to \"include\".\n * @type {'use-credentials'}\n */\nconst USE_CREDENTIALS = 'use-credentials'\n\n/**\n * The EventSource interface is used to receive server-sent events. It\n * connects to a server over HTTP and receives events in text/event-stream\n * format without closing the connection.\n * @extends {EventTarget}\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events\n * @api public\n */\nclass EventSource extends EventTarget {\n #events = {\n open: null,\n error: null,\n message: null\n }\n\n #url = null\n #withCredentials = false\n\n #readyState = CONNECTING\n\n #request = null\n #controller = null\n\n #dispatcher\n\n /**\n * @type {import('./eventsource-stream').eventSourceSettings}\n */\n #state\n\n /**\n * Creates a new EventSource object.\n * @param {string} url\n * @param {EventSourceInit} [eventSourceInitDict]\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface\n */\n constructor (url, eventSourceInitDict = {}) {\n // 1. Let ev be a new EventSource object.\n super()\n\n webidl.util.markAsUncloneable(this)\n\n const prefix = 'EventSource constructor'\n webidl.argumentLengthCheck(arguments, 1, prefix)\n\n if (!experimentalWarned) {\n experimentalWarned = true\n process.emitWarning('EventSource is experimental, expect them to change at any time.', {\n code: 'UNDICI-ES'\n })\n }\n\n url = webidl.converters.USVString(url, prefix, 'url')\n eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, 'eventSourceInitDict')\n\n this.#dispatcher = eventSourceInitDict.dispatcher\n this.#state = {\n lastEventId: '',\n reconnectionTime: defaultReconnectionTime\n }\n\n // 2. Let settings be ev's relevant settings object.\n // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object\n const settings = environmentSettingsObject\n\n let urlRecord\n\n try {\n // 3. Let urlRecord be the result of encoding-parsing a URL given url, relative to settings.\n urlRecord = new URL(url, settings.settingsObject.baseUrl)\n this.#state.origin = urlRecord.origin\n } catch (e) {\n // 4. If urlRecord is failure, then throw a \"SyntaxError\" DOMException.\n throw new DOMException(e, 'SyntaxError')\n }\n\n // 5. Set ev's url to urlRecord.\n this.#url = urlRecord.href\n\n // 6. Let corsAttributeState be Anonymous.\n let corsAttributeState = ANONYMOUS\n\n // 7. If the value of eventSourceInitDict's withCredentials member is true,\n // then set corsAttributeState to Use Credentials and set ev's\n // withCredentials attribute to true.\n if (eventSourceInitDict.withCredentials) {\n corsAttributeState = USE_CREDENTIALS\n this.#withCredentials = true\n }\n\n // 8. Let request be the result of creating a potential-CORS request given\n // urlRecord, the empty string, and corsAttributeState.\n const initRequest = {\n redirect: 'follow',\n keepalive: true,\n // @see https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes\n mode: 'cors',\n credentials: corsAttributeState === 'anonymous'\n ? 'same-origin'\n : 'omit',\n referrer: 'no-referrer'\n }\n\n // 9. Set request's client to settings.\n initRequest.client = environmentSettingsObject.settingsObject\n\n // 10. User agents may set (`Accept`, `text/event-stream`) in request's header list.\n initRequest.headersList = [['accept', { name: 'accept', value: 'text/event-stream' }]]\n\n // 11. Set request's cache mode to \"no-store\".\n initRequest.cache = 'no-store'\n\n // 12. Set request's initiator type to \"other\".\n initRequest.initiator = 'other'\n\n initRequest.urlList = [new URL(this.#url)]\n\n // 13. Set ev's request to request.\n this.#request = makeRequest(initRequest)\n\n this.#connect()\n }\n\n /**\n * Returns the state of this EventSource object's connection. It can have the\n * values described below.\n * @returns {0|1|2}\n * @readonly\n */\n get readyState () {\n return this.#readyState\n }\n\n /**\n * Returns the URL providing the event stream.\n * @readonly\n * @returns {string}\n */\n get url () {\n return this.#url\n }\n\n /**\n * Returns a boolean indicating whether the EventSource object was\n * instantiated with CORS credentials set (true), or not (false, the default).\n */\n get withCredentials () {\n return this.#withCredentials\n }\n\n #connect () {\n if (this.#readyState === CLOSED) return\n\n this.#readyState = CONNECTING\n\n const fetchParams = {\n request: this.#request,\n dispatcher: this.#dispatcher\n }\n\n // 14. Let processEventSourceEndOfBody given response res be the following step: if res is not a network error, then reestablish the connection.\n const processEventSourceEndOfBody = (response) => {\n if (isNetworkError(response)) {\n this.dispatchEvent(new Event('error'))\n this.close()\n }\n\n this.#reconnect()\n }\n\n // 15. Fetch request, with processResponseEndOfBody set to processEventSourceEndOfBody...\n fetchParams.processResponseEndOfBody = processEventSourceEndOfBody\n\n // and processResponse set to the following steps given response res:\n fetchParams.processResponse = (response) => {\n // 1. If res is an aborted network error, then fail the connection.\n\n if (isNetworkError(response)) {\n // 1. When a user agent is to fail the connection, the user agent\n // must queue a task which, if the readyState attribute is set to a\n // value other than CLOSED, sets the readyState attribute to CLOSED\n // and fires an event named error at the EventSource object. Once the\n // user agent has failed the connection, it does not attempt to\n // reconnect.\n if (response.aborted) {\n this.close()\n this.dispatchEvent(new Event('error'))\n return\n // 2. Otherwise, if res is a network error, then reestablish the\n // connection, unless the user agent knows that to be futile, in\n // which case the user agent may fail the connection.\n } else {\n this.#reconnect()\n return\n }\n }\n\n // 3. Otherwise, if res's status is not 200, or if res's `Content-Type`\n // is not `text/event-stream`, then fail the connection.\n const contentType = response.headersList.get('content-type', true)\n const mimeType = contentType !== null ? parseMIMEType(contentType) : 'failure'\n const contentTypeValid = mimeType !== 'failure' && mimeType.essence === 'text/event-stream'\n if (\n response.status !== 200 ||\n contentTypeValid === false\n ) {\n this.close()\n this.dispatchEvent(new Event('error'))\n return\n }\n\n // 4. Otherwise, announce the connection and interpret res's body\n // line by line.\n\n // When a user agent is to announce the connection, the user agent\n // must queue a task which, if the readyState attribute is set to a\n // value other than CLOSED, sets the readyState attribute to OPEN\n // and fires an event named open at the EventSource object.\n // @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model\n this.#readyState = OPEN\n this.dispatchEvent(new Event('open'))\n\n // If redirected to a different origin, set the origin to the new origin.\n this.#state.origin = response.urlList[response.urlList.length - 1].origin\n\n const eventSourceStream = new EventSourceStream({\n eventSourceSettings: this.#state,\n push: (event) => {\n this.dispatchEvent(createFastMessageEvent(\n event.type,\n event.options\n ))\n }\n })\n\n pipeline(response.body.stream,\n eventSourceStream,\n (error) => {\n if (\n error?.aborted === false\n ) {\n this.close()\n this.dispatchEvent(new Event('error'))\n }\n })\n }\n\n this.#controller = fetching(fetchParams)\n }\n\n /**\n * @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model\n * @returns {Promise}\n */\n async #reconnect () {\n // When a user agent is to reestablish the connection, the user agent must\n // run the following steps. These steps are run in parallel, not as part of\n // a task. (The tasks that it queues, of course, are run like normal tasks\n // and not themselves in parallel.)\n\n // 1. Queue a task to run the following steps:\n\n // 1. If the readyState attribute is set to CLOSED, abort the task.\n if (this.#readyState === CLOSED) return\n\n // 2. Set the readyState attribute to CONNECTING.\n this.#readyState = CONNECTING\n\n // 3. Fire an event named error at the EventSource object.\n this.dispatchEvent(new Event('error'))\n\n // 2. Wait a delay equal to the reconnection time of the event source.\n await delay(this.#state.reconnectionTime)\n\n // 5. Queue a task to run the following steps:\n\n // 1. If the EventSource object's readyState attribute is not set to\n // CONNECTING, then return.\n if (this.#readyState !== CONNECTING) return\n\n // 2. Let request be the EventSource object's request.\n // 3. If the EventSource object's last event ID string is not the empty\n // string, then:\n // 1. Let lastEventIDValue be the EventSource object's last event ID\n // string, encoded as UTF-8.\n // 2. Set (`Last-Event-ID`, lastEventIDValue) in request's header\n // list.\n if (this.#state.lastEventId.length) {\n this.#request.headersList.set('last-event-id', this.#state.lastEventId, true)\n }\n\n // 4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this section.\n this.#connect()\n }\n\n /**\n * Closes the connection, if any, and sets the readyState attribute to\n * CLOSED.\n */\n close () {\n webidl.brandCheck(this, EventSource)\n\n if (this.#readyState === CLOSED) return\n this.#readyState = CLOSED\n this.#controller.abort()\n this.#request = null\n }\n\n get onopen () {\n return this.#events.open\n }\n\n set onopen (fn) {\n if (this.#events.open) {\n this.removeEventListener('open', this.#events.open)\n }\n\n if (typeof fn === 'function') {\n this.#events.open = fn\n this.addEventListener('open', fn)\n } else {\n this.#events.open = null\n }\n }\n\n get onmessage () {\n return this.#events.message\n }\n\n set onmessage (fn) {\n if (this.#events.message) {\n this.removeEventListener('message', this.#events.message)\n }\n\n if (typeof fn === 'function') {\n this.#events.message = fn\n this.addEventListener('message', fn)\n } else {\n this.#events.message = null\n }\n }\n\n get onerror () {\n return this.#events.error\n }\n\n set onerror (fn) {\n if (this.#events.error) {\n this.removeEventListener('error', this.#events.error)\n }\n\n if (typeof fn === 'function') {\n this.#events.error = fn\n this.addEventListener('error', fn)\n } else {\n this.#events.error = null\n }\n }\n}\n\nconst constantsPropertyDescriptors = {\n CONNECTING: {\n __proto__: null,\n configurable: false,\n enumerable: true,\n value: CONNECTING,\n writable: false\n },\n OPEN: {\n __proto__: null,\n configurable: false,\n enumerable: true,\n value: OPEN,\n writable: false\n },\n CLOSED: {\n __proto__: null,\n configurable: false,\n enumerable: true,\n value: CLOSED,\n writable: false\n }\n}\n\nObject.defineProperties(EventSource, constantsPropertyDescriptors)\nObject.defineProperties(EventSource.prototype, constantsPropertyDescriptors)\n\nObject.defineProperties(EventSource.prototype, {\n close: kEnumerableProperty,\n onerror: kEnumerableProperty,\n onmessage: kEnumerableProperty,\n onopen: kEnumerableProperty,\n readyState: kEnumerableProperty,\n url: kEnumerableProperty,\n withCredentials: kEnumerableProperty\n})\n\nwebidl.converters.EventSourceInitDict = webidl.dictionaryConverter([\n {\n key: 'withCredentials',\n converter: webidl.converters.boolean,\n defaultValue: () => false\n },\n {\n key: 'dispatcher', // undici only\n converter: webidl.converters.any\n }\n])\n\nmodule.exports = {\n EventSource,\n defaultReconnectionTime\n}\n","'use strict'\n\nconst Client = require('./lib/dispatcher/client')\nconst Dispatcher = require('./lib/dispatcher/dispatcher')\nconst Pool = require('./lib/dispatcher/pool')\nconst BalancedPool = require('./lib/dispatcher/balanced-pool')\nconst Agent = require('./lib/dispatcher/agent')\nconst ProxyAgent = require('./lib/dispatcher/proxy-agent')\nconst EnvHttpProxyAgent = require('./lib/dispatcher/env-http-proxy-agent')\nconst RetryAgent = require('./lib/dispatcher/retry-agent')\nconst errors = require('./lib/core/errors')\nconst util = require('./lib/core/util')\nconst { InvalidArgumentError } = errors\nconst api = require('./lib/api')\nconst buildConnector = require('./lib/core/connect')\nconst MockClient = require('./lib/mock/mock-client')\nconst MockAgent = require('./lib/mock/mock-agent')\nconst MockPool = require('./lib/mock/mock-pool')\nconst mockErrors = require('./lib/mock/mock-errors')\nconst RetryHandler = require('./lib/handler/retry-handler')\nconst { getGlobalDispatcher, setGlobalDispatcher } = require('./lib/global')\nconst DecoratorHandler = require('./lib/handler/decorator-handler')\nconst RedirectHandler = require('./lib/handler/redirect-handler')\nconst createRedirectInterceptor = require('./lib/interceptor/redirect-interceptor')\n\nObject.assign(Dispatcher.prototype, api)\n\nmodule.exports.Dispatcher = Dispatcher\nmodule.exports.Client = Client\nmodule.exports.Pool = Pool\nmodule.exports.BalancedPool = BalancedPool\nmodule.exports.Agent = Agent\nmodule.exports.ProxyAgent = ProxyAgent\nmodule.exports.EnvHttpProxyAgent = EnvHttpProxyAgent\nmodule.exports.RetryAgent = RetryAgent\nmodule.exports.RetryHandler = RetryHandler\n\nmodule.exports.DecoratorHandler = DecoratorHandler\nmodule.exports.RedirectHandler = RedirectHandler\nmodule.exports.createRedirectInterceptor = createRedirectInterceptor\nmodule.exports.interceptors = {\n redirect: require('./lib/interceptor/redirect'),\n retry: require('./lib/interceptor/retry'),\n dump: require('./lib/interceptor/dump'),\n dns: require('./lib/interceptor/dns')\n}\n\nmodule.exports.buildConnector = buildConnector\nmodule.exports.errors = errors\nmodule.exports.util = {\n parseHeaders: util.parseHeaders,\n headerNameToString: util.headerNameToString\n}\n\nfunction makeDispatcher (fn) {\n return (url, opts, handler) => {\n if (typeof opts === 'function') {\n handler = opts\n opts = null\n }\n\n if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) {\n throw new InvalidArgumentError('invalid url')\n }\n\n if (opts != null && typeof opts !== 'object') {\n throw new InvalidArgumentError('invalid opts')\n }\n\n if (opts && opts.path != null) {\n if (typeof opts.path !== 'string') {\n throw new InvalidArgumentError('invalid opts.path')\n }\n\n let path = opts.path\n if (!opts.path.startsWith('/')) {\n path = `/${path}`\n }\n\n url = new URL(util.parseOrigin(url).origin + path)\n } else {\n if (!opts) {\n opts = typeof url === 'object' ? url : {}\n }\n\n url = util.parseURL(url)\n }\n\n const { agent, dispatcher = getGlobalDispatcher() } = opts\n\n if (agent) {\n throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?')\n }\n\n return fn.call(dispatcher, {\n ...opts,\n origin: url.origin,\n path: url.search ? `${url.pathname}${url.search}` : url.pathname,\n method: opts.method || (opts.body ? 'PUT' : 'GET')\n }, handler)\n }\n}\n\nmodule.exports.setGlobalDispatcher = setGlobalDispatcher\nmodule.exports.getGlobalDispatcher = getGlobalDispatcher\n\nconst fetchImpl = require('./lib/web/fetch').fetch\nmodule.exports.fetch = async function fetch (init, options = undefined) {\n try {\n return await fetchImpl(init, options)\n } catch (err) {\n if (err && typeof err === 'object') {\n Error.captureStackTrace(err)\n }\n\n throw err\n }\n}\nmodule.exports.Headers = require('./lib/web/fetch/headers').Headers\nmodule.exports.Response = require('./lib/web/fetch/response').Response\nmodule.exports.Request = require('./lib/web/fetch/request').Request\nmodule.exports.FormData = require('./lib/web/fetch/formdata').FormData\nmodule.exports.File = globalThis.File ?? require('node:buffer').File\nmodule.exports.FileReader = require('./lib/web/fileapi/filereader').FileReader\n\nconst { setGlobalOrigin, getGlobalOrigin } = require('./lib/web/fetch/global')\n\nmodule.exports.setGlobalOrigin = setGlobalOrigin\nmodule.exports.getGlobalOrigin = getGlobalOrigin\n\nconst { CacheStorage } = require('./lib/web/cache/cachestorage')\nconst { kConstruct } = require('./lib/web/cache/symbols')\n\n// Cache & CacheStorage are tightly coupled with fetch. Even if it may run\n// in an older version of Node, it doesn't have any use without fetch.\nmodule.exports.caches = new CacheStorage(kConstruct)\n\nconst { deleteCookie, getCookies, getSetCookies, setCookie } = require('./lib/web/cookies')\n\nmodule.exports.deleteCookie = deleteCookie\nmodule.exports.getCookies = getCookies\nmodule.exports.getSetCookies = getSetCookies\nmodule.exports.setCookie = setCookie\n\nconst { parseMIMEType, serializeAMimeType } = require('./lib/web/fetch/data-url')\n\nmodule.exports.parseMIMEType = parseMIMEType\nmodule.exports.serializeAMimeType = serializeAMimeType\n\nconst { CloseEvent, ErrorEvent, MessageEvent } = require('./lib/web/websocket/events')\nmodule.exports.WebSocket = require('./lib/web/websocket/websocket').WebSocket\nmodule.exports.CloseEvent = CloseEvent\nmodule.exports.ErrorEvent = ErrorEvent\nmodule.exports.MessageEvent = MessageEvent\n\nmodule.exports.request = makeDispatcher(api.request)\nmodule.exports.stream = makeDispatcher(api.stream)\nmodule.exports.pipeline = makeDispatcher(api.pipeline)\nmodule.exports.connect = makeDispatcher(api.connect)\nmodule.exports.upgrade = makeDispatcher(api.upgrade)\n\nmodule.exports.MockClient = MockClient\nmodule.exports.MockPool = MockPool\nmodule.exports.MockAgent = MockAgent\nmodule.exports.mockErrors = mockErrors\n\nconst { EventSource } = require('./lib/web/eventsource/eventsource')\n\nmodule.exports.EventSource = EventSource\n",null,null,"export function getUserAgent() {\n if (typeof navigator === \"object\" && \"userAgent\" in navigator) {\n return navigator.userAgent;\n }\n\n if (typeof process === \"object\" && process.version !== undefined) {\n return `Node.js/${process.version.substr(1)} (${process.platform}; ${\n process.arch\n })`;\n }\n\n return \"\";\n}\n","// @ts-check\n\nexport function register(state, name, method, options) {\n if (typeof method !== \"function\") {\n throw new Error(\"method for before hook must be a function\");\n }\n\n if (!options) {\n options = {};\n }\n\n if (Array.isArray(name)) {\n return name.reverse().reduce((callback, name) => {\n return register.bind(null, state, name, callback, options);\n }, method)();\n }\n\n return Promise.resolve().then(() => {\n if (!state.registry[name]) {\n return method(options);\n }\n\n return state.registry[name].reduce((method, registered) => {\n return registered.hook.bind(null, method, options);\n }, method)();\n });\n}\n","// @ts-check\n\nexport function addHook(state, kind, name, hook) {\n const orig = hook;\n if (!state.registry[name]) {\n state.registry[name] = [];\n }\n\n if (kind === \"before\") {\n hook = (method, options) => {\n return Promise.resolve()\n .then(orig.bind(null, options))\n .then(method.bind(null, options));\n };\n }\n\n if (kind === \"after\") {\n hook = (method, options) => {\n let result;\n return Promise.resolve()\n .then(method.bind(null, options))\n .then((result_) => {\n result = result_;\n return orig(result, options);\n })\n .then(() => {\n return result;\n });\n };\n }\n\n if (kind === \"error\") {\n hook = (method, options) => {\n return Promise.resolve()\n .then(method.bind(null, options))\n .catch((error) => {\n return orig(error, options);\n });\n };\n }\n\n state.registry[name].push({\n hook: hook,\n orig: orig,\n });\n}\n","// @ts-check\n\nexport function removeHook(state, name, method) {\n if (!state.registry[name]) {\n return;\n }\n\n const index = state.registry[name]\n .map((registered) => {\n return registered.orig;\n })\n .indexOf(method);\n\n if (index === -1) {\n return;\n }\n\n state.registry[name].splice(index, 1);\n}\n","// @ts-check\n\nimport { register } from \"./lib/register.js\";\nimport { addHook } from \"./lib/add.js\";\nimport { removeHook } from \"./lib/remove.js\";\n\n// bind with array of arguments: https://stackoverflow.com/a/21792913\nconst bind = Function.bind;\nconst bindable = bind.bind(bind);\n\nfunction bindApi(hook, state, name) {\n const removeHookRef = bindable(removeHook, null).apply(\n null,\n name ? [state, name] : [state]\n );\n hook.api = { remove: removeHookRef };\n hook.remove = removeHookRef;\n [\"before\", \"error\", \"after\", \"wrap\"].forEach((kind) => {\n const args = name ? [state, kind, name] : [state, kind];\n hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args);\n });\n}\n\nfunction Singular() {\n const singularHookName = Symbol(\"Singular\");\n const singularHookState = {\n registry: {},\n };\n const singularHook = register.bind(null, singularHookState, singularHookName);\n bindApi(singularHook, singularHookState, singularHookName);\n return singularHook;\n}\n\nfunction Collection() {\n const state = {\n registry: {},\n };\n\n const hook = register.bind(null, state);\n bindApi(hook, state);\n\n return hook;\n}\n\nexport default { Singular, Collection };\n","export function getUserAgent() {\n if (typeof navigator === \"object\" && \"userAgent\" in navigator) {\n return navigator.userAgent;\n }\n\n if (typeof process === \"object\" && process.version !== undefined) {\n return `Node.js/${process.version.substr(1)} (${process.platform}; ${\n process.arch\n })`;\n }\n\n return \"\";\n}\n","// pkg/dist-src/defaults.js\nimport { getUserAgent } from \"universal-user-agent\";\n\n// pkg/dist-src/version.js\nvar VERSION = \"0.0.0-development\";\n\n// pkg/dist-src/defaults.js\nvar userAgent = `octokit-endpoint.js/${VERSION} ${getUserAgent()}`;\nvar DEFAULTS = {\n method: \"GET\",\n baseUrl: \"https://api.github.com\",\n headers: {\n accept: \"application/vnd.github.v3+json\",\n \"user-agent\": userAgent\n },\n mediaType: {\n format: \"\"\n }\n};\n\n// pkg/dist-src/util/lowercase-keys.js\nfunction lowercaseKeys(object) {\n if (!object) {\n return {};\n }\n return Object.keys(object).reduce((newObj, key) => {\n newObj[key.toLowerCase()] = object[key];\n return newObj;\n }, {});\n}\n\n// pkg/dist-src/util/is-plain-object.js\nfunction isPlainObject(value) {\n if (typeof value !== \"object\" || value === null) return false;\n if (Object.prototype.toString.call(value) !== \"[object Object]\") return false;\n const proto = Object.getPrototypeOf(value);\n if (proto === null) return true;\n const Ctor = Object.prototype.hasOwnProperty.call(proto, \"constructor\") && proto.constructor;\n return typeof Ctor === \"function\" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value);\n}\n\n// pkg/dist-src/util/merge-deep.js\nfunction mergeDeep(defaults, options) {\n const result = Object.assign({}, defaults);\n Object.keys(options).forEach((key) => {\n if (isPlainObject(options[key])) {\n if (!(key in defaults)) Object.assign(result, { [key]: options[key] });\n else result[key] = mergeDeep(defaults[key], options[key]);\n } else {\n Object.assign(result, { [key]: options[key] });\n }\n });\n return result;\n}\n\n// pkg/dist-src/util/remove-undefined-properties.js\nfunction removeUndefinedProperties(obj) {\n for (const key in obj) {\n if (obj[key] === void 0) {\n delete obj[key];\n }\n }\n return obj;\n}\n\n// pkg/dist-src/merge.js\nfunction merge(defaults, route, options) {\n if (typeof route === \"string\") {\n let [method, url] = route.split(\" \");\n options = Object.assign(url ? { method, url } : { url: method }, options);\n } else {\n options = Object.assign({}, route);\n }\n options.headers = lowercaseKeys(options.headers);\n removeUndefinedProperties(options);\n removeUndefinedProperties(options.headers);\n const mergedOptions = mergeDeep(defaults || {}, options);\n if (options.url === \"/graphql\") {\n if (defaults && defaults.mediaType.previews?.length) {\n mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(\n (preview) => !mergedOptions.mediaType.previews.includes(preview)\n ).concat(mergedOptions.mediaType.previews);\n }\n mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, \"\"));\n }\n return mergedOptions;\n}\n\n// pkg/dist-src/util/add-query-parameters.js\nfunction addQueryParameters(url, parameters) {\n const separator = /\\?/.test(url) ? \"&\" : \"?\";\n const names = Object.keys(parameters);\n if (names.length === 0) {\n return url;\n }\n return url + separator + names.map((name) => {\n if (name === \"q\") {\n return \"q=\" + parameters.q.split(\"+\").map(encodeURIComponent).join(\"+\");\n }\n return `${name}=${encodeURIComponent(parameters[name])}`;\n }).join(\"&\");\n}\n\n// pkg/dist-src/util/extract-url-variable-names.js\nvar urlVariableRegex = /\\{[^{}}]+\\}/g;\nfunction removeNonChars(variableName) {\n return variableName.replace(/(?:^\\W+)|(?:(? a.concat(b), []);\n}\n\n// pkg/dist-src/util/omit.js\nfunction omit(object, keysToOmit) {\n const result = { __proto__: null };\n for (const key of Object.keys(object)) {\n if (keysToOmit.indexOf(key) === -1) {\n result[key] = object[key];\n }\n }\n return result;\n}\n\n// pkg/dist-src/util/url-template.js\nfunction encodeReserved(str) {\n return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) {\n if (!/%[0-9A-Fa-f]/.test(part)) {\n part = encodeURI(part).replace(/%5B/g, \"[\").replace(/%5D/g, \"]\");\n }\n return part;\n }).join(\"\");\n}\nfunction encodeUnreserved(str) {\n return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {\n return \"%\" + c.charCodeAt(0).toString(16).toUpperCase();\n });\n}\nfunction encodeValue(operator, value, key) {\n value = operator === \"+\" || operator === \"#\" ? encodeReserved(value) : encodeUnreserved(value);\n if (key) {\n return encodeUnreserved(key) + \"=\" + value;\n } else {\n return value;\n }\n}\nfunction isDefined(value) {\n return value !== void 0 && value !== null;\n}\nfunction isKeyOperator(operator) {\n return operator === \";\" || operator === \"&\" || operator === \"?\";\n}\nfunction getValues(context, operator, key, modifier) {\n var value = context[key], result = [];\n if (isDefined(value) && value !== \"\") {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"bigint\" || typeof value === \"boolean\") {\n value = value.toString();\n if (modifier && modifier !== \"*\") {\n value = value.substring(0, parseInt(modifier, 10));\n }\n result.push(\n encodeValue(operator, value, isKeyOperator(operator) ? key : \"\")\n );\n } else {\n if (modifier === \"*\") {\n if (Array.isArray(value)) {\n value.filter(isDefined).forEach(function(value2) {\n result.push(\n encodeValue(operator, value2, isKeyOperator(operator) ? key : \"\")\n );\n });\n } else {\n Object.keys(value).forEach(function(k) {\n if (isDefined(value[k])) {\n result.push(encodeValue(operator, value[k], k));\n }\n });\n }\n } else {\n const tmp = [];\n if (Array.isArray(value)) {\n value.filter(isDefined).forEach(function(value2) {\n tmp.push(encodeValue(operator, value2));\n });\n } else {\n Object.keys(value).forEach(function(k) {\n if (isDefined(value[k])) {\n tmp.push(encodeUnreserved(k));\n tmp.push(encodeValue(operator, value[k].toString()));\n }\n });\n }\n if (isKeyOperator(operator)) {\n result.push(encodeUnreserved(key) + \"=\" + tmp.join(\",\"));\n } else if (tmp.length !== 0) {\n result.push(tmp.join(\",\"));\n }\n }\n }\n } else {\n if (operator === \";\") {\n if (isDefined(value)) {\n result.push(encodeUnreserved(key));\n }\n } else if (value === \"\" && (operator === \"&\" || operator === \"?\")) {\n result.push(encodeUnreserved(key) + \"=\");\n } else if (value === \"\") {\n result.push(\"\");\n }\n }\n return result;\n}\nfunction parseUrl(template) {\n return {\n expand: expand.bind(null, template)\n };\n}\nfunction expand(template, context) {\n var operators = [\"+\", \"#\", \".\", \"/\", \";\", \"?\", \"&\"];\n template = template.replace(\n /\\{([^\\{\\}]+)\\}|([^\\{\\}]+)/g,\n function(_, expression, literal) {\n if (expression) {\n let operator = \"\";\n const values = [];\n if (operators.indexOf(expression.charAt(0)) !== -1) {\n operator = expression.charAt(0);\n expression = expression.substr(1);\n }\n expression.split(/,/g).forEach(function(variable) {\n var tmp = /([^:\\*]*)(?::(\\d+)|(\\*))?/.exec(variable);\n values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3]));\n });\n if (operator && operator !== \"+\") {\n var separator = \",\";\n if (operator === \"?\") {\n separator = \"&\";\n } else if (operator !== \"#\") {\n separator = operator;\n }\n return (values.length !== 0 ? operator : \"\") + values.join(separator);\n } else {\n return values.join(\",\");\n }\n } else {\n return encodeReserved(literal);\n }\n }\n );\n if (template === \"/\") {\n return template;\n } else {\n return template.replace(/\\/$/, \"\");\n }\n}\n\n// pkg/dist-src/parse.js\nfunction parse(options) {\n let method = options.method.toUpperCase();\n let url = (options.url || \"/\").replace(/:([a-z]\\w+)/g, \"{$1}\");\n let headers = Object.assign({}, options.headers);\n let body;\n let parameters = omit(options, [\n \"method\",\n \"baseUrl\",\n \"url\",\n \"headers\",\n \"request\",\n \"mediaType\"\n ]);\n const urlVariableNames = extractUrlVariableNames(url);\n url = parseUrl(url).expand(parameters);\n if (!/^http/.test(url)) {\n url = options.baseUrl + url;\n }\n const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat(\"baseUrl\");\n const remainingParameters = omit(parameters, omittedParameters);\n const isBinaryRequest = /application\\/octet-stream/i.test(headers.accept);\n if (!isBinaryRequest) {\n if (options.mediaType.format) {\n headers.accept = headers.accept.split(/,/).map(\n (format) => format.replace(\n /application\\/vnd(\\.\\w+)(\\.v3)?(\\.\\w+)?(\\+json)?$/,\n `application/vnd$1$2.${options.mediaType.format}`\n )\n ).join(\",\");\n }\n if (url.endsWith(\"/graphql\")) {\n if (options.mediaType.previews?.length) {\n const previewsFromAcceptHeader = headers.accept.match(/(? {\n const format = options.mediaType.format ? `.${options.mediaType.format}` : \"+json\";\n return `application/vnd.github.${preview}-preview${format}`;\n }).join(\",\");\n }\n }\n }\n if ([\"GET\", \"HEAD\"].includes(method)) {\n url = addQueryParameters(url, remainingParameters);\n } else {\n if (\"data\" in remainingParameters) {\n body = remainingParameters.data;\n } else {\n if (Object.keys(remainingParameters).length) {\n body = remainingParameters;\n }\n }\n }\n if (!headers[\"content-type\"] && typeof body !== \"undefined\") {\n headers[\"content-type\"] = \"application/json; charset=utf-8\";\n }\n if ([\"PATCH\", \"PUT\"].includes(method) && typeof body === \"undefined\") {\n body = \"\";\n }\n return Object.assign(\n { method, url, headers },\n typeof body !== \"undefined\" ? { body } : null,\n options.request ? { request: options.request } : null\n );\n}\n\n// pkg/dist-src/endpoint-with-defaults.js\nfunction endpointWithDefaults(defaults, route, options) {\n return parse(merge(defaults, route, options));\n}\n\n// pkg/dist-src/with-defaults.js\nfunction withDefaults(oldDefaults, newDefaults) {\n const DEFAULTS2 = merge(oldDefaults, newDefaults);\n const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2);\n return Object.assign(endpoint2, {\n DEFAULTS: DEFAULTS2,\n defaults: withDefaults.bind(null, DEFAULTS2),\n merge: merge.bind(null, DEFAULTS2),\n parse\n });\n}\n\n// pkg/dist-src/index.js\nvar endpoint = withDefaults(null, DEFAULTS);\nexport {\n endpoint\n};\n","export function getUserAgent() {\n if (typeof navigator === \"object\" && \"userAgent\" in navigator) {\n return navigator.userAgent;\n }\n\n if (typeof process === \"object\" && process.version !== undefined) {\n return `Node.js/${process.version.substr(1)} (${process.platform}; ${\n process.arch\n })`;\n }\n\n return \"\";\n}\n","'use strict'\n\nconst NullObject = function NullObject () { }\nNullObject.prototype = Object.create(null)\n\n/**\n * RegExp to match *( \";\" parameter ) in RFC 7231 sec 3.1.1.1\n *\n * parameter = token \"=\" ( token / quoted-string )\n * token = 1*tchar\n * tchar = \"!\" / \"#\" / \"$\" / \"%\" / \"&\" / \"'\" / \"*\"\n * / \"+\" / \"-\" / \".\" / \"^\" / \"_\" / \"`\" / \"|\" / \"~\"\n * / DIGIT / ALPHA\n * ; any VCHAR, except delimiters\n * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE\n * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text\n * obs-text = %x80-FF\n * quoted-pair = \"\\\" ( HTAB / SP / VCHAR / obs-text )\n */\nconst paramRE = /; *([!#$%&'*+.^\\w`|~-]+)=(\"(?:[\\v\\u0020\\u0021\\u0023-\\u005b\\u005d-\\u007e\\u0080-\\u00ff]|\\\\[\\v\\u0020-\\u00ff])*\"|[!#$%&'*+.^\\w`|~-]+) */gu\n\n/**\n * RegExp to match quoted-pair in RFC 7230 sec 3.2.6\n *\n * quoted-pair = \"\\\" ( HTAB / SP / VCHAR / obs-text )\n * obs-text = %x80-FF\n */\nconst quotedPairRE = /\\\\([\\v\\u0020-\\u00ff])/gu\n\n/**\n * RegExp to match type in RFC 7231 sec 3.1.1.1\n *\n * media-type = type \"/\" subtype\n * type = token\n * subtype = token\n */\nconst mediaTypeRE = /^[!#$%&'*+.^\\w|~-]+\\/[!#$%&'*+.^\\w|~-]+$/u\n\n// default ContentType to prevent repeated object creation\nconst defaultContentType = { type: '', parameters: new NullObject() }\nObject.freeze(defaultContentType.parameters)\nObject.freeze(defaultContentType)\n\n/**\n * Parse media type to object.\n *\n * @param {string|object} header\n * @return {Object}\n * @public\n */\n\nfunction parse (header) {\n if (typeof header !== 'string') {\n throw new TypeError('argument header is required and must be a string')\n }\n\n let index = header.indexOf(';')\n const type = index !== -1\n ? header.slice(0, index).trim()\n : header.trim()\n\n if (mediaTypeRE.test(type) === false) {\n throw new TypeError('invalid media type')\n }\n\n const result = {\n type: type.toLowerCase(),\n parameters: new NullObject()\n }\n\n // parse parameters\n if (index === -1) {\n return result\n }\n\n let key\n let match\n let value\n\n paramRE.lastIndex = index\n\n while ((match = paramRE.exec(header))) {\n if (match.index !== index) {\n throw new TypeError('invalid parameter format')\n }\n\n index += match[0].length\n key = match[1].toLowerCase()\n value = match[2]\n\n if (value[0] === '\"') {\n // remove quotes and escapes\n value = value\n .slice(1, value.length - 1)\n\n quotedPairRE.test(value) && (value = value.replace(quotedPairRE, '$1'))\n }\n\n result.parameters[key] = value\n }\n\n if (index !== header.length) {\n throw new TypeError('invalid parameter format')\n }\n\n return result\n}\n\nfunction safeParse (header) {\n if (typeof header !== 'string') {\n return defaultContentType\n }\n\n let index = header.indexOf(';')\n const type = index !== -1\n ? header.slice(0, index).trim()\n : header.trim()\n\n if (mediaTypeRE.test(type) === false) {\n return defaultContentType\n }\n\n const result = {\n type: type.toLowerCase(),\n parameters: new NullObject()\n }\n\n // parse parameters\n if (index === -1) {\n return result\n }\n\n let key\n let match\n let value\n\n paramRE.lastIndex = index\n\n while ((match = paramRE.exec(header))) {\n if (match.index !== index) {\n return defaultContentType\n }\n\n index += match[0].length\n key = match[1].toLowerCase()\n value = match[2]\n\n if (value[0] === '\"') {\n // remove quotes and escapes\n value = value\n .slice(1, value.length - 1)\n\n quotedPairRE.test(value) && (value = value.replace(quotedPairRE, '$1'))\n }\n\n result.parameters[key] = value\n }\n\n if (index !== header.length) {\n return defaultContentType\n }\n\n return result\n}\n\nmodule.exports.default = { parse, safeParse }\nmodule.exports.parse = parse\nmodule.exports.safeParse = safeParse\nmodule.exports.defaultContentType = defaultContentType\n","const intRegex = /^-?\\d+$/;\nconst noiseValue = /^-?\\d+n+$/; // Noise - strings that match the custom format before being converted to it\nconst originalStringify = JSON.stringify;\nconst originalParse = JSON.parse;\nconst customFormat = /^-?\\d+n$/;\n\nconst bigIntsStringify = /([\\[:])?\"(-?\\d+)n\"($|([\\\\n]|\\s)*(\\s|[\\\\n])*[,\\}\\]])/g;\nconst noiseStringify =\n /([\\[:])?(\"-?\\d+n+)n(\"$|\"([\\\\n]|\\s)*(\\s|[\\\\n])*[,\\}\\]])/g;\n\n/**\n * @typedef {(this: any, key: string | number | undefined, value: any) => any} Replacer\n * @typedef {(key: string | number | undefined, value: any, context?: { source: string }) => any} Reviver\n */\n\n/**\n * Converts a JavaScript value to a JSON string.\n *\n * Supports serialization of BigInt values using two strategies:\n * 1. Custom format \"123n\" → \"123\" (universal fallback)\n * 2. Native JSON.rawJSON() (Node.js 22+, fastest) when available\n *\n * All other values are serialized exactly like native JSON.stringify().\n *\n * @param {*} value The value to convert to a JSON string.\n * @param {Replacer | Array | null} [replacer]\n * A function that alters the behavior of the stringification process,\n * or an array of strings/numbers to indicate properties to exclude.\n * @param {string | number} [space]\n * A string or number to specify indentation or pretty-printing.\n * @returns {string} The JSON string representation.\n */\nconst JSONStringify = (value, replacer, space) => {\n if (\"rawJSON\" in JSON) {\n return originalStringify(\n value,\n (key, value) => {\n if (typeof value === \"bigint\") return JSON.rawJSON(value.toString());\n\n if (typeof replacer === \"function\") return replacer(key, value);\n\n if (Array.isArray(replacer) && replacer.includes(key)) return value;\n\n return value;\n },\n space,\n );\n }\n\n if (!value) return originalStringify(value, replacer, space);\n\n const convertedToCustomJSON = originalStringify(\n value,\n (key, value) => {\n const isNoise = typeof value === \"string\" && noiseValue.test(value);\n\n if (isNoise) return value.toString() + \"n\"; // Mark noise values with additional \"n\" to offset the deletion of one \"n\" during the processing\n\n if (typeof value === \"bigint\") return value.toString() + \"n\";\n\n if (typeof replacer === \"function\") return replacer(key, value);\n\n if (Array.isArray(replacer) && replacer.includes(key)) return value;\n\n return value;\n },\n space,\n );\n const processedJSON = convertedToCustomJSON.replace(\n bigIntsStringify,\n \"$1$2$3\",\n ); // Delete one \"n\" off the end of every BigInt value\n const denoisedJSON = processedJSON.replace(noiseStringify, \"$1$2$3\"); // Remove one \"n\" off the end of every noisy string\n\n return denoisedJSON;\n};\n\nconst featureCache = new Map();\n\n/**\n * Detects if the current JSON.parse implementation supports the context.source feature.\n *\n * Uses toString() fingerprinting to cache results and automatically detect runtime\n * replacements of JSON.parse (polyfills, mocks, etc.).\n *\n * @returns {boolean} true if context.source is supported, false otherwise.\n */\nconst isContextSourceSupported = () => {\n const parseFingerprint = JSON.parse.toString();\n\n if (featureCache.has(parseFingerprint)) {\n return featureCache.get(parseFingerprint);\n }\n\n try {\n const result = JSON.parse(\n \"1\",\n (_, __, context) => !!context?.source && context.source === \"1\",\n );\n featureCache.set(parseFingerprint, result);\n\n return result;\n } catch {\n featureCache.set(parseFingerprint, false);\n\n return false;\n }\n};\n\n/**\n * Reviver function that converts custom-format BigInt strings back to BigInt values.\n * Also handles \"noise\" strings that accidentally match the BigInt format.\n *\n * @param {string | number | undefined} key The object key.\n * @param {*} value The value being parsed.\n * @param {object} [context] Parse context (if supported by JSON.parse).\n * @param {Reviver} [userReviver] User's custom reviver function.\n * @returns {any} The transformed value.\n */\nconst convertMarkedBigIntsReviver = (key, value, context, userReviver) => {\n const isCustomFormatBigInt =\n typeof value === \"string\" && customFormat.test(value);\n if (isCustomFormatBigInt) return BigInt(value.slice(0, -1));\n\n const isNoiseValue = typeof value === \"string\" && noiseValue.test(value);\n if (isNoiseValue) return value.slice(0, -1);\n\n if (typeof userReviver !== \"function\") return value;\n\n return userReviver(key, value, context);\n};\n\n/**\n * Fast JSON.parse implementation (~2x faster than classic fallback).\n * Uses JSON.parse's context.source feature to detect integers and convert\n * large numbers directly to BigInt without string manipulation.\n *\n * Does not support legacy custom format from v1 of this library.\n *\n * @param {string} text JSON string to parse.\n * @param {Reviver} [reviver] Transform function to apply to each value.\n * @returns {any} Parsed JavaScript value.\n */\nconst JSONParseV2 = (text, reviver) => {\n return JSON.parse(text, (key, value, context) => {\n const isBigNumber =\n typeof value === \"number\" &&\n (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER);\n const isInt = context && intRegex.test(context.source);\n const isBigInt = isBigNumber && isInt;\n\n if (isBigInt) return BigInt(context.source);\n\n if (typeof reviver !== \"function\") return value;\n\n return reviver(key, value, context);\n });\n};\n\nconst MAX_INT = Number.MAX_SAFE_INTEGER.toString();\nconst MAX_DIGITS = MAX_INT.length;\nconst stringsOrLargeNumbers =\n /\"(?:\\\\.|[^\"])*\"|-?(0|[1-9][0-9]*)(\\.[0-9]+)?([eE][+-]?[0-9]+)?/g;\nconst noiseValueWithQuotes = /^\"-?\\d+n+\"$/; // Noise - strings that match the custom format before being converted to it\n\n/**\n * Converts a JSON string into a JavaScript value.\n *\n * Supports parsing of large integers using two strategies:\n * 1. Classic fallback: Marks large numbers with \"123n\" format, then converts to BigInt\n * 2. Fast path (JSONParseV2): Uses context.source feature (~2x faster) when available\n *\n * All other JSON values are parsed exactly like native JSON.parse().\n *\n * @param {string} text A valid JSON string.\n * @param {Reviver} [reviver]\n * A function that transforms the results. This function is called for each member\n * of the object. If a member contains nested objects, the nested objects are\n * transformed before the parent object is.\n * @returns {any} The parsed JavaScript value.\n * @throws {SyntaxError} If text is not valid JSON.\n */\nconst JSONParse = (text, reviver) => {\n if (!text) return originalParse(text, reviver);\n\n if (isContextSourceSupported()) return JSONParseV2(text, reviver); // Shortcut to a faster (2x) and simpler version\n\n // Find and mark big numbers with \"n\"\n const serializedData = text.replace(\n stringsOrLargeNumbers,\n (text, digits, fractional, exponential) => {\n const isString = text[0] === '\"';\n const isNoise = isString && noiseValueWithQuotes.test(text);\n\n if (isNoise) return text.substring(0, text.length - 1) + 'n\"'; // Mark noise values with additional \"n\" to offset the deletion of one \"n\" during the processing\n\n const isFractionalOrExponential = fractional || exponential;\n const isLessThanMaxSafeInt =\n digits &&\n (digits.length < MAX_DIGITS ||\n (digits.length === MAX_DIGITS && digits <= MAX_INT)); // With a fixed number of digits, we can correctly use lexicographical comparison to do a numeric comparison\n\n if (isString || isFractionalOrExponential || isLessThanMaxSafeInt)\n return text;\n\n return '\"' + text + 'n\"';\n },\n );\n\n return originalParse(serializedData, (key, value, context) =>\n convertMarkedBigIntsReviver(key, value, context, reviver),\n );\n};\n\nexport { JSONStringify, JSONParse };\n","class RequestError extends Error {\n name;\n /**\n * http status code\n */\n status;\n /**\n * Request options that lead to the error.\n */\n request;\n /**\n * Response object if a response was received\n */\n response;\n constructor(message, statusCode, options) {\n super(message, { cause: options.cause });\n this.name = \"HttpError\";\n this.status = Number.parseInt(statusCode);\n if (Number.isNaN(this.status)) {\n this.status = 0;\n }\n /* v8 ignore else -- @preserve -- Bug with vitest coverage where it sees an else branch that doesn't exist */\n if (\"response\" in options) {\n this.response = options.response;\n }\n const requestCopy = Object.assign({}, options.request);\n if (options.request.headers.authorization) {\n requestCopy.headers = Object.assign({}, options.request.headers, {\n authorization: options.request.headers.authorization.replace(\n /(? \"\";\nasync function fetchWrapper(requestOptions) {\n const fetch = requestOptions.request?.fetch || globalThis.fetch;\n if (!fetch) {\n throw new Error(\n \"fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing\"\n );\n }\n const log = requestOptions.request?.log || console;\n const parseSuccessResponseBody = requestOptions.request?.parseSuccessResponseBody !== false;\n const body = isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body) ? JSONStringify(requestOptions.body) : requestOptions.body;\n const requestHeaders = Object.fromEntries(\n Object.entries(requestOptions.headers).map(([name, value]) => [\n name,\n String(value)\n ])\n );\n let fetchResponse;\n try {\n fetchResponse = await fetch(requestOptions.url, {\n method: requestOptions.method,\n body,\n redirect: requestOptions.request?.redirect,\n headers: requestHeaders,\n signal: requestOptions.request?.signal,\n // duplex must be set if request.body is ReadableStream or Async Iterables.\n // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex.\n ...requestOptions.body && { duplex: \"half\" }\n });\n } catch (error) {\n let message = \"Unknown Error\";\n if (error instanceof Error) {\n if (error.name === \"AbortError\") {\n error.status = 500;\n throw error;\n }\n message = error.message;\n if (error.name === \"TypeError\" && \"cause\" in error) {\n if (error.cause instanceof Error) {\n message = error.cause.message;\n } else if (typeof error.cause === \"string\") {\n message = error.cause;\n }\n }\n }\n const requestError = new RequestError(message, 500, {\n request: requestOptions\n });\n requestError.cause = error;\n throw requestError;\n }\n const status = fetchResponse.status;\n const url = fetchResponse.url;\n const responseHeaders = {};\n for (const [key, value] of fetchResponse.headers) {\n responseHeaders[key] = value;\n }\n const octokitResponse = {\n url,\n status,\n headers: responseHeaders,\n data: \"\"\n };\n if (\"deprecation\" in responseHeaders) {\n const matches = responseHeaders.link && responseHeaders.link.match(/<([^<>]+)>; rel=\"deprecation\"/);\n const deprecationLink = matches && matches.pop();\n log.warn(\n `[@octokit/request] \"${requestOptions.method} ${requestOptions.url}\" is deprecated. It is scheduled to be removed on ${responseHeaders.sunset}${deprecationLink ? `. See ${deprecationLink}` : \"\"}`\n );\n }\n if (status === 204 || status === 205) {\n return octokitResponse;\n }\n if (requestOptions.method === \"HEAD\") {\n if (status < 400) {\n return octokitResponse;\n }\n throw new RequestError(fetchResponse.statusText, status, {\n response: octokitResponse,\n request: requestOptions\n });\n }\n if (status === 304) {\n octokitResponse.data = await getResponseData(fetchResponse);\n throw new RequestError(\"Not modified\", status, {\n response: octokitResponse,\n request: requestOptions\n });\n }\n if (status >= 400) {\n octokitResponse.data = await getResponseData(fetchResponse);\n throw new RequestError(toErrorMessage(octokitResponse.data), status, {\n response: octokitResponse,\n request: requestOptions\n });\n }\n octokitResponse.data = parseSuccessResponseBody ? await getResponseData(fetchResponse) : fetchResponse.body;\n return octokitResponse;\n}\nasync function getResponseData(response) {\n const contentType = response.headers.get(\"content-type\");\n if (!contentType) {\n return response.text().catch(noop);\n }\n const mimetype = safeParse(contentType);\n if (isJSONResponse(mimetype)) {\n let text = \"\";\n try {\n text = await response.text();\n return JSONParse(text);\n } catch (err) {\n return text;\n }\n } else if (mimetype.type.startsWith(\"text/\") || mimetype.parameters.charset?.toLowerCase() === \"utf-8\") {\n return response.text().catch(noop);\n } else {\n return response.arrayBuffer().catch(\n /* v8 ignore next -- @preserve */\n () => new ArrayBuffer(0)\n );\n }\n}\nfunction isJSONResponse(mimetype) {\n return mimetype.type === \"application/json\" || mimetype.type === \"application/scim+json\";\n}\nfunction toErrorMessage(data) {\n if (typeof data === \"string\") {\n return data;\n }\n if (data instanceof ArrayBuffer) {\n return \"Unknown error\";\n }\n if (\"message\" in data) {\n const suffix = \"documentation_url\" in data ? ` - ${data.documentation_url}` : \"\";\n return Array.isArray(data.errors) ? `${data.message}: ${data.errors.map((v) => JSON.stringify(v)).join(\", \")}${suffix}` : `${data.message}${suffix}`;\n }\n return `Unknown error: ${JSON.stringify(data)}`;\n}\n\n// pkg/dist-src/with-defaults.js\nfunction withDefaults(oldEndpoint, newDefaults) {\n const endpoint2 = oldEndpoint.defaults(newDefaults);\n const newApi = function(route, parameters) {\n const endpointOptions = endpoint2.merge(route, parameters);\n if (!endpointOptions.request || !endpointOptions.request.hook) {\n return fetchWrapper(endpoint2.parse(endpointOptions));\n }\n const request2 = (route2, parameters2) => {\n return fetchWrapper(\n endpoint2.parse(endpoint2.merge(route2, parameters2))\n );\n };\n Object.assign(request2, {\n endpoint: endpoint2,\n defaults: withDefaults.bind(null, endpoint2)\n });\n return endpointOptions.request.hook(request2, endpointOptions);\n };\n return Object.assign(newApi, {\n endpoint: endpoint2,\n defaults: withDefaults.bind(null, endpoint2)\n });\n}\n\n// pkg/dist-src/index.js\nvar request = withDefaults(endpoint, defaults_default);\nexport {\n request\n};\n/* v8 ignore next -- @preserve */\n/* v8 ignore else -- @preserve */\n","export function getUserAgent() {\n if (typeof navigator === \"object\" && \"userAgent\" in navigator) {\n return navigator.userAgent;\n }\n\n if (typeof process === \"object\" && process.version !== undefined) {\n return `Node.js/${process.version.substr(1)} (${process.platform}; ${\n process.arch\n })`;\n }\n\n return \"\";\n}\n","// pkg/dist-src/index.js\nimport { request } from \"@octokit/request\";\nimport { getUserAgent } from \"universal-user-agent\";\n\n// pkg/dist-src/version.js\nvar VERSION = \"0.0.0-development\";\n\n// pkg/dist-src/with-defaults.js\nimport { request as Request2 } from \"@octokit/request\";\n\n// pkg/dist-src/graphql.js\nimport { request as Request } from \"@octokit/request\";\n\n// pkg/dist-src/error.js\nfunction _buildMessageForResponseErrors(data) {\n return `Request failed due to following response errors:\n` + data.errors.map((e) => ` - ${e.message}`).join(\"\\n\");\n}\nvar GraphqlResponseError = class extends Error {\n constructor(request2, headers, response) {\n super(_buildMessageForResponseErrors(response));\n this.request = request2;\n this.headers = headers;\n this.response = response;\n this.errors = response.errors;\n this.data = response.data;\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n name = \"GraphqlResponseError\";\n errors;\n data;\n};\n\n// pkg/dist-src/graphql.js\nvar NON_VARIABLE_OPTIONS = [\n \"method\",\n \"baseUrl\",\n \"url\",\n \"headers\",\n \"request\",\n \"query\",\n \"mediaType\",\n \"operationName\"\n];\nvar FORBIDDEN_VARIABLE_OPTIONS = [\"query\", \"method\", \"url\"];\nvar GHES_V3_SUFFIX_REGEX = /\\/api\\/v3\\/?$/;\nfunction graphql(request2, query, options) {\n if (options) {\n if (typeof query === \"string\" && \"query\" in options) {\n return Promise.reject(\n new Error(`[@octokit/graphql] \"query\" cannot be used as variable name`)\n );\n }\n for (const key in options) {\n if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue;\n return Promise.reject(\n new Error(\n `[@octokit/graphql] \"${key}\" cannot be used as variable name`\n )\n );\n }\n }\n const parsedOptions = typeof query === \"string\" ? Object.assign({ query }, options) : query;\n const requestOptions = Object.keys(\n parsedOptions\n ).reduce((result, key) => {\n if (NON_VARIABLE_OPTIONS.includes(key)) {\n result[key] = parsedOptions[key];\n return result;\n }\n if (!result.variables) {\n result.variables = {};\n }\n result.variables[key] = parsedOptions[key];\n return result;\n }, {});\n const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl;\n if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) {\n requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, \"/api/graphql\");\n }\n return request2(requestOptions).then((response) => {\n if (response.data.errors) {\n const headers = {};\n for (const key of Object.keys(response.headers)) {\n headers[key] = response.headers[key];\n }\n throw new GraphqlResponseError(\n requestOptions,\n headers,\n response.data\n );\n }\n return response.data.data;\n });\n}\n\n// pkg/dist-src/with-defaults.js\nfunction withDefaults(request2, newDefaults) {\n const newRequest = request2.defaults(newDefaults);\n const newApi = (query, options) => {\n return graphql(newRequest, query, options);\n };\n return Object.assign(newApi, {\n defaults: withDefaults.bind(null, newRequest),\n endpoint: newRequest.endpoint\n });\n}\n\n// pkg/dist-src/index.js\nvar graphql2 = withDefaults(request, {\n headers: {\n \"user-agent\": `octokit-graphql.js/${VERSION} ${getUserAgent()}`\n },\n method: \"POST\",\n url: \"/graphql\"\n});\nfunction withCustomRequest(customRequest) {\n return withDefaults(customRequest, {\n method: \"POST\",\n url: \"/graphql\"\n });\n}\nexport {\n GraphqlResponseError,\n graphql2 as graphql,\n withCustomRequest\n};\n","// pkg/dist-src/is-jwt.js\nvar b64url = \"(?:[a-zA-Z0-9_-]+)\";\nvar sep = \"\\\\.\";\nvar jwtRE = new RegExp(`^${b64url}${sep}${b64url}${sep}${b64url}$`);\nvar isJWT = jwtRE.test.bind(jwtRE);\n\n// pkg/dist-src/auth.js\nasync function auth(token) {\n const isApp = isJWT(token);\n const isInstallation = token.startsWith(\"v1.\") || token.startsWith(\"ghs_\");\n const isUserToServer = token.startsWith(\"ghu_\");\n const tokenType = isApp ? \"app\" : isInstallation ? \"installation\" : isUserToServer ? \"user-to-server\" : \"oauth\";\n return {\n type: \"token\",\n token,\n tokenType\n };\n}\n\n// pkg/dist-src/with-authorization-prefix.js\nfunction withAuthorizationPrefix(token) {\n if (token.split(/\\./).length === 3) {\n return `bearer ${token}`;\n }\n return `token ${token}`;\n}\n\n// pkg/dist-src/hook.js\nasync function hook(token, request, route, parameters) {\n const endpoint = request.endpoint.merge(\n route,\n parameters\n );\n endpoint.headers.authorization = withAuthorizationPrefix(token);\n return request(endpoint);\n}\n\n// pkg/dist-src/index.js\nvar createTokenAuth = function createTokenAuth2(token) {\n if (!token) {\n throw new Error(\"[@octokit/auth-token] No token passed to createTokenAuth\");\n }\n if (typeof token !== \"string\") {\n throw new Error(\n \"[@octokit/auth-token] Token passed to createTokenAuth is not a string\"\n );\n }\n token = token.replace(/^(token|bearer) +/i, \"\");\n return Object.assign(auth.bind(null, token), {\n hook: hook.bind(null, token)\n });\n};\nexport {\n createTokenAuth\n};\n","const VERSION = \"7.0.6\";\nexport {\n VERSION\n};\n","import { getUserAgent } from \"universal-user-agent\";\nimport Hook from \"before-after-hook\";\nimport { request } from \"@octokit/request\";\nimport { withCustomRequest } from \"@octokit/graphql\";\nimport { createTokenAuth } from \"@octokit/auth-token\";\nimport { VERSION } from \"./version.js\";\nconst noop = () => {\n};\nconst consoleWarn = console.warn.bind(console);\nconst consoleError = console.error.bind(console);\nfunction createLogger(logger = {}) {\n if (typeof logger.debug !== \"function\") {\n logger.debug = noop;\n }\n if (typeof logger.info !== \"function\") {\n logger.info = noop;\n }\n if (typeof logger.warn !== \"function\") {\n logger.warn = consoleWarn;\n }\n if (typeof logger.error !== \"function\") {\n logger.error = consoleError;\n }\n return logger;\n}\nconst userAgentTrail = `octokit-core.js/${VERSION} ${getUserAgent()}`;\nclass Octokit {\n static VERSION = VERSION;\n static defaults(defaults) {\n const OctokitWithDefaults = class extends this {\n constructor(...args) {\n const options = args[0] || {};\n if (typeof defaults === \"function\") {\n super(defaults(options));\n return;\n }\n super(\n Object.assign(\n {},\n defaults,\n options,\n options.userAgent && defaults.userAgent ? {\n userAgent: `${options.userAgent} ${defaults.userAgent}`\n } : null\n )\n );\n }\n };\n return OctokitWithDefaults;\n }\n static plugins = [];\n /**\n * Attach a plugin (or many) to your Octokit instance.\n *\n * @example\n * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...)\n */\n static plugin(...newPlugins) {\n const currentPlugins = this.plugins;\n const NewOctokit = class extends this {\n static plugins = currentPlugins.concat(\n newPlugins.filter((plugin) => !currentPlugins.includes(plugin))\n );\n };\n return NewOctokit;\n }\n constructor(options = {}) {\n const hook = new Hook.Collection();\n const requestDefaults = {\n baseUrl: request.endpoint.DEFAULTS.baseUrl,\n headers: {},\n request: Object.assign({}, options.request, {\n // @ts-ignore internal usage only, no need to type\n hook: hook.bind(null, \"request\")\n }),\n mediaType: {\n previews: [],\n format: \"\"\n }\n };\n requestDefaults.headers[\"user-agent\"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail;\n if (options.baseUrl) {\n requestDefaults.baseUrl = options.baseUrl;\n }\n if (options.previews) {\n requestDefaults.mediaType.previews = options.previews;\n }\n if (options.timeZone) {\n requestDefaults.headers[\"time-zone\"] = options.timeZone;\n }\n this.request = request.defaults(requestDefaults);\n this.graphql = withCustomRequest(this.request).defaults(requestDefaults);\n this.log = createLogger(options.log);\n this.hook = hook;\n if (!options.authStrategy) {\n if (!options.auth) {\n this.auth = async () => ({\n type: \"unauthenticated\"\n });\n } else {\n const auth = createTokenAuth(options.auth);\n hook.wrap(\"request\", auth.hook);\n this.auth = auth;\n }\n } else {\n const { authStrategy, ...otherOptions } = options;\n const auth = authStrategy(\n Object.assign(\n {\n request: this.request,\n log: this.log,\n // we pass the current octokit instance as well as its constructor options\n // to allow for authentication strategies that return a new octokit instance\n // that shares the same internal state as the current one. The original\n // requirement for this was the \"event-octokit\" authentication strategy\n // of https://github.com/probot/octokit-auth-probot.\n octokit: this,\n octokitOptions: otherOptions\n },\n options.auth\n )\n );\n hook.wrap(\"request\", auth.hook);\n this.auth = auth;\n }\n const classConstructor = this.constructor;\n for (let i = 0; i < classConstructor.plugins.length; ++i) {\n Object.assign(this, classConstructor.plugins[i](this, options));\n }\n }\n // assigned during constructor\n request;\n graphql;\n log;\n hook;\n // TODO: type `octokit.auth` based on passed options.authStrategy\n auth;\n}\nexport {\n Octokit\n};\n","export const VERSION = \"17.0.0\";\n","import type { EndpointsDefaultsAndDecorations } from \"../types.js\";\nconst Endpoints: EndpointsDefaultsAndDecorations = {\n actions: {\n addCustomLabelsToSelfHostedRunnerForOrg: [\n \"POST /orgs/{org}/actions/runners/{runner_id}/labels\",\n ],\n addCustomLabelsToSelfHostedRunnerForRepo: [\n \"POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels\",\n ],\n addRepoAccessToSelfHostedRunnerGroupInOrg: [\n \"PUT /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories/{repository_id}\",\n ],\n addSelectedRepoToOrgSecret: [\n \"PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}\",\n ],\n addSelectedRepoToOrgVariable: [\n \"PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}\",\n ],\n approveWorkflowRun: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve\",\n ],\n cancelWorkflowRun: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel\",\n ],\n createEnvironmentVariable: [\n \"POST /repos/{owner}/{repo}/environments/{environment_name}/variables\",\n ],\n createHostedRunnerForOrg: [\"POST /orgs/{org}/actions/hosted-runners\"],\n createOrUpdateEnvironmentSecret: [\n \"PUT /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}\",\n ],\n createOrUpdateOrgSecret: [\"PUT /orgs/{org}/actions/secrets/{secret_name}\"],\n createOrUpdateRepoSecret: [\n \"PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}\",\n ],\n createOrgVariable: [\"POST /orgs/{org}/actions/variables\"],\n createRegistrationTokenForOrg: [\n \"POST /orgs/{org}/actions/runners/registration-token\",\n ],\n createRegistrationTokenForRepo: [\n \"POST /repos/{owner}/{repo}/actions/runners/registration-token\",\n ],\n createRemoveTokenForOrg: [\"POST /orgs/{org}/actions/runners/remove-token\"],\n createRemoveTokenForRepo: [\n \"POST /repos/{owner}/{repo}/actions/runners/remove-token\",\n ],\n createRepoVariable: [\"POST /repos/{owner}/{repo}/actions/variables\"],\n createWorkflowDispatch: [\n \"POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches\",\n ],\n deleteActionsCacheById: [\n \"DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}\",\n ],\n deleteActionsCacheByKey: [\n \"DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}\",\n ],\n deleteArtifact: [\n \"DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}\",\n ],\n deleteCustomImageFromOrg: [\n \"DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}\",\n ],\n deleteCustomImageVersionFromOrg: [\n \"DELETE /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}\",\n ],\n deleteEnvironmentSecret: [\n \"DELETE /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}\",\n ],\n deleteEnvironmentVariable: [\n \"DELETE /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}\",\n ],\n deleteHostedRunnerForOrg: [\n \"DELETE /orgs/{org}/actions/hosted-runners/{hosted_runner_id}\",\n ],\n deleteOrgSecret: [\"DELETE /orgs/{org}/actions/secrets/{secret_name}\"],\n deleteOrgVariable: [\"DELETE /orgs/{org}/actions/variables/{name}\"],\n deleteRepoSecret: [\n \"DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}\",\n ],\n deleteRepoVariable: [\n \"DELETE /repos/{owner}/{repo}/actions/variables/{name}\",\n ],\n deleteSelfHostedRunnerFromOrg: [\n \"DELETE /orgs/{org}/actions/runners/{runner_id}\",\n ],\n deleteSelfHostedRunnerFromRepo: [\n \"DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}\",\n ],\n deleteWorkflowRun: [\"DELETE /repos/{owner}/{repo}/actions/runs/{run_id}\"],\n deleteWorkflowRunLogs: [\n \"DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs\",\n ],\n disableSelectedRepositoryGithubActionsOrganization: [\n \"DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}\",\n ],\n disableWorkflow: [\n \"PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable\",\n ],\n downloadArtifact: [\n \"GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}\",\n ],\n downloadJobLogsForWorkflowRun: [\n \"GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs\",\n ],\n downloadWorkflowRunAttemptLogs: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs\",\n ],\n downloadWorkflowRunLogs: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs\",\n ],\n enableSelectedRepositoryGithubActionsOrganization: [\n \"PUT /orgs/{org}/actions/permissions/repositories/{repository_id}\",\n ],\n enableWorkflow: [\n \"PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable\",\n ],\n forceCancelWorkflowRun: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel\",\n ],\n generateRunnerJitconfigForOrg: [\n \"POST /orgs/{org}/actions/runners/generate-jitconfig\",\n ],\n generateRunnerJitconfigForRepo: [\n \"POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig\",\n ],\n getActionsCacheList: [\"GET /repos/{owner}/{repo}/actions/caches\"],\n getActionsCacheUsage: [\"GET /repos/{owner}/{repo}/actions/cache/usage\"],\n getActionsCacheUsageByRepoForOrg: [\n \"GET /orgs/{org}/actions/cache/usage-by-repository\",\n ],\n getActionsCacheUsageForOrg: [\"GET /orgs/{org}/actions/cache/usage\"],\n getAllowedActionsOrganization: [\n \"GET /orgs/{org}/actions/permissions/selected-actions\",\n ],\n getAllowedActionsRepository: [\n \"GET /repos/{owner}/{repo}/actions/permissions/selected-actions\",\n ],\n getArtifact: [\"GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}\"],\n getCustomImageForOrg: [\n \"GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}\",\n ],\n getCustomImageVersionForOrg: [\n \"GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions/{version}\",\n ],\n getCustomOidcSubClaimForRepo: [\n \"GET /repos/{owner}/{repo}/actions/oidc/customization/sub\",\n ],\n getEnvironmentPublicKey: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/public-key\",\n ],\n getEnvironmentSecret: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/secrets/{secret_name}\",\n ],\n getEnvironmentVariable: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}\",\n ],\n getGithubActionsDefaultWorkflowPermissionsOrganization: [\n \"GET /orgs/{org}/actions/permissions/workflow\",\n ],\n getGithubActionsDefaultWorkflowPermissionsRepository: [\n \"GET /repos/{owner}/{repo}/actions/permissions/workflow\",\n ],\n getGithubActionsPermissionsOrganization: [\n \"GET /orgs/{org}/actions/permissions\",\n ],\n getGithubActionsPermissionsRepository: [\n \"GET /repos/{owner}/{repo}/actions/permissions\",\n ],\n getHostedRunnerForOrg: [\n \"GET /orgs/{org}/actions/hosted-runners/{hosted_runner_id}\",\n ],\n getHostedRunnersGithubOwnedImagesForOrg: [\n \"GET /orgs/{org}/actions/hosted-runners/images/github-owned\",\n ],\n getHostedRunnersLimitsForOrg: [\n \"GET /orgs/{org}/actions/hosted-runners/limits\",\n ],\n getHostedRunnersMachineSpecsForOrg: [\n \"GET /orgs/{org}/actions/hosted-runners/machine-sizes\",\n ],\n getHostedRunnersPartnerImagesForOrg: [\n \"GET /orgs/{org}/actions/hosted-runners/images/partner\",\n ],\n getHostedRunnersPlatformsForOrg: [\n \"GET /orgs/{org}/actions/hosted-runners/platforms\",\n ],\n getJobForWorkflowRun: [\"GET /repos/{owner}/{repo}/actions/jobs/{job_id}\"],\n getOrgPublicKey: [\"GET /orgs/{org}/actions/secrets/public-key\"],\n getOrgSecret: [\"GET /orgs/{org}/actions/secrets/{secret_name}\"],\n getOrgVariable: [\"GET /orgs/{org}/actions/variables/{name}\"],\n getPendingDeploymentsForRun: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments\",\n ],\n getRepoPermissions: [\n \"GET /repos/{owner}/{repo}/actions/permissions\",\n {},\n { renamed: [\"actions\", \"getGithubActionsPermissionsRepository\"] },\n ],\n getRepoPublicKey: [\"GET /repos/{owner}/{repo}/actions/secrets/public-key\"],\n getRepoSecret: [\"GET /repos/{owner}/{repo}/actions/secrets/{secret_name}\"],\n getRepoVariable: [\"GET /repos/{owner}/{repo}/actions/variables/{name}\"],\n getReviewsForRun: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals\",\n ],\n getSelfHostedRunnerForOrg: [\"GET /orgs/{org}/actions/runners/{runner_id}\"],\n getSelfHostedRunnerForRepo: [\n \"GET /repos/{owner}/{repo}/actions/runners/{runner_id}\",\n ],\n getWorkflow: [\"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}\"],\n getWorkflowAccessToRepository: [\n \"GET /repos/{owner}/{repo}/actions/permissions/access\",\n ],\n getWorkflowRun: [\"GET /repos/{owner}/{repo}/actions/runs/{run_id}\"],\n getWorkflowRunAttempt: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}\",\n ],\n getWorkflowRunUsage: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing\",\n ],\n getWorkflowUsage: [\n \"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing\",\n ],\n listArtifactsForRepo: [\"GET /repos/{owner}/{repo}/actions/artifacts\"],\n listCustomImageVersionsForOrg: [\n \"GET /orgs/{org}/actions/hosted-runners/images/custom/{image_definition_id}/versions\",\n ],\n listCustomImagesForOrg: [\n \"GET /orgs/{org}/actions/hosted-runners/images/custom\",\n ],\n listEnvironmentSecrets: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/secrets\",\n ],\n listEnvironmentVariables: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/variables\",\n ],\n listGithubHostedRunnersInGroupForOrg: [\n \"GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners\",\n ],\n listHostedRunnersForOrg: [\"GET /orgs/{org}/actions/hosted-runners\"],\n listJobsForWorkflowRun: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs\",\n ],\n listJobsForWorkflowRunAttempt: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs\",\n ],\n listLabelsForSelfHostedRunnerForOrg: [\n \"GET /orgs/{org}/actions/runners/{runner_id}/labels\",\n ],\n listLabelsForSelfHostedRunnerForRepo: [\n \"GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels\",\n ],\n listOrgSecrets: [\"GET /orgs/{org}/actions/secrets\"],\n listOrgVariables: [\"GET /orgs/{org}/actions/variables\"],\n listRepoOrganizationSecrets: [\n \"GET /repos/{owner}/{repo}/actions/organization-secrets\",\n ],\n listRepoOrganizationVariables: [\n \"GET /repos/{owner}/{repo}/actions/organization-variables\",\n ],\n listRepoSecrets: [\"GET /repos/{owner}/{repo}/actions/secrets\"],\n listRepoVariables: [\"GET /repos/{owner}/{repo}/actions/variables\"],\n listRepoWorkflows: [\"GET /repos/{owner}/{repo}/actions/workflows\"],\n listRunnerApplicationsForOrg: [\"GET /orgs/{org}/actions/runners/downloads\"],\n listRunnerApplicationsForRepo: [\n \"GET /repos/{owner}/{repo}/actions/runners/downloads\",\n ],\n listSelectedReposForOrgSecret: [\n \"GET /orgs/{org}/actions/secrets/{secret_name}/repositories\",\n ],\n listSelectedReposForOrgVariable: [\n \"GET /orgs/{org}/actions/variables/{name}/repositories\",\n ],\n listSelectedRepositoriesEnabledGithubActionsOrganization: [\n \"GET /orgs/{org}/actions/permissions/repositories\",\n ],\n listSelfHostedRunnersForOrg: [\"GET /orgs/{org}/actions/runners\"],\n listSelfHostedRunnersForRepo: [\"GET /repos/{owner}/{repo}/actions/runners\"],\n listWorkflowRunArtifacts: [\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts\",\n ],\n listWorkflowRuns: [\n \"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs\",\n ],\n listWorkflowRunsForRepo: [\"GET /repos/{owner}/{repo}/actions/runs\"],\n reRunJobForWorkflowRun: [\n \"POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun\",\n ],\n reRunWorkflow: [\"POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun\"],\n reRunWorkflowFailedJobs: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs\",\n ],\n removeAllCustomLabelsFromSelfHostedRunnerForOrg: [\n \"DELETE /orgs/{org}/actions/runners/{runner_id}/labels\",\n ],\n removeAllCustomLabelsFromSelfHostedRunnerForRepo: [\n \"DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels\",\n ],\n removeCustomLabelFromSelfHostedRunnerForOrg: [\n \"DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}\",\n ],\n removeCustomLabelFromSelfHostedRunnerForRepo: [\n \"DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}\",\n ],\n removeSelectedRepoFromOrgSecret: [\n \"DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}\",\n ],\n removeSelectedRepoFromOrgVariable: [\n \"DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}\",\n ],\n reviewCustomGatesForRun: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule\",\n ],\n reviewPendingDeploymentsForRun: [\n \"POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments\",\n ],\n setAllowedActionsOrganization: [\n \"PUT /orgs/{org}/actions/permissions/selected-actions\",\n ],\n setAllowedActionsRepository: [\n \"PUT /repos/{owner}/{repo}/actions/permissions/selected-actions\",\n ],\n setCustomLabelsForSelfHostedRunnerForOrg: [\n \"PUT /orgs/{org}/actions/runners/{runner_id}/labels\",\n ],\n setCustomLabelsForSelfHostedRunnerForRepo: [\n \"PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels\",\n ],\n setCustomOidcSubClaimForRepo: [\n \"PUT /repos/{owner}/{repo}/actions/oidc/customization/sub\",\n ],\n setGithubActionsDefaultWorkflowPermissionsOrganization: [\n \"PUT /orgs/{org}/actions/permissions/workflow\",\n ],\n setGithubActionsDefaultWorkflowPermissionsRepository: [\n \"PUT /repos/{owner}/{repo}/actions/permissions/workflow\",\n ],\n setGithubActionsPermissionsOrganization: [\n \"PUT /orgs/{org}/actions/permissions\",\n ],\n setGithubActionsPermissionsRepository: [\n \"PUT /repos/{owner}/{repo}/actions/permissions\",\n ],\n setSelectedReposForOrgSecret: [\n \"PUT /orgs/{org}/actions/secrets/{secret_name}/repositories\",\n ],\n setSelectedReposForOrgVariable: [\n \"PUT /orgs/{org}/actions/variables/{name}/repositories\",\n ],\n setSelectedRepositoriesEnabledGithubActionsOrganization: [\n \"PUT /orgs/{org}/actions/permissions/repositories\",\n ],\n setWorkflowAccessToRepository: [\n \"PUT /repos/{owner}/{repo}/actions/permissions/access\",\n ],\n updateEnvironmentVariable: [\n \"PATCH /repos/{owner}/{repo}/environments/{environment_name}/variables/{name}\",\n ],\n updateHostedRunnerForOrg: [\n \"PATCH /orgs/{org}/actions/hosted-runners/{hosted_runner_id}\",\n ],\n updateOrgVariable: [\"PATCH /orgs/{org}/actions/variables/{name}\"],\n updateRepoVariable: [\n \"PATCH /repos/{owner}/{repo}/actions/variables/{name}\",\n ],\n },\n activity: {\n checkRepoIsStarredByAuthenticatedUser: [\"GET /user/starred/{owner}/{repo}\"],\n deleteRepoSubscription: [\"DELETE /repos/{owner}/{repo}/subscription\"],\n deleteThreadSubscription: [\n \"DELETE /notifications/threads/{thread_id}/subscription\",\n ],\n getFeeds: [\"GET /feeds\"],\n getRepoSubscription: [\"GET /repos/{owner}/{repo}/subscription\"],\n getThread: [\"GET /notifications/threads/{thread_id}\"],\n getThreadSubscriptionForAuthenticatedUser: [\n \"GET /notifications/threads/{thread_id}/subscription\",\n ],\n listEventsForAuthenticatedUser: [\"GET /users/{username}/events\"],\n listNotificationsForAuthenticatedUser: [\"GET /notifications\"],\n listOrgEventsForAuthenticatedUser: [\n \"GET /users/{username}/events/orgs/{org}\",\n ],\n listPublicEvents: [\"GET /events\"],\n listPublicEventsForRepoNetwork: [\"GET /networks/{owner}/{repo}/events\"],\n listPublicEventsForUser: [\"GET /users/{username}/events/public\"],\n listPublicOrgEvents: [\"GET /orgs/{org}/events\"],\n listReceivedEventsForUser: [\"GET /users/{username}/received_events\"],\n listReceivedPublicEventsForUser: [\n \"GET /users/{username}/received_events/public\",\n ],\n listRepoEvents: [\"GET /repos/{owner}/{repo}/events\"],\n listRepoNotificationsForAuthenticatedUser: [\n \"GET /repos/{owner}/{repo}/notifications\",\n ],\n listReposStarredByAuthenticatedUser: [\"GET /user/starred\"],\n listReposStarredByUser: [\"GET /users/{username}/starred\"],\n listReposWatchedByUser: [\"GET /users/{username}/subscriptions\"],\n listStargazersForRepo: [\"GET /repos/{owner}/{repo}/stargazers\"],\n listWatchedReposForAuthenticatedUser: [\"GET /user/subscriptions\"],\n listWatchersForRepo: [\"GET /repos/{owner}/{repo}/subscribers\"],\n markNotificationsAsRead: [\"PUT /notifications\"],\n markRepoNotificationsAsRead: [\"PUT /repos/{owner}/{repo}/notifications\"],\n markThreadAsDone: [\"DELETE /notifications/threads/{thread_id}\"],\n markThreadAsRead: [\"PATCH /notifications/threads/{thread_id}\"],\n setRepoSubscription: [\"PUT /repos/{owner}/{repo}/subscription\"],\n setThreadSubscription: [\n \"PUT /notifications/threads/{thread_id}/subscription\",\n ],\n starRepoForAuthenticatedUser: [\"PUT /user/starred/{owner}/{repo}\"],\n unstarRepoForAuthenticatedUser: [\"DELETE /user/starred/{owner}/{repo}\"],\n },\n apps: {\n addRepoToInstallation: [\n \"PUT /user/installations/{installation_id}/repositories/{repository_id}\",\n {},\n { renamed: [\"apps\", \"addRepoToInstallationForAuthenticatedUser\"] },\n ],\n addRepoToInstallationForAuthenticatedUser: [\n \"PUT /user/installations/{installation_id}/repositories/{repository_id}\",\n ],\n checkToken: [\"POST /applications/{client_id}/token\"],\n createFromManifest: [\"POST /app-manifests/{code}/conversions\"],\n createInstallationAccessToken: [\n \"POST /app/installations/{installation_id}/access_tokens\",\n ],\n deleteAuthorization: [\"DELETE /applications/{client_id}/grant\"],\n deleteInstallation: [\"DELETE /app/installations/{installation_id}\"],\n deleteToken: [\"DELETE /applications/{client_id}/token\"],\n getAuthenticated: [\"GET /app\"],\n getBySlug: [\"GET /apps/{app_slug}\"],\n getInstallation: [\"GET /app/installations/{installation_id}\"],\n getOrgInstallation: [\"GET /orgs/{org}/installation\"],\n getRepoInstallation: [\"GET /repos/{owner}/{repo}/installation\"],\n getSubscriptionPlanForAccount: [\n \"GET /marketplace_listing/accounts/{account_id}\",\n ],\n getSubscriptionPlanForAccountStubbed: [\n \"GET /marketplace_listing/stubbed/accounts/{account_id}\",\n ],\n getUserInstallation: [\"GET /users/{username}/installation\"],\n getWebhookConfigForApp: [\"GET /app/hook/config\"],\n getWebhookDelivery: [\"GET /app/hook/deliveries/{delivery_id}\"],\n listAccountsForPlan: [\"GET /marketplace_listing/plans/{plan_id}/accounts\"],\n listAccountsForPlanStubbed: [\n \"GET /marketplace_listing/stubbed/plans/{plan_id}/accounts\",\n ],\n listInstallationReposForAuthenticatedUser: [\n \"GET /user/installations/{installation_id}/repositories\",\n ],\n listInstallationRequestsForAuthenticatedApp: [\n \"GET /app/installation-requests\",\n ],\n listInstallations: [\"GET /app/installations\"],\n listInstallationsForAuthenticatedUser: [\"GET /user/installations\"],\n listPlans: [\"GET /marketplace_listing/plans\"],\n listPlansStubbed: [\"GET /marketplace_listing/stubbed/plans\"],\n listReposAccessibleToInstallation: [\"GET /installation/repositories\"],\n listSubscriptionsForAuthenticatedUser: [\"GET /user/marketplace_purchases\"],\n listSubscriptionsForAuthenticatedUserStubbed: [\n \"GET /user/marketplace_purchases/stubbed\",\n ],\n listWebhookDeliveries: [\"GET /app/hook/deliveries\"],\n redeliverWebhookDelivery: [\n \"POST /app/hook/deliveries/{delivery_id}/attempts\",\n ],\n removeRepoFromInstallation: [\n \"DELETE /user/installations/{installation_id}/repositories/{repository_id}\",\n {},\n { renamed: [\"apps\", \"removeRepoFromInstallationForAuthenticatedUser\"] },\n ],\n removeRepoFromInstallationForAuthenticatedUser: [\n \"DELETE /user/installations/{installation_id}/repositories/{repository_id}\",\n ],\n resetToken: [\"PATCH /applications/{client_id}/token\"],\n revokeInstallationAccessToken: [\"DELETE /installation/token\"],\n scopeToken: [\"POST /applications/{client_id}/token/scoped\"],\n suspendInstallation: [\"PUT /app/installations/{installation_id}/suspended\"],\n unsuspendInstallation: [\n \"DELETE /app/installations/{installation_id}/suspended\",\n ],\n updateWebhookConfigForApp: [\"PATCH /app/hook/config\"],\n },\n billing: {\n getGithubActionsBillingOrg: [\"GET /orgs/{org}/settings/billing/actions\"],\n getGithubActionsBillingUser: [\n \"GET /users/{username}/settings/billing/actions\",\n ],\n getGithubBillingPremiumRequestUsageReportOrg: [\n \"GET /organizations/{org}/settings/billing/premium_request/usage\",\n ],\n getGithubBillingPremiumRequestUsageReportUser: [\n \"GET /users/{username}/settings/billing/premium_request/usage\",\n ],\n getGithubBillingUsageReportOrg: [\n \"GET /organizations/{org}/settings/billing/usage\",\n ],\n getGithubBillingUsageReportUser: [\n \"GET /users/{username}/settings/billing/usage\",\n ],\n getGithubPackagesBillingOrg: [\"GET /orgs/{org}/settings/billing/packages\"],\n getGithubPackagesBillingUser: [\n \"GET /users/{username}/settings/billing/packages\",\n ],\n getSharedStorageBillingOrg: [\n \"GET /orgs/{org}/settings/billing/shared-storage\",\n ],\n getSharedStorageBillingUser: [\n \"GET /users/{username}/settings/billing/shared-storage\",\n ],\n },\n campaigns: {\n createCampaign: [\"POST /orgs/{org}/campaigns\"],\n deleteCampaign: [\"DELETE /orgs/{org}/campaigns/{campaign_number}\"],\n getCampaignSummary: [\"GET /orgs/{org}/campaigns/{campaign_number}\"],\n listOrgCampaigns: [\"GET /orgs/{org}/campaigns\"],\n updateCampaign: [\"PATCH /orgs/{org}/campaigns/{campaign_number}\"],\n },\n checks: {\n create: [\"POST /repos/{owner}/{repo}/check-runs\"],\n createSuite: [\"POST /repos/{owner}/{repo}/check-suites\"],\n get: [\"GET /repos/{owner}/{repo}/check-runs/{check_run_id}\"],\n getSuite: [\"GET /repos/{owner}/{repo}/check-suites/{check_suite_id}\"],\n listAnnotations: [\n \"GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations\",\n ],\n listForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/check-runs\"],\n listForSuite: [\n \"GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs\",\n ],\n listSuitesForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/check-suites\"],\n rerequestRun: [\n \"POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest\",\n ],\n rerequestSuite: [\n \"POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest\",\n ],\n setSuitesPreferences: [\n \"PATCH /repos/{owner}/{repo}/check-suites/preferences\",\n ],\n update: [\"PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}\"],\n },\n codeScanning: {\n commitAutofix: [\n \"POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix/commits\",\n ],\n createAutofix: [\n \"POST /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix\",\n ],\n createVariantAnalysis: [\n \"POST /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses\",\n ],\n deleteAnalysis: [\n \"DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}\",\n ],\n deleteCodeqlDatabase: [\n \"DELETE /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}\",\n ],\n getAlert: [\n \"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}\",\n {},\n { renamedParameters: { alert_id: \"alert_number\" } },\n ],\n getAnalysis: [\n \"GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}\",\n ],\n getAutofix: [\n \"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/autofix\",\n ],\n getCodeqlDatabase: [\n \"GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}\",\n ],\n getDefaultSetup: [\"GET /repos/{owner}/{repo}/code-scanning/default-setup\"],\n getSarif: [\"GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}\"],\n getVariantAnalysis: [\n \"GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}\",\n ],\n getVariantAnalysisRepoTask: [\n \"GET /repos/{owner}/{repo}/code-scanning/codeql/variant-analyses/{codeql_variant_analysis_id}/repos/{repo_owner}/{repo_name}\",\n ],\n listAlertInstances: [\n \"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances\",\n ],\n listAlertsForOrg: [\"GET /orgs/{org}/code-scanning/alerts\"],\n listAlertsForRepo: [\"GET /repos/{owner}/{repo}/code-scanning/alerts\"],\n listAlertsInstances: [\n \"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances\",\n {},\n { renamed: [\"codeScanning\", \"listAlertInstances\"] },\n ],\n listCodeqlDatabases: [\n \"GET /repos/{owner}/{repo}/code-scanning/codeql/databases\",\n ],\n listRecentAnalyses: [\"GET /repos/{owner}/{repo}/code-scanning/analyses\"],\n updateAlert: [\n \"PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}\",\n ],\n updateDefaultSetup: [\n \"PATCH /repos/{owner}/{repo}/code-scanning/default-setup\",\n ],\n uploadSarif: [\"POST /repos/{owner}/{repo}/code-scanning/sarifs\"],\n },\n codeSecurity: {\n attachConfiguration: [\n \"POST /orgs/{org}/code-security/configurations/{configuration_id}/attach\",\n ],\n attachEnterpriseConfiguration: [\n \"POST /enterprises/{enterprise}/code-security/configurations/{configuration_id}/attach\",\n ],\n createConfiguration: [\"POST /orgs/{org}/code-security/configurations\"],\n createConfigurationForEnterprise: [\n \"POST /enterprises/{enterprise}/code-security/configurations\",\n ],\n deleteConfiguration: [\n \"DELETE /orgs/{org}/code-security/configurations/{configuration_id}\",\n ],\n deleteConfigurationForEnterprise: [\n \"DELETE /enterprises/{enterprise}/code-security/configurations/{configuration_id}\",\n ],\n detachConfiguration: [\n \"DELETE /orgs/{org}/code-security/configurations/detach\",\n ],\n getConfiguration: [\n \"GET /orgs/{org}/code-security/configurations/{configuration_id}\",\n ],\n getConfigurationForRepository: [\n \"GET /repos/{owner}/{repo}/code-security-configuration\",\n ],\n getConfigurationsForEnterprise: [\n \"GET /enterprises/{enterprise}/code-security/configurations\",\n ],\n getConfigurationsForOrg: [\"GET /orgs/{org}/code-security/configurations\"],\n getDefaultConfigurations: [\n \"GET /orgs/{org}/code-security/configurations/defaults\",\n ],\n getDefaultConfigurationsForEnterprise: [\n \"GET /enterprises/{enterprise}/code-security/configurations/defaults\",\n ],\n getRepositoriesForConfiguration: [\n \"GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories\",\n ],\n getRepositoriesForEnterpriseConfiguration: [\n \"GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories\",\n ],\n getSingleConfigurationForEnterprise: [\n \"GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}\",\n ],\n setConfigurationAsDefault: [\n \"PUT /orgs/{org}/code-security/configurations/{configuration_id}/defaults\",\n ],\n setConfigurationAsDefaultForEnterprise: [\n \"PUT /enterprises/{enterprise}/code-security/configurations/{configuration_id}/defaults\",\n ],\n updateConfiguration: [\n \"PATCH /orgs/{org}/code-security/configurations/{configuration_id}\",\n ],\n updateEnterpriseConfiguration: [\n \"PATCH /enterprises/{enterprise}/code-security/configurations/{configuration_id}\",\n ],\n },\n codesOfConduct: {\n getAllCodesOfConduct: [\"GET /codes_of_conduct\"],\n getConductCode: [\"GET /codes_of_conduct/{key}\"],\n },\n codespaces: {\n addRepositoryForSecretForAuthenticatedUser: [\n \"PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}\",\n ],\n addSelectedRepoToOrgSecret: [\n \"PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}\",\n ],\n checkPermissionsForDevcontainer: [\n \"GET /repos/{owner}/{repo}/codespaces/permissions_check\",\n ],\n codespaceMachinesForAuthenticatedUser: [\n \"GET /user/codespaces/{codespace_name}/machines\",\n ],\n createForAuthenticatedUser: [\"POST /user/codespaces\"],\n createOrUpdateOrgSecret: [\n \"PUT /orgs/{org}/codespaces/secrets/{secret_name}\",\n ],\n createOrUpdateRepoSecret: [\n \"PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}\",\n ],\n createOrUpdateSecretForAuthenticatedUser: [\n \"PUT /user/codespaces/secrets/{secret_name}\",\n ],\n createWithPrForAuthenticatedUser: [\n \"POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces\",\n ],\n createWithRepoForAuthenticatedUser: [\n \"POST /repos/{owner}/{repo}/codespaces\",\n ],\n deleteForAuthenticatedUser: [\"DELETE /user/codespaces/{codespace_name}\"],\n deleteFromOrganization: [\n \"DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}\",\n ],\n deleteOrgSecret: [\"DELETE /orgs/{org}/codespaces/secrets/{secret_name}\"],\n deleteRepoSecret: [\n \"DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}\",\n ],\n deleteSecretForAuthenticatedUser: [\n \"DELETE /user/codespaces/secrets/{secret_name}\",\n ],\n exportForAuthenticatedUser: [\n \"POST /user/codespaces/{codespace_name}/exports\",\n ],\n getCodespacesForUserInOrg: [\n \"GET /orgs/{org}/members/{username}/codespaces\",\n ],\n getExportDetailsForAuthenticatedUser: [\n \"GET /user/codespaces/{codespace_name}/exports/{export_id}\",\n ],\n getForAuthenticatedUser: [\"GET /user/codespaces/{codespace_name}\"],\n getOrgPublicKey: [\"GET /orgs/{org}/codespaces/secrets/public-key\"],\n getOrgSecret: [\"GET /orgs/{org}/codespaces/secrets/{secret_name}\"],\n getPublicKeyForAuthenticatedUser: [\n \"GET /user/codespaces/secrets/public-key\",\n ],\n getRepoPublicKey: [\n \"GET /repos/{owner}/{repo}/codespaces/secrets/public-key\",\n ],\n getRepoSecret: [\n \"GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}\",\n ],\n getSecretForAuthenticatedUser: [\n \"GET /user/codespaces/secrets/{secret_name}\",\n ],\n listDevcontainersInRepositoryForAuthenticatedUser: [\n \"GET /repos/{owner}/{repo}/codespaces/devcontainers\",\n ],\n listForAuthenticatedUser: [\"GET /user/codespaces\"],\n listInOrganization: [\n \"GET /orgs/{org}/codespaces\",\n {},\n { renamedParameters: { org_id: \"org\" } },\n ],\n listInRepositoryForAuthenticatedUser: [\n \"GET /repos/{owner}/{repo}/codespaces\",\n ],\n listOrgSecrets: [\"GET /orgs/{org}/codespaces/secrets\"],\n listRepoSecrets: [\"GET /repos/{owner}/{repo}/codespaces/secrets\"],\n listRepositoriesForSecretForAuthenticatedUser: [\n \"GET /user/codespaces/secrets/{secret_name}/repositories\",\n ],\n listSecretsForAuthenticatedUser: [\"GET /user/codespaces/secrets\"],\n listSelectedReposForOrgSecret: [\n \"GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories\",\n ],\n preFlightWithRepoForAuthenticatedUser: [\n \"GET /repos/{owner}/{repo}/codespaces/new\",\n ],\n publishForAuthenticatedUser: [\n \"POST /user/codespaces/{codespace_name}/publish\",\n ],\n removeRepositoryForSecretForAuthenticatedUser: [\n \"DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}\",\n ],\n removeSelectedRepoFromOrgSecret: [\n \"DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}\",\n ],\n repoMachinesForAuthenticatedUser: [\n \"GET /repos/{owner}/{repo}/codespaces/machines\",\n ],\n setRepositoriesForSecretForAuthenticatedUser: [\n \"PUT /user/codespaces/secrets/{secret_name}/repositories\",\n ],\n setSelectedReposForOrgSecret: [\n \"PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories\",\n ],\n startForAuthenticatedUser: [\"POST /user/codespaces/{codespace_name}/start\"],\n stopForAuthenticatedUser: [\"POST /user/codespaces/{codespace_name}/stop\"],\n stopInOrganization: [\n \"POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop\",\n ],\n updateForAuthenticatedUser: [\"PATCH /user/codespaces/{codespace_name}\"],\n },\n copilot: {\n addCopilotSeatsForTeams: [\n \"POST /orgs/{org}/copilot/billing/selected_teams\",\n ],\n addCopilotSeatsForUsers: [\n \"POST /orgs/{org}/copilot/billing/selected_users\",\n ],\n cancelCopilotSeatAssignmentForTeams: [\n \"DELETE /orgs/{org}/copilot/billing/selected_teams\",\n ],\n cancelCopilotSeatAssignmentForUsers: [\n \"DELETE /orgs/{org}/copilot/billing/selected_users\",\n ],\n copilotMetricsForOrganization: [\"GET /orgs/{org}/copilot/metrics\"],\n copilotMetricsForTeam: [\"GET /orgs/{org}/team/{team_slug}/copilot/metrics\"],\n getCopilotOrganizationDetails: [\"GET /orgs/{org}/copilot/billing\"],\n getCopilotSeatDetailsForUser: [\n \"GET /orgs/{org}/members/{username}/copilot\",\n ],\n listCopilotSeats: [\"GET /orgs/{org}/copilot/billing/seats\"],\n },\n credentials: { revoke: [\"POST /credentials/revoke\"] },\n dependabot: {\n addSelectedRepoToOrgSecret: [\n \"PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}\",\n ],\n createOrUpdateOrgSecret: [\n \"PUT /orgs/{org}/dependabot/secrets/{secret_name}\",\n ],\n createOrUpdateRepoSecret: [\n \"PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}\",\n ],\n deleteOrgSecret: [\"DELETE /orgs/{org}/dependabot/secrets/{secret_name}\"],\n deleteRepoSecret: [\n \"DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}\",\n ],\n getAlert: [\"GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}\"],\n getOrgPublicKey: [\"GET /orgs/{org}/dependabot/secrets/public-key\"],\n getOrgSecret: [\"GET /orgs/{org}/dependabot/secrets/{secret_name}\"],\n getRepoPublicKey: [\n \"GET /repos/{owner}/{repo}/dependabot/secrets/public-key\",\n ],\n getRepoSecret: [\n \"GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}\",\n ],\n listAlertsForEnterprise: [\n \"GET /enterprises/{enterprise}/dependabot/alerts\",\n ],\n listAlertsForOrg: [\"GET /orgs/{org}/dependabot/alerts\"],\n listAlertsForRepo: [\"GET /repos/{owner}/{repo}/dependabot/alerts\"],\n listOrgSecrets: [\"GET /orgs/{org}/dependabot/secrets\"],\n listRepoSecrets: [\"GET /repos/{owner}/{repo}/dependabot/secrets\"],\n listSelectedReposForOrgSecret: [\n \"GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories\",\n ],\n removeSelectedRepoFromOrgSecret: [\n \"DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}\",\n ],\n repositoryAccessForOrg: [\n \"GET /organizations/{org}/dependabot/repository-access\",\n ],\n setRepositoryAccessDefaultLevel: [\n \"PUT /organizations/{org}/dependabot/repository-access/default-level\",\n ],\n setSelectedReposForOrgSecret: [\n \"PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories\",\n ],\n updateAlert: [\n \"PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}\",\n ],\n updateRepositoryAccessForOrg: [\n \"PATCH /organizations/{org}/dependabot/repository-access\",\n ],\n },\n dependencyGraph: {\n createRepositorySnapshot: [\n \"POST /repos/{owner}/{repo}/dependency-graph/snapshots\",\n ],\n diffRange: [\n \"GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}\",\n ],\n exportSbom: [\"GET /repos/{owner}/{repo}/dependency-graph/sbom\"],\n },\n emojis: { get: [\"GET /emojis\"] },\n enterpriseTeamMemberships: {\n add: [\n \"PUT /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}\",\n ],\n bulkAdd: [\n \"POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/add\",\n ],\n bulkRemove: [\n \"POST /enterprises/{enterprise}/teams/{enterprise-team}/memberships/remove\",\n ],\n get: [\n \"GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}\",\n ],\n list: [\"GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships\"],\n remove: [\n \"DELETE /enterprises/{enterprise}/teams/{enterprise-team}/memberships/{username}\",\n ],\n },\n enterpriseTeamOrganizations: {\n add: [\n \"PUT /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}\",\n ],\n bulkAdd: [\n \"POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/add\",\n ],\n bulkRemove: [\n \"POST /enterprises/{enterprise}/teams/{enterprise-team}/organizations/remove\",\n ],\n delete: [\n \"DELETE /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}\",\n ],\n getAssignment: [\n \"GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations/{org}\",\n ],\n getAssignments: [\n \"GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations\",\n ],\n },\n enterpriseTeams: {\n create: [\"POST /enterprises/{enterprise}/teams\"],\n delete: [\"DELETE /enterprises/{enterprise}/teams/{team_slug}\"],\n get: [\"GET /enterprises/{enterprise}/teams/{team_slug}\"],\n list: [\"GET /enterprises/{enterprise}/teams\"],\n update: [\"PATCH /enterprises/{enterprise}/teams/{team_slug}\"],\n },\n gists: {\n checkIsStarred: [\"GET /gists/{gist_id}/star\"],\n create: [\"POST /gists\"],\n createComment: [\"POST /gists/{gist_id}/comments\"],\n delete: [\"DELETE /gists/{gist_id}\"],\n deleteComment: [\"DELETE /gists/{gist_id}/comments/{comment_id}\"],\n fork: [\"POST /gists/{gist_id}/forks\"],\n get: [\"GET /gists/{gist_id}\"],\n getComment: [\"GET /gists/{gist_id}/comments/{comment_id}\"],\n getRevision: [\"GET /gists/{gist_id}/{sha}\"],\n list: [\"GET /gists\"],\n listComments: [\"GET /gists/{gist_id}/comments\"],\n listCommits: [\"GET /gists/{gist_id}/commits\"],\n listForUser: [\"GET /users/{username}/gists\"],\n listForks: [\"GET /gists/{gist_id}/forks\"],\n listPublic: [\"GET /gists/public\"],\n listStarred: [\"GET /gists/starred\"],\n star: [\"PUT /gists/{gist_id}/star\"],\n unstar: [\"DELETE /gists/{gist_id}/star\"],\n update: [\"PATCH /gists/{gist_id}\"],\n updateComment: [\"PATCH /gists/{gist_id}/comments/{comment_id}\"],\n },\n git: {\n createBlob: [\"POST /repos/{owner}/{repo}/git/blobs\"],\n createCommit: [\"POST /repos/{owner}/{repo}/git/commits\"],\n createRef: [\"POST /repos/{owner}/{repo}/git/refs\"],\n createTag: [\"POST /repos/{owner}/{repo}/git/tags\"],\n createTree: [\"POST /repos/{owner}/{repo}/git/trees\"],\n deleteRef: [\"DELETE /repos/{owner}/{repo}/git/refs/{ref}\"],\n getBlob: [\"GET /repos/{owner}/{repo}/git/blobs/{file_sha}\"],\n getCommit: [\"GET /repos/{owner}/{repo}/git/commits/{commit_sha}\"],\n getRef: [\"GET /repos/{owner}/{repo}/git/ref/{ref}\"],\n getTag: [\"GET /repos/{owner}/{repo}/git/tags/{tag_sha}\"],\n getTree: [\"GET /repos/{owner}/{repo}/git/trees/{tree_sha}\"],\n listMatchingRefs: [\"GET /repos/{owner}/{repo}/git/matching-refs/{ref}\"],\n updateRef: [\"PATCH /repos/{owner}/{repo}/git/refs/{ref}\"],\n },\n gitignore: {\n getAllTemplates: [\"GET /gitignore/templates\"],\n getTemplate: [\"GET /gitignore/templates/{name}\"],\n },\n hostedCompute: {\n createNetworkConfigurationForOrg: [\n \"POST /orgs/{org}/settings/network-configurations\",\n ],\n deleteNetworkConfigurationFromOrg: [\n \"DELETE /orgs/{org}/settings/network-configurations/{network_configuration_id}\",\n ],\n getNetworkConfigurationForOrg: [\n \"GET /orgs/{org}/settings/network-configurations/{network_configuration_id}\",\n ],\n getNetworkSettingsForOrg: [\n \"GET /orgs/{org}/settings/network-settings/{network_settings_id}\",\n ],\n listNetworkConfigurationsForOrg: [\n \"GET /orgs/{org}/settings/network-configurations\",\n ],\n updateNetworkConfigurationForOrg: [\n \"PATCH /orgs/{org}/settings/network-configurations/{network_configuration_id}\",\n ],\n },\n interactions: {\n getRestrictionsForAuthenticatedUser: [\"GET /user/interaction-limits\"],\n getRestrictionsForOrg: [\"GET /orgs/{org}/interaction-limits\"],\n getRestrictionsForRepo: [\"GET /repos/{owner}/{repo}/interaction-limits\"],\n getRestrictionsForYourPublicRepos: [\n \"GET /user/interaction-limits\",\n {},\n { renamed: [\"interactions\", \"getRestrictionsForAuthenticatedUser\"] },\n ],\n removeRestrictionsForAuthenticatedUser: [\"DELETE /user/interaction-limits\"],\n removeRestrictionsForOrg: [\"DELETE /orgs/{org}/interaction-limits\"],\n removeRestrictionsForRepo: [\n \"DELETE /repos/{owner}/{repo}/interaction-limits\",\n ],\n removeRestrictionsForYourPublicRepos: [\n \"DELETE /user/interaction-limits\",\n {},\n { renamed: [\"interactions\", \"removeRestrictionsForAuthenticatedUser\"] },\n ],\n setRestrictionsForAuthenticatedUser: [\"PUT /user/interaction-limits\"],\n setRestrictionsForOrg: [\"PUT /orgs/{org}/interaction-limits\"],\n setRestrictionsForRepo: [\"PUT /repos/{owner}/{repo}/interaction-limits\"],\n setRestrictionsForYourPublicRepos: [\n \"PUT /user/interaction-limits\",\n {},\n { renamed: [\"interactions\", \"setRestrictionsForAuthenticatedUser\"] },\n ],\n },\n issues: {\n addAssignees: [\n \"POST /repos/{owner}/{repo}/issues/{issue_number}/assignees\",\n ],\n addBlockedByDependency: [\n \"POST /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by\",\n ],\n addLabels: [\"POST /repos/{owner}/{repo}/issues/{issue_number}/labels\"],\n addSubIssue: [\n \"POST /repos/{owner}/{repo}/issues/{issue_number}/sub_issues\",\n ],\n checkUserCanBeAssigned: [\"GET /repos/{owner}/{repo}/assignees/{assignee}\"],\n checkUserCanBeAssignedToIssue: [\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}\",\n ],\n create: [\"POST /repos/{owner}/{repo}/issues\"],\n createComment: [\n \"POST /repos/{owner}/{repo}/issues/{issue_number}/comments\",\n ],\n createLabel: [\"POST /repos/{owner}/{repo}/labels\"],\n createMilestone: [\"POST /repos/{owner}/{repo}/milestones\"],\n deleteComment: [\n \"DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}\",\n ],\n deleteLabel: [\"DELETE /repos/{owner}/{repo}/labels/{name}\"],\n deleteMilestone: [\n \"DELETE /repos/{owner}/{repo}/milestones/{milestone_number}\",\n ],\n get: [\"GET /repos/{owner}/{repo}/issues/{issue_number}\"],\n getComment: [\"GET /repos/{owner}/{repo}/issues/comments/{comment_id}\"],\n getEvent: [\"GET /repos/{owner}/{repo}/issues/events/{event_id}\"],\n getLabel: [\"GET /repos/{owner}/{repo}/labels/{name}\"],\n getMilestone: [\"GET /repos/{owner}/{repo}/milestones/{milestone_number}\"],\n getParent: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/parent\"],\n list: [\"GET /issues\"],\n listAssignees: [\"GET /repos/{owner}/{repo}/assignees\"],\n listComments: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/comments\"],\n listCommentsForRepo: [\"GET /repos/{owner}/{repo}/issues/comments\"],\n listDependenciesBlockedBy: [\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by\",\n ],\n listDependenciesBlocking: [\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking\",\n ],\n listEvents: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/events\"],\n listEventsForRepo: [\"GET /repos/{owner}/{repo}/issues/events\"],\n listEventsForTimeline: [\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/timeline\",\n ],\n listForAuthenticatedUser: [\"GET /user/issues\"],\n listForOrg: [\"GET /orgs/{org}/issues\"],\n listForRepo: [\"GET /repos/{owner}/{repo}/issues\"],\n listLabelsForMilestone: [\n \"GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels\",\n ],\n listLabelsForRepo: [\"GET /repos/{owner}/{repo}/labels\"],\n listLabelsOnIssue: [\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/labels\",\n ],\n listMilestones: [\"GET /repos/{owner}/{repo}/milestones\"],\n listSubIssues: [\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues\",\n ],\n lock: [\"PUT /repos/{owner}/{repo}/issues/{issue_number}/lock\"],\n removeAllLabels: [\n \"DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels\",\n ],\n removeAssignees: [\n \"DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees\",\n ],\n removeDependencyBlockedBy: [\n \"DELETE /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by/{issue_id}\",\n ],\n removeLabel: [\n \"DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}\",\n ],\n removeSubIssue: [\n \"DELETE /repos/{owner}/{repo}/issues/{issue_number}/sub_issue\",\n ],\n reprioritizeSubIssue: [\n \"PATCH /repos/{owner}/{repo}/issues/{issue_number}/sub_issues/priority\",\n ],\n setLabels: [\"PUT /repos/{owner}/{repo}/issues/{issue_number}/labels\"],\n unlock: [\"DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock\"],\n update: [\"PATCH /repos/{owner}/{repo}/issues/{issue_number}\"],\n updateComment: [\"PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}\"],\n updateLabel: [\"PATCH /repos/{owner}/{repo}/labels/{name}\"],\n updateMilestone: [\n \"PATCH /repos/{owner}/{repo}/milestones/{milestone_number}\",\n ],\n },\n licenses: {\n get: [\"GET /licenses/{license}\"],\n getAllCommonlyUsed: [\"GET /licenses\"],\n getForRepo: [\"GET /repos/{owner}/{repo}/license\"],\n },\n markdown: {\n render: [\"POST /markdown\"],\n renderRaw: [\n \"POST /markdown/raw\",\n { headers: { \"content-type\": \"text/plain; charset=utf-8\" } },\n ],\n },\n meta: {\n get: [\"GET /meta\"],\n getAllVersions: [\"GET /versions\"],\n getOctocat: [\"GET /octocat\"],\n getZen: [\"GET /zen\"],\n root: [\"GET /\"],\n },\n migrations: {\n deleteArchiveForAuthenticatedUser: [\n \"DELETE /user/migrations/{migration_id}/archive\",\n ],\n deleteArchiveForOrg: [\n \"DELETE /orgs/{org}/migrations/{migration_id}/archive\",\n ],\n downloadArchiveForOrg: [\n \"GET /orgs/{org}/migrations/{migration_id}/archive\",\n ],\n getArchiveForAuthenticatedUser: [\n \"GET /user/migrations/{migration_id}/archive\",\n ],\n getStatusForAuthenticatedUser: [\"GET /user/migrations/{migration_id}\"],\n getStatusForOrg: [\"GET /orgs/{org}/migrations/{migration_id}\"],\n listForAuthenticatedUser: [\"GET /user/migrations\"],\n listForOrg: [\"GET /orgs/{org}/migrations\"],\n listReposForAuthenticatedUser: [\n \"GET /user/migrations/{migration_id}/repositories\",\n ],\n listReposForOrg: [\"GET /orgs/{org}/migrations/{migration_id}/repositories\"],\n listReposForUser: [\n \"GET /user/migrations/{migration_id}/repositories\",\n {},\n { renamed: [\"migrations\", \"listReposForAuthenticatedUser\"] },\n ],\n startForAuthenticatedUser: [\"POST /user/migrations\"],\n startForOrg: [\"POST /orgs/{org}/migrations\"],\n unlockRepoForAuthenticatedUser: [\n \"DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock\",\n ],\n unlockRepoForOrg: [\n \"DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock\",\n ],\n },\n oidc: {\n getOidcCustomSubTemplateForOrg: [\n \"GET /orgs/{org}/actions/oidc/customization/sub\",\n ],\n updateOidcCustomSubTemplateForOrg: [\n \"PUT /orgs/{org}/actions/oidc/customization/sub\",\n ],\n },\n orgs: {\n addSecurityManagerTeam: [\n \"PUT /orgs/{org}/security-managers/teams/{team_slug}\",\n {},\n {\n deprecated:\n \"octokit.rest.orgs.addSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#add-a-security-manager-team\",\n },\n ],\n assignTeamToOrgRole: [\n \"PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}\",\n ],\n assignUserToOrgRole: [\n \"PUT /orgs/{org}/organization-roles/users/{username}/{role_id}\",\n ],\n blockUser: [\"PUT /orgs/{org}/blocks/{username}\"],\n cancelInvitation: [\"DELETE /orgs/{org}/invitations/{invitation_id}\"],\n checkBlockedUser: [\"GET /orgs/{org}/blocks/{username}\"],\n checkMembershipForUser: [\"GET /orgs/{org}/members/{username}\"],\n checkPublicMembershipForUser: [\"GET /orgs/{org}/public_members/{username}\"],\n convertMemberToOutsideCollaborator: [\n \"PUT /orgs/{org}/outside_collaborators/{username}\",\n ],\n createArtifactStorageRecord: [\n \"POST /orgs/{org}/artifacts/metadata/storage-record\",\n ],\n createInvitation: [\"POST /orgs/{org}/invitations\"],\n createIssueType: [\"POST /orgs/{org}/issue-types\"],\n createWebhook: [\"POST /orgs/{org}/hooks\"],\n customPropertiesForOrgsCreateOrUpdateOrganizationValues: [\n \"PATCH /organizations/{org}/org-properties/values\",\n ],\n customPropertiesForOrgsGetOrganizationValues: [\n \"GET /organizations/{org}/org-properties/values\",\n ],\n customPropertiesForReposCreateOrUpdateOrganizationDefinition: [\n \"PUT /orgs/{org}/properties/schema/{custom_property_name}\",\n ],\n customPropertiesForReposCreateOrUpdateOrganizationDefinitions: [\n \"PATCH /orgs/{org}/properties/schema\",\n ],\n customPropertiesForReposCreateOrUpdateOrganizationValues: [\n \"PATCH /orgs/{org}/properties/values\",\n ],\n customPropertiesForReposDeleteOrganizationDefinition: [\n \"DELETE /orgs/{org}/properties/schema/{custom_property_name}\",\n ],\n customPropertiesForReposGetOrganizationDefinition: [\n \"GET /orgs/{org}/properties/schema/{custom_property_name}\",\n ],\n customPropertiesForReposGetOrganizationDefinitions: [\n \"GET /orgs/{org}/properties/schema\",\n ],\n customPropertiesForReposGetOrganizationValues: [\n \"GET /orgs/{org}/properties/values\",\n ],\n delete: [\"DELETE /orgs/{org}\"],\n deleteAttestationsBulk: [\"POST /orgs/{org}/attestations/delete-request\"],\n deleteAttestationsById: [\n \"DELETE /orgs/{org}/attestations/{attestation_id}\",\n ],\n deleteAttestationsBySubjectDigest: [\n \"DELETE /orgs/{org}/attestations/digest/{subject_digest}\",\n ],\n deleteIssueType: [\"DELETE /orgs/{org}/issue-types/{issue_type_id}\"],\n deleteWebhook: [\"DELETE /orgs/{org}/hooks/{hook_id}\"],\n disableSelectedRepositoryImmutableReleasesOrganization: [\n \"DELETE /orgs/{org}/settings/immutable-releases/repositories/{repository_id}\",\n ],\n enableSelectedRepositoryImmutableReleasesOrganization: [\n \"PUT /orgs/{org}/settings/immutable-releases/repositories/{repository_id}\",\n ],\n get: [\"GET /orgs/{org}\"],\n getImmutableReleasesSettings: [\n \"GET /orgs/{org}/settings/immutable-releases\",\n ],\n getImmutableReleasesSettingsRepositories: [\n \"GET /orgs/{org}/settings/immutable-releases/repositories\",\n ],\n getMembershipForAuthenticatedUser: [\"GET /user/memberships/orgs/{org}\"],\n getMembershipForUser: [\"GET /orgs/{org}/memberships/{username}\"],\n getOrgRole: [\"GET /orgs/{org}/organization-roles/{role_id}\"],\n getOrgRulesetHistory: [\"GET /orgs/{org}/rulesets/{ruleset_id}/history\"],\n getOrgRulesetVersion: [\n \"GET /orgs/{org}/rulesets/{ruleset_id}/history/{version_id}\",\n ],\n getWebhook: [\"GET /orgs/{org}/hooks/{hook_id}\"],\n getWebhookConfigForOrg: [\"GET /orgs/{org}/hooks/{hook_id}/config\"],\n getWebhookDelivery: [\n \"GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}\",\n ],\n list: [\"GET /organizations\"],\n listAppInstallations: [\"GET /orgs/{org}/installations\"],\n listArtifactStorageRecords: [\n \"GET /orgs/{org}/artifacts/{subject_digest}/metadata/storage-records\",\n ],\n listAttestationRepositories: [\"GET /orgs/{org}/attestations/repositories\"],\n listAttestations: [\"GET /orgs/{org}/attestations/{subject_digest}\"],\n listAttestationsBulk: [\n \"POST /orgs/{org}/attestations/bulk-list{?per_page,before,after}\",\n ],\n listBlockedUsers: [\"GET /orgs/{org}/blocks\"],\n listFailedInvitations: [\"GET /orgs/{org}/failed_invitations\"],\n listForAuthenticatedUser: [\"GET /user/orgs\"],\n listForUser: [\"GET /users/{username}/orgs\"],\n listInvitationTeams: [\"GET /orgs/{org}/invitations/{invitation_id}/teams\"],\n listIssueTypes: [\"GET /orgs/{org}/issue-types\"],\n listMembers: [\"GET /orgs/{org}/members\"],\n listMembershipsForAuthenticatedUser: [\"GET /user/memberships/orgs\"],\n listOrgRoleTeams: [\"GET /orgs/{org}/organization-roles/{role_id}/teams\"],\n listOrgRoleUsers: [\"GET /orgs/{org}/organization-roles/{role_id}/users\"],\n listOrgRoles: [\"GET /orgs/{org}/organization-roles\"],\n listOrganizationFineGrainedPermissions: [\n \"GET /orgs/{org}/organization-fine-grained-permissions\",\n ],\n listOutsideCollaborators: [\"GET /orgs/{org}/outside_collaborators\"],\n listPatGrantRepositories: [\n \"GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories\",\n ],\n listPatGrantRequestRepositories: [\n \"GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories\",\n ],\n listPatGrantRequests: [\"GET /orgs/{org}/personal-access-token-requests\"],\n listPatGrants: [\"GET /orgs/{org}/personal-access-tokens\"],\n listPendingInvitations: [\"GET /orgs/{org}/invitations\"],\n listPublicMembers: [\"GET /orgs/{org}/public_members\"],\n listSecurityManagerTeams: [\n \"GET /orgs/{org}/security-managers\",\n {},\n {\n deprecated:\n \"octokit.rest.orgs.listSecurityManagerTeams() is deprecated, see https://docs.github.com/rest/orgs/security-managers#list-security-manager-teams\",\n },\n ],\n listWebhookDeliveries: [\"GET /orgs/{org}/hooks/{hook_id}/deliveries\"],\n listWebhooks: [\"GET /orgs/{org}/hooks\"],\n pingWebhook: [\"POST /orgs/{org}/hooks/{hook_id}/pings\"],\n redeliverWebhookDelivery: [\n \"POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts\",\n ],\n removeMember: [\"DELETE /orgs/{org}/members/{username}\"],\n removeMembershipForUser: [\"DELETE /orgs/{org}/memberships/{username}\"],\n removeOutsideCollaborator: [\n \"DELETE /orgs/{org}/outside_collaborators/{username}\",\n ],\n removePublicMembershipForAuthenticatedUser: [\n \"DELETE /orgs/{org}/public_members/{username}\",\n ],\n removeSecurityManagerTeam: [\n \"DELETE /orgs/{org}/security-managers/teams/{team_slug}\",\n {},\n {\n deprecated:\n \"octokit.rest.orgs.removeSecurityManagerTeam() is deprecated, see https://docs.github.com/rest/orgs/security-managers#remove-a-security-manager-team\",\n },\n ],\n reviewPatGrantRequest: [\n \"POST /orgs/{org}/personal-access-token-requests/{pat_request_id}\",\n ],\n reviewPatGrantRequestsInBulk: [\n \"POST /orgs/{org}/personal-access-token-requests\",\n ],\n revokeAllOrgRolesTeam: [\n \"DELETE /orgs/{org}/organization-roles/teams/{team_slug}\",\n ],\n revokeAllOrgRolesUser: [\n \"DELETE /orgs/{org}/organization-roles/users/{username}\",\n ],\n revokeOrgRoleTeam: [\n \"DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}\",\n ],\n revokeOrgRoleUser: [\n \"DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}\",\n ],\n setImmutableReleasesSettings: [\n \"PUT /orgs/{org}/settings/immutable-releases\",\n ],\n setImmutableReleasesSettingsRepositories: [\n \"PUT /orgs/{org}/settings/immutable-releases/repositories\",\n ],\n setMembershipForUser: [\"PUT /orgs/{org}/memberships/{username}\"],\n setPublicMembershipForAuthenticatedUser: [\n \"PUT /orgs/{org}/public_members/{username}\",\n ],\n unblockUser: [\"DELETE /orgs/{org}/blocks/{username}\"],\n update: [\"PATCH /orgs/{org}\"],\n updateIssueType: [\"PUT /orgs/{org}/issue-types/{issue_type_id}\"],\n updateMembershipForAuthenticatedUser: [\n \"PATCH /user/memberships/orgs/{org}\",\n ],\n updatePatAccess: [\"POST /orgs/{org}/personal-access-tokens/{pat_id}\"],\n updatePatAccesses: [\"POST /orgs/{org}/personal-access-tokens\"],\n updateWebhook: [\"PATCH /orgs/{org}/hooks/{hook_id}\"],\n updateWebhookConfigForOrg: [\"PATCH /orgs/{org}/hooks/{hook_id}/config\"],\n },\n packages: {\n deletePackageForAuthenticatedUser: [\n \"DELETE /user/packages/{package_type}/{package_name}\",\n ],\n deletePackageForOrg: [\n \"DELETE /orgs/{org}/packages/{package_type}/{package_name}\",\n ],\n deletePackageForUser: [\n \"DELETE /users/{username}/packages/{package_type}/{package_name}\",\n ],\n deletePackageVersionForAuthenticatedUser: [\n \"DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}\",\n ],\n deletePackageVersionForOrg: [\n \"DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}\",\n ],\n deletePackageVersionForUser: [\n \"DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}\",\n ],\n getAllPackageVersionsForAPackageOwnedByAnOrg: [\n \"GET /orgs/{org}/packages/{package_type}/{package_name}/versions\",\n {},\n { renamed: [\"packages\", \"getAllPackageVersionsForPackageOwnedByOrg\"] },\n ],\n getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [\n \"GET /user/packages/{package_type}/{package_name}/versions\",\n {},\n {\n renamed: [\n \"packages\",\n \"getAllPackageVersionsForPackageOwnedByAuthenticatedUser\",\n ],\n },\n ],\n getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [\n \"GET /user/packages/{package_type}/{package_name}/versions\",\n ],\n getAllPackageVersionsForPackageOwnedByOrg: [\n \"GET /orgs/{org}/packages/{package_type}/{package_name}/versions\",\n ],\n getAllPackageVersionsForPackageOwnedByUser: [\n \"GET /users/{username}/packages/{package_type}/{package_name}/versions\",\n ],\n getPackageForAuthenticatedUser: [\n \"GET /user/packages/{package_type}/{package_name}\",\n ],\n getPackageForOrganization: [\n \"GET /orgs/{org}/packages/{package_type}/{package_name}\",\n ],\n getPackageForUser: [\n \"GET /users/{username}/packages/{package_type}/{package_name}\",\n ],\n getPackageVersionForAuthenticatedUser: [\n \"GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}\",\n ],\n getPackageVersionForOrganization: [\n \"GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}\",\n ],\n getPackageVersionForUser: [\n \"GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}\",\n ],\n listDockerMigrationConflictingPackagesForAuthenticatedUser: [\n \"GET /user/docker/conflicts\",\n ],\n listDockerMigrationConflictingPackagesForOrganization: [\n \"GET /orgs/{org}/docker/conflicts\",\n ],\n listDockerMigrationConflictingPackagesForUser: [\n \"GET /users/{username}/docker/conflicts\",\n ],\n listPackagesForAuthenticatedUser: [\"GET /user/packages\"],\n listPackagesForOrganization: [\"GET /orgs/{org}/packages\"],\n listPackagesForUser: [\"GET /users/{username}/packages\"],\n restorePackageForAuthenticatedUser: [\n \"POST /user/packages/{package_type}/{package_name}/restore{?token}\",\n ],\n restorePackageForOrg: [\n \"POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}\",\n ],\n restorePackageForUser: [\n \"POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}\",\n ],\n restorePackageVersionForAuthenticatedUser: [\n \"POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore\",\n ],\n restorePackageVersionForOrg: [\n \"POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore\",\n ],\n restorePackageVersionForUser: [\n \"POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore\",\n ],\n },\n privateRegistries: {\n createOrgPrivateRegistry: [\"POST /orgs/{org}/private-registries\"],\n deleteOrgPrivateRegistry: [\n \"DELETE /orgs/{org}/private-registries/{secret_name}\",\n ],\n getOrgPrivateRegistry: [\"GET /orgs/{org}/private-registries/{secret_name}\"],\n getOrgPublicKey: [\"GET /orgs/{org}/private-registries/public-key\"],\n listOrgPrivateRegistries: [\"GET /orgs/{org}/private-registries\"],\n updateOrgPrivateRegistry: [\n \"PATCH /orgs/{org}/private-registries/{secret_name}\",\n ],\n },\n projects: {\n addItemForOrg: [\"POST /orgs/{org}/projectsV2/{project_number}/items\"],\n addItemForUser: [\n \"POST /users/{username}/projectsV2/{project_number}/items\",\n ],\n deleteItemForOrg: [\n \"DELETE /orgs/{org}/projectsV2/{project_number}/items/{item_id}\",\n ],\n deleteItemForUser: [\n \"DELETE /users/{username}/projectsV2/{project_number}/items/{item_id}\",\n ],\n getFieldForOrg: [\n \"GET /orgs/{org}/projectsV2/{project_number}/fields/{field_id}\",\n ],\n getFieldForUser: [\n \"GET /users/{username}/projectsV2/{project_number}/fields/{field_id}\",\n ],\n getForOrg: [\"GET /orgs/{org}/projectsV2/{project_number}\"],\n getForUser: [\"GET /users/{username}/projectsV2/{project_number}\"],\n getOrgItem: [\"GET /orgs/{org}/projectsV2/{project_number}/items/{item_id}\"],\n getUserItem: [\n \"GET /users/{username}/projectsV2/{project_number}/items/{item_id}\",\n ],\n listFieldsForOrg: [\"GET /orgs/{org}/projectsV2/{project_number}/fields\"],\n listFieldsForUser: [\n \"GET /users/{username}/projectsV2/{project_number}/fields\",\n ],\n listForOrg: [\"GET /orgs/{org}/projectsV2\"],\n listForUser: [\"GET /users/{username}/projectsV2\"],\n listItemsForOrg: [\"GET /orgs/{org}/projectsV2/{project_number}/items\"],\n listItemsForUser: [\n \"GET /users/{username}/projectsV2/{project_number}/items\",\n ],\n updateItemForOrg: [\n \"PATCH /orgs/{org}/projectsV2/{project_number}/items/{item_id}\",\n ],\n updateItemForUser: [\n \"PATCH /users/{username}/projectsV2/{project_number}/items/{item_id}\",\n ],\n },\n pulls: {\n checkIfMerged: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/merge\"],\n create: [\"POST /repos/{owner}/{repo}/pulls\"],\n createReplyForReviewComment: [\n \"POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies\",\n ],\n createReview: [\"POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews\"],\n createReviewComment: [\n \"POST /repos/{owner}/{repo}/pulls/{pull_number}/comments\",\n ],\n deletePendingReview: [\n \"DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\",\n ],\n deleteReviewComment: [\n \"DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}\",\n ],\n dismissReview: [\n \"PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals\",\n ],\n get: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}\"],\n getReview: [\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\",\n ],\n getReviewComment: [\"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}\"],\n list: [\"GET /repos/{owner}/{repo}/pulls\"],\n listCommentsForReview: [\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments\",\n ],\n listCommits: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/commits\"],\n listFiles: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/files\"],\n listRequestedReviewers: [\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\",\n ],\n listReviewComments: [\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/comments\",\n ],\n listReviewCommentsForRepo: [\"GET /repos/{owner}/{repo}/pulls/comments\"],\n listReviews: [\"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews\"],\n merge: [\"PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge\"],\n removeRequestedReviewers: [\n \"DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\",\n ],\n requestReviewers: [\n \"POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers\",\n ],\n submitReview: [\n \"POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events\",\n ],\n update: [\"PATCH /repos/{owner}/{repo}/pulls/{pull_number}\"],\n updateBranch: [\n \"PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch\",\n ],\n updateReview: [\n \"PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}\",\n ],\n updateReviewComment: [\n \"PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}\",\n ],\n },\n rateLimit: { get: [\"GET /rate_limit\"] },\n reactions: {\n createForCommitComment: [\n \"POST /repos/{owner}/{repo}/comments/{comment_id}/reactions\",\n ],\n createForIssue: [\n \"POST /repos/{owner}/{repo}/issues/{issue_number}/reactions\",\n ],\n createForIssueComment: [\n \"POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions\",\n ],\n createForPullRequestReviewComment: [\n \"POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions\",\n ],\n createForRelease: [\n \"POST /repos/{owner}/{repo}/releases/{release_id}/reactions\",\n ],\n createForTeamDiscussionCommentInOrg: [\n \"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions\",\n ],\n createForTeamDiscussionInOrg: [\n \"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions\",\n ],\n deleteForCommitComment: [\n \"DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}\",\n ],\n deleteForIssue: [\n \"DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}\",\n ],\n deleteForIssueComment: [\n \"DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}\",\n ],\n deleteForPullRequestComment: [\n \"DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}\",\n ],\n deleteForRelease: [\n \"DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}\",\n ],\n deleteForTeamDiscussion: [\n \"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}\",\n ],\n deleteForTeamDiscussionComment: [\n \"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}\",\n ],\n listForCommitComment: [\n \"GET /repos/{owner}/{repo}/comments/{comment_id}/reactions\",\n ],\n listForIssue: [\"GET /repos/{owner}/{repo}/issues/{issue_number}/reactions\"],\n listForIssueComment: [\n \"GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions\",\n ],\n listForPullRequestReviewComment: [\n \"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions\",\n ],\n listForRelease: [\n \"GET /repos/{owner}/{repo}/releases/{release_id}/reactions\",\n ],\n listForTeamDiscussionCommentInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions\",\n ],\n listForTeamDiscussionInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions\",\n ],\n },\n repos: {\n acceptInvitation: [\n \"PATCH /user/repository_invitations/{invitation_id}\",\n {},\n { renamed: [\"repos\", \"acceptInvitationForAuthenticatedUser\"] },\n ],\n acceptInvitationForAuthenticatedUser: [\n \"PATCH /user/repository_invitations/{invitation_id}\",\n ],\n addAppAccessRestrictions: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\",\n {},\n { mapToData: \"apps\" },\n ],\n addCollaborator: [\"PUT /repos/{owner}/{repo}/collaborators/{username}\"],\n addStatusCheckContexts: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\",\n {},\n { mapToData: \"contexts\" },\n ],\n addTeamAccessRestrictions: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\",\n {},\n { mapToData: \"teams\" },\n ],\n addUserAccessRestrictions: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\",\n {},\n { mapToData: \"users\" },\n ],\n cancelPagesDeployment: [\n \"POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel\",\n ],\n checkAutomatedSecurityFixes: [\n \"GET /repos/{owner}/{repo}/automated-security-fixes\",\n ],\n checkCollaborator: [\"GET /repos/{owner}/{repo}/collaborators/{username}\"],\n checkImmutableReleases: [\"GET /repos/{owner}/{repo}/immutable-releases\"],\n checkPrivateVulnerabilityReporting: [\n \"GET /repos/{owner}/{repo}/private-vulnerability-reporting\",\n ],\n checkVulnerabilityAlerts: [\n \"GET /repos/{owner}/{repo}/vulnerability-alerts\",\n ],\n codeownersErrors: [\"GET /repos/{owner}/{repo}/codeowners/errors\"],\n compareCommits: [\"GET /repos/{owner}/{repo}/compare/{base}...{head}\"],\n compareCommitsWithBasehead: [\n \"GET /repos/{owner}/{repo}/compare/{basehead}\",\n ],\n createAttestation: [\"POST /repos/{owner}/{repo}/attestations\"],\n createAutolink: [\"POST /repos/{owner}/{repo}/autolinks\"],\n createCommitComment: [\n \"POST /repos/{owner}/{repo}/commits/{commit_sha}/comments\",\n ],\n createCommitSignatureProtection: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\",\n ],\n createCommitStatus: [\"POST /repos/{owner}/{repo}/statuses/{sha}\"],\n createDeployKey: [\"POST /repos/{owner}/{repo}/keys\"],\n createDeployment: [\"POST /repos/{owner}/{repo}/deployments\"],\n createDeploymentBranchPolicy: [\n \"POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies\",\n ],\n createDeploymentProtectionRule: [\n \"POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules\",\n ],\n createDeploymentStatus: [\n \"POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses\",\n ],\n createDispatchEvent: [\"POST /repos/{owner}/{repo}/dispatches\"],\n createForAuthenticatedUser: [\"POST /user/repos\"],\n createFork: [\"POST /repos/{owner}/{repo}/forks\"],\n createInOrg: [\"POST /orgs/{org}/repos\"],\n createOrUpdateEnvironment: [\n \"PUT /repos/{owner}/{repo}/environments/{environment_name}\",\n ],\n createOrUpdateFileContents: [\"PUT /repos/{owner}/{repo}/contents/{path}\"],\n createOrgRuleset: [\"POST /orgs/{org}/rulesets\"],\n createPagesDeployment: [\"POST /repos/{owner}/{repo}/pages/deployments\"],\n createPagesSite: [\"POST /repos/{owner}/{repo}/pages\"],\n createRelease: [\"POST /repos/{owner}/{repo}/releases\"],\n createRepoRuleset: [\"POST /repos/{owner}/{repo}/rulesets\"],\n createUsingTemplate: [\n \"POST /repos/{template_owner}/{template_repo}/generate\",\n ],\n createWebhook: [\"POST /repos/{owner}/{repo}/hooks\"],\n customPropertiesForReposCreateOrUpdateRepositoryValues: [\n \"PATCH /repos/{owner}/{repo}/properties/values\",\n ],\n customPropertiesForReposGetRepositoryValues: [\n \"GET /repos/{owner}/{repo}/properties/values\",\n ],\n declineInvitation: [\n \"DELETE /user/repository_invitations/{invitation_id}\",\n {},\n { renamed: [\"repos\", \"declineInvitationForAuthenticatedUser\"] },\n ],\n declineInvitationForAuthenticatedUser: [\n \"DELETE /user/repository_invitations/{invitation_id}\",\n ],\n delete: [\"DELETE /repos/{owner}/{repo}\"],\n deleteAccessRestrictions: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions\",\n ],\n deleteAdminBranchProtection: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\",\n ],\n deleteAnEnvironment: [\n \"DELETE /repos/{owner}/{repo}/environments/{environment_name}\",\n ],\n deleteAutolink: [\"DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}\"],\n deleteBranchProtection: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection\",\n ],\n deleteCommitComment: [\"DELETE /repos/{owner}/{repo}/comments/{comment_id}\"],\n deleteCommitSignatureProtection: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\",\n ],\n deleteDeployKey: [\"DELETE /repos/{owner}/{repo}/keys/{key_id}\"],\n deleteDeployment: [\n \"DELETE /repos/{owner}/{repo}/deployments/{deployment_id}\",\n ],\n deleteDeploymentBranchPolicy: [\n \"DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}\",\n ],\n deleteFile: [\"DELETE /repos/{owner}/{repo}/contents/{path}\"],\n deleteInvitation: [\n \"DELETE /repos/{owner}/{repo}/invitations/{invitation_id}\",\n ],\n deleteOrgRuleset: [\"DELETE /orgs/{org}/rulesets/{ruleset_id}\"],\n deletePagesSite: [\"DELETE /repos/{owner}/{repo}/pages\"],\n deletePullRequestReviewProtection: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\",\n ],\n deleteRelease: [\"DELETE /repos/{owner}/{repo}/releases/{release_id}\"],\n deleteReleaseAsset: [\n \"DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}\",\n ],\n deleteRepoRuleset: [\"DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}\"],\n deleteWebhook: [\"DELETE /repos/{owner}/{repo}/hooks/{hook_id}\"],\n disableAutomatedSecurityFixes: [\n \"DELETE /repos/{owner}/{repo}/automated-security-fixes\",\n ],\n disableDeploymentProtectionRule: [\n \"DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}\",\n ],\n disableImmutableReleases: [\n \"DELETE /repos/{owner}/{repo}/immutable-releases\",\n ],\n disablePrivateVulnerabilityReporting: [\n \"DELETE /repos/{owner}/{repo}/private-vulnerability-reporting\",\n ],\n disableVulnerabilityAlerts: [\n \"DELETE /repos/{owner}/{repo}/vulnerability-alerts\",\n ],\n downloadArchive: [\n \"GET /repos/{owner}/{repo}/zipball/{ref}\",\n {},\n { renamed: [\"repos\", \"downloadZipballArchive\"] },\n ],\n downloadTarballArchive: [\"GET /repos/{owner}/{repo}/tarball/{ref}\"],\n downloadZipballArchive: [\"GET /repos/{owner}/{repo}/zipball/{ref}\"],\n enableAutomatedSecurityFixes: [\n \"PUT /repos/{owner}/{repo}/automated-security-fixes\",\n ],\n enableImmutableReleases: [\"PUT /repos/{owner}/{repo}/immutable-releases\"],\n enablePrivateVulnerabilityReporting: [\n \"PUT /repos/{owner}/{repo}/private-vulnerability-reporting\",\n ],\n enableVulnerabilityAlerts: [\n \"PUT /repos/{owner}/{repo}/vulnerability-alerts\",\n ],\n generateReleaseNotes: [\n \"POST /repos/{owner}/{repo}/releases/generate-notes\",\n ],\n get: [\"GET /repos/{owner}/{repo}\"],\n getAccessRestrictions: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions\",\n ],\n getAdminBranchProtection: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\",\n ],\n getAllDeploymentProtectionRules: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules\",\n ],\n getAllEnvironments: [\"GET /repos/{owner}/{repo}/environments\"],\n getAllStatusCheckContexts: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\",\n ],\n getAllTopics: [\"GET /repos/{owner}/{repo}/topics\"],\n getAppsWithAccessToProtectedBranch: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\",\n ],\n getAutolink: [\"GET /repos/{owner}/{repo}/autolinks/{autolink_id}\"],\n getBranch: [\"GET /repos/{owner}/{repo}/branches/{branch}\"],\n getBranchProtection: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection\",\n ],\n getBranchRules: [\"GET /repos/{owner}/{repo}/rules/branches/{branch}\"],\n getClones: [\"GET /repos/{owner}/{repo}/traffic/clones\"],\n getCodeFrequencyStats: [\"GET /repos/{owner}/{repo}/stats/code_frequency\"],\n getCollaboratorPermissionLevel: [\n \"GET /repos/{owner}/{repo}/collaborators/{username}/permission\",\n ],\n getCombinedStatusForRef: [\"GET /repos/{owner}/{repo}/commits/{ref}/status\"],\n getCommit: [\"GET /repos/{owner}/{repo}/commits/{ref}\"],\n getCommitActivityStats: [\"GET /repos/{owner}/{repo}/stats/commit_activity\"],\n getCommitComment: [\"GET /repos/{owner}/{repo}/comments/{comment_id}\"],\n getCommitSignatureProtection: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures\",\n ],\n getCommunityProfileMetrics: [\"GET /repos/{owner}/{repo}/community/profile\"],\n getContent: [\"GET /repos/{owner}/{repo}/contents/{path}\"],\n getContributorsStats: [\"GET /repos/{owner}/{repo}/stats/contributors\"],\n getCustomDeploymentProtectionRule: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}\",\n ],\n getDeployKey: [\"GET /repos/{owner}/{repo}/keys/{key_id}\"],\n getDeployment: [\"GET /repos/{owner}/{repo}/deployments/{deployment_id}\"],\n getDeploymentBranchPolicy: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}\",\n ],\n getDeploymentStatus: [\n \"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}\",\n ],\n getEnvironment: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}\",\n ],\n getLatestPagesBuild: [\"GET /repos/{owner}/{repo}/pages/builds/latest\"],\n getLatestRelease: [\"GET /repos/{owner}/{repo}/releases/latest\"],\n getOrgRuleSuite: [\"GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}\"],\n getOrgRuleSuites: [\"GET /orgs/{org}/rulesets/rule-suites\"],\n getOrgRuleset: [\"GET /orgs/{org}/rulesets/{ruleset_id}\"],\n getOrgRulesets: [\"GET /orgs/{org}/rulesets\"],\n getPages: [\"GET /repos/{owner}/{repo}/pages\"],\n getPagesBuild: [\"GET /repos/{owner}/{repo}/pages/builds/{build_id}\"],\n getPagesDeployment: [\n \"GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}\",\n ],\n getPagesHealthCheck: [\"GET /repos/{owner}/{repo}/pages/health\"],\n getParticipationStats: [\"GET /repos/{owner}/{repo}/stats/participation\"],\n getPullRequestReviewProtection: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\",\n ],\n getPunchCardStats: [\"GET /repos/{owner}/{repo}/stats/punch_card\"],\n getReadme: [\"GET /repos/{owner}/{repo}/readme\"],\n getReadmeInDirectory: [\"GET /repos/{owner}/{repo}/readme/{dir}\"],\n getRelease: [\"GET /repos/{owner}/{repo}/releases/{release_id}\"],\n getReleaseAsset: [\"GET /repos/{owner}/{repo}/releases/assets/{asset_id}\"],\n getReleaseByTag: [\"GET /repos/{owner}/{repo}/releases/tags/{tag}\"],\n getRepoRuleSuite: [\n \"GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}\",\n ],\n getRepoRuleSuites: [\"GET /repos/{owner}/{repo}/rulesets/rule-suites\"],\n getRepoRuleset: [\"GET /repos/{owner}/{repo}/rulesets/{ruleset_id}\"],\n getRepoRulesetHistory: [\n \"GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history\",\n ],\n getRepoRulesetVersion: [\n \"GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history/{version_id}\",\n ],\n getRepoRulesets: [\"GET /repos/{owner}/{repo}/rulesets\"],\n getStatusChecksProtection: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\",\n ],\n getTeamsWithAccessToProtectedBranch: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\",\n ],\n getTopPaths: [\"GET /repos/{owner}/{repo}/traffic/popular/paths\"],\n getTopReferrers: [\"GET /repos/{owner}/{repo}/traffic/popular/referrers\"],\n getUsersWithAccessToProtectedBranch: [\n \"GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\",\n ],\n getViews: [\"GET /repos/{owner}/{repo}/traffic/views\"],\n getWebhook: [\"GET /repos/{owner}/{repo}/hooks/{hook_id}\"],\n getWebhookConfigForRepo: [\n \"GET /repos/{owner}/{repo}/hooks/{hook_id}/config\",\n ],\n getWebhookDelivery: [\n \"GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}\",\n ],\n listActivities: [\"GET /repos/{owner}/{repo}/activity\"],\n listAttestations: [\n \"GET /repos/{owner}/{repo}/attestations/{subject_digest}\",\n ],\n listAutolinks: [\"GET /repos/{owner}/{repo}/autolinks\"],\n listBranches: [\"GET /repos/{owner}/{repo}/branches\"],\n listBranchesForHeadCommit: [\n \"GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head\",\n ],\n listCollaborators: [\"GET /repos/{owner}/{repo}/collaborators\"],\n listCommentsForCommit: [\n \"GET /repos/{owner}/{repo}/commits/{commit_sha}/comments\",\n ],\n listCommitCommentsForRepo: [\"GET /repos/{owner}/{repo}/comments\"],\n listCommitStatusesForRef: [\n \"GET /repos/{owner}/{repo}/commits/{ref}/statuses\",\n ],\n listCommits: [\"GET /repos/{owner}/{repo}/commits\"],\n listContributors: [\"GET /repos/{owner}/{repo}/contributors\"],\n listCustomDeploymentRuleIntegrations: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps\",\n ],\n listDeployKeys: [\"GET /repos/{owner}/{repo}/keys\"],\n listDeploymentBranchPolicies: [\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies\",\n ],\n listDeploymentStatuses: [\n \"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses\",\n ],\n listDeployments: [\"GET /repos/{owner}/{repo}/deployments\"],\n listForAuthenticatedUser: [\"GET /user/repos\"],\n listForOrg: [\"GET /orgs/{org}/repos\"],\n listForUser: [\"GET /users/{username}/repos\"],\n listForks: [\"GET /repos/{owner}/{repo}/forks\"],\n listInvitations: [\"GET /repos/{owner}/{repo}/invitations\"],\n listInvitationsForAuthenticatedUser: [\"GET /user/repository_invitations\"],\n listLanguages: [\"GET /repos/{owner}/{repo}/languages\"],\n listPagesBuilds: [\"GET /repos/{owner}/{repo}/pages/builds\"],\n listPublic: [\"GET /repositories\"],\n listPullRequestsAssociatedWithCommit: [\n \"GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls\",\n ],\n listReleaseAssets: [\n \"GET /repos/{owner}/{repo}/releases/{release_id}/assets\",\n ],\n listReleases: [\"GET /repos/{owner}/{repo}/releases\"],\n listTags: [\"GET /repos/{owner}/{repo}/tags\"],\n listTeams: [\"GET /repos/{owner}/{repo}/teams\"],\n listWebhookDeliveries: [\n \"GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries\",\n ],\n listWebhooks: [\"GET /repos/{owner}/{repo}/hooks\"],\n merge: [\"POST /repos/{owner}/{repo}/merges\"],\n mergeUpstream: [\"POST /repos/{owner}/{repo}/merge-upstream\"],\n pingWebhook: [\"POST /repos/{owner}/{repo}/hooks/{hook_id}/pings\"],\n redeliverWebhookDelivery: [\n \"POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts\",\n ],\n removeAppAccessRestrictions: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\",\n {},\n { mapToData: \"apps\" },\n ],\n removeCollaborator: [\n \"DELETE /repos/{owner}/{repo}/collaborators/{username}\",\n ],\n removeStatusCheckContexts: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\",\n {},\n { mapToData: \"contexts\" },\n ],\n removeStatusCheckProtection: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\",\n ],\n removeTeamAccessRestrictions: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\",\n {},\n { mapToData: \"teams\" },\n ],\n removeUserAccessRestrictions: [\n \"DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\",\n {},\n { mapToData: \"users\" },\n ],\n renameBranch: [\"POST /repos/{owner}/{repo}/branches/{branch}/rename\"],\n replaceAllTopics: [\"PUT /repos/{owner}/{repo}/topics\"],\n requestPagesBuild: [\"POST /repos/{owner}/{repo}/pages/builds\"],\n setAdminBranchProtection: [\n \"POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins\",\n ],\n setAppAccessRestrictions: [\n \"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps\",\n {},\n { mapToData: \"apps\" },\n ],\n setStatusCheckContexts: [\n \"PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts\",\n {},\n { mapToData: \"contexts\" },\n ],\n setTeamAccessRestrictions: [\n \"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams\",\n {},\n { mapToData: \"teams\" },\n ],\n setUserAccessRestrictions: [\n \"PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users\",\n {},\n { mapToData: \"users\" },\n ],\n testPushWebhook: [\"POST /repos/{owner}/{repo}/hooks/{hook_id}/tests\"],\n transfer: [\"POST /repos/{owner}/{repo}/transfer\"],\n update: [\"PATCH /repos/{owner}/{repo}\"],\n updateBranchProtection: [\n \"PUT /repos/{owner}/{repo}/branches/{branch}/protection\",\n ],\n updateCommitComment: [\"PATCH /repos/{owner}/{repo}/comments/{comment_id}\"],\n updateDeploymentBranchPolicy: [\n \"PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}\",\n ],\n updateInformationAboutPagesSite: [\"PUT /repos/{owner}/{repo}/pages\"],\n updateInvitation: [\n \"PATCH /repos/{owner}/{repo}/invitations/{invitation_id}\",\n ],\n updateOrgRuleset: [\"PUT /orgs/{org}/rulesets/{ruleset_id}\"],\n updatePullRequestReviewProtection: [\n \"PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews\",\n ],\n updateRelease: [\"PATCH /repos/{owner}/{repo}/releases/{release_id}\"],\n updateReleaseAsset: [\n \"PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}\",\n ],\n updateRepoRuleset: [\"PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}\"],\n updateStatusCheckPotection: [\n \"PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\",\n {},\n { renamed: [\"repos\", \"updateStatusCheckProtection\"] },\n ],\n updateStatusCheckProtection: [\n \"PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks\",\n ],\n updateWebhook: [\"PATCH /repos/{owner}/{repo}/hooks/{hook_id}\"],\n updateWebhookConfigForRepo: [\n \"PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config\",\n ],\n uploadReleaseAsset: [\n \"POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}\",\n { baseUrl: \"https://uploads.github.com\" },\n ],\n },\n search: {\n code: [\"GET /search/code\"],\n commits: [\"GET /search/commits\"],\n issuesAndPullRequests: [\"GET /search/issues\"],\n labels: [\"GET /search/labels\"],\n repos: [\"GET /search/repositories\"],\n topics: [\"GET /search/topics\"],\n users: [\"GET /search/users\"],\n },\n secretScanning: {\n createPushProtectionBypass: [\n \"POST /repos/{owner}/{repo}/secret-scanning/push-protection-bypasses\",\n ],\n getAlert: [\n \"GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}\",\n ],\n getScanHistory: [\"GET /repos/{owner}/{repo}/secret-scanning/scan-history\"],\n listAlertsForOrg: [\"GET /orgs/{org}/secret-scanning/alerts\"],\n listAlertsForRepo: [\"GET /repos/{owner}/{repo}/secret-scanning/alerts\"],\n listLocationsForAlert: [\n \"GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations\",\n ],\n listOrgPatternConfigs: [\n \"GET /orgs/{org}/secret-scanning/pattern-configurations\",\n ],\n updateAlert: [\n \"PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}\",\n ],\n updateOrgPatternConfigs: [\n \"PATCH /orgs/{org}/secret-scanning/pattern-configurations\",\n ],\n },\n securityAdvisories: {\n createFork: [\n \"POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks\",\n ],\n createPrivateVulnerabilityReport: [\n \"POST /repos/{owner}/{repo}/security-advisories/reports\",\n ],\n createRepositoryAdvisory: [\n \"POST /repos/{owner}/{repo}/security-advisories\",\n ],\n createRepositoryAdvisoryCveRequest: [\n \"POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve\",\n ],\n getGlobalAdvisory: [\"GET /advisories/{ghsa_id}\"],\n getRepositoryAdvisory: [\n \"GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}\",\n ],\n listGlobalAdvisories: [\"GET /advisories\"],\n listOrgRepositoryAdvisories: [\"GET /orgs/{org}/security-advisories\"],\n listRepositoryAdvisories: [\"GET /repos/{owner}/{repo}/security-advisories\"],\n updateRepositoryAdvisory: [\n \"PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}\",\n ],\n },\n teams: {\n addOrUpdateMembershipForUserInOrg: [\n \"PUT /orgs/{org}/teams/{team_slug}/memberships/{username}\",\n ],\n addOrUpdateRepoPermissionsInOrg: [\n \"PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\",\n ],\n checkPermissionsForRepoInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\",\n ],\n create: [\"POST /orgs/{org}/teams\"],\n createDiscussionCommentInOrg: [\n \"POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments\",\n ],\n createDiscussionInOrg: [\"POST /orgs/{org}/teams/{team_slug}/discussions\"],\n deleteDiscussionCommentInOrg: [\n \"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\",\n ],\n deleteDiscussionInOrg: [\n \"DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\",\n ],\n deleteInOrg: [\"DELETE /orgs/{org}/teams/{team_slug}\"],\n getByName: [\"GET /orgs/{org}/teams/{team_slug}\"],\n getDiscussionCommentInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\",\n ],\n getDiscussionInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\",\n ],\n getMembershipForUserInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/memberships/{username}\",\n ],\n list: [\"GET /orgs/{org}/teams\"],\n listChildInOrg: [\"GET /orgs/{org}/teams/{team_slug}/teams\"],\n listDiscussionCommentsInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments\",\n ],\n listDiscussionsInOrg: [\"GET /orgs/{org}/teams/{team_slug}/discussions\"],\n listForAuthenticatedUser: [\"GET /user/teams\"],\n listMembersInOrg: [\"GET /orgs/{org}/teams/{team_slug}/members\"],\n listPendingInvitationsInOrg: [\n \"GET /orgs/{org}/teams/{team_slug}/invitations\",\n ],\n listReposInOrg: [\"GET /orgs/{org}/teams/{team_slug}/repos\"],\n removeMembershipForUserInOrg: [\n \"DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}\",\n ],\n removeRepoInOrg: [\n \"DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}\",\n ],\n updateDiscussionCommentInOrg: [\n \"PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}\",\n ],\n updateDiscussionInOrg: [\n \"PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}\",\n ],\n updateInOrg: [\"PATCH /orgs/{org}/teams/{team_slug}\"],\n },\n users: {\n addEmailForAuthenticated: [\n \"POST /user/emails\",\n {},\n { renamed: [\"users\", \"addEmailForAuthenticatedUser\"] },\n ],\n addEmailForAuthenticatedUser: [\"POST /user/emails\"],\n addSocialAccountForAuthenticatedUser: [\"POST /user/social_accounts\"],\n block: [\"PUT /user/blocks/{username}\"],\n checkBlocked: [\"GET /user/blocks/{username}\"],\n checkFollowingForUser: [\"GET /users/{username}/following/{target_user}\"],\n checkPersonIsFollowedByAuthenticated: [\"GET /user/following/{username}\"],\n createGpgKeyForAuthenticated: [\n \"POST /user/gpg_keys\",\n {},\n { renamed: [\"users\", \"createGpgKeyForAuthenticatedUser\"] },\n ],\n createGpgKeyForAuthenticatedUser: [\"POST /user/gpg_keys\"],\n createPublicSshKeyForAuthenticated: [\n \"POST /user/keys\",\n {},\n { renamed: [\"users\", \"createPublicSshKeyForAuthenticatedUser\"] },\n ],\n createPublicSshKeyForAuthenticatedUser: [\"POST /user/keys\"],\n createSshSigningKeyForAuthenticatedUser: [\"POST /user/ssh_signing_keys\"],\n deleteAttestationsBulk: [\n \"POST /users/{username}/attestations/delete-request\",\n ],\n deleteAttestationsById: [\n \"DELETE /users/{username}/attestations/{attestation_id}\",\n ],\n deleteAttestationsBySubjectDigest: [\n \"DELETE /users/{username}/attestations/digest/{subject_digest}\",\n ],\n deleteEmailForAuthenticated: [\n \"DELETE /user/emails\",\n {},\n { renamed: [\"users\", \"deleteEmailForAuthenticatedUser\"] },\n ],\n deleteEmailForAuthenticatedUser: [\"DELETE /user/emails\"],\n deleteGpgKeyForAuthenticated: [\n \"DELETE /user/gpg_keys/{gpg_key_id}\",\n {},\n { renamed: [\"users\", \"deleteGpgKeyForAuthenticatedUser\"] },\n ],\n deleteGpgKeyForAuthenticatedUser: [\"DELETE /user/gpg_keys/{gpg_key_id}\"],\n deletePublicSshKeyForAuthenticated: [\n \"DELETE /user/keys/{key_id}\",\n {},\n { renamed: [\"users\", \"deletePublicSshKeyForAuthenticatedUser\"] },\n ],\n deletePublicSshKeyForAuthenticatedUser: [\"DELETE /user/keys/{key_id}\"],\n deleteSocialAccountForAuthenticatedUser: [\"DELETE /user/social_accounts\"],\n deleteSshSigningKeyForAuthenticatedUser: [\n \"DELETE /user/ssh_signing_keys/{ssh_signing_key_id}\",\n ],\n follow: [\"PUT /user/following/{username}\"],\n getAuthenticated: [\"GET /user\"],\n getById: [\"GET /user/{account_id}\"],\n getByUsername: [\"GET /users/{username}\"],\n getContextForUser: [\"GET /users/{username}/hovercard\"],\n getGpgKeyForAuthenticated: [\n \"GET /user/gpg_keys/{gpg_key_id}\",\n {},\n { renamed: [\"users\", \"getGpgKeyForAuthenticatedUser\"] },\n ],\n getGpgKeyForAuthenticatedUser: [\"GET /user/gpg_keys/{gpg_key_id}\"],\n getPublicSshKeyForAuthenticated: [\n \"GET /user/keys/{key_id}\",\n {},\n { renamed: [\"users\", \"getPublicSshKeyForAuthenticatedUser\"] },\n ],\n getPublicSshKeyForAuthenticatedUser: [\"GET /user/keys/{key_id}\"],\n getSshSigningKeyForAuthenticatedUser: [\n \"GET /user/ssh_signing_keys/{ssh_signing_key_id}\",\n ],\n list: [\"GET /users\"],\n listAttestations: [\"GET /users/{username}/attestations/{subject_digest}\"],\n listAttestationsBulk: [\n \"POST /users/{username}/attestations/bulk-list{?per_page,before,after}\",\n ],\n listBlockedByAuthenticated: [\n \"GET /user/blocks\",\n {},\n { renamed: [\"users\", \"listBlockedByAuthenticatedUser\"] },\n ],\n listBlockedByAuthenticatedUser: [\"GET /user/blocks\"],\n listEmailsForAuthenticated: [\n \"GET /user/emails\",\n {},\n { renamed: [\"users\", \"listEmailsForAuthenticatedUser\"] },\n ],\n listEmailsForAuthenticatedUser: [\"GET /user/emails\"],\n listFollowedByAuthenticated: [\n \"GET /user/following\",\n {},\n { renamed: [\"users\", \"listFollowedByAuthenticatedUser\"] },\n ],\n listFollowedByAuthenticatedUser: [\"GET /user/following\"],\n listFollowersForAuthenticatedUser: [\"GET /user/followers\"],\n listFollowersForUser: [\"GET /users/{username}/followers\"],\n listFollowingForUser: [\"GET /users/{username}/following\"],\n listGpgKeysForAuthenticated: [\n \"GET /user/gpg_keys\",\n {},\n { renamed: [\"users\", \"listGpgKeysForAuthenticatedUser\"] },\n ],\n listGpgKeysForAuthenticatedUser: [\"GET /user/gpg_keys\"],\n listGpgKeysForUser: [\"GET /users/{username}/gpg_keys\"],\n listPublicEmailsForAuthenticated: [\n \"GET /user/public_emails\",\n {},\n { renamed: [\"users\", \"listPublicEmailsForAuthenticatedUser\"] },\n ],\n listPublicEmailsForAuthenticatedUser: [\"GET /user/public_emails\"],\n listPublicKeysForUser: [\"GET /users/{username}/keys\"],\n listPublicSshKeysForAuthenticated: [\n \"GET /user/keys\",\n {},\n { renamed: [\"users\", \"listPublicSshKeysForAuthenticatedUser\"] },\n ],\n listPublicSshKeysForAuthenticatedUser: [\"GET /user/keys\"],\n listSocialAccountsForAuthenticatedUser: [\"GET /user/social_accounts\"],\n listSocialAccountsForUser: [\"GET /users/{username}/social_accounts\"],\n listSshSigningKeysForAuthenticatedUser: [\"GET /user/ssh_signing_keys\"],\n listSshSigningKeysForUser: [\"GET /users/{username}/ssh_signing_keys\"],\n setPrimaryEmailVisibilityForAuthenticated: [\n \"PATCH /user/email/visibility\",\n {},\n { renamed: [\"users\", \"setPrimaryEmailVisibilityForAuthenticatedUser\"] },\n ],\n setPrimaryEmailVisibilityForAuthenticatedUser: [\n \"PATCH /user/email/visibility\",\n ],\n unblock: [\"DELETE /user/blocks/{username}\"],\n unfollow: [\"DELETE /user/following/{username}\"],\n updateAuthenticated: [\"PATCH /user\"],\n },\n};\n\nexport default Endpoints;\n","import type { Octokit } from \"@octokit/core\";\nimport type { EndpointOptions, RequestParameters, Route } from \"@octokit/types\";\nimport ENDPOINTS from \"./generated/endpoints.js\";\nimport type { RestEndpointMethods } from \"./generated/method-types.js\";\nimport type { EndpointDecorations } from \"./types.js\";\n\n// The following code was refactored in: https://github.com/octokit/plugin-rest-endpoint-methods.js/pull/622\n// to optimise the runtime performance of Octokit initialization.\n//\n// This optimization involves two key changes:\n// 1. Pre-Computation: The endpoint methods are pre-computed once at module load\n// time instead of each invocation of `endpointsToMethods()`.\n// 2. Lazy initialization and caching: We use a Proxy for each scope to only\n// initialize methods that are actually called. This reduces runtime overhead\n// as the initialization involves deep merging of objects. The initialized\n// methods are then cached for future use.\n\nconst endpointMethodsMap = new Map();\nfor (const [scope, endpoints] of Object.entries(ENDPOINTS)) {\n for (const [methodName, endpoint] of Object.entries(endpoints)) {\n const [route, defaults, decorations] = endpoint;\n const [method, url] = route.split(/ /);\n const endpointDefaults = Object.assign(\n {\n method,\n url,\n },\n defaults,\n );\n\n if (!endpointMethodsMap.has(scope)) {\n endpointMethodsMap.set(scope, new Map());\n }\n\n endpointMethodsMap.get(scope).set(methodName, {\n scope,\n methodName,\n endpointDefaults,\n decorations,\n });\n }\n}\n\ntype ProxyTarget = {\n octokit: Octokit;\n scope: string;\n cache: Record any>;\n};\n\nconst handler = {\n has({ scope }: ProxyTarget, methodName: string) {\n return endpointMethodsMap.get(scope).has(methodName);\n },\n getOwnPropertyDescriptor(target: ProxyTarget, methodName: string) {\n return {\n value: this.get(target, methodName), // ensures method is in the cache\n configurable: true,\n writable: true,\n enumerable: true,\n };\n },\n defineProperty(\n target: ProxyTarget,\n methodName: string,\n descriptor: PropertyDescriptor,\n ) {\n Object.defineProperty(target.cache, methodName, descriptor);\n return true;\n },\n deleteProperty(target: ProxyTarget, methodName: string) {\n delete target.cache[methodName];\n return true;\n },\n ownKeys({ scope }: ProxyTarget) {\n return [...endpointMethodsMap.get(scope).keys()];\n },\n set(target: ProxyTarget, methodName: string, value: any) {\n return (target.cache[methodName] = value);\n },\n get({ octokit, scope, cache }: ProxyTarget, methodName: string) {\n if (cache[methodName]) {\n return cache[methodName];\n }\n\n const method = endpointMethodsMap.get(scope).get(methodName);\n if (!method) {\n return undefined;\n }\n\n const { endpointDefaults, decorations } = method;\n\n if (decorations) {\n cache[methodName] = decorate(\n octokit,\n scope,\n methodName,\n endpointDefaults,\n decorations,\n );\n } else {\n cache[methodName] = octokit.request.defaults(endpointDefaults);\n }\n\n return cache[methodName];\n },\n};\n\nexport function endpointsToMethods(octokit: Octokit): RestEndpointMethods {\n const newMethods = {} as { [key: string]: object };\n\n for (const scope of endpointMethodsMap.keys()) {\n newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler);\n }\n\n return newMethods as RestEndpointMethods;\n}\n\nfunction decorate(\n octokit: Octokit,\n scope: string,\n methodName: string,\n defaults: EndpointOptions,\n decorations: EndpointDecorations,\n) {\n const requestWithDefaults = octokit.request.defaults(defaults);\n\n /* istanbul ignore next */\n function withDecorations(\n ...args: [Route, RequestParameters?] | [EndpointOptions]\n ) {\n // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488\n let options = requestWithDefaults.endpoint.merge(...args);\n\n // There are currently no other decorations than `.mapToData`\n if (decorations.mapToData) {\n options = Object.assign({}, options, {\n data: options[decorations.mapToData],\n [decorations.mapToData]: undefined,\n });\n return requestWithDefaults(options);\n }\n\n if (decorations.renamed) {\n const [newScope, newMethodName] = decorations.renamed;\n octokit.log.warn(\n `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()`,\n );\n }\n if (decorations.deprecated) {\n octokit.log.warn(decorations.deprecated);\n }\n\n if (decorations.renamedParameters) {\n // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488\n const options = requestWithDefaults.endpoint.merge(...args);\n\n for (const [name, alias] of Object.entries(\n decorations.renamedParameters,\n )) {\n if (name in options) {\n octokit.log.warn(\n `\"${name}\" parameter is deprecated for \"octokit.${scope}.${methodName}()\". Use \"${alias}\" instead`,\n );\n if (!(alias in options)) {\n options[alias] = options[name];\n }\n delete options[name];\n }\n }\n return requestWithDefaults(options);\n }\n\n // @ts-ignore https://github.com/microsoft/TypeScript/issues/25488\n return requestWithDefaults(...args);\n }\n return Object.assign(withDecorations, requestWithDefaults);\n}\n","import type { Octokit } from \"@octokit/core\";\n\nexport type { RestEndpointMethodTypes } from \"./generated/parameters-and-response-types.js\";\nimport { VERSION } from \"./version.js\";\nimport type { Api } from \"./types.js\";\nimport { endpointsToMethods } from \"./endpoints-to-methods.js\";\n\n// Export the type for downstream users in order to fix a TypeScript error\n// The inferred type of 'Octokit' cannot be named without a reference to '../node_modules/@octokit/plugin-rest-endpoint-methods/dist-types/types.js'. This is likely not portable. A type annotation is necessary.\nexport type { Api };\n\nexport function restEndpointMethods(octokit: Octokit): Api {\n const api = endpointsToMethods(octokit);\n return {\n rest: api,\n };\n}\nrestEndpointMethods.VERSION = VERSION;\n\nexport function legacyRestEndpointMethods(octokit: Octokit): Api[\"rest\"] & Api {\n const api = endpointsToMethods(octokit);\n return {\n ...api,\n rest: api,\n };\n}\nlegacyRestEndpointMethods.VERSION = VERSION;\n","// pkg/dist-src/version.js\nvar VERSION = \"0.0.0-development\";\n\n// pkg/dist-src/normalize-paginated-list-response.js\nfunction normalizePaginatedListResponse(response) {\n if (!response.data) {\n return {\n ...response,\n data: []\n };\n }\n const responseNeedsNormalization = (\"total_count\" in response.data || \"total_commits\" in response.data) && !(\"url\" in response.data);\n if (!responseNeedsNormalization) return response;\n const incompleteResults = response.data.incomplete_results;\n const repositorySelection = response.data.repository_selection;\n const totalCount = response.data.total_count;\n const totalCommits = response.data.total_commits;\n delete response.data.incomplete_results;\n delete response.data.repository_selection;\n delete response.data.total_count;\n delete response.data.total_commits;\n const namespaceKey = Object.keys(response.data)[0];\n const data = response.data[namespaceKey];\n response.data = data;\n if (typeof incompleteResults !== \"undefined\") {\n response.data.incomplete_results = incompleteResults;\n }\n if (typeof repositorySelection !== \"undefined\") {\n response.data.repository_selection = repositorySelection;\n }\n response.data.total_count = totalCount;\n response.data.total_commits = totalCommits;\n return response;\n}\n\n// pkg/dist-src/iterator.js\nfunction iterator(octokit, route, parameters) {\n const options = typeof route === \"function\" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters);\n const requestMethod = typeof route === \"function\" ? route : octokit.request;\n const method = options.method;\n const headers = options.headers;\n let url = options.url;\n return {\n [Symbol.asyncIterator]: () => ({\n async next() {\n if (!url) return { done: true };\n try {\n const response = await requestMethod({ method, url, headers });\n const normalizedResponse = normalizePaginatedListResponse(response);\n url = ((normalizedResponse.headers.link || \"\").match(\n /<([^<>]+)>;\\s*rel=\"next\"/\n ) || [])[1];\n if (!url && \"total_commits\" in normalizedResponse.data) {\n const parsedUrl = new URL(normalizedResponse.url);\n const params = parsedUrl.searchParams;\n const page = parseInt(params.get(\"page\") || \"1\", 10);\n const per_page = parseInt(params.get(\"per_page\") || \"250\", 10);\n if (page * per_page < normalizedResponse.data.total_commits) {\n params.set(\"page\", String(page + 1));\n url = parsedUrl.toString();\n }\n }\n return { value: normalizedResponse };\n } catch (error) {\n if (error.status !== 409) throw error;\n url = \"\";\n return {\n value: {\n status: 200,\n headers: {},\n data: []\n }\n };\n }\n }\n })\n };\n}\n\n// pkg/dist-src/paginate.js\nfunction paginate(octokit, route, parameters, mapFn) {\n if (typeof parameters === \"function\") {\n mapFn = parameters;\n parameters = void 0;\n }\n return gather(\n octokit,\n [],\n iterator(octokit, route, parameters)[Symbol.asyncIterator](),\n mapFn\n );\n}\nfunction gather(octokit, results, iterator2, mapFn) {\n return iterator2.next().then((result) => {\n if (result.done) {\n return results;\n }\n let earlyExit = false;\n function done() {\n earlyExit = true;\n }\n results = results.concat(\n mapFn ? mapFn(result.value, done) : result.value.data\n );\n if (earlyExit) {\n return results;\n }\n return gather(octokit, results, iterator2, mapFn);\n });\n}\n\n// pkg/dist-src/compose-paginate.js\nvar composePaginateRest = Object.assign(paginate, {\n iterator\n});\n\n// pkg/dist-src/generated/paginating-endpoints.js\nvar paginatingEndpoints = [\n \"GET /advisories\",\n \"GET /app/hook/deliveries\",\n \"GET /app/installation-requests\",\n \"GET /app/installations\",\n \"GET /assignments/{assignment_id}/accepted_assignments\",\n \"GET /classrooms\",\n \"GET /classrooms/{classroom_id}/assignments\",\n \"GET /enterprises/{enterprise}/code-security/configurations\",\n \"GET /enterprises/{enterprise}/code-security/configurations/{configuration_id}/repositories\",\n \"GET /enterprises/{enterprise}/dependabot/alerts\",\n \"GET /enterprises/{enterprise}/teams\",\n \"GET /enterprises/{enterprise}/teams/{enterprise-team}/memberships\",\n \"GET /enterprises/{enterprise}/teams/{enterprise-team}/organizations\",\n \"GET /events\",\n \"GET /gists\",\n \"GET /gists/public\",\n \"GET /gists/starred\",\n \"GET /gists/{gist_id}/comments\",\n \"GET /gists/{gist_id}/commits\",\n \"GET /gists/{gist_id}/forks\",\n \"GET /installation/repositories\",\n \"GET /issues\",\n \"GET /licenses\",\n \"GET /marketplace_listing/plans\",\n \"GET /marketplace_listing/plans/{plan_id}/accounts\",\n \"GET /marketplace_listing/stubbed/plans\",\n \"GET /marketplace_listing/stubbed/plans/{plan_id}/accounts\",\n \"GET /networks/{owner}/{repo}/events\",\n \"GET /notifications\",\n \"GET /organizations\",\n \"GET /organizations/{org}/dependabot/repository-access\",\n \"GET /orgs/{org}/actions/cache/usage-by-repository\",\n \"GET /orgs/{org}/actions/hosted-runners\",\n \"GET /orgs/{org}/actions/permissions/repositories\",\n \"GET /orgs/{org}/actions/permissions/self-hosted-runners/repositories\",\n \"GET /orgs/{org}/actions/runner-groups\",\n \"GET /orgs/{org}/actions/runner-groups/{runner_group_id}/hosted-runners\",\n \"GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories\",\n \"GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners\",\n \"GET /orgs/{org}/actions/runners\",\n \"GET /orgs/{org}/actions/secrets\",\n \"GET /orgs/{org}/actions/secrets/{secret_name}/repositories\",\n \"GET /orgs/{org}/actions/variables\",\n \"GET /orgs/{org}/actions/variables/{name}/repositories\",\n \"GET /orgs/{org}/attestations/repositories\",\n \"GET /orgs/{org}/attestations/{subject_digest}\",\n \"GET /orgs/{org}/blocks\",\n \"GET /orgs/{org}/campaigns\",\n \"GET /orgs/{org}/code-scanning/alerts\",\n \"GET /orgs/{org}/code-security/configurations\",\n \"GET /orgs/{org}/code-security/configurations/{configuration_id}/repositories\",\n \"GET /orgs/{org}/codespaces\",\n \"GET /orgs/{org}/codespaces/secrets\",\n \"GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories\",\n \"GET /orgs/{org}/copilot/billing/seats\",\n \"GET /orgs/{org}/copilot/metrics\",\n \"GET /orgs/{org}/dependabot/alerts\",\n \"GET /orgs/{org}/dependabot/secrets\",\n \"GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories\",\n \"GET /orgs/{org}/events\",\n \"GET /orgs/{org}/failed_invitations\",\n \"GET /orgs/{org}/hooks\",\n \"GET /orgs/{org}/hooks/{hook_id}/deliveries\",\n \"GET /orgs/{org}/insights/api/route-stats/{actor_type}/{actor_id}\",\n \"GET /orgs/{org}/insights/api/subject-stats\",\n \"GET /orgs/{org}/insights/api/user-stats/{user_id}\",\n \"GET /orgs/{org}/installations\",\n \"GET /orgs/{org}/invitations\",\n \"GET /orgs/{org}/invitations/{invitation_id}/teams\",\n \"GET /orgs/{org}/issues\",\n \"GET /orgs/{org}/members\",\n \"GET /orgs/{org}/members/{username}/codespaces\",\n \"GET /orgs/{org}/migrations\",\n \"GET /orgs/{org}/migrations/{migration_id}/repositories\",\n \"GET /orgs/{org}/organization-roles/{role_id}/teams\",\n \"GET /orgs/{org}/organization-roles/{role_id}/users\",\n \"GET /orgs/{org}/outside_collaborators\",\n \"GET /orgs/{org}/packages\",\n \"GET /orgs/{org}/packages/{package_type}/{package_name}/versions\",\n \"GET /orgs/{org}/personal-access-token-requests\",\n \"GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories\",\n \"GET /orgs/{org}/personal-access-tokens\",\n \"GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories\",\n \"GET /orgs/{org}/private-registries\",\n \"GET /orgs/{org}/projects\",\n \"GET /orgs/{org}/projectsV2\",\n \"GET /orgs/{org}/projectsV2/{project_number}/fields\",\n \"GET /orgs/{org}/projectsV2/{project_number}/items\",\n \"GET /orgs/{org}/properties/values\",\n \"GET /orgs/{org}/public_members\",\n \"GET /orgs/{org}/repos\",\n \"GET /orgs/{org}/rulesets\",\n \"GET /orgs/{org}/rulesets/rule-suites\",\n \"GET /orgs/{org}/rulesets/{ruleset_id}/history\",\n \"GET /orgs/{org}/secret-scanning/alerts\",\n \"GET /orgs/{org}/security-advisories\",\n \"GET /orgs/{org}/settings/immutable-releases/repositories\",\n \"GET /orgs/{org}/settings/network-configurations\",\n \"GET /orgs/{org}/team/{team_slug}/copilot/metrics\",\n \"GET /orgs/{org}/teams\",\n \"GET /orgs/{org}/teams/{team_slug}/discussions\",\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments\",\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions\",\n \"GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions\",\n \"GET /orgs/{org}/teams/{team_slug}/invitations\",\n \"GET /orgs/{org}/teams/{team_slug}/members\",\n \"GET /orgs/{org}/teams/{team_slug}/projects\",\n \"GET /orgs/{org}/teams/{team_slug}/repos\",\n \"GET /orgs/{org}/teams/{team_slug}/teams\",\n \"GET /projects/{project_id}/collaborators\",\n \"GET /repos/{owner}/{repo}/actions/artifacts\",\n \"GET /repos/{owner}/{repo}/actions/caches\",\n \"GET /repos/{owner}/{repo}/actions/organization-secrets\",\n \"GET /repos/{owner}/{repo}/actions/organization-variables\",\n \"GET /repos/{owner}/{repo}/actions/runners\",\n \"GET /repos/{owner}/{repo}/actions/runs\",\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts\",\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs\",\n \"GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs\",\n \"GET /repos/{owner}/{repo}/actions/secrets\",\n \"GET /repos/{owner}/{repo}/actions/variables\",\n \"GET /repos/{owner}/{repo}/actions/workflows\",\n \"GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs\",\n \"GET /repos/{owner}/{repo}/activity\",\n \"GET /repos/{owner}/{repo}/assignees\",\n \"GET /repos/{owner}/{repo}/attestations/{subject_digest}\",\n \"GET /repos/{owner}/{repo}/branches\",\n \"GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations\",\n \"GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs\",\n \"GET /repos/{owner}/{repo}/code-scanning/alerts\",\n \"GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances\",\n \"GET /repos/{owner}/{repo}/code-scanning/analyses\",\n \"GET /repos/{owner}/{repo}/codespaces\",\n \"GET /repos/{owner}/{repo}/codespaces/devcontainers\",\n \"GET /repos/{owner}/{repo}/codespaces/secrets\",\n \"GET /repos/{owner}/{repo}/collaborators\",\n \"GET /repos/{owner}/{repo}/comments\",\n \"GET /repos/{owner}/{repo}/comments/{comment_id}/reactions\",\n \"GET /repos/{owner}/{repo}/commits\",\n \"GET /repos/{owner}/{repo}/commits/{commit_sha}/comments\",\n \"GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls\",\n \"GET /repos/{owner}/{repo}/commits/{ref}/check-runs\",\n \"GET /repos/{owner}/{repo}/commits/{ref}/check-suites\",\n \"GET /repos/{owner}/{repo}/commits/{ref}/status\",\n \"GET /repos/{owner}/{repo}/commits/{ref}/statuses\",\n \"GET /repos/{owner}/{repo}/compare/{basehead}\",\n \"GET /repos/{owner}/{repo}/compare/{base}...{head}\",\n \"GET /repos/{owner}/{repo}/contributors\",\n \"GET /repos/{owner}/{repo}/dependabot/alerts\",\n \"GET /repos/{owner}/{repo}/dependabot/secrets\",\n \"GET /repos/{owner}/{repo}/deployments\",\n \"GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses\",\n \"GET /repos/{owner}/{repo}/environments\",\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies\",\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps\",\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/secrets\",\n \"GET /repos/{owner}/{repo}/environments/{environment_name}/variables\",\n \"GET /repos/{owner}/{repo}/events\",\n \"GET /repos/{owner}/{repo}/forks\",\n \"GET /repos/{owner}/{repo}/hooks\",\n \"GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries\",\n \"GET /repos/{owner}/{repo}/invitations\",\n \"GET /repos/{owner}/{repo}/issues\",\n \"GET /repos/{owner}/{repo}/issues/comments\",\n \"GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions\",\n \"GET /repos/{owner}/{repo}/issues/events\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/comments\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocked_by\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/dependencies/blocking\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/events\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/labels\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/reactions\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/sub_issues\",\n \"GET /repos/{owner}/{repo}/issues/{issue_number}/timeline\",\n \"GET /repos/{owner}/{repo}/keys\",\n \"GET /repos/{owner}/{repo}/labels\",\n \"GET /repos/{owner}/{repo}/milestones\",\n \"GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels\",\n \"GET /repos/{owner}/{repo}/notifications\",\n \"GET /repos/{owner}/{repo}/pages/builds\",\n \"GET /repos/{owner}/{repo}/projects\",\n \"GET /repos/{owner}/{repo}/pulls\",\n \"GET /repos/{owner}/{repo}/pulls/comments\",\n \"GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions\",\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/comments\",\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/commits\",\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/files\",\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews\",\n \"GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments\",\n \"GET /repos/{owner}/{repo}/releases\",\n \"GET /repos/{owner}/{repo}/releases/{release_id}/assets\",\n \"GET /repos/{owner}/{repo}/releases/{release_id}/reactions\",\n \"GET /repos/{owner}/{repo}/rules/branches/{branch}\",\n \"GET /repos/{owner}/{repo}/rulesets\",\n \"GET /repos/{owner}/{repo}/rulesets/rule-suites\",\n \"GET /repos/{owner}/{repo}/rulesets/{ruleset_id}/history\",\n \"GET /repos/{owner}/{repo}/secret-scanning/alerts\",\n \"GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations\",\n \"GET /repos/{owner}/{repo}/security-advisories\",\n \"GET /repos/{owner}/{repo}/stargazers\",\n \"GET /repos/{owner}/{repo}/subscribers\",\n \"GET /repos/{owner}/{repo}/tags\",\n \"GET /repos/{owner}/{repo}/teams\",\n \"GET /repos/{owner}/{repo}/topics\",\n \"GET /repositories\",\n \"GET /search/code\",\n \"GET /search/commits\",\n \"GET /search/issues\",\n \"GET /search/labels\",\n \"GET /search/repositories\",\n \"GET /search/topics\",\n \"GET /search/users\",\n \"GET /teams/{team_id}/discussions\",\n \"GET /teams/{team_id}/discussions/{discussion_number}/comments\",\n \"GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions\",\n \"GET /teams/{team_id}/discussions/{discussion_number}/reactions\",\n \"GET /teams/{team_id}/invitations\",\n \"GET /teams/{team_id}/members\",\n \"GET /teams/{team_id}/projects\",\n \"GET /teams/{team_id}/repos\",\n \"GET /teams/{team_id}/teams\",\n \"GET /user/blocks\",\n \"GET /user/codespaces\",\n \"GET /user/codespaces/secrets\",\n \"GET /user/emails\",\n \"GET /user/followers\",\n \"GET /user/following\",\n \"GET /user/gpg_keys\",\n \"GET /user/installations\",\n \"GET /user/installations/{installation_id}/repositories\",\n \"GET /user/issues\",\n \"GET /user/keys\",\n \"GET /user/marketplace_purchases\",\n \"GET /user/marketplace_purchases/stubbed\",\n \"GET /user/memberships/orgs\",\n \"GET /user/migrations\",\n \"GET /user/migrations/{migration_id}/repositories\",\n \"GET /user/orgs\",\n \"GET /user/packages\",\n \"GET /user/packages/{package_type}/{package_name}/versions\",\n \"GET /user/public_emails\",\n \"GET /user/repos\",\n \"GET /user/repository_invitations\",\n \"GET /user/social_accounts\",\n \"GET /user/ssh_signing_keys\",\n \"GET /user/starred\",\n \"GET /user/subscriptions\",\n \"GET /user/teams\",\n \"GET /users\",\n \"GET /users/{username}/attestations/{subject_digest}\",\n \"GET /users/{username}/events\",\n \"GET /users/{username}/events/orgs/{org}\",\n \"GET /users/{username}/events/public\",\n \"GET /users/{username}/followers\",\n \"GET /users/{username}/following\",\n \"GET /users/{username}/gists\",\n \"GET /users/{username}/gpg_keys\",\n \"GET /users/{username}/keys\",\n \"GET /users/{username}/orgs\",\n \"GET /users/{username}/packages\",\n \"GET /users/{username}/projects\",\n \"GET /users/{username}/projectsV2\",\n \"GET /users/{username}/projectsV2/{project_number}/fields\",\n \"GET /users/{username}/projectsV2/{project_number}/items\",\n \"GET /users/{username}/received_events\",\n \"GET /users/{username}/received_events/public\",\n \"GET /users/{username}/repos\",\n \"GET /users/{username}/social_accounts\",\n \"GET /users/{username}/ssh_signing_keys\",\n \"GET /users/{username}/starred\",\n \"GET /users/{username}/subscriptions\"\n];\n\n// pkg/dist-src/paginating-endpoints.js\nfunction isPaginatingEndpoint(arg) {\n if (typeof arg === \"string\") {\n return paginatingEndpoints.includes(arg);\n } else {\n return false;\n }\n}\n\n// pkg/dist-src/index.js\nfunction paginateRest(octokit) {\n return {\n paginate: Object.assign(paginate.bind(null, octokit), {\n iterator: iterator.bind(null, octokit)\n })\n };\n}\npaginateRest.VERSION = VERSION;\nexport {\n composePaginateRest,\n isPaginatingEndpoint,\n paginateRest,\n paginatingEndpoints\n};\n","const VERSION = \"6.0.0\";\nexport {\n VERSION\n};\n","import { VERSION } from \"./version.js\";\nfunction requestLog(octokit) {\n octokit.hook.wrap(\"request\", (request, options) => {\n octokit.log.debug(\"request\", options);\n const start = Date.now();\n const requestOptions = octokit.request.endpoint.parse(options);\n const path = requestOptions.url.replace(options.baseUrl, \"\");\n return request(options).then((response) => {\n const requestId = response.headers[\"x-github-request-id\"];\n octokit.log.info(\n `${requestOptions.method} ${path} - ${response.status} with id ${requestId} in ${Date.now() - start}ms`\n );\n return response;\n }).catch((error) => {\n const requestId = error.response?.headers[\"x-github-request-id\"] || \"UNKNOWN\";\n octokit.log.error(\n `${requestOptions.method} ${path} - ${error.status} with id ${requestId} in ${Date.now() - start}ms`\n );\n throw error;\n });\n });\n}\nrequestLog.VERSION = VERSION;\nexport {\n requestLog\n};\n","const VERSION = \"22.0.1\";\nexport {\n VERSION\n};\n","import { Octokit as Core } from \"@octokit/core\";\nimport { requestLog } from \"@octokit/plugin-request-log\";\nimport {\n paginateRest\n} from \"@octokit/plugin-paginate-rest\";\nimport { legacyRestEndpointMethods } from \"@octokit/plugin-rest-endpoint-methods\";\nimport { VERSION } from \"./version.js\";\nconst Octokit = Core.plugin(requestLog, legacyRestEndpointMethods, paginateRest).defaults(\n {\n userAgent: `octokit-rest.js/${VERSION}`\n }\n);\nexport {\n Octokit\n};\n","/**\n * This file contains the Bottleneck library (MIT), compiled to ES2017, and without Clustering support.\n * https://github.com/SGrondin/bottleneck\n */\n(function (global, factory) {\n\ttypeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n\ttypeof define === 'function' && define.amd ? define(factory) :\n\t(global.Bottleneck = factory());\n}(this, (function () { 'use strict';\n\n\tvar commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n\n\tfunction getCjsExportFromNamespace (n) {\n\t\treturn n && n['default'] || n;\n\t}\n\n\tvar load = function(received, defaults, onto = {}) {\n\t var k, ref, v;\n\t for (k in defaults) {\n\t v = defaults[k];\n\t onto[k] = (ref = received[k]) != null ? ref : v;\n\t }\n\t return onto;\n\t};\n\n\tvar overwrite = function(received, defaults, onto = {}) {\n\t var k, v;\n\t for (k in received) {\n\t v = received[k];\n\t if (defaults[k] !== void 0) {\n\t onto[k] = v;\n\t }\n\t }\n\t return onto;\n\t};\n\n\tvar parser = {\n\t\tload: load,\n\t\toverwrite: overwrite\n\t};\n\n\tvar DLList;\n\n\tDLList = class DLList {\n\t constructor(incr, decr) {\n\t this.incr = incr;\n\t this.decr = decr;\n\t this._first = null;\n\t this._last = null;\n\t this.length = 0;\n\t }\n\n\t push(value) {\n\t var node;\n\t this.length++;\n\t if (typeof this.incr === \"function\") {\n\t this.incr();\n\t }\n\t node = {\n\t value,\n\t prev: this._last,\n\t next: null\n\t };\n\t if (this._last != null) {\n\t this._last.next = node;\n\t this._last = node;\n\t } else {\n\t this._first = this._last = node;\n\t }\n\t return void 0;\n\t }\n\n\t shift() {\n\t var value;\n\t if (this._first == null) {\n\t return;\n\t } else {\n\t this.length--;\n\t if (typeof this.decr === \"function\") {\n\t this.decr();\n\t }\n\t }\n\t value = this._first.value;\n\t if ((this._first = this._first.next) != null) {\n\t this._first.prev = null;\n\t } else {\n\t this._last = null;\n\t }\n\t return value;\n\t }\n\n\t first() {\n\t if (this._first != null) {\n\t return this._first.value;\n\t }\n\t }\n\n\t getArray() {\n\t var node, ref, results;\n\t node = this._first;\n\t results = [];\n\t while (node != null) {\n\t results.push((ref = node, node = node.next, ref.value));\n\t }\n\t return results;\n\t }\n\n\t forEachShift(cb) {\n\t var node;\n\t node = this.shift();\n\t while (node != null) {\n\t (cb(node), node = this.shift());\n\t }\n\t return void 0;\n\t }\n\n\t debug() {\n\t var node, ref, ref1, ref2, results;\n\t node = this._first;\n\t results = [];\n\t while (node != null) {\n\t results.push((ref = node, node = node.next, {\n\t value: ref.value,\n\t prev: (ref1 = ref.prev) != null ? ref1.value : void 0,\n\t next: (ref2 = ref.next) != null ? ref2.value : void 0\n\t }));\n\t }\n\t return results;\n\t }\n\n\t};\n\n\tvar DLList_1 = DLList;\n\n\tvar Events;\n\n\tEvents = class Events {\n\t constructor(instance) {\n\t this.instance = instance;\n\t this._events = {};\n\t if ((this.instance.on != null) || (this.instance.once != null) || (this.instance.removeAllListeners != null)) {\n\t throw new Error(\"An Emitter already exists for this object\");\n\t }\n\t this.instance.on = (name, cb) => {\n\t return this._addListener(name, \"many\", cb);\n\t };\n\t this.instance.once = (name, cb) => {\n\t return this._addListener(name, \"once\", cb);\n\t };\n\t this.instance.removeAllListeners = (name = null) => {\n\t if (name != null) {\n\t return delete this._events[name];\n\t } else {\n\t return this._events = {};\n\t }\n\t };\n\t }\n\n\t _addListener(name, status, cb) {\n\t var base;\n\t if ((base = this._events)[name] == null) {\n\t base[name] = [];\n\t }\n\t this._events[name].push({cb, status});\n\t return this.instance;\n\t }\n\n\t listenerCount(name) {\n\t if (this._events[name] != null) {\n\t return this._events[name].length;\n\t } else {\n\t return 0;\n\t }\n\t }\n\n\t async trigger(name, ...args) {\n\t var e, promises;\n\t try {\n\t if (name !== \"debug\") {\n\t this.trigger(\"debug\", `Event triggered: ${name}`, args);\n\t }\n\t if (this._events[name] == null) {\n\t return;\n\t }\n\t this._events[name] = this._events[name].filter(function(listener) {\n\t return listener.status !== \"none\";\n\t });\n\t promises = this._events[name].map(async(listener) => {\n\t var e, returned;\n\t if (listener.status === \"none\") {\n\t return;\n\t }\n\t if (listener.status === \"once\") {\n\t listener.status = \"none\";\n\t }\n\t try {\n\t returned = typeof listener.cb === \"function\" ? listener.cb(...args) : void 0;\n\t if (typeof (returned != null ? returned.then : void 0) === \"function\") {\n\t return (await returned);\n\t } else {\n\t return returned;\n\t }\n\t } catch (error) {\n\t e = error;\n\t {\n\t this.trigger(\"error\", e);\n\t }\n\t return null;\n\t }\n\t });\n\t return ((await Promise.all(promises))).find(function(x) {\n\t return x != null;\n\t });\n\t } catch (error) {\n\t e = error;\n\t {\n\t this.trigger(\"error\", e);\n\t }\n\t return null;\n\t }\n\t }\n\n\t};\n\n\tvar Events_1 = Events;\n\n\tvar DLList$1, Events$1, Queues;\n\n\tDLList$1 = DLList_1;\n\n\tEvents$1 = Events_1;\n\n\tQueues = class Queues {\n\t constructor(num_priorities) {\n\t var i;\n\t this.Events = new Events$1(this);\n\t this._length = 0;\n\t this._lists = (function() {\n\t var j, ref, results;\n\t results = [];\n\t for (i = j = 1, ref = num_priorities; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) {\n\t results.push(new DLList$1((() => {\n\t return this.incr();\n\t }), (() => {\n\t return this.decr();\n\t })));\n\t }\n\t return results;\n\t }).call(this);\n\t }\n\n\t incr() {\n\t if (this._length++ === 0) {\n\t return this.Events.trigger(\"leftzero\");\n\t }\n\t }\n\n\t decr() {\n\t if (--this._length === 0) {\n\t return this.Events.trigger(\"zero\");\n\t }\n\t }\n\n\t push(job) {\n\t return this._lists[job.options.priority].push(job);\n\t }\n\n\t queued(priority) {\n\t if (priority != null) {\n\t return this._lists[priority].length;\n\t } else {\n\t return this._length;\n\t }\n\t }\n\n\t shiftAll(fn) {\n\t return this._lists.forEach(function(list) {\n\t return list.forEachShift(fn);\n\t });\n\t }\n\n\t getFirst(arr = this._lists) {\n\t var j, len, list;\n\t for (j = 0, len = arr.length; j < len; j++) {\n\t list = arr[j];\n\t if (list.length > 0) {\n\t return list;\n\t }\n\t }\n\t return [];\n\t }\n\n\t shiftLastFrom(priority) {\n\t return this.getFirst(this._lists.slice(priority).reverse()).shift();\n\t }\n\n\t};\n\n\tvar Queues_1 = Queues;\n\n\tvar BottleneckError;\n\n\tBottleneckError = class BottleneckError extends Error {};\n\n\tvar BottleneckError_1 = BottleneckError;\n\n\tvar BottleneckError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1;\n\n\tNUM_PRIORITIES = 10;\n\n\tDEFAULT_PRIORITY = 5;\n\n\tparser$1 = parser;\n\n\tBottleneckError$1 = BottleneckError_1;\n\n\tJob = class Job {\n\t constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) {\n\t this.task = task;\n\t this.args = args;\n\t this.rejectOnDrop = rejectOnDrop;\n\t this.Events = Events;\n\t this._states = _states;\n\t this.Promise = Promise;\n\t this.options = parser$1.load(options, jobDefaults);\n\t this.options.priority = this._sanitizePriority(this.options.priority);\n\t if (this.options.id === jobDefaults.id) {\n\t this.options.id = `${this.options.id}-${this._randomIndex()}`;\n\t }\n\t this.promise = new this.Promise((_resolve, _reject) => {\n\t this._resolve = _resolve;\n\t this._reject = _reject;\n\t });\n\t this.retryCount = 0;\n\t }\n\n\t _sanitizePriority(priority) {\n\t var sProperty;\n\t sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority;\n\t if (sProperty < 0) {\n\t return 0;\n\t } else if (sProperty > NUM_PRIORITIES - 1) {\n\t return NUM_PRIORITIES - 1;\n\t } else {\n\t return sProperty;\n\t }\n\t }\n\n\t _randomIndex() {\n\t return Math.random().toString(36).slice(2);\n\t }\n\n\t doDrop({error, message = \"This job has been dropped by Bottleneck\"} = {}) {\n\t if (this._states.remove(this.options.id)) {\n\t if (this.rejectOnDrop) {\n\t this._reject(error != null ? error : new BottleneckError$1(message));\n\t }\n\t this.Events.trigger(\"dropped\", {args: this.args, options: this.options, task: this.task, promise: this.promise});\n\t return true;\n\t } else {\n\t return false;\n\t }\n\t }\n\n\t _assertStatus(expected) {\n\t var status;\n\t status = this._states.jobStatus(this.options.id);\n\t if (!(status === expected || (expected === \"DONE\" && status === null))) {\n\t throw new BottleneckError$1(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`);\n\t }\n\t }\n\n\t doReceive() {\n\t this._states.start(this.options.id);\n\t return this.Events.trigger(\"received\", {args: this.args, options: this.options});\n\t }\n\n\t doQueue(reachedHWM, blocked) {\n\t this._assertStatus(\"RECEIVED\");\n\t this._states.next(this.options.id);\n\t return this.Events.trigger(\"queued\", {args: this.args, options: this.options, reachedHWM, blocked});\n\t }\n\n\t doRun() {\n\t if (this.retryCount === 0) {\n\t this._assertStatus(\"QUEUED\");\n\t this._states.next(this.options.id);\n\t } else {\n\t this._assertStatus(\"EXECUTING\");\n\t }\n\t return this.Events.trigger(\"scheduled\", {args: this.args, options: this.options});\n\t }\n\n\t async doExecute(chained, clearGlobalState, run, free) {\n\t var error, eventInfo, passed;\n\t if (this.retryCount === 0) {\n\t this._assertStatus(\"RUNNING\");\n\t this._states.next(this.options.id);\n\t } else {\n\t this._assertStatus(\"EXECUTING\");\n\t }\n\t eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount};\n\t this.Events.trigger(\"executing\", eventInfo);\n\t try {\n\t passed = (await (chained != null ? chained.schedule(this.options, this.task, ...this.args) : this.task(...this.args)));\n\t if (clearGlobalState()) {\n\t this.doDone(eventInfo);\n\t await free(this.options, eventInfo);\n\t this._assertStatus(\"DONE\");\n\t return this._resolve(passed);\n\t }\n\t } catch (error1) {\n\t error = error1;\n\t return this._onFailure(error, eventInfo, clearGlobalState, run, free);\n\t }\n\t }\n\n\t doExpire(clearGlobalState, run, free) {\n\t var error, eventInfo;\n\t if (this._states.jobStatus(this.options.id === \"RUNNING\")) {\n\t this._states.next(this.options.id);\n\t }\n\t this._assertStatus(\"EXECUTING\");\n\t eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount};\n\t error = new BottleneckError$1(`This job timed out after ${this.options.expiration} ms.`);\n\t return this._onFailure(error, eventInfo, clearGlobalState, run, free);\n\t }\n\n\t async _onFailure(error, eventInfo, clearGlobalState, run, free) {\n\t var retry, retryAfter;\n\t if (clearGlobalState()) {\n\t retry = (await this.Events.trigger(\"failed\", error, eventInfo));\n\t if (retry != null) {\n\t retryAfter = ~~retry;\n\t this.Events.trigger(\"retry\", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo);\n\t this.retryCount++;\n\t return run(retryAfter);\n\t } else {\n\t this.doDone(eventInfo);\n\t await free(this.options, eventInfo);\n\t this._assertStatus(\"DONE\");\n\t return this._reject(error);\n\t }\n\t }\n\t }\n\n\t doDone(eventInfo) {\n\t this._assertStatus(\"EXECUTING\");\n\t this._states.next(this.options.id);\n\t return this.Events.trigger(\"done\", eventInfo);\n\t }\n\n\t};\n\n\tvar Job_1 = Job;\n\n\tvar BottleneckError$2, LocalDatastore, parser$2;\n\n\tparser$2 = parser;\n\n\tBottleneckError$2 = BottleneckError_1;\n\n\tLocalDatastore = class LocalDatastore {\n\t constructor(instance, storeOptions, storeInstanceOptions) {\n\t this.instance = instance;\n\t this.storeOptions = storeOptions;\n\t this.clientId = this.instance._randomIndex();\n\t parser$2.load(storeInstanceOptions, storeInstanceOptions, this);\n\t this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now();\n\t this._running = 0;\n\t this._done = 0;\n\t this._unblockTime = 0;\n\t this.ready = this.Promise.resolve();\n\t this.clients = {};\n\t this._startHeartbeat();\n\t }\n\n\t _startHeartbeat() {\n\t var base;\n\t if ((this.heartbeat == null) && (((this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) || ((this.storeOptions.reservoirIncreaseInterval != null) && (this.storeOptions.reservoirIncreaseAmount != null)))) {\n\t return typeof (base = (this.heartbeat = setInterval(() => {\n\t var amount, incr, maximum, now, reservoir;\n\t now = Date.now();\n\t if ((this.storeOptions.reservoirRefreshInterval != null) && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) {\n\t this._lastReservoirRefresh = now;\n\t this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount;\n\t this.instance._drainAll(this.computeCapacity());\n\t }\n\t if ((this.storeOptions.reservoirIncreaseInterval != null) && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) {\n\t ({\n\t reservoirIncreaseAmount: amount,\n\t reservoirIncreaseMaximum: maximum,\n\t reservoir\n\t } = this.storeOptions);\n\t this._lastReservoirIncrease = now;\n\t incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount;\n\t if (incr > 0) {\n\t this.storeOptions.reservoir += incr;\n\t return this.instance._drainAll(this.computeCapacity());\n\t }\n\t }\n\t }, this.heartbeatInterval))).unref === \"function\" ? base.unref() : void 0;\n\t } else {\n\t return clearInterval(this.heartbeat);\n\t }\n\t }\n\n\t async __publish__(message) {\n\t await this.yieldLoop();\n\t return this.instance.Events.trigger(\"message\", message.toString());\n\t }\n\n\t async __disconnect__(flush) {\n\t await this.yieldLoop();\n\t clearInterval(this.heartbeat);\n\t return this.Promise.resolve();\n\t }\n\n\t yieldLoop(t = 0) {\n\t return new this.Promise(function(resolve, reject) {\n\t return setTimeout(resolve, t);\n\t });\n\t }\n\n\t computePenalty() {\n\t var ref;\n\t return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000;\n\t }\n\n\t async __updateSettings__(options) {\n\t await this.yieldLoop();\n\t parser$2.overwrite(options, options, this.storeOptions);\n\t this._startHeartbeat();\n\t this.instance._drainAll(this.computeCapacity());\n\t return true;\n\t }\n\n\t async __running__() {\n\t await this.yieldLoop();\n\t return this._running;\n\t }\n\n\t async __queued__() {\n\t await this.yieldLoop();\n\t return this.instance.queued();\n\t }\n\n\t async __done__() {\n\t await this.yieldLoop();\n\t return this._done;\n\t }\n\n\t async __groupCheck__(time) {\n\t await this.yieldLoop();\n\t return (this._nextRequest + this.timeout) < time;\n\t }\n\n\t computeCapacity() {\n\t var maxConcurrent, reservoir;\n\t ({maxConcurrent, reservoir} = this.storeOptions);\n\t if ((maxConcurrent != null) && (reservoir != null)) {\n\t return Math.min(maxConcurrent - this._running, reservoir);\n\t } else if (maxConcurrent != null) {\n\t return maxConcurrent - this._running;\n\t } else if (reservoir != null) {\n\t return reservoir;\n\t } else {\n\t return null;\n\t }\n\t }\n\n\t conditionsCheck(weight) {\n\t var capacity;\n\t capacity = this.computeCapacity();\n\t return (capacity == null) || weight <= capacity;\n\t }\n\n\t async __incrementReservoir__(incr) {\n\t var reservoir;\n\t await this.yieldLoop();\n\t reservoir = this.storeOptions.reservoir += incr;\n\t this.instance._drainAll(this.computeCapacity());\n\t return reservoir;\n\t }\n\n\t async __currentReservoir__() {\n\t await this.yieldLoop();\n\t return this.storeOptions.reservoir;\n\t }\n\n\t isBlocked(now) {\n\t return this._unblockTime >= now;\n\t }\n\n\t check(weight, now) {\n\t return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0;\n\t }\n\n\t async __check__(weight) {\n\t var now;\n\t await this.yieldLoop();\n\t now = Date.now();\n\t return this.check(weight, now);\n\t }\n\n\t async __register__(index, weight, expiration) {\n\t var now, wait;\n\t await this.yieldLoop();\n\t now = Date.now();\n\t if (this.conditionsCheck(weight)) {\n\t this._running += weight;\n\t if (this.storeOptions.reservoir != null) {\n\t this.storeOptions.reservoir -= weight;\n\t }\n\t wait = Math.max(this._nextRequest - now, 0);\n\t this._nextRequest = now + wait + this.storeOptions.minTime;\n\t return {\n\t success: true,\n\t wait,\n\t reservoir: this.storeOptions.reservoir\n\t };\n\t } else {\n\t return {\n\t success: false\n\t };\n\t }\n\t }\n\n\t strategyIsBlock() {\n\t return this.storeOptions.strategy === 3;\n\t }\n\n\t async __submit__(queueLength, weight) {\n\t var blocked, now, reachedHWM;\n\t await this.yieldLoop();\n\t if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) {\n\t throw new BottleneckError$2(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`);\n\t }\n\t now = Date.now();\n\t reachedHWM = (this.storeOptions.highWater != null) && queueLength === this.storeOptions.highWater && !this.check(weight, now);\n\t blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now));\n\t if (blocked) {\n\t this._unblockTime = now + this.computePenalty();\n\t this._nextRequest = this._unblockTime + this.storeOptions.minTime;\n\t this.instance._dropAllQueued();\n\t }\n\t return {\n\t reachedHWM,\n\t blocked,\n\t strategy: this.storeOptions.strategy\n\t };\n\t }\n\n\t async __free__(index, weight) {\n\t await this.yieldLoop();\n\t this._running -= weight;\n\t this._done += weight;\n\t this.instance._drainAll(this.computeCapacity());\n\t return {\n\t running: this._running\n\t };\n\t }\n\n\t};\n\n\tvar LocalDatastore_1 = LocalDatastore;\n\n\tvar BottleneckError$3, States;\n\n\tBottleneckError$3 = BottleneckError_1;\n\n\tStates = class States {\n\t constructor(status1) {\n\t this.status = status1;\n\t this._jobs = {};\n\t this.counts = this.status.map(function() {\n\t return 0;\n\t });\n\t }\n\n\t next(id) {\n\t var current, next;\n\t current = this._jobs[id];\n\t next = current + 1;\n\t if ((current != null) && next < this.status.length) {\n\t this.counts[current]--;\n\t this.counts[next]++;\n\t return this._jobs[id]++;\n\t } else if (current != null) {\n\t this.counts[current]--;\n\t return delete this._jobs[id];\n\t }\n\t }\n\n\t start(id) {\n\t var initial;\n\t initial = 0;\n\t this._jobs[id] = initial;\n\t return this.counts[initial]++;\n\t }\n\n\t remove(id) {\n\t var current;\n\t current = this._jobs[id];\n\t if (current != null) {\n\t this.counts[current]--;\n\t delete this._jobs[id];\n\t }\n\t return current != null;\n\t }\n\n\t jobStatus(id) {\n\t var ref;\n\t return (ref = this.status[this._jobs[id]]) != null ? ref : null;\n\t }\n\n\t statusJobs(status) {\n\t var k, pos, ref, results, v;\n\t if (status != null) {\n\t pos = this.status.indexOf(status);\n\t if (pos < 0) {\n\t throw new BottleneckError$3(`status must be one of ${this.status.join(', ')}`);\n\t }\n\t ref = this._jobs;\n\t results = [];\n\t for (k in ref) {\n\t v = ref[k];\n\t if (v === pos) {\n\t results.push(k);\n\t }\n\t }\n\t return results;\n\t } else {\n\t return Object.keys(this._jobs);\n\t }\n\t }\n\n\t statusCounts() {\n\t return this.counts.reduce(((acc, v, i) => {\n\t acc[this.status[i]] = v;\n\t return acc;\n\t }), {});\n\t }\n\n\t};\n\n\tvar States_1 = States;\n\n\tvar DLList$2, Sync;\n\n\tDLList$2 = DLList_1;\n\n\tSync = class Sync {\n\t constructor(name, Promise) {\n\t this.schedule = this.schedule.bind(this);\n\t this.name = name;\n\t this.Promise = Promise;\n\t this._running = 0;\n\t this._queue = new DLList$2();\n\t }\n\n\t isEmpty() {\n\t return this._queue.length === 0;\n\t }\n\n\t async _tryToRun() {\n\t var args, cb, error, reject, resolve, returned, task;\n\t if ((this._running < 1) && this._queue.length > 0) {\n\t this._running++;\n\t ({task, args, resolve, reject} = this._queue.shift());\n\t cb = (await (async function() {\n\t try {\n\t returned = (await task(...args));\n\t return function() {\n\t return resolve(returned);\n\t };\n\t } catch (error1) {\n\t error = error1;\n\t return function() {\n\t return reject(error);\n\t };\n\t }\n\t })());\n\t this._running--;\n\t this._tryToRun();\n\t return cb();\n\t }\n\t }\n\n\t schedule(task, ...args) {\n\t var promise, reject, resolve;\n\t resolve = reject = null;\n\t promise = new this.Promise(function(_resolve, _reject) {\n\t resolve = _resolve;\n\t return reject = _reject;\n\t });\n\t this._queue.push({task, args, resolve, reject});\n\t this._tryToRun();\n\t return promise;\n\t }\n\n\t};\n\n\tvar Sync_1 = Sync;\n\n\tvar version = \"2.19.5\";\n\tvar version$1 = {\n\t\tversion: version\n\t};\n\n\tvar version$2 = /*#__PURE__*/Object.freeze({\n\t\tversion: version,\n\t\tdefault: version$1\n\t});\n\n\tvar require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.');\n\n\tvar require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.');\n\n\tvar require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.');\n\n\tvar Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3;\n\n\tparser$3 = parser;\n\n\tEvents$2 = Events_1;\n\n\tRedisConnection$1 = require$$2;\n\n\tIORedisConnection$1 = require$$3;\n\n\tScripts$1 = require$$4;\n\n\tGroup = (function() {\n\t class Group {\n\t constructor(limiterOptions = {}) {\n\t this.deleteKey = this.deleteKey.bind(this);\n\t this.limiterOptions = limiterOptions;\n\t parser$3.load(this.limiterOptions, this.defaults, this);\n\t this.Events = new Events$2(this);\n\t this.instances = {};\n\t this.Bottleneck = Bottleneck_1;\n\t this._startAutoCleanup();\n\t this.sharedConnection = this.connection != null;\n\t if (this.connection == null) {\n\t if (this.limiterOptions.datastore === \"redis\") {\n\t this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events}));\n\t } else if (this.limiterOptions.datastore === \"ioredis\") {\n\t this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events}));\n\t }\n\t }\n\t }\n\n\t key(key = \"\") {\n\t var ref;\n\t return (ref = this.instances[key]) != null ? ref : (() => {\n\t var limiter;\n\t limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, {\n\t id: `${this.id}-${key}`,\n\t timeout: this.timeout,\n\t connection: this.connection\n\t }));\n\t this.Events.trigger(\"created\", limiter, key);\n\t return limiter;\n\t })();\n\t }\n\n\t async deleteKey(key = \"\") {\n\t var deleted, instance;\n\t instance = this.instances[key];\n\t if (this.connection) {\n\t deleted = (await this.connection.__runCommand__(['del', ...Scripts$1.allKeys(`${this.id}-${key}`)]));\n\t }\n\t if (instance != null) {\n\t delete this.instances[key];\n\t await instance.disconnect();\n\t }\n\t return (instance != null) || deleted > 0;\n\t }\n\n\t limiters() {\n\t var k, ref, results, v;\n\t ref = this.instances;\n\t results = [];\n\t for (k in ref) {\n\t v = ref[k];\n\t results.push({\n\t key: k,\n\t limiter: v\n\t });\n\t }\n\t return results;\n\t }\n\n\t keys() {\n\t return Object.keys(this.instances);\n\t }\n\n\t async clusterKeys() {\n\t var cursor, end, found, i, k, keys, len, next, start;\n\t if (this.connection == null) {\n\t return this.Promise.resolve(this.keys());\n\t }\n\t keys = [];\n\t cursor = null;\n\t start = `b_${this.id}-`.length;\n\t end = \"_settings\".length;\n\t while (cursor !== 0) {\n\t [next, found] = (await this.connection.__runCommand__([\"scan\", cursor != null ? cursor : 0, \"match\", `b_${this.id}-*_settings`, \"count\", 10000]));\n\t cursor = ~~next;\n\t for (i = 0, len = found.length; i < len; i++) {\n\t k = found[i];\n\t keys.push(k.slice(start, -end));\n\t }\n\t }\n\t return keys;\n\t }\n\n\t _startAutoCleanup() {\n\t var base;\n\t clearInterval(this.interval);\n\t return typeof (base = (this.interval = setInterval(async() => {\n\t var e, k, ref, results, time, v;\n\t time = Date.now();\n\t ref = this.instances;\n\t results = [];\n\t for (k in ref) {\n\t v = ref[k];\n\t try {\n\t if ((await v._store.__groupCheck__(time))) {\n\t results.push(this.deleteKey(k));\n\t } else {\n\t results.push(void 0);\n\t }\n\t } catch (error) {\n\t e = error;\n\t results.push(v.Events.trigger(\"error\", e));\n\t }\n\t }\n\t return results;\n\t }, this.timeout / 2))).unref === \"function\" ? base.unref() : void 0;\n\t }\n\n\t updateSettings(options = {}) {\n\t parser$3.overwrite(options, this.defaults, this);\n\t parser$3.overwrite(options, options, this.limiterOptions);\n\t if (options.timeout != null) {\n\t return this._startAutoCleanup();\n\t }\n\t }\n\n\t disconnect(flush = true) {\n\t var ref;\n\t if (!this.sharedConnection) {\n\t return (ref = this.connection) != null ? ref.disconnect(flush) : void 0;\n\t }\n\t }\n\n\t }\n\t Group.prototype.defaults = {\n\t timeout: 1000 * 60 * 5,\n\t connection: null,\n\t Promise: Promise,\n\t id: \"group-key\"\n\t };\n\n\t return Group;\n\n\t}).call(commonjsGlobal);\n\n\tvar Group_1 = Group;\n\n\tvar Batcher, Events$3, parser$4;\n\n\tparser$4 = parser;\n\n\tEvents$3 = Events_1;\n\n\tBatcher = (function() {\n\t class Batcher {\n\t constructor(options = {}) {\n\t this.options = options;\n\t parser$4.load(this.options, this.defaults, this);\n\t this.Events = new Events$3(this);\n\t this._arr = [];\n\t this._resetPromise();\n\t this._lastFlush = Date.now();\n\t }\n\n\t _resetPromise() {\n\t return this._promise = new this.Promise((res, rej) => {\n\t return this._resolve = res;\n\t });\n\t }\n\n\t _flush() {\n\t clearTimeout(this._timeout);\n\t this._lastFlush = Date.now();\n\t this._resolve();\n\t this.Events.trigger(\"batch\", this._arr);\n\t this._arr = [];\n\t return this._resetPromise();\n\t }\n\n\t add(data) {\n\t var ret;\n\t this._arr.push(data);\n\t ret = this._promise;\n\t if (this._arr.length === this.maxSize) {\n\t this._flush();\n\t } else if ((this.maxTime != null) && this._arr.length === 1) {\n\t this._timeout = setTimeout(() => {\n\t return this._flush();\n\t }, this.maxTime);\n\t }\n\t return ret;\n\t }\n\n\t }\n\t Batcher.prototype.defaults = {\n\t maxTime: null,\n\t maxSize: null,\n\t Promise: Promise\n\t };\n\n\t return Batcher;\n\n\t}).call(commonjsGlobal);\n\n\tvar Batcher_1 = Batcher;\n\n\tvar require$$4$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.');\n\n\tvar require$$8 = getCjsExportFromNamespace(version$2);\n\n\tvar Bottleneck, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5,\n\t splice = [].splice;\n\n\tNUM_PRIORITIES$1 = 10;\n\n\tDEFAULT_PRIORITY$1 = 5;\n\n\tparser$5 = parser;\n\n\tQueues$1 = Queues_1;\n\n\tJob$1 = Job_1;\n\n\tLocalDatastore$1 = LocalDatastore_1;\n\n\tRedisDatastore$1 = require$$4$1;\n\n\tEvents$4 = Events_1;\n\n\tStates$1 = States_1;\n\n\tSync$1 = Sync_1;\n\n\tBottleneck = (function() {\n\t class Bottleneck {\n\t constructor(options = {}, ...invalid) {\n\t var storeInstanceOptions, storeOptions;\n\t this._addToQueue = this._addToQueue.bind(this);\n\t this._validateOptions(options, invalid);\n\t parser$5.load(options, this.instanceDefaults, this);\n\t this._queues = new Queues$1(NUM_PRIORITIES$1);\n\t this._scheduled = {};\n\t this._states = new States$1([\"RECEIVED\", \"QUEUED\", \"RUNNING\", \"EXECUTING\"].concat(this.trackDoneStatus ? [\"DONE\"] : []));\n\t this._limiter = null;\n\t this.Events = new Events$4(this);\n\t this._submitLock = new Sync$1(\"submit\", this.Promise);\n\t this._registerLock = new Sync$1(\"register\", this.Promise);\n\t storeOptions = parser$5.load(options, this.storeDefaults, {});\n\t this._store = (function() {\n\t if (this.datastore === \"redis\" || this.datastore === \"ioredis\" || (this.connection != null)) {\n\t storeInstanceOptions = parser$5.load(options, this.redisStoreDefaults, {});\n\t return new RedisDatastore$1(this, storeOptions, storeInstanceOptions);\n\t } else if (this.datastore === \"local\") {\n\t storeInstanceOptions = parser$5.load(options, this.localStoreDefaults, {});\n\t return new LocalDatastore$1(this, storeOptions, storeInstanceOptions);\n\t } else {\n\t throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`);\n\t }\n\t }).call(this);\n\t this._queues.on(\"leftzero\", () => {\n\t var ref;\n\t return (ref = this._store.heartbeat) != null ? typeof ref.ref === \"function\" ? ref.ref() : void 0 : void 0;\n\t });\n\t this._queues.on(\"zero\", () => {\n\t var ref;\n\t return (ref = this._store.heartbeat) != null ? typeof ref.unref === \"function\" ? ref.unref() : void 0 : void 0;\n\t });\n\t }\n\n\t _validateOptions(options, invalid) {\n\t if (!((options != null) && typeof options === \"object\" && invalid.length === 0)) {\n\t throw new Bottleneck.prototype.BottleneckError(\"Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1.\");\n\t }\n\t }\n\n\t ready() {\n\t return this._store.ready;\n\t }\n\n\t clients() {\n\t return this._store.clients;\n\t }\n\n\t channel() {\n\t return `b_${this.id}`;\n\t }\n\n\t channel_client() {\n\t return `b_${this.id}_${this._store.clientId}`;\n\t }\n\n\t publish(message) {\n\t return this._store.__publish__(message);\n\t }\n\n\t disconnect(flush = true) {\n\t return this._store.__disconnect__(flush);\n\t }\n\n\t chain(_limiter) {\n\t this._limiter = _limiter;\n\t return this;\n\t }\n\n\t queued(priority) {\n\t return this._queues.queued(priority);\n\t }\n\n\t clusterQueued() {\n\t return this._store.__queued__();\n\t }\n\n\t empty() {\n\t return this.queued() === 0 && this._submitLock.isEmpty();\n\t }\n\n\t running() {\n\t return this._store.__running__();\n\t }\n\n\t done() {\n\t return this._store.__done__();\n\t }\n\n\t jobStatus(id) {\n\t return this._states.jobStatus(id);\n\t }\n\n\t jobs(status) {\n\t return this._states.statusJobs(status);\n\t }\n\n\t counts() {\n\t return this._states.statusCounts();\n\t }\n\n\t _randomIndex() {\n\t return Math.random().toString(36).slice(2);\n\t }\n\n\t check(weight = 1) {\n\t return this._store.__check__(weight);\n\t }\n\n\t _clearGlobalState(index) {\n\t if (this._scheduled[index] != null) {\n\t clearTimeout(this._scheduled[index].expiration);\n\t delete this._scheduled[index];\n\t return true;\n\t } else {\n\t return false;\n\t }\n\t }\n\n\t async _free(index, job, options, eventInfo) {\n\t var e, running;\n\t try {\n\t ({running} = (await this._store.__free__(index, options.weight)));\n\t this.Events.trigger(\"debug\", `Freed ${options.id}`, eventInfo);\n\t if (running === 0 && this.empty()) {\n\t return this.Events.trigger(\"idle\");\n\t }\n\t } catch (error1) {\n\t e = error1;\n\t return this.Events.trigger(\"error\", e);\n\t }\n\t }\n\n\t _run(index, job, wait) {\n\t var clearGlobalState, free, run;\n\t job.doRun();\n\t clearGlobalState = this._clearGlobalState.bind(this, index);\n\t run = this._run.bind(this, index, job);\n\t free = this._free.bind(this, index, job);\n\t return this._scheduled[index] = {\n\t timeout: setTimeout(() => {\n\t return job.doExecute(this._limiter, clearGlobalState, run, free);\n\t }, wait),\n\t expiration: job.options.expiration != null ? setTimeout(function() {\n\t return job.doExpire(clearGlobalState, run, free);\n\t }, wait + job.options.expiration) : void 0,\n\t job: job\n\t };\n\t }\n\n\t _drainOne(capacity) {\n\t return this._registerLock.schedule(() => {\n\t var args, index, next, options, queue;\n\t if (this.queued() === 0) {\n\t return this.Promise.resolve(null);\n\t }\n\t queue = this._queues.getFirst();\n\t ({options, args} = next = queue.first());\n\t if ((capacity != null) && options.weight > capacity) {\n\t return this.Promise.resolve(null);\n\t }\n\t this.Events.trigger(\"debug\", `Draining ${options.id}`, {args, options});\n\t index = this._randomIndex();\n\t return this._store.__register__(index, options.weight, options.expiration).then(({success, wait, reservoir}) => {\n\t var empty;\n\t this.Events.trigger(\"debug\", `Drained ${options.id}`, {success, args, options});\n\t if (success) {\n\t queue.shift();\n\t empty = this.empty();\n\t if (empty) {\n\t this.Events.trigger(\"empty\");\n\t }\n\t if (reservoir === 0) {\n\t this.Events.trigger(\"depleted\", empty);\n\t }\n\t this._run(index, next, wait);\n\t return this.Promise.resolve(options.weight);\n\t } else {\n\t return this.Promise.resolve(null);\n\t }\n\t });\n\t });\n\t }\n\n\t _drainAll(capacity, total = 0) {\n\t return this._drainOne(capacity).then((drained) => {\n\t var newCapacity;\n\t if (drained != null) {\n\t newCapacity = capacity != null ? capacity - drained : capacity;\n\t return this._drainAll(newCapacity, total + drained);\n\t } else {\n\t return this.Promise.resolve(total);\n\t }\n\t }).catch((e) => {\n\t return this.Events.trigger(\"error\", e);\n\t });\n\t }\n\n\t _dropAllQueued(message) {\n\t return this._queues.shiftAll(function(job) {\n\t return job.doDrop({message});\n\t });\n\t }\n\n\t stop(options = {}) {\n\t var done, waitForExecuting;\n\t options = parser$5.load(options, this.stopDefaults);\n\t waitForExecuting = (at) => {\n\t var finished;\n\t finished = () => {\n\t var counts;\n\t counts = this._states.counts;\n\t return (counts[0] + counts[1] + counts[2] + counts[3]) === at;\n\t };\n\t return new this.Promise((resolve, reject) => {\n\t if (finished()) {\n\t return resolve();\n\t } else {\n\t return this.on(\"done\", () => {\n\t if (finished()) {\n\t this.removeAllListeners(\"done\");\n\t return resolve();\n\t }\n\t });\n\t }\n\t });\n\t };\n\t done = options.dropWaitingJobs ? (this._run = function(index, next) {\n\t return next.doDrop({\n\t message: options.dropErrorMessage\n\t });\n\t }, this._drainOne = () => {\n\t return this.Promise.resolve(null);\n\t }, this._registerLock.schedule(() => {\n\t return this._submitLock.schedule(() => {\n\t var k, ref, v;\n\t ref = this._scheduled;\n\t for (k in ref) {\n\t v = ref[k];\n\t if (this.jobStatus(v.job.options.id) === \"RUNNING\") {\n\t clearTimeout(v.timeout);\n\t clearTimeout(v.expiration);\n\t v.job.doDrop({\n\t message: options.dropErrorMessage\n\t });\n\t }\n\t }\n\t this._dropAllQueued(options.dropErrorMessage);\n\t return waitForExecuting(0);\n\t });\n\t })) : this.schedule({\n\t priority: NUM_PRIORITIES$1 - 1,\n\t weight: 0\n\t }, () => {\n\t return waitForExecuting(1);\n\t });\n\t this._receive = function(job) {\n\t return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage));\n\t };\n\t this.stop = () => {\n\t return this.Promise.reject(new Bottleneck.prototype.BottleneckError(\"stop() has already been called\"));\n\t };\n\t return done;\n\t }\n\n\t async _addToQueue(job) {\n\t var args, blocked, error, options, reachedHWM, shifted, strategy;\n\t ({args, options} = job);\n\t try {\n\t ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight)));\n\t } catch (error1) {\n\t error = error1;\n\t this.Events.trigger(\"debug\", `Could not queue ${options.id}`, {args, options, error});\n\t job.doDrop({error});\n\t return false;\n\t }\n\t if (blocked) {\n\t job.doDrop();\n\t return true;\n\t } else if (reachedHWM) {\n\t shifted = strategy === Bottleneck.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0;\n\t if (shifted != null) {\n\t shifted.doDrop();\n\t }\n\t if ((shifted == null) || strategy === Bottleneck.prototype.strategy.OVERFLOW) {\n\t if (shifted == null) {\n\t job.doDrop();\n\t }\n\t return reachedHWM;\n\t }\n\t }\n\t job.doQueue(reachedHWM, blocked);\n\t this._queues.push(job);\n\t await this._drainAll();\n\t return reachedHWM;\n\t }\n\n\t _receive(job) {\n\t if (this._states.jobStatus(job.options.id) != null) {\n\t job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`));\n\t return false;\n\t } else {\n\t job.doReceive();\n\t return this._submitLock.schedule(this._addToQueue, job);\n\t }\n\t }\n\n\t submit(...args) {\n\t var cb, fn, job, options, ref, ref1, task;\n\t if (typeof args[0] === \"function\") {\n\t ref = args, [fn, ...args] = ref, [cb] = splice.call(args, -1);\n\t options = parser$5.load({}, this.jobDefaults);\n\t } else {\n\t ref1 = args, [options, fn, ...args] = ref1, [cb] = splice.call(args, -1);\n\t options = parser$5.load(options, this.jobDefaults);\n\t }\n\t task = (...args) => {\n\t return new this.Promise(function(resolve, reject) {\n\t return fn(...args, function(...args) {\n\t return (args[0] != null ? reject : resolve)(args);\n\t });\n\t });\n\t };\n\t job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise);\n\t job.promise.then(function(args) {\n\t return typeof cb === \"function\" ? cb(...args) : void 0;\n\t }).catch(function(args) {\n\t if (Array.isArray(args)) {\n\t return typeof cb === \"function\" ? cb(...args) : void 0;\n\t } else {\n\t return typeof cb === \"function\" ? cb(args) : void 0;\n\t }\n\t });\n\t return this._receive(job);\n\t }\n\n\t schedule(...args) {\n\t var job, options, task;\n\t if (typeof args[0] === \"function\") {\n\t [task, ...args] = args;\n\t options = {};\n\t } else {\n\t [options, task, ...args] = args;\n\t }\n\t job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise);\n\t this._receive(job);\n\t return job.promise;\n\t }\n\n\t wrap(fn) {\n\t var schedule, wrapped;\n\t schedule = this.schedule.bind(this);\n\t wrapped = function(...args) {\n\t return schedule(fn.bind(this), ...args);\n\t };\n\t wrapped.withOptions = function(options, ...args) {\n\t return schedule(options, fn, ...args);\n\t };\n\t return wrapped;\n\t }\n\n\t async updateSettings(options = {}) {\n\t await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults));\n\t parser$5.overwrite(options, this.instanceDefaults, this);\n\t return this;\n\t }\n\n\t currentReservoir() {\n\t return this._store.__currentReservoir__();\n\t }\n\n\t incrementReservoir(incr = 0) {\n\t return this._store.__incrementReservoir__(incr);\n\t }\n\n\t }\n\t Bottleneck.default = Bottleneck;\n\n\t Bottleneck.Events = Events$4;\n\n\t Bottleneck.version = Bottleneck.prototype.version = require$$8.version;\n\n\t Bottleneck.strategy = Bottleneck.prototype.strategy = {\n\t LEAK: 1,\n\t OVERFLOW: 2,\n\t OVERFLOW_PRIORITY: 4,\n\t BLOCK: 3\n\t };\n\n\t Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1;\n\n\t Bottleneck.Group = Bottleneck.prototype.Group = Group_1;\n\n\t Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2;\n\n\t Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3;\n\n\t Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1;\n\n\t Bottleneck.prototype.jobDefaults = {\n\t priority: DEFAULT_PRIORITY$1,\n\t weight: 1,\n\t expiration: null,\n\t id: \"\"\n\t };\n\n\t Bottleneck.prototype.storeDefaults = {\n\t maxConcurrent: null,\n\t minTime: 0,\n\t highWater: null,\n\t strategy: Bottleneck.prototype.strategy.LEAK,\n\t penalty: null,\n\t reservoir: null,\n\t reservoirRefreshInterval: null,\n\t reservoirRefreshAmount: null,\n\t reservoirIncreaseInterval: null,\n\t reservoirIncreaseAmount: null,\n\t reservoirIncreaseMaximum: null\n\t };\n\n\t Bottleneck.prototype.localStoreDefaults = {\n\t Promise: Promise,\n\t timeout: null,\n\t heartbeatInterval: 250\n\t };\n\n\t Bottleneck.prototype.redisStoreDefaults = {\n\t Promise: Promise,\n\t timeout: null,\n\t heartbeatInterval: 5000,\n\t clientTimeout: 10000,\n\t Redis: null,\n\t clientOptions: {},\n\t clusterNodes: null,\n\t clearDatastore: false,\n\t connection: null\n\t };\n\n\t Bottleneck.prototype.instanceDefaults = {\n\t datastore: \"local\",\n\t connection: null,\n\t id: \"\",\n\t rejectOnDrop: true,\n\t trackDoneStatus: false,\n\t Promise: Promise\n\t };\n\n\t Bottleneck.prototype.stopDefaults = {\n\t enqueueErrorMessage: \"This limiter has been stopped and cannot accept new jobs.\",\n\t dropWaitingJobs: true,\n\t dropErrorMessage: \"This limiter has been stopped.\"\n\t };\n\n\t return Bottleneck;\n\n\t}).call(commonjsGlobal);\n\n\tvar Bottleneck_1 = Bottleneck;\n\n\tvar lib = Bottleneck_1;\n\n\treturn lib;\n\n})));\n","class RequestError extends Error {\n name;\n /**\n * http status code\n */\n status;\n /**\n * Request options that lead to the error.\n */\n request;\n /**\n * Response object if a response was received\n */\n response;\n constructor(message, statusCode, options) {\n super(message);\n this.name = \"HttpError\";\n this.status = Number.parseInt(statusCode);\n if (Number.isNaN(this.status)) {\n this.status = 0;\n }\n if (\"response\" in options) {\n this.response = options.response;\n }\n const requestCopy = Object.assign({}, options.request);\n if (options.request.headers.authorization) {\n requestCopy.headers = Object.assign({}, options.request.headers, {\n authorization: options.request.headers.authorization.replace(\n /(?= 400 && !state.doNotRetry.includes(error.status)) {\n const retries = options.request.retries != null ? options.request.retries : state.retries;\n const retryAfter = Math.pow((options.request.retryCount || 0) + 1, 2);\n throw octokit.retry.retryRequest(error, retries, retryAfter);\n }\n throw error;\n}\n\n// pkg/dist-src/wrap-request.js\nimport Bottleneck from \"bottleneck/light.js\";\nimport { RequestError } from \"@octokit/request-error\";\nasync function wrapRequest(state, octokit, request, options) {\n const limiter = new Bottleneck();\n limiter.on(\"failed\", function(error, info) {\n const maxRetries = ~~error.request.request.retries;\n const after = ~~error.request.request.retryAfter;\n options.request.retryCount = info.retryCount + 1;\n if (maxRetries > info.retryCount) {\n return after * state.retryAfterBaseValue;\n }\n });\n return limiter.schedule(\n requestWithGraphqlErrorHandling.bind(null, state, octokit, request),\n options\n );\n}\nasync function requestWithGraphqlErrorHandling(state, octokit, request, options) {\n const response = await request(request, options);\n if (response.data && response.data.errors && response.data.errors.length > 0 && /Something went wrong while executing your query/.test(\n response.data.errors[0].message\n )) {\n const error = new RequestError(response.data.errors[0].message, 500, {\n request: options,\n response\n });\n return errorRequest(state, octokit, error, options);\n }\n return response;\n}\n\n// pkg/dist-src/index.js\nfunction retry(octokit, octokitOptions) {\n const state = Object.assign(\n {\n enabled: true,\n retryAfterBaseValue: 1e3,\n doNotRetry: [400, 401, 403, 404, 410, 422, 451],\n retries: 3\n },\n octokitOptions.retry\n );\n if (state.enabled) {\n octokit.hook.error(\"request\", errorRequest.bind(null, state, octokit));\n octokit.hook.wrap(\"request\", wrapRequest.bind(null, state, octokit));\n }\n return {\n retry: {\n retryRequest: (error, retries, retryAfter) => {\n error.request.request = Object.assign({}, error.request.request, {\n retries,\n retryAfter\n });\n return error;\n }\n }\n };\n}\nretry.VERSION = VERSION;\nexport {\n VERSION,\n retry\n};\n","module.exports = {\n /* The local file header */\n LOCHDR : 30, // LOC header size\n LOCSIG : 0x04034b50, // \"PK\\003\\004\"\n LOCVER : 4,\t// version needed to extract\n LOCFLG : 6, // general purpose bit flag\n LOCHOW : 8, // compression method\n LOCTIM : 10, // modification time (2 bytes time, 2 bytes date)\n LOCCRC : 14, // uncompressed file crc-32 value\n LOCSIZ : 18, // compressed size\n LOCLEN : 22, // uncompressed size\n LOCNAM : 26, // filename length\n LOCEXT : 28, // extra field length\n\n /* The Data descriptor */\n EXTSIG : 0x08074b50, // \"PK\\007\\008\"\n EXTHDR : 16, // EXT header size\n EXTCRC : 4, // uncompressed file crc-32 value\n EXTSIZ : 8, // compressed size\n EXTLEN : 12, // uncompressed size\n\n /* The central directory file header */\n CENHDR : 46, // CEN header size\n CENSIG : 0x02014b50, // \"PK\\001\\002\"\n CENVEM : 4, // version made by\n CENVER : 6, // version needed to extract\n CENFLG : 8, // encrypt, decrypt flags\n CENHOW : 10, // compression method\n CENTIM : 12, // modification time (2 bytes time, 2 bytes date)\n CENCRC : 16, // uncompressed file crc-32 value\n CENSIZ : 20, // compressed size\n CENLEN : 24, // uncompressed size\n CENNAM : 28, // filename length\n CENEXT : 30, // extra field length\n CENCOM : 32, // file comment length\n CENDSK : 34, // volume number start\n CENATT : 36, // internal file attributes\n CENATX : 38, // external file attributes (host system dependent)\n CENOFF : 42, // LOC header offset\n\n /* The entries in the end of central directory */\n ENDHDR : 22, // END header size\n ENDSIG : 0x06054b50, // \"PK\\005\\006\"\n ENDSUB : 8, // number of entries on this disk\n ENDTOT : 10, // total number of entries\n ENDSIZ : 12, // central directory size in bytes\n ENDOFF : 16, // offset of first CEN header\n ENDCOM : 20, // zip file comment length\n\n END64HDR : 20, // zip64 END header size\n END64SIG : 0x07064b50, // zip64 Locator signature, \"PK\\006\\007\"\n END64START : 4, // number of the disk with the start of the zip64\n END64OFF : 8, // relative offset of the zip64 end of central directory\n END64NUMDISKS : 16, // total number of disks\n\n ZIP64SIG : 0x06064b50, // zip64 signature, \"PK\\006\\006\"\n ZIP64HDR : 56, // zip64 record minimum size\n ZIP64LEAD : 12, // leading bytes at the start of the record, not counted by the value stored in ZIP64SIZE\n ZIP64SIZE : 4, // zip64 size of the central directory record\n ZIP64VEM : 12, // zip64 version made by\n ZIP64VER : 14, // zip64 version needed to extract\n ZIP64DSK : 16, // zip64 number of this disk\n ZIP64DSKDIR : 20, // number of the disk with the start of the record directory\n ZIP64SUB : 24, // number of entries on this disk\n ZIP64TOT : 32, // total number of entries\n ZIP64SIZB : 40, // zip64 central directory size in bytes\n ZIP64OFF : 48, // offset of start of central directory with respect to the starting disk number\n ZIP64EXTRA : 56, // extensible data sector\n\n /* Compression methods */\n STORED : 0, // no compression\n SHRUNK : 1, // shrunk\n REDUCED1 : 2, // reduced with compression factor 1\n REDUCED2 : 3, // reduced with compression factor 2\n REDUCED3 : 4, // reduced with compression factor 3\n REDUCED4 : 5, // reduced with compression factor 4\n IMPLODED : 6, // imploded\n // 7 reserved for Tokenizing compression algorithm\n DEFLATED : 8, // deflated\n ENHANCED_DEFLATED: 9, // enhanced deflated\n PKWARE : 10,// PKWare DCL imploded\n // 11 reserved by PKWARE\n BZIP2 : 12, // compressed using BZIP2\n // 13 reserved by PKWARE\n LZMA : 14, // LZMA\n // 15-17 reserved by PKWARE\n IBM_TERSE : 18, // compressed using IBM TERSE\n IBM_LZ77 : 19, // IBM LZ77 z\n AES_ENCRYPT : 99, // WinZIP AES encryption method\n\n /* General purpose bit flag */\n // values can obtained with expression 2**bitnr\n FLG_ENC : 1, // Bit 0: encrypted file\n FLG_COMP1 : 2, // Bit 1, compression option\n FLG_COMP2 : 4, // Bit 2, compression option\n FLG_DESC : 8, // Bit 3, data descriptor\n FLG_ENH : 16, // Bit 4, enhanced deflating\n FLG_PATCH : 32, // Bit 5, indicates that the file is compressed patched data.\n FLG_STR : 64, // Bit 6, strong encryption (patented)\n // Bits 7-10: Currently unused.\n FLG_EFS : 2048, // Bit 11: Language encoding flag (EFS)\n // Bit 12: Reserved by PKWARE for enhanced compression.\n // Bit 13: encrypted the Central Directory (patented).\n // Bits 14-15: Reserved by PKWARE.\n FLG_MSK : 4096, // mask header values\n\n /* Load type */\n FILE : 2,\n BUFFER : 1,\n NONE : 0,\n\n /* 4.5 Extensible data fields */\n EF_ID : 0,\n EF_SIZE : 2,\n\n /* Header IDs */\n ID_ZIP64 : 0x0001,\n ID_AVINFO : 0x0007,\n ID_PFS : 0x0008,\n ID_OS2 : 0x0009,\n ID_NTFS : 0x000a,\n ID_OPENVMS : 0x000c,\n ID_UNIX : 0x000d,\n ID_FORK : 0x000e,\n ID_PATCH : 0x000f,\n ID_X509_PKCS7 : 0x0014,\n ID_X509_CERTID_F : 0x0015,\n ID_X509_CERTID_C : 0x0016,\n ID_STRONGENC : 0x0017,\n ID_RECORD_MGT : 0x0018,\n ID_X509_PKCS7_RL : 0x0019,\n ID_IBM1 : 0x0065,\n ID_IBM2 : 0x0066,\n ID_POSZIP : 0x4690,\n\n EF_ZIP64_OR_32 : 0xffffffff,\n EF_ZIP64_OR_16 : 0xffff,\n EF_ZIP64_SUNCOMP : 0,\n EF_ZIP64_SCOMP : 8,\n EF_ZIP64_RHO : 16,\n EF_ZIP64_DSN : 24\n};\n","const errors = {\n /* Header error messages */\n INVALID_LOC: \"Invalid LOC header (bad signature)\",\n INVALID_CEN: \"Invalid CEN header (bad signature)\",\n INVALID_END: \"Invalid END header (bad signature)\",\n\n /* Descriptor */\n DESCRIPTOR_NOT_EXIST: \"No descriptor present\",\n DESCRIPTOR_UNKNOWN: \"Unknown descriptor format\",\n DESCRIPTOR_FAULTY: \"Descriptor data is malformed\",\n\n /* ZipEntry error messages*/\n NO_DATA: \"Nothing to decompress\",\n BAD_CRC: \"CRC32 checksum failed {0}\",\n FILE_IN_THE_WAY: \"There is a file in the way: {0}\",\n UNKNOWN_METHOD: \"Invalid/unsupported compression method\",\n\n /* Inflater error messages */\n AVAIL_DATA: \"inflate::Available inflate data did not terminate\",\n INVALID_DISTANCE: \"inflate::Invalid literal/length or distance code in fixed or dynamic block\",\n TO_MANY_CODES: \"inflate::Dynamic block code description: too many length or distance codes\",\n INVALID_REPEAT_LEN: \"inflate::Dynamic block code description: repeat more than specified lengths\",\n INVALID_REPEAT_FIRST: \"inflate::Dynamic block code description: repeat lengths with no first length\",\n INCOMPLETE_CODES: \"inflate::Dynamic block code description: code lengths codes incomplete\",\n INVALID_DYN_DISTANCE: \"inflate::Dynamic block code description: invalid distance code lengths\",\n INVALID_CODES_LEN: \"inflate::Dynamic block code description: invalid literal/length code lengths\",\n INVALID_STORE_BLOCK: \"inflate::Stored block length did not match one's complement\",\n INVALID_BLOCK_TYPE: \"inflate::Invalid block type (type == 3)\",\n\n /* ADM-ZIP error messages */\n CANT_EXTRACT_FILE: \"Could not extract the file\",\n CANT_OVERRIDE: \"Target file already exists\",\n DISK_ENTRY_TOO_LARGE: \"Number of disk entries is too large\",\n NO_ZIP: \"No zip file was loaded\",\n NO_ENTRY: \"Entry doesn't exist\",\n DIRECTORY_CONTENT_ERROR: \"A directory cannot have content\",\n FILE_NOT_FOUND: 'File not found: \"{0}\"',\n NOT_IMPLEMENTED: \"Not implemented\",\n INVALID_FILENAME: \"Invalid filename\",\n INVALID_FORMAT: \"Invalid or unsupported zip format. No END header found\",\n INVALID_PASS_PARAM: \"Incompatible password parameter\",\n WRONG_PASSWORD: \"Wrong Password\",\n\n /* ADM-ZIP */\n COMMENT_TOO_LONG: \"Comment is too long\", // Comment can be max 65535 bytes long (NOTE: some non-US characters may take more space)\n EXTRA_FIELD_PARSE_ERROR: \"Extra field parsing error\"\n};\n\n// template\nfunction E(message) {\n return function (...args) {\n if (args.length) { // Allow {0} .. {9} arguments in error message, based on argument number\n message = message.replace(/\\{(\\d)\\}/g, (_, n) => args[n] || '');\n }\n\n return new Error('ADM-ZIP: ' + message);\n };\n}\n\n// Init errors with template\nfor (const msg of Object.keys(errors)) {\n exports[msg] = E(errors[msg]);\n}\n","const fsystem = require(\"fs\");\nconst pth = require(\"path\");\nconst Constants = require(\"./constants\");\nconst Errors = require(\"./errors\");\nconst isWin = typeof process === \"object\" && \"win32\" === process.platform;\n\nconst is_Obj = (obj) => typeof obj === \"object\" && obj !== null;\n\n// generate CRC32 lookup table\nconst crcTable = new Uint32Array(256).map((t, c) => {\n for (let k = 0; k < 8; k++) {\n if ((c & 1) !== 0) {\n c = 0xedb88320 ^ (c >>> 1);\n } else {\n c >>>= 1;\n }\n }\n return c >>> 0;\n});\n\n// UTILS functions\n\nfunction Utils(opts) {\n this.sep = pth.sep;\n this.fs = fsystem;\n\n if (is_Obj(opts)) {\n // custom filesystem\n if (is_Obj(opts.fs) && typeof opts.fs.statSync === \"function\") {\n this.fs = opts.fs;\n }\n }\n}\n\nmodule.exports = Utils;\n\n// INSTANTIABLE functions\n\nUtils.prototype.makeDir = function (/*String*/ folder) {\n const self = this;\n\n // Sync - make directories tree\n function mkdirSync(/*String*/ fpath) {\n let resolvedPath = fpath.split(self.sep)[0];\n fpath.split(self.sep).forEach(function (name) {\n if (!name || name.substr(-1, 1) === \":\") return;\n resolvedPath += self.sep + name;\n var stat;\n try {\n stat = self.fs.statSync(resolvedPath);\n } catch (e) {\n if (e.message && e.message.startsWith('ENOENT')) {\n self.fs.mkdirSync(resolvedPath);\n } else {\n throw e;\n }\n }\n if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY(`\"${resolvedPath}\"`);\n });\n }\n\n mkdirSync(folder);\n};\n\nUtils.prototype.writeFileTo = function (/*String*/ path, /*Buffer*/ content, /*Boolean*/ overwrite, /*Number*/ attr) {\n const self = this;\n if (self.fs.existsSync(path)) {\n if (!overwrite) return false; // cannot overwrite\n\n var stat = self.fs.statSync(path);\n if (stat.isDirectory()) {\n return false;\n }\n }\n var folder = pth.dirname(path);\n if (!self.fs.existsSync(folder)) {\n self.makeDir(folder);\n }\n\n var fd;\n try {\n fd = self.fs.openSync(path, \"w\", 0o666); // 0666\n } catch (e) {\n self.fs.chmodSync(path, 0o666);\n fd = self.fs.openSync(path, \"w\", 0o666);\n }\n if (fd) {\n try {\n self.fs.writeSync(fd, content, 0, content.length, 0);\n } finally {\n self.fs.closeSync(fd);\n }\n }\n self.fs.chmodSync(path, attr || 0o666);\n return true;\n};\n\nUtils.prototype.writeFileToAsync = function (/*String*/ path, /*Buffer*/ content, /*Boolean*/ overwrite, /*Number*/ attr, /*Function*/ callback) {\n if (typeof attr === \"function\") {\n callback = attr;\n attr = undefined;\n }\n\n const self = this;\n\n self.fs.exists(path, function (exist) {\n if (exist && !overwrite) return callback(false);\n\n self.fs.stat(path, function (err, stat) {\n if (exist && stat.isDirectory()) {\n return callback(false);\n }\n\n var folder = pth.dirname(path);\n self.fs.exists(folder, function (exists) {\n if (!exists) self.makeDir(folder);\n\n self.fs.open(path, \"w\", 0o666, function (err, fd) {\n if (err) {\n self.fs.chmod(path, 0o666, function () {\n self.fs.open(path, \"w\", 0o666, function (err, fd) {\n self.fs.write(fd, content, 0, content.length, 0, function () {\n self.fs.close(fd, function () {\n self.fs.chmod(path, attr || 0o666, function () {\n callback(true);\n });\n });\n });\n });\n });\n } else if (fd) {\n self.fs.write(fd, content, 0, content.length, 0, function () {\n self.fs.close(fd, function () {\n self.fs.chmod(path, attr || 0o666, function () {\n callback(true);\n });\n });\n });\n } else {\n self.fs.chmod(path, attr || 0o666, function () {\n callback(true);\n });\n }\n });\n });\n });\n });\n};\n\nUtils.prototype.findFiles = function (/*String*/ path) {\n const self = this;\n\n function findSync(/*String*/ dir, /*RegExp*/ pattern, /*Boolean*/ recursive) {\n if (typeof pattern === \"boolean\") {\n recursive = pattern;\n pattern = undefined;\n }\n let files = [];\n self.fs.readdirSync(dir).forEach(function (file) {\n const path = pth.join(dir, file);\n const stat = self.fs.statSync(path);\n\n if (!pattern || pattern.test(path)) {\n files.push(pth.normalize(path) + (stat.isDirectory() ? self.sep : \"\"));\n }\n\n if (stat.isDirectory() && recursive) files = files.concat(findSync(path, pattern, recursive));\n });\n return files;\n }\n\n return findSync(path, undefined, true);\n};\n\n/**\n * Callback for showing if everything was done.\n *\n * @callback filelistCallback\n * @param {Error} err - Error object\n * @param {string[]} list - was request fully completed\n */\n\n/**\n *\n * @param {string} dir\n * @param {filelistCallback} cb\n */\nUtils.prototype.findFilesAsync = function (dir, cb) {\n const self = this;\n let results = [];\n self.fs.readdir(dir, function (err, list) {\n if (err) return cb(err);\n let list_length = list.length;\n if (!list_length) return cb(null, results);\n list.forEach(function (file) {\n file = pth.join(dir, file);\n self.fs.stat(file, function (err, stat) {\n if (err) return cb(err);\n if (stat) {\n results.push(pth.normalize(file) + (stat.isDirectory() ? self.sep : \"\"));\n if (stat.isDirectory()) {\n self.findFilesAsync(file, function (err, res) {\n if (err) return cb(err);\n results = results.concat(res);\n if (!--list_length) cb(null, results);\n });\n } else {\n if (!--list_length) cb(null, results);\n }\n }\n });\n });\n });\n};\n\nUtils.prototype.getAttributes = function () {};\n\nUtils.prototype.setAttributes = function () {};\n\n// STATIC functions\n\n// crc32 single update (it is part of crc32)\nUtils.crc32update = function (crc, byte) {\n return crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);\n};\n\nUtils.crc32 = function (buf) {\n if (typeof buf === \"string\") {\n buf = Buffer.from(buf, \"utf8\");\n }\n\n let len = buf.length;\n let crc = ~0;\n for (let off = 0; off < len; ) crc = Utils.crc32update(crc, buf[off++]);\n // xor and cast as uint32 number\n return ~crc >>> 0;\n};\n\nUtils.methodToString = function (/*Number*/ method) {\n switch (method) {\n case Constants.STORED:\n return \"STORED (\" + method + \")\";\n case Constants.DEFLATED:\n return \"DEFLATED (\" + method + \")\";\n default:\n return \"UNSUPPORTED (\" + method + \")\";\n }\n};\n\n/**\n * removes \"..\" style path elements\n * @param {string} path - fixable path\n * @returns string - fixed filepath\n */\nUtils.canonical = function (/*string*/ path) {\n if (!path) return \"\";\n // trick normalize think path is absolute\n const safeSuffix = pth.posix.normalize(\"/\" + path.split(\"\\\\\").join(\"/\"));\n return pth.join(\".\", safeSuffix);\n};\n\n/**\n * fix file names in achive\n * @param {string} path - fixable path\n * @returns string - fixed filepath\n */\n\nUtils.zipnamefix = function (path) {\n if (!path) return \"\";\n // trick normalize think path is absolute\n const safeSuffix = pth.posix.normalize(\"/\" + path.split(\"\\\\\").join(\"/\"));\n return pth.posix.join(\".\", safeSuffix);\n};\n\n/**\n *\n * @param {Array} arr\n * @param {function} callback\n * @returns\n */\nUtils.findLast = function (arr, callback) {\n if (!Array.isArray(arr)) throw new TypeError(\"arr is not array\");\n\n const len = arr.length >>> 0;\n for (let i = len - 1; i >= 0; i--) {\n if (callback(arr[i], i, arr)) {\n return arr[i];\n }\n }\n return void 0;\n};\n\n// make abolute paths taking prefix as root folder\nUtils.sanitize = function (/*string*/ prefix, /*string*/ name) {\n prefix = pth.resolve(pth.normalize(prefix));\n var parts = name.split(\"/\");\n for (var i = 0, l = parts.length; i < l; i++) {\n var path = pth.normalize(pth.join(prefix, parts.slice(i, l).join(pth.sep)));\n if (path.indexOf(prefix) === 0) {\n return path;\n }\n }\n return pth.normalize(pth.join(prefix, pth.basename(name)));\n};\n\n// converts buffer, Uint8Array, string types to buffer\nUtils.toBuffer = function toBuffer(/*buffer, Uint8Array, string*/ input, /* function */ encoder) {\n if (Buffer.isBuffer(input)) {\n return input;\n } else if (input instanceof Uint8Array) {\n return Buffer.from(input);\n } else {\n // expect string all other values are invalid and return empty buffer\n return typeof input === \"string\" ? encoder(input) : Buffer.alloc(0);\n }\n};\n\nUtils.readBigUInt64LE = function (/*Buffer*/ buffer, /*int*/ index) {\n const lo = buffer.readUInt32LE(index);\n const hi = buffer.readUInt32LE(index + 4);\n return hi * 0x100000000 + lo;\n};\n\nUtils.fromDOS2Date = function (val) {\n return new Date(((val >> 25) & 0x7f) + 1980, Math.max(((val >> 21) & 0x0f) - 1, 0), Math.max((val >> 16) & 0x1f, 1), (val >> 11) & 0x1f, (val >> 5) & 0x3f, (val & 0x1f) << 1);\n};\n\nUtils.fromDate2DOS = function (val) {\n let date = 0;\n let time = 0;\n if (val.getFullYear() > 1979) {\n date = (((val.getFullYear() - 1980) & 0x7f) << 9) | ((val.getMonth() + 1) << 5) | val.getDate();\n time = (val.getHours() << 11) | (val.getMinutes() << 5) | (val.getSeconds() >> 1);\n }\n return (date << 16) | time;\n};\n\nUtils.isWin = isWin; // Do we have windows system\nUtils.crcTable = crcTable;\n","const pth = require(\"path\");\n\nmodule.exports = function (/*String*/ path, /*Utils object*/ { fs }) {\n var _path = path || \"\",\n _obj = newAttr(),\n _stat = null;\n\n function newAttr() {\n return {\n directory: false,\n readonly: false,\n hidden: false,\n executable: false,\n mtime: 0,\n atime: 0\n };\n }\n\n if (_path && fs.existsSync(_path)) {\n _stat = fs.statSync(_path);\n _obj.directory = _stat.isDirectory();\n _obj.mtime = _stat.mtime;\n _obj.atime = _stat.atime;\n _obj.executable = (0o111 & _stat.mode) !== 0; // file is executable who ever har right not just owner\n _obj.readonly = (0o200 & _stat.mode) === 0; // readonly if owner has no write right\n _obj.hidden = pth.basename(_path)[0] === \".\";\n } else {\n console.warn(\"Invalid path: \" + _path);\n }\n\n return {\n get directory() {\n return _obj.directory;\n },\n\n get readOnly() {\n return _obj.readonly;\n },\n\n get hidden() {\n return _obj.hidden;\n },\n\n get mtime() {\n return _obj.mtime;\n },\n\n get atime() {\n return _obj.atime;\n },\n\n get executable() {\n return _obj.executable;\n },\n\n decodeAttributes: function () {},\n\n encodeAttributes: function () {},\n\n toJSON: function () {\n return {\n path: _path,\n isDirectory: _obj.directory,\n isReadOnly: _obj.readonly,\n isHidden: _obj.hidden,\n isExecutable: _obj.executable,\n mTime: _obj.mtime,\n aTime: _obj.atime\n };\n },\n\n toString: function () {\n return JSON.stringify(this.toJSON(), null, \"\\t\");\n }\n };\n};\n","module.exports = {\n efs: true,\n encode: (data) => Buffer.from(data, \"utf8\"),\n decode: (data) => data.toString(\"utf8\")\n};\n","module.exports = require(\"./utils\");\nmodule.exports.Constants = require(\"./constants\");\nmodule.exports.Errors = require(\"./errors\");\nmodule.exports.FileAttr = require(\"./fattr\");\nmodule.exports.decoder = require(\"./decoder\");\n","var Utils = require(\"../util\"),\n Constants = Utils.Constants;\n\n/* The central directory file header */\nmodule.exports = function () {\n var _verMade = 20, // v2.0\n _version = 10, // v1.0\n _flags = 0,\n _method = 0,\n _time = 0,\n _crc = 0,\n _compressedSize = 0,\n _size = 0,\n _fnameLen = 0,\n _extraLen = 0,\n _comLen = 0,\n _diskStart = 0,\n _inattr = 0,\n _attr = 0,\n _offset = 0;\n\n _verMade |= Utils.isWin ? 0x0a00 : 0x0300;\n\n // Set EFS flag since filename and comment fields are all by default encoded using UTF-8.\n // Without it file names may be corrupted for other apps when file names use unicode chars\n _flags |= Constants.FLG_EFS;\n\n const _localHeader = {\n extraLen: 0\n };\n\n // casting\n const uint32 = (val) => Math.max(0, val) >>> 0;\n const uint16 = (val) => Math.max(0, val) & 0xffff;\n const uint8 = (val) => Math.max(0, val) & 0xff;\n\n _time = Utils.fromDate2DOS(new Date());\n\n return {\n get made() {\n return _verMade;\n },\n set made(val) {\n _verMade = val;\n },\n\n get version() {\n return _version;\n },\n set version(val) {\n _version = val;\n },\n\n get flags() {\n return _flags;\n },\n set flags(val) {\n _flags = val;\n },\n\n get flags_efs() {\n return (_flags & Constants.FLG_EFS) > 0;\n },\n set flags_efs(val) {\n if (val) {\n _flags |= Constants.FLG_EFS;\n } else {\n _flags &= ~Constants.FLG_EFS;\n }\n },\n\n get flags_desc() {\n return (_flags & Constants.FLG_DESC) > 0;\n },\n set flags_desc(val) {\n if (val) {\n _flags |= Constants.FLG_DESC;\n } else {\n _flags &= ~Constants.FLG_DESC;\n }\n },\n\n get method() {\n return _method;\n },\n set method(val) {\n switch (val) {\n case Constants.STORED:\n this.version = 10;\n case Constants.DEFLATED:\n default:\n this.version = 20;\n }\n _method = val;\n },\n\n get time() {\n return Utils.fromDOS2Date(this.timeval);\n },\n set time(val) {\n val = new Date(val);\n this.timeval = Utils.fromDate2DOS(val);\n },\n\n get timeval() {\n return _time;\n },\n set timeval(val) {\n _time = uint32(val);\n },\n\n get timeHighByte() {\n return uint8(_time >>> 8);\n },\n get crc() {\n return _crc;\n },\n set crc(val) {\n _crc = uint32(val);\n },\n\n get compressedSize() {\n return _compressedSize;\n },\n set compressedSize(val) {\n _compressedSize = uint32(val);\n },\n\n get size() {\n return _size;\n },\n set size(val) {\n _size = uint32(val);\n },\n\n get fileNameLength() {\n return _fnameLen;\n },\n set fileNameLength(val) {\n _fnameLen = val;\n },\n\n get extraLength() {\n return _extraLen;\n },\n set extraLength(val) {\n _extraLen = val;\n },\n\n get extraLocalLength() {\n return _localHeader.extraLen;\n },\n set extraLocalLength(val) {\n _localHeader.extraLen = val;\n },\n\n get commentLength() {\n return _comLen;\n },\n set commentLength(val) {\n _comLen = val;\n },\n\n get diskNumStart() {\n return _diskStart;\n },\n set diskNumStart(val) {\n _diskStart = uint32(val);\n },\n\n get inAttr() {\n return _inattr;\n },\n set inAttr(val) {\n _inattr = uint32(val);\n },\n\n get attr() {\n return _attr;\n },\n set attr(val) {\n _attr = uint32(val);\n },\n\n // get Unix file permissions\n get fileAttr() {\n return (_attr || 0) >> 16 & 0xfff;\n },\n\n get offset() {\n return _offset;\n },\n set offset(val) {\n _offset = uint32(val);\n },\n\n get encrypted() {\n return (_flags & Constants.FLG_ENC) === Constants.FLG_ENC;\n },\n\n get centralHeaderSize() {\n return Constants.CENHDR + _fnameLen + _extraLen + _comLen;\n },\n\n get realDataOffset() {\n return _offset + Constants.LOCHDR + _localHeader.fnameLen + _localHeader.extraLen;\n },\n\n get localHeader() {\n return _localHeader;\n },\n\n loadLocalHeaderFromBinary: function (/*Buffer*/ input) {\n var data = input.slice(_offset, _offset + Constants.LOCHDR);\n // 30 bytes and should start with \"PK\\003\\004\"\n if (data.readUInt32LE(0) !== Constants.LOCSIG) {\n throw Utils.Errors.INVALID_LOC();\n }\n\n // version needed to extract\n _localHeader.version = data.readUInt16LE(Constants.LOCVER);\n // general purpose bit flag\n _localHeader.flags = data.readUInt16LE(Constants.LOCFLG);\n // desc flag\n _localHeader.flags_desc = (_localHeader.flags & Constants.FLG_DESC) > 0;\n // compression method\n _localHeader.method = data.readUInt16LE(Constants.LOCHOW);\n // modification time (2 bytes time, 2 bytes date)\n _localHeader.time = data.readUInt32LE(Constants.LOCTIM);\n // uncompressed file crc-32 valu\n _localHeader.crc = data.readUInt32LE(Constants.LOCCRC);\n // compressed size\n _localHeader.compressedSize = data.readUInt32LE(Constants.LOCSIZ);\n // uncompressed size\n _localHeader.size = data.readUInt32LE(Constants.LOCLEN);\n // filename length\n _localHeader.fnameLen = data.readUInt16LE(Constants.LOCNAM);\n // extra field length\n _localHeader.extraLen = data.readUInt16LE(Constants.LOCEXT);\n\n // read extra data\n const extraStart = _offset + Constants.LOCHDR + _localHeader.fnameLen;\n const extraEnd = extraStart + _localHeader.extraLen;\n return input.slice(extraStart, extraEnd);\n },\n\n loadFromBinary: function (/*Buffer*/ data) {\n // data should be 46 bytes and start with \"PK 01 02\"\n if (data.length !== Constants.CENHDR || data.readUInt32LE(0) !== Constants.CENSIG) {\n throw Utils.Errors.INVALID_CEN();\n }\n // version made by\n _verMade = data.readUInt16LE(Constants.CENVEM);\n // version needed to extract\n _version = data.readUInt16LE(Constants.CENVER);\n // encrypt, decrypt flags\n _flags = data.readUInt16LE(Constants.CENFLG);\n // compression method\n _method = data.readUInt16LE(Constants.CENHOW);\n // modification time (2 bytes time, 2 bytes date)\n _time = data.readUInt32LE(Constants.CENTIM);\n // uncompressed file crc-32 value\n _crc = data.readUInt32LE(Constants.CENCRC);\n // compressed size\n _compressedSize = data.readUInt32LE(Constants.CENSIZ);\n // uncompressed size\n _size = data.readUInt32LE(Constants.CENLEN);\n // filename length\n _fnameLen = data.readUInt16LE(Constants.CENNAM);\n // extra field length\n _extraLen = data.readUInt16LE(Constants.CENEXT);\n // file comment length\n _comLen = data.readUInt16LE(Constants.CENCOM);\n // volume number start\n _diskStart = data.readUInt16LE(Constants.CENDSK);\n // internal file attributes\n _inattr = data.readUInt16LE(Constants.CENATT);\n // external file attributes\n _attr = data.readUInt32LE(Constants.CENATX);\n // LOC header offset\n _offset = data.readUInt32LE(Constants.CENOFF);\n },\n\n localHeaderToBinary: function () {\n // LOC header size (30 bytes)\n var data = Buffer.alloc(Constants.LOCHDR);\n // \"PK\\003\\004\"\n data.writeUInt32LE(Constants.LOCSIG, 0);\n // version needed to extract\n data.writeUInt16LE(_version, Constants.LOCVER);\n // general purpose bit flag\n data.writeUInt16LE(_flags, Constants.LOCFLG);\n // compression method\n data.writeUInt16LE(_method, Constants.LOCHOW);\n // modification time (2 bytes time, 2 bytes date)\n data.writeUInt32LE(_time, Constants.LOCTIM);\n // uncompressed file crc-32 value\n data.writeUInt32LE(_crc, Constants.LOCCRC);\n // compressed size\n data.writeUInt32LE(_compressedSize, Constants.LOCSIZ);\n // uncompressed size\n data.writeUInt32LE(_size, Constants.LOCLEN);\n // filename length\n data.writeUInt16LE(_fnameLen, Constants.LOCNAM);\n // extra field length\n data.writeUInt16LE(_localHeader.extraLen, Constants.LOCEXT);\n return data;\n },\n\n centralHeaderToBinary: function () {\n // CEN header size (46 bytes)\n var data = Buffer.alloc(Constants.CENHDR + _fnameLen + _extraLen + _comLen);\n // \"PK\\001\\002\"\n data.writeUInt32LE(Constants.CENSIG, 0);\n // version made by\n data.writeUInt16LE(_verMade, Constants.CENVEM);\n // version needed to extract\n data.writeUInt16LE(_version, Constants.CENVER);\n // encrypt, decrypt flags\n data.writeUInt16LE(_flags, Constants.CENFLG);\n // compression method\n data.writeUInt16LE(_method, Constants.CENHOW);\n // modification time (2 bytes time, 2 bytes date)\n data.writeUInt32LE(_time, Constants.CENTIM);\n // uncompressed file crc-32 value\n data.writeUInt32LE(_crc, Constants.CENCRC);\n // compressed size\n data.writeUInt32LE(_compressedSize, Constants.CENSIZ);\n // uncompressed size\n data.writeUInt32LE(_size, Constants.CENLEN);\n // filename length\n data.writeUInt16LE(_fnameLen, Constants.CENNAM);\n // extra field length\n data.writeUInt16LE(_extraLen, Constants.CENEXT);\n // file comment length\n data.writeUInt16LE(_comLen, Constants.CENCOM);\n // volume number start\n data.writeUInt16LE(_diskStart, Constants.CENDSK);\n // internal file attributes\n data.writeUInt16LE(_inattr, Constants.CENATT);\n // external file attributes\n data.writeUInt32LE(_attr, Constants.CENATX);\n // LOC header offset\n data.writeUInt32LE(_offset, Constants.CENOFF);\n return data;\n },\n\n toJSON: function () {\n const bytes = function (nr) {\n return nr + \" bytes\";\n };\n\n return {\n made: _verMade,\n version: _version,\n flags: _flags,\n method: Utils.methodToString(_method),\n time: this.time,\n crc: \"0x\" + _crc.toString(16).toUpperCase(),\n compressedSize: bytes(_compressedSize),\n size: bytes(_size),\n fileNameLength: bytes(_fnameLen),\n extraLength: bytes(_extraLen),\n commentLength: bytes(_comLen),\n diskNumStart: _diskStart,\n inAttr: _inattr,\n attr: _attr,\n offset: _offset,\n centralHeaderSize: bytes(Constants.CENHDR + _fnameLen + _extraLen + _comLen)\n };\n },\n\n toString: function () {\n return JSON.stringify(this.toJSON(), null, \"\\t\");\n }\n };\n};\n","var Utils = require(\"../util\"),\n Constants = Utils.Constants;\n\n/* The entries in the end of central directory */\nmodule.exports = function () {\n var _volumeEntries = 0,\n _totalEntries = 0,\n _size = 0,\n _offset = 0,\n _commentLength = 0;\n\n return {\n get diskEntries() {\n return _volumeEntries;\n },\n set diskEntries(/*Number*/ val) {\n _volumeEntries = _totalEntries = val;\n },\n\n get totalEntries() {\n return _totalEntries;\n },\n set totalEntries(/*Number*/ val) {\n _totalEntries = _volumeEntries = val;\n },\n\n get size() {\n return _size;\n },\n set size(/*Number*/ val) {\n _size = val;\n },\n\n get offset() {\n return _offset;\n },\n set offset(/*Number*/ val) {\n _offset = val;\n },\n\n get commentLength() {\n return _commentLength;\n },\n set commentLength(/*Number*/ val) {\n _commentLength = val;\n },\n\n get mainHeaderSize() {\n return Constants.ENDHDR + _commentLength;\n },\n\n loadFromBinary: function (/*Buffer*/ data) {\n // data should be 22 bytes and start with \"PK 05 06\"\n // or be 56+ bytes and start with \"PK 06 06\" for Zip64\n if (\n (data.length !== Constants.ENDHDR || data.readUInt32LE(0) !== Constants.ENDSIG) &&\n (data.length < Constants.ZIP64HDR || data.readUInt32LE(0) !== Constants.ZIP64SIG)\n ) {\n throw Utils.Errors.INVALID_END();\n }\n\n if (data.readUInt32LE(0) === Constants.ENDSIG) {\n // number of entries on this volume\n _volumeEntries = data.readUInt16LE(Constants.ENDSUB);\n // total number of entries\n _totalEntries = data.readUInt16LE(Constants.ENDTOT);\n // central directory size in bytes\n _size = data.readUInt32LE(Constants.ENDSIZ);\n // offset of first CEN header\n _offset = data.readUInt32LE(Constants.ENDOFF);\n // zip file comment length\n _commentLength = data.readUInt16LE(Constants.ENDCOM);\n } else {\n // number of entries on this volume\n _volumeEntries = Utils.readBigUInt64LE(data, Constants.ZIP64SUB);\n // total number of entries\n _totalEntries = Utils.readBigUInt64LE(data, Constants.ZIP64TOT);\n // central directory size in bytes\n _size = Utils.readBigUInt64LE(data, Constants.ZIP64SIZE);\n // offset of first CEN header\n _offset = Utils.readBigUInt64LE(data, Constants.ZIP64OFF);\n\n _commentLength = 0;\n }\n },\n\n toBinary: function () {\n var b = Buffer.alloc(Constants.ENDHDR + _commentLength);\n // \"PK 05 06\" signature\n b.writeUInt32LE(Constants.ENDSIG, 0);\n b.writeUInt32LE(0, 4);\n // number of entries on this volume\n b.writeUInt16LE(_volumeEntries, Constants.ENDSUB);\n // total number of entries\n b.writeUInt16LE(_totalEntries, Constants.ENDTOT);\n // central directory size in bytes\n b.writeUInt32LE(_size, Constants.ENDSIZ);\n // offset of first CEN header\n b.writeUInt32LE(_offset, Constants.ENDOFF);\n // zip file comment length\n b.writeUInt16LE(_commentLength, Constants.ENDCOM);\n // fill comment memory with spaces so no garbage is left there\n b.fill(\" \", Constants.ENDHDR);\n\n return b;\n },\n\n toJSON: function () {\n // creates 0x0000 style output\n const offset = function (nr, len) {\n let offs = nr.toString(16).toUpperCase();\n while (offs.length < len) offs = \"0\" + offs;\n return \"0x\" + offs;\n };\n\n return {\n diskEntries: _volumeEntries,\n totalEntries: _totalEntries,\n size: _size + \" bytes\",\n offset: offset(_offset, 4),\n commentLength: _commentLength\n };\n },\n\n toString: function () {\n return JSON.stringify(this.toJSON(), null, \"\\t\");\n }\n };\n};\n// Misspelled\n","exports.EntryHeader = require(\"./entryHeader\");\nexports.MainHeader = require(\"./mainHeader\");\n","module.exports = function (/*Buffer*/ inbuf) {\n var zlib = require(\"zlib\");\n\n var opts = { chunkSize: (parseInt(inbuf.length / 1024) + 1) * 1024 };\n\n return {\n deflate: function () {\n return zlib.deflateRawSync(inbuf, opts);\n },\n\n deflateAsync: function (/*Function*/ callback) {\n var tmp = zlib.createDeflateRaw(opts),\n parts = [],\n total = 0;\n tmp.on(\"data\", function (data) {\n parts.push(data);\n total += data.length;\n });\n tmp.on(\"end\", function () {\n var buf = Buffer.alloc(total),\n written = 0;\n buf.fill(0);\n for (var i = 0; i < parts.length; i++) {\n var part = parts[i];\n part.copy(buf, written);\n written += part.length;\n }\n callback && callback(buf);\n });\n tmp.end(inbuf);\n }\n };\n};\n","const version = +(process.versions ? process.versions.node : \"\").split(\".\")[0] || 0;\n\nmodule.exports = function (/*Buffer*/ inbuf, /*number*/ expectedLength) {\n var zlib = require(\"zlib\");\n const option = version >= 15 && expectedLength > 0 ? { maxOutputLength: expectedLength } : {};\n\n return {\n inflate: function () {\n return zlib.inflateRawSync(inbuf, option);\n },\n\n inflateAsync: function (/*Function*/ callback) {\n var tmp = zlib.createInflateRaw(option),\n parts = [],\n total = 0;\n tmp.on(\"data\", function (data) {\n parts.push(data);\n total += data.length;\n });\n tmp.on(\"end\", function () {\n var buf = Buffer.alloc(total),\n written = 0;\n buf.fill(0);\n for (var i = 0; i < parts.length; i++) {\n var part = parts[i];\n part.copy(buf, written);\n written += part.length;\n }\n callback && callback(buf);\n });\n tmp.end(inbuf);\n }\n };\n};\n","\"use strict\";\n\n// node crypt, we use it for generate salt\n// eslint-disable-next-line node/no-unsupported-features/node-builtins\nconst { randomFillSync } = require(\"crypto\");\nconst Errors = require(\"../util/errors\");\n\n// generate CRC32 lookup table\nconst crctable = new Uint32Array(256).map((t, crc) => {\n for (let j = 0; j < 8; j++) {\n if (0 !== (crc & 1)) {\n crc = (crc >>> 1) ^ 0xedb88320;\n } else {\n crc >>>= 1;\n }\n }\n return crc >>> 0;\n});\n\n// C-style uInt32 Multiply (discards higher bits, when JS multiply discards lower bits)\nconst uMul = (a, b) => Math.imul(a, b) >>> 0;\n\n// crc32 byte single update (actually same function is part of utils.crc32 function :) )\nconst crc32update = (pCrc32, bval) => {\n return crctable[(pCrc32 ^ bval) & 0xff] ^ (pCrc32 >>> 8);\n};\n\n// function for generating salt for encrytion header\nconst genSalt = () => {\n if (\"function\" === typeof randomFillSync) {\n return randomFillSync(Buffer.alloc(12));\n } else {\n // fallback if function is not defined\n return genSalt.node();\n }\n};\n\n// salt generation with node random function (mainly as fallback)\ngenSalt.node = () => {\n const salt = Buffer.alloc(12);\n const len = salt.length;\n for (let i = 0; i < len; i++) salt[i] = (Math.random() * 256) & 0xff;\n return salt;\n};\n\n// general config\nconst config = {\n genSalt\n};\n\n// Class Initkeys handles same basic ops with keys\nfunction Initkeys(pw) {\n const pass = Buffer.isBuffer(pw) ? pw : Buffer.from(pw);\n this.keys = new Uint32Array([0x12345678, 0x23456789, 0x34567890]);\n for (let i = 0; i < pass.length; i++) {\n this.updateKeys(pass[i]);\n }\n}\n\nInitkeys.prototype.updateKeys = function (byteValue) {\n const keys = this.keys;\n keys[0] = crc32update(keys[0], byteValue);\n keys[1] += keys[0] & 0xff;\n keys[1] = uMul(keys[1], 134775813) + 1;\n keys[2] = crc32update(keys[2], keys[1] >>> 24);\n return byteValue;\n};\n\nInitkeys.prototype.next = function () {\n const k = (this.keys[2] | 2) >>> 0; // key\n return (uMul(k, k ^ 1) >> 8) & 0xff; // decode\n};\n\nfunction make_decrypter(/*Buffer*/ pwd) {\n // 1. Stage initialize key\n const keys = new Initkeys(pwd);\n\n // return decrypter function\n return function (/*Buffer*/ data) {\n // result - we create new Buffer for results\n const result = Buffer.alloc(data.length);\n let pos = 0;\n // process input data\n for (let c of data) {\n //c ^= keys.next();\n //result[pos++] = c; // decode & Save Value\n result[pos++] = keys.updateKeys(c ^ keys.next()); // update keys with decoded byte\n }\n return result;\n };\n}\n\nfunction make_encrypter(/*Buffer*/ pwd) {\n // 1. Stage initialize key\n const keys = new Initkeys(pwd);\n\n // return encrypting function, result and pos is here so we dont have to merge buffers later\n return function (/*Buffer*/ data, /*Buffer*/ result, /* Number */ pos = 0) {\n // result - we create new Buffer for results\n if (!result) result = Buffer.alloc(data.length);\n // process input data\n for (let c of data) {\n const k = keys.next(); // save key byte\n result[pos++] = c ^ k; // save val\n keys.updateKeys(c); // update keys with decoded byte\n }\n return result;\n };\n}\n\nfunction decrypt(/*Buffer*/ data, /*Object*/ header, /*String, Buffer*/ pwd) {\n if (!data || !Buffer.isBuffer(data) || data.length < 12) {\n return Buffer.alloc(0);\n }\n\n // 1. We Initialize and generate decrypting function\n const decrypter = make_decrypter(pwd);\n\n // 2. decrypt salt what is always 12 bytes and is a part of file content\n const salt = decrypter(data.slice(0, 12));\n\n // if bit 3 (0x08) of the general-purpose flags field is set, check salt[11] with the high byte of the header time\n // 2 byte data block (as per Info-Zip spec), otherwise check with the high byte of the header entry\n const verifyByte = (header.flags & 0x8) === 0x8 ? header.timeHighByte : header.crc >>> 24;\n\n //3. does password meet expectations\n if (salt[11] !== verifyByte) {\n throw Errors.WRONG_PASSWORD();\n }\n\n // 4. decode content\n return decrypter(data.slice(12));\n}\n\n// lets add way to populate salt, NOT RECOMMENDED for production but maybe useful for testing general functionality\nfunction _salter(data) {\n if (Buffer.isBuffer(data) && data.length >= 12) {\n // be aware - currently salting buffer data is modified\n config.genSalt = function () {\n return data.slice(0, 12);\n };\n } else if (data === \"node\") {\n // test salt generation with node random function\n config.genSalt = genSalt.node;\n } else {\n // if value is not acceptable config gets reset.\n config.genSalt = genSalt;\n }\n}\n\nfunction encrypt(/*Buffer*/ data, /*Object*/ header, /*String, Buffer*/ pwd, /*Boolean*/ oldlike = false) {\n // 1. test data if data is not Buffer we make buffer from it\n if (data == null) data = Buffer.alloc(0);\n // if data is not buffer be make buffer from it\n if (!Buffer.isBuffer(data)) data = Buffer.from(data.toString());\n\n // 2. We Initialize and generate encrypting function\n const encrypter = make_encrypter(pwd);\n\n // 3. generate salt (12-bytes of random data)\n const salt = config.genSalt();\n salt[11] = (header.crc >>> 24) & 0xff;\n\n // old implementations (before PKZip 2.04g) used two byte check\n if (oldlike) salt[10] = (header.crc >>> 16) & 0xff;\n\n // 4. create output\n const result = Buffer.alloc(data.length + 12);\n encrypter(salt, result);\n\n // finally encode content\n return encrypter(data, result, 12);\n}\n\nmodule.exports = { decrypt, encrypt, _salter };\n","exports.Deflater = require(\"./deflater\");\nexports.Inflater = require(\"./inflater\");\nexports.ZipCrypto = require(\"./zipcrypto\");\n","var Utils = require(\"./util\"),\n Headers = require(\"./headers\"),\n Constants = Utils.Constants,\n Methods = require(\"./methods\");\n\nmodule.exports = function (/** object */ options, /*Buffer*/ input) {\n var _centralHeader = new Headers.EntryHeader(),\n _entryName = Buffer.alloc(0),\n _comment = Buffer.alloc(0),\n _isDirectory = false,\n uncompressedData = null,\n _extra = Buffer.alloc(0),\n _extralocal = Buffer.alloc(0),\n _efs = true;\n\n // assign options\n const opts = options;\n\n const decoder = typeof opts.decoder === \"object\" ? opts.decoder : Utils.decoder;\n _efs = decoder.hasOwnProperty(\"efs\") ? decoder.efs : false;\n\n function getCompressedDataFromZip() {\n //if (!input || !Buffer.isBuffer(input)) {\n if (!input || !(input instanceof Uint8Array)) {\n return Buffer.alloc(0);\n }\n _extralocal = _centralHeader.loadLocalHeaderFromBinary(input);\n return input.slice(_centralHeader.realDataOffset, _centralHeader.realDataOffset + _centralHeader.compressedSize);\n }\n\n function crc32OK(data) {\n // if bit 3 (0x08) of the general-purpose flags field is set, then the CRC-32 and file sizes are not known when the local header is written\n if (!_centralHeader.flags_desc && !_centralHeader.localHeader.flags_desc) {\n if (Utils.crc32(data) !== _centralHeader.localHeader.crc) {\n return false;\n }\n } else {\n const descriptor = {};\n const dataEndOffset = _centralHeader.realDataOffset + _centralHeader.compressedSize;\n // no descriptor after compressed data, instead new local header\n if (input.readUInt32LE(dataEndOffset) == Constants.LOCSIG || input.readUInt32LE(dataEndOffset) == Constants.CENSIG) {\n throw Utils.Errors.DESCRIPTOR_NOT_EXIST();\n }\n\n // get decriptor data\n if (input.readUInt32LE(dataEndOffset) == Constants.EXTSIG) {\n // descriptor with signature\n descriptor.crc = input.readUInt32LE(dataEndOffset + Constants.EXTCRC);\n descriptor.compressedSize = input.readUInt32LE(dataEndOffset + Constants.EXTSIZ);\n descriptor.size = input.readUInt32LE(dataEndOffset + Constants.EXTLEN);\n } else if (input.readUInt16LE(dataEndOffset + 12) === 0x4b50) {\n // descriptor without signature (we check is new header starting where we expect)\n descriptor.crc = input.readUInt32LE(dataEndOffset + Constants.EXTCRC - 4);\n descriptor.compressedSize = input.readUInt32LE(dataEndOffset + Constants.EXTSIZ - 4);\n descriptor.size = input.readUInt32LE(dataEndOffset + Constants.EXTLEN - 4);\n } else {\n throw Utils.Errors.DESCRIPTOR_UNKNOWN();\n }\n\n // check data integrity\n if (descriptor.compressedSize !== _centralHeader.compressedSize || descriptor.size !== _centralHeader.size || descriptor.crc !== _centralHeader.crc) {\n throw Utils.Errors.DESCRIPTOR_FAULTY();\n }\n if (Utils.crc32(data) !== descriptor.crc) {\n return false;\n }\n\n // @TODO: zip64 bit descriptor fields\n // if bit 3 is set and any value in local header \"zip64 Extended information\" extra field are set 0 (place holder)\n // then 64-bit descriptor format is used instead of 32-bit\n // central header - \"zip64 Extended information\" extra field should store real values and not place holders\n }\n return true;\n }\n\n function decompress(/*Boolean*/ async, /*Function*/ callback, /*String, Buffer*/ pass) {\n if (typeof callback === \"undefined\" && typeof async === \"string\") {\n pass = async;\n async = void 0;\n }\n if (_isDirectory) {\n if (async && callback) {\n callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR()); //si added error.\n }\n return Buffer.alloc(0);\n }\n\n var compressedData = getCompressedDataFromZip();\n\n if (compressedData.length === 0) {\n // File is empty, nothing to decompress.\n if (async && callback) callback(compressedData);\n return compressedData;\n }\n\n if (_centralHeader.encrypted) {\n if (\"string\" !== typeof pass && !Buffer.isBuffer(pass)) {\n throw Utils.Errors.INVALID_PASS_PARAM();\n }\n compressedData = Methods.ZipCrypto.decrypt(compressedData, _centralHeader, pass);\n }\n\n var data = Buffer.alloc(_centralHeader.size);\n\n switch (_centralHeader.method) {\n case Utils.Constants.STORED:\n compressedData.copy(data);\n if (!crc32OK(data)) {\n if (async && callback) callback(data, Utils.Errors.BAD_CRC()); //si added error\n throw Utils.Errors.BAD_CRC();\n } else {\n //si added otherwise did not seem to return data.\n if (async && callback) callback(data);\n return data;\n }\n case Utils.Constants.DEFLATED:\n var inflater = new Methods.Inflater(compressedData, _centralHeader.size);\n if (!async) {\n const result = inflater.inflate(data);\n result.copy(data, 0);\n if (!crc32OK(data)) {\n throw Utils.Errors.BAD_CRC(`\"${decoder.decode(_entryName)}\"`);\n }\n return data;\n } else {\n inflater.inflateAsync(function (result) {\n result.copy(result, 0);\n if (callback) {\n if (!crc32OK(result)) {\n callback(result, Utils.Errors.BAD_CRC()); //si added error\n } else {\n callback(result);\n }\n }\n });\n }\n break;\n default:\n if (async && callback) callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD());\n throw Utils.Errors.UNKNOWN_METHOD();\n }\n }\n\n function compress(/*Boolean*/ async, /*Function*/ callback) {\n if ((!uncompressedData || !uncompressedData.length) && Buffer.isBuffer(input)) {\n // no data set or the data wasn't changed to require recompression\n if (async && callback) callback(getCompressedDataFromZip());\n return getCompressedDataFromZip();\n }\n\n if (uncompressedData.length && !_isDirectory) {\n var compressedData;\n // Local file header\n switch (_centralHeader.method) {\n case Utils.Constants.STORED:\n _centralHeader.compressedSize = _centralHeader.size;\n\n compressedData = Buffer.alloc(uncompressedData.length);\n uncompressedData.copy(compressedData);\n\n if (async && callback) callback(compressedData);\n return compressedData;\n default:\n case Utils.Constants.DEFLATED:\n var deflater = new Methods.Deflater(uncompressedData);\n if (!async) {\n var deflated = deflater.deflate();\n _centralHeader.compressedSize = deflated.length;\n return deflated;\n } else {\n deflater.deflateAsync(function (data) {\n compressedData = Buffer.alloc(data.length);\n _centralHeader.compressedSize = data.length;\n data.copy(compressedData);\n callback && callback(compressedData);\n });\n }\n deflater = null;\n break;\n }\n } else if (async && callback) {\n callback(Buffer.alloc(0));\n } else {\n return Buffer.alloc(0);\n }\n }\n\n function readUInt64LE(buffer, offset) {\n return Utils.readBigUInt64LE(buffer, offset);\n }\n\n function parseExtra(data) {\n try {\n var offset = 0;\n var signature, size, part;\n while (offset + 4 < data.length) {\n signature = data.readUInt16LE(offset);\n offset += 2;\n size = data.readUInt16LE(offset);\n offset += 2;\n part = data.slice(offset, offset + size);\n offset += size;\n if (Constants.ID_ZIP64 === signature) {\n parseZip64ExtendedInformation(part);\n }\n }\n } catch (error) {\n throw Utils.Errors.EXTRA_FIELD_PARSE_ERROR();\n }\n }\n\n //Override header field values with values from the ZIP64 extra field\n function parseZip64ExtendedInformation(data) {\n var size, compressedSize, offset, diskNumStart;\n\n if (data.length >= Constants.EF_ZIP64_SCOMP) {\n size = readUInt64LE(data, Constants.EF_ZIP64_SUNCOMP);\n if (_centralHeader.size === Constants.EF_ZIP64_OR_32) {\n _centralHeader.size = size;\n }\n }\n if (data.length >= Constants.EF_ZIP64_RHO) {\n compressedSize = readUInt64LE(data, Constants.EF_ZIP64_SCOMP);\n if (_centralHeader.compressedSize === Constants.EF_ZIP64_OR_32) {\n _centralHeader.compressedSize = compressedSize;\n }\n }\n if (data.length >= Constants.EF_ZIP64_DSN) {\n offset = readUInt64LE(data, Constants.EF_ZIP64_RHO);\n if (_centralHeader.offset === Constants.EF_ZIP64_OR_32) {\n _centralHeader.offset = offset;\n }\n }\n if (data.length >= Constants.EF_ZIP64_DSN + 4) {\n diskNumStart = data.readUInt32LE(Constants.EF_ZIP64_DSN);\n if (_centralHeader.diskNumStart === Constants.EF_ZIP64_OR_16) {\n _centralHeader.diskNumStart = diskNumStart;\n }\n }\n }\n\n return {\n get entryName() {\n return decoder.decode(_entryName);\n },\n get rawEntryName() {\n return _entryName;\n },\n set entryName(val) {\n _entryName = Utils.toBuffer(val, decoder.encode);\n var lastChar = _entryName[_entryName.length - 1];\n _isDirectory = lastChar === 47 || lastChar === 92;\n _centralHeader.fileNameLength = _entryName.length;\n },\n\n get efs() {\n if (typeof _efs === \"function\") {\n return _efs(this.entryName);\n } else {\n return _efs;\n }\n },\n\n get extra() {\n return _extra;\n },\n set extra(val) {\n _extra = val;\n _centralHeader.extraLength = val.length;\n parseExtra(val);\n },\n\n get comment() {\n return decoder.decode(_comment);\n },\n set comment(val) {\n _comment = Utils.toBuffer(val, decoder.encode);\n _centralHeader.commentLength = _comment.length;\n if (_comment.length > 0xffff) throw Utils.Errors.COMMENT_TOO_LONG();\n },\n\n get name() {\n var n = decoder.decode(_entryName);\n return _isDirectory\n ? n\n .substr(n.length - 1)\n .split(\"/\")\n .pop()\n : n.split(\"/\").pop();\n },\n get isDirectory() {\n return _isDirectory;\n },\n\n getCompressedData: function () {\n return compress(false, null);\n },\n\n getCompressedDataAsync: function (/*Function*/ callback) {\n compress(true, callback);\n },\n\n setData: function (value) {\n uncompressedData = Utils.toBuffer(value, Utils.decoder.encode);\n if (!_isDirectory && uncompressedData.length) {\n _centralHeader.size = uncompressedData.length;\n _centralHeader.method = Utils.Constants.DEFLATED;\n _centralHeader.crc = Utils.crc32(value);\n _centralHeader.changed = true;\n } else {\n // folders and blank files should be stored\n _centralHeader.method = Utils.Constants.STORED;\n }\n },\n\n getData: function (pass) {\n if (_centralHeader.changed) {\n return uncompressedData;\n } else {\n return decompress(false, null, pass);\n }\n },\n\n getDataAsync: function (/*Function*/ callback, pass) {\n if (_centralHeader.changed) {\n callback(uncompressedData);\n } else {\n decompress(true, callback, pass);\n }\n },\n\n set attr(attr) {\n _centralHeader.attr = attr;\n },\n get attr() {\n return _centralHeader.attr;\n },\n\n set header(/*Buffer*/ data) {\n _centralHeader.loadFromBinary(data);\n },\n\n get header() {\n return _centralHeader;\n },\n\n packCentralHeader: function () {\n _centralHeader.flags_efs = this.efs;\n _centralHeader.extraLength = _extra.length;\n // 1. create header (buffer)\n var header = _centralHeader.centralHeaderToBinary();\n var addpos = Utils.Constants.CENHDR;\n // 2. add file name\n _entryName.copy(header, addpos);\n addpos += _entryName.length;\n // 3. add extra data\n _extra.copy(header, addpos);\n addpos += _centralHeader.extraLength;\n // 4. add file comment\n _comment.copy(header, addpos);\n return header;\n },\n\n packLocalHeader: function () {\n let addpos = 0;\n _centralHeader.flags_efs = this.efs;\n _centralHeader.extraLocalLength = _extralocal.length;\n // 1. construct local header Buffer\n const localHeaderBuf = _centralHeader.localHeaderToBinary();\n // 2. localHeader - crate header buffer\n const localHeader = Buffer.alloc(localHeaderBuf.length + _entryName.length + _centralHeader.extraLocalLength);\n // 2.1 add localheader\n localHeaderBuf.copy(localHeader, addpos);\n addpos += localHeaderBuf.length;\n // 2.2 add file name\n _entryName.copy(localHeader, addpos);\n addpos += _entryName.length;\n // 2.3 add extra field\n _extralocal.copy(localHeader, addpos);\n addpos += _extralocal.length;\n\n return localHeader;\n },\n\n toJSON: function () {\n const bytes = function (nr) {\n return \"<\" + ((nr && nr.length + \" bytes buffer\") || \"null\") + \">\";\n };\n\n return {\n entryName: this.entryName,\n name: this.name,\n comment: this.comment,\n isDirectory: this.isDirectory,\n header: _centralHeader.toJSON(),\n compressedData: bytes(input),\n data: bytes(uncompressedData)\n };\n },\n\n toString: function () {\n return JSON.stringify(this.toJSON(), null, \"\\t\");\n }\n };\n};\n","const ZipEntry = require(\"./zipEntry\");\nconst Headers = require(\"./headers\");\nconst Utils = require(\"./util\");\n\nmodule.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) {\n var entryList = [],\n entryTable = {},\n _comment = Buffer.alloc(0),\n mainHeader = new Headers.MainHeader(),\n loadedEntries = false;\n var password = null;\n const temporary = new Set();\n\n // assign options\n const opts = options;\n\n const { noSort, decoder } = opts;\n\n if (inBuffer) {\n // is a memory buffer\n readMainHeader(opts.readEntries);\n } else {\n // none. is a new file\n loadedEntries = true;\n }\n\n function makeTemporaryFolders() {\n const foldersList = new Set();\n\n // Make list of all folders in file\n for (const elem of Object.keys(entryTable)) {\n const elements = elem.split(\"/\");\n elements.pop(); // filename\n if (!elements.length) continue; // no folders\n for (let i = 0; i < elements.length; i++) {\n const sub = elements.slice(0, i + 1).join(\"/\") + \"/\";\n foldersList.add(sub);\n }\n }\n\n // create missing folders as temporary\n for (const elem of foldersList) {\n if (!(elem in entryTable)) {\n const tempfolder = new ZipEntry(opts);\n tempfolder.entryName = elem;\n tempfolder.attr = 0x10;\n tempfolder.temporary = true;\n entryList.push(tempfolder);\n entryTable[tempfolder.entryName] = tempfolder;\n temporary.add(tempfolder);\n }\n }\n }\n\n function readEntries() {\n loadedEntries = true;\n entryTable = {};\n if (mainHeader.diskEntries > (inBuffer.length - mainHeader.offset) / Utils.Constants.CENHDR) {\n throw Utils.Errors.DISK_ENTRY_TOO_LARGE();\n }\n entryList = new Array(mainHeader.diskEntries); // total number of entries\n var index = mainHeader.offset; // offset of first CEN header\n for (var i = 0; i < entryList.length; i++) {\n var tmp = index,\n entry = new ZipEntry(opts, inBuffer);\n entry.header = inBuffer.slice(tmp, (tmp += Utils.Constants.CENHDR));\n\n entry.entryName = inBuffer.slice(tmp, (tmp += entry.header.fileNameLength));\n\n if (entry.header.extraLength) {\n entry.extra = inBuffer.slice(tmp, (tmp += entry.header.extraLength));\n }\n\n if (entry.header.commentLength) entry.comment = inBuffer.slice(tmp, tmp + entry.header.commentLength);\n\n index += entry.header.centralHeaderSize;\n\n entryList[i] = entry;\n entryTable[entry.entryName] = entry;\n }\n temporary.clear();\n makeTemporaryFolders();\n }\n\n function readMainHeader(/*Boolean*/ readNow) {\n var i = inBuffer.length - Utils.Constants.ENDHDR, // END header size\n max = Math.max(0, i - 0xffff), // 0xFFFF is the max zip file comment length\n n = max,\n endStart = inBuffer.length,\n endOffset = -1, // Start offset of the END header\n commentEnd = 0;\n\n // option to search header form entire file\n const trailingSpace = typeof opts.trailingSpace === \"boolean\" ? opts.trailingSpace : false;\n if (trailingSpace) max = 0;\n\n for (i; i >= n; i--) {\n if (inBuffer[i] !== 0x50) continue; // quick check that the byte is 'P'\n if (inBuffer.readUInt32LE(i) === Utils.Constants.ENDSIG) {\n // \"PK\\005\\006\"\n endOffset = i;\n commentEnd = i;\n endStart = i + Utils.Constants.ENDHDR;\n // We already found a regular signature, let's look just a bit further to check if there's any zip64 signature\n n = i - Utils.Constants.END64HDR;\n continue;\n }\n\n if (inBuffer.readUInt32LE(i) === Utils.Constants.END64SIG) {\n // Found a zip64 signature, let's continue reading the whole zip64 record\n n = max;\n continue;\n }\n\n if (inBuffer.readUInt32LE(i) === Utils.Constants.ZIP64SIG) {\n // Found the zip64 record, let's determine it's size\n endOffset = i;\n endStart = i + Utils.readBigUInt64LE(inBuffer, i + Utils.Constants.ZIP64SIZE) + Utils.Constants.ZIP64LEAD;\n break;\n }\n }\n\n if (endOffset == -1) throw Utils.Errors.INVALID_FORMAT();\n\n mainHeader.loadFromBinary(inBuffer.slice(endOffset, endStart));\n if (mainHeader.commentLength) {\n _comment = inBuffer.slice(commentEnd + Utils.Constants.ENDHDR);\n }\n if (readNow) readEntries();\n }\n\n function sortEntries() {\n if (entryList.length > 1 && !noSort) {\n entryList.sort((a, b) => a.entryName.toLowerCase().localeCompare(b.entryName.toLowerCase()));\n }\n }\n\n return {\n /**\n * Returns an array of ZipEntry objects existent in the current opened archive\n * @return Array\n */\n get entries() {\n if (!loadedEntries) {\n readEntries();\n }\n return entryList.filter((e) => !temporary.has(e));\n },\n\n /**\n * Archive comment\n * @return {String}\n */\n get comment() {\n return decoder.decode(_comment);\n },\n set comment(val) {\n _comment = Utils.toBuffer(val, decoder.encode);\n mainHeader.commentLength = _comment.length;\n },\n\n getEntryCount: function () {\n if (!loadedEntries) {\n return mainHeader.diskEntries;\n }\n\n return entryList.length;\n },\n\n forEach: function (callback) {\n this.entries.forEach(callback);\n },\n\n /**\n * Returns a reference to the entry with the given name or null if entry is inexistent\n *\n * @param entryName\n * @return ZipEntry\n */\n getEntry: function (/*String*/ entryName) {\n if (!loadedEntries) {\n readEntries();\n }\n return entryTable[entryName] || null;\n },\n\n /**\n * Adds the given entry to the entry list\n *\n * @param entry\n */\n setEntry: function (/*ZipEntry*/ entry) {\n if (!loadedEntries) {\n readEntries();\n }\n entryList.push(entry);\n entryTable[entry.entryName] = entry;\n mainHeader.totalEntries = entryList.length;\n },\n\n /**\n * Removes the file with the given name from the entry list.\n *\n * If the entry is a directory, then all nested files and directories will be removed\n * @param entryName\n * @returns {void}\n */\n deleteFile: function (/*String*/ entryName, withsubfolders = true) {\n if (!loadedEntries) {\n readEntries();\n }\n const entry = entryTable[entryName];\n const list = this.getEntryChildren(entry, withsubfolders).map((child) => child.entryName);\n\n list.forEach(this.deleteEntry);\n },\n\n /**\n * Removes the entry with the given name from the entry list.\n *\n * @param {string} entryName\n * @returns {void}\n */\n deleteEntry: function (/*String*/ entryName) {\n if (!loadedEntries) {\n readEntries();\n }\n const entry = entryTable[entryName];\n const index = entryList.indexOf(entry);\n if (index >= 0) {\n entryList.splice(index, 1);\n delete entryTable[entryName];\n mainHeader.totalEntries = entryList.length;\n }\n },\n\n /**\n * Iterates and returns all nested files and directories of the given entry\n *\n * @param entry\n * @return Array\n */\n getEntryChildren: function (/*ZipEntry*/ entry, subfolders = true) {\n if (!loadedEntries) {\n readEntries();\n }\n if (typeof entry === \"object\") {\n if (entry.isDirectory && subfolders) {\n const list = [];\n const name = entry.entryName;\n\n for (const zipEntry of entryList) {\n if (zipEntry.entryName.startsWith(name)) {\n list.push(zipEntry);\n }\n }\n return list;\n } else {\n return [entry];\n }\n }\n return [];\n },\n\n /**\n * How many child elements entry has\n *\n * @param {ZipEntry} entry\n * @return {integer}\n */\n getChildCount: function (entry) {\n if (entry && entry.isDirectory) {\n const list = this.getEntryChildren(entry);\n return list.includes(entry) ? list.length - 1 : list.length;\n }\n return 0;\n },\n\n /**\n * Returns the zip file\n *\n * @return Buffer\n */\n compressToBuffer: function () {\n if (!loadedEntries) {\n readEntries();\n }\n sortEntries();\n\n const dataBlock = [];\n const headerBlocks = [];\n let totalSize = 0;\n let dindex = 0;\n\n mainHeader.size = 0;\n mainHeader.offset = 0;\n let totalEntries = 0;\n\n for (const entry of this.entries) {\n // compress data and set local and entry header accordingly. Reason why is called first\n const compressedData = entry.getCompressedData();\n entry.header.offset = dindex;\n\n // 1. construct local header\n const localHeader = entry.packLocalHeader();\n\n // 2. offsets\n const dataLength = localHeader.length + compressedData.length;\n dindex += dataLength;\n\n // 3. store values in sequence\n dataBlock.push(localHeader);\n dataBlock.push(compressedData);\n\n // 4. construct central header\n const centralHeader = entry.packCentralHeader();\n headerBlocks.push(centralHeader);\n // 5. update main header\n mainHeader.size += centralHeader.length;\n totalSize += dataLength + centralHeader.length;\n totalEntries++;\n }\n\n totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length\n // point to end of data and beginning of central directory first record\n mainHeader.offset = dindex;\n mainHeader.totalEntries = totalEntries;\n\n dindex = 0;\n const outBuffer = Buffer.alloc(totalSize);\n // write data blocks\n for (const content of dataBlock) {\n content.copy(outBuffer, dindex);\n dindex += content.length;\n }\n\n // write central directory entries\n for (const content of headerBlocks) {\n content.copy(outBuffer, dindex);\n dindex += content.length;\n }\n\n // write main header\n const mh = mainHeader.toBinary();\n if (_comment) {\n _comment.copy(mh, Utils.Constants.ENDHDR); // add zip file comment\n }\n mh.copy(outBuffer, dindex);\n\n // Since we update entry and main header offsets,\n // they are no longer valid and we have to reset content\n // (Issue 64)\n\n inBuffer = outBuffer;\n loadedEntries = false;\n\n return outBuffer;\n },\n\n toAsyncBuffer: function (/*Function*/ onSuccess, /*Function*/ onFail, /*Function*/ onItemStart, /*Function*/ onItemEnd) {\n try {\n if (!loadedEntries) {\n readEntries();\n }\n sortEntries();\n\n const dataBlock = [];\n const centralHeaders = [];\n let totalSize = 0;\n let dindex = 0;\n let totalEntries = 0;\n\n mainHeader.size = 0;\n mainHeader.offset = 0;\n\n const compress2Buffer = function (entryLists) {\n if (entryLists.length > 0) {\n const entry = entryLists.shift();\n const name = entry.entryName + entry.extra.toString();\n if (onItemStart) onItemStart(name);\n entry.getCompressedDataAsync(function (compressedData) {\n if (onItemEnd) onItemEnd(name);\n entry.header.offset = dindex;\n\n // 1. construct local header\n const localHeader = entry.packLocalHeader();\n\n // 2. offsets\n const dataLength = localHeader.length + compressedData.length;\n dindex += dataLength;\n\n // 3. store values in sequence\n dataBlock.push(localHeader);\n dataBlock.push(compressedData);\n\n // central header\n const centalHeader = entry.packCentralHeader();\n centralHeaders.push(centalHeader);\n mainHeader.size += centalHeader.length;\n totalSize += dataLength + centalHeader.length;\n totalEntries++;\n\n compress2Buffer(entryLists);\n });\n } else {\n totalSize += mainHeader.mainHeaderSize; // also includes zip file comment length\n // point to end of data and beginning of central directory first record\n mainHeader.offset = dindex;\n mainHeader.totalEntries = totalEntries;\n\n dindex = 0;\n const outBuffer = Buffer.alloc(totalSize);\n dataBlock.forEach(function (content) {\n content.copy(outBuffer, dindex); // write data blocks\n dindex += content.length;\n });\n centralHeaders.forEach(function (content) {\n content.copy(outBuffer, dindex); // write central directory entries\n dindex += content.length;\n });\n\n const mh = mainHeader.toBinary();\n if (_comment) {\n _comment.copy(mh, Utils.Constants.ENDHDR); // add zip file comment\n }\n\n mh.copy(outBuffer, dindex); // write main header\n\n // Since we update entry and main header offsets, they are no\n // longer valid and we have to reset content using our new buffer\n // (Issue 64)\n\n inBuffer = outBuffer;\n loadedEntries = false;\n\n onSuccess(outBuffer);\n }\n };\n\n compress2Buffer(Array.from(this.entries));\n } catch (e) {\n onFail(e);\n }\n }\n };\n};\n","const Utils = require(\"./util\");\nconst pth = require(\"path\");\nconst ZipEntry = require(\"./zipEntry\");\nconst ZipFile = require(\"./zipFile\");\n\nconst get_Bool = (...val) => Utils.findLast(val, (c) => typeof c === \"boolean\");\nconst get_Str = (...val) => Utils.findLast(val, (c) => typeof c === \"string\");\nconst get_Fun = (...val) => Utils.findLast(val, (c) => typeof c === \"function\");\n\nconst defaultOptions = {\n // option \"noSort\" : if true it disables files sorting\n noSort: false,\n // read entries during load (initial loading may be slower)\n readEntries: false,\n // default method is none\n method: Utils.Constants.NONE,\n // file system\n fs: null\n};\n\nmodule.exports = function (/**String*/ input, /** object */ options) {\n let inBuffer = null;\n\n // create object based default options, allowing them to be overwritten\n const opts = Object.assign(Object.create(null), defaultOptions);\n\n // test input variable\n if (input && \"object\" === typeof input) {\n // if value is not buffer we accept it to be object with options\n if (!(input instanceof Uint8Array)) {\n Object.assign(opts, input);\n input = opts.input ? opts.input : undefined;\n if (opts.input) delete opts.input;\n }\n\n // if input is buffer\n if (Buffer.isBuffer(input)) {\n inBuffer = input;\n opts.method = Utils.Constants.BUFFER;\n input = undefined;\n }\n }\n\n // assign options\n Object.assign(opts, options);\n\n // instanciate utils filesystem\n const filetools = new Utils(opts);\n\n if (typeof opts.decoder !== \"object\" || typeof opts.decoder.encode !== \"function\" || typeof opts.decoder.decode !== \"function\") {\n opts.decoder = Utils.decoder;\n }\n\n // if input is file name we retrieve its content\n if (input && \"string\" === typeof input) {\n // load zip file\n if (filetools.fs.existsSync(input)) {\n opts.method = Utils.Constants.FILE;\n opts.filename = input;\n inBuffer = filetools.fs.readFileSync(input);\n } else {\n throw Utils.Errors.INVALID_FILENAME();\n }\n }\n\n // create variable\n const _zip = new ZipFile(inBuffer, opts);\n\n const { canonical, sanitize, zipnamefix } = Utils;\n\n function getEntry(/**Object*/ entry) {\n if (entry && _zip) {\n var item;\n // If entry was given as a file name\n if (typeof entry === \"string\") item = _zip.getEntry(pth.posix.normalize(entry));\n // if entry was given as a ZipEntry object\n if (typeof entry === \"object\" && typeof entry.entryName !== \"undefined\" && typeof entry.header !== \"undefined\") item = _zip.getEntry(entry.entryName);\n\n if (item) {\n return item;\n }\n }\n return null;\n }\n\n function fixPath(zipPath) {\n const { join, normalize, sep } = pth.posix;\n // convert windows file separators and normalize\n return join(pth.isAbsolute(zipPath) ? \"/\": '.', normalize(sep + zipPath.split(\"\\\\\").join(sep) + sep));\n }\n\n function filenameFilter(filterfn) {\n if (filterfn instanceof RegExp) {\n // if filter is RegExp wrap it\n return (function (rx) {\n return function (filename) {\n return rx.test(filename);\n };\n })(filterfn);\n } else if (\"function\" !== typeof filterfn) {\n // if filter is not function we will replace it\n return () => true;\n }\n return filterfn;\n }\n\n // keep last character on folders\n const relativePath = (local, entry) => {\n let lastChar = entry.slice(-1);\n lastChar = lastChar === filetools.sep ? filetools.sep : \"\";\n return pth.relative(local, entry) + lastChar;\n };\n\n return {\n /**\n * Extracts the given entry from the archive and returns the content as a Buffer object\n * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry\n * @param {Buffer|string} [pass] - password\n * @return Buffer or Null in case of error\n */\n readFile: function (entry, pass) {\n var item = getEntry(entry);\n return (item && item.getData(pass)) || null;\n },\n\n /**\n * Returns how many child elements has on entry (directories) on files it is always 0\n * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry\n * @returns {integer}\n */\n childCount: function (entry) {\n const item = getEntry(entry);\n if (item) {\n return _zip.getChildCount(item);\n }\n },\n\n /**\n * Asynchronous readFile\n * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry\n * @param {callback} callback\n *\n * @return Buffer or Null in case of error\n */\n readFileAsync: function (entry, callback) {\n var item = getEntry(entry);\n if (item) {\n item.getDataAsync(callback);\n } else {\n callback(null, \"getEntry failed for:\" + entry);\n }\n },\n\n /**\n * Extracts the given entry from the archive and returns the content as plain text in the given encoding\n * @param {ZipEntry|string} entry - ZipEntry object or String with the full path of the entry\n * @param {string} encoding - Optional. If no encoding is specified utf8 is used\n *\n * @return String\n */\n readAsText: function (entry, encoding) {\n var item = getEntry(entry);\n if (item) {\n var data = item.getData();\n if (data && data.length) {\n return data.toString(encoding || \"utf8\");\n }\n }\n return \"\";\n },\n\n /**\n * Asynchronous readAsText\n * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry\n * @param {callback} callback\n * @param {string} [encoding] - Optional. If no encoding is specified utf8 is used\n *\n * @return String\n */\n readAsTextAsync: function (entry, callback, encoding) {\n var item = getEntry(entry);\n if (item) {\n item.getDataAsync(function (data, err) {\n if (err) {\n callback(data, err);\n return;\n }\n\n if (data && data.length) {\n callback(data.toString(encoding || \"utf8\"));\n } else {\n callback(\"\");\n }\n });\n } else {\n callback(\"\");\n }\n },\n\n /**\n * Remove the entry from the file or the entry and all it's nested directories and files if the given entry is a directory\n *\n * @param {ZipEntry|string} entry\n * @returns {void}\n */\n deleteFile: function (entry, withsubfolders = true) {\n // @TODO: test deleteFile\n var item = getEntry(entry);\n if (item) {\n _zip.deleteFile(item.entryName, withsubfolders);\n }\n },\n\n /**\n * Remove the entry from the file or directory without affecting any nested entries\n *\n * @param {ZipEntry|string} entry\n * @returns {void}\n */\n deleteEntry: function (entry) {\n // @TODO: test deleteEntry\n var item = getEntry(entry);\n if (item) {\n _zip.deleteEntry(item.entryName);\n }\n },\n\n /**\n * Adds a comment to the zip. The zip must be rewritten after adding the comment.\n *\n * @param {string} comment\n */\n addZipComment: function (comment) {\n // @TODO: test addZipComment\n _zip.comment = comment;\n },\n\n /**\n * Returns the zip comment\n *\n * @return String\n */\n getZipComment: function () {\n return _zip.comment || \"\";\n },\n\n /**\n * Adds a comment to a specified zipEntry. The zip must be rewritten after adding the comment\n * The comment cannot exceed 65535 characters in length\n *\n * @param {ZipEntry} entry\n * @param {string} comment\n */\n addZipEntryComment: function (entry, comment) {\n var item = getEntry(entry);\n if (item) {\n item.comment = comment;\n }\n },\n\n /**\n * Returns the comment of the specified entry\n *\n * @param {ZipEntry} entry\n * @return String\n */\n getZipEntryComment: function (entry) {\n var item = getEntry(entry);\n if (item) {\n return item.comment || \"\";\n }\n return \"\";\n },\n\n /**\n * Updates the content of an existing entry inside the archive. The zip must be rewritten after updating the content\n *\n * @param {ZipEntry} entry\n * @param {Buffer} content\n */\n updateFile: function (entry, content) {\n var item = getEntry(entry);\n if (item) {\n item.setData(content);\n }\n },\n\n /**\n * Adds a file from the disk to the archive\n *\n * @param {string} localPath File to add to zip\n * @param {string} [zipPath] Optional path inside the zip\n * @param {string} [zipName] Optional name for the file\n * @param {string} [comment] Optional file comment\n */\n addLocalFile: function (localPath, zipPath, zipName, comment) {\n if (filetools.fs.existsSync(localPath)) {\n // fix ZipPath\n zipPath = zipPath ? fixPath(zipPath) : \"\";\n\n // p - local file name\n const p = pth.win32.basename(pth.win32.normalize(localPath));\n\n // add file name into zippath\n zipPath += zipName ? zipName : p;\n\n // read file attributes\n const _attr = filetools.fs.statSync(localPath);\n\n // get file content\n const data = _attr.isFile() ? filetools.fs.readFileSync(localPath) : Buffer.alloc(0);\n\n // if folder\n if (_attr.isDirectory()) zipPath += filetools.sep;\n\n // add file into zip file\n this.addFile(zipPath, data, comment, _attr);\n } else {\n throw Utils.Errors.FILE_NOT_FOUND(localPath);\n }\n },\n\n /**\n * Callback for showing if everything was done.\n *\n * @callback doneCallback\n * @param {Error} err - Error object\n * @param {boolean} done - was request fully completed\n */\n\n /**\n * Adds a file from the disk to the archive\n *\n * @param {(object|string)} options - options object, if it is string it us used as localPath.\n * @param {string} options.localPath - Local path to the file.\n * @param {string} [options.comment] - Optional file comment.\n * @param {string} [options.zipPath] - Optional path inside the zip\n * @param {string} [options.zipName] - Optional name for the file\n * @param {doneCallback} callback - The callback that handles the response.\n */\n addLocalFileAsync: function (options, callback) {\n options = typeof options === \"object\" ? options : { localPath: options };\n const localPath = pth.resolve(options.localPath);\n const { comment } = options;\n let { zipPath, zipName } = options;\n const self = this;\n\n filetools.fs.stat(localPath, function (err, stats) {\n if (err) return callback(err, false);\n // fix ZipPath\n zipPath = zipPath ? fixPath(zipPath) : \"\";\n // p - local file name\n const p = pth.win32.basename(pth.win32.normalize(localPath));\n // add file name into zippath\n zipPath += zipName ? zipName : p;\n\n if (stats.isFile()) {\n filetools.fs.readFile(localPath, function (err, data) {\n if (err) return callback(err, false);\n self.addFile(zipPath, data, comment, stats);\n return setImmediate(callback, undefined, true);\n });\n } else if (stats.isDirectory()) {\n zipPath += filetools.sep;\n self.addFile(zipPath, Buffer.alloc(0), comment, stats);\n return setImmediate(callback, undefined, true);\n }\n });\n },\n\n /**\n * Adds a local directory and all its nested files and directories to the archive\n *\n * @param {string} localPath - local path to the folder\n * @param {string} [zipPath] - optional path inside zip\n * @param {(RegExp|function)} [filter] - optional RegExp or Function if files match will be included.\n */\n addLocalFolder: function (localPath, zipPath, filter) {\n // Prepare filter\n filter = filenameFilter(filter);\n\n // fix ZipPath\n zipPath = zipPath ? fixPath(zipPath) : \"\";\n\n // normalize the path first\n localPath = pth.normalize(localPath);\n\n if (filetools.fs.existsSync(localPath)) {\n const items = filetools.findFiles(localPath);\n const self = this;\n\n if (items.length) {\n for (const filepath of items) {\n const p = pth.join(zipPath, relativePath(localPath, filepath));\n if (filter(p)) {\n self.addLocalFile(filepath, pth.dirname(p));\n }\n }\n }\n } else {\n throw Utils.Errors.FILE_NOT_FOUND(localPath);\n }\n },\n\n /**\n * Asynchronous addLocalFolder\n * @param {string} localPath\n * @param {callback} callback\n * @param {string} [zipPath] optional path inside zip\n * @param {RegExp|function} [filter] optional RegExp or Function if files match will\n * be included.\n */\n addLocalFolderAsync: function (localPath, callback, zipPath, filter) {\n // Prepare filter\n filter = filenameFilter(filter);\n\n // fix ZipPath\n zipPath = zipPath ? fixPath(zipPath) : \"\";\n\n // normalize the path first\n localPath = pth.normalize(localPath);\n\n var self = this;\n filetools.fs.open(localPath, \"r\", function (err) {\n if (err && err.code === \"ENOENT\") {\n callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath));\n } else if (err) {\n callback(undefined, err);\n } else {\n var items = filetools.findFiles(localPath);\n var i = -1;\n\n var next = function () {\n i += 1;\n if (i < items.length) {\n var filepath = items[i];\n var p = relativePath(localPath, filepath).split(\"\\\\\").join(\"/\"); //windows fix\n p = p\n .normalize(\"NFD\")\n .replace(/[\\u0300-\\u036f]/g, \"\")\n .replace(/[^\\x20-\\x7E]/g, \"\"); // accent fix\n if (filter(p)) {\n filetools.fs.stat(filepath, function (er0, stats) {\n if (er0) callback(undefined, er0);\n if (stats.isFile()) {\n filetools.fs.readFile(filepath, function (er1, data) {\n if (er1) {\n callback(undefined, er1);\n } else {\n self.addFile(zipPath + p, data, \"\", stats);\n next();\n }\n });\n } else {\n self.addFile(zipPath + p + \"/\", Buffer.alloc(0), \"\", stats);\n next();\n }\n });\n } else {\n process.nextTick(() => {\n next();\n });\n }\n } else {\n callback(true, undefined);\n }\n };\n\n next();\n }\n });\n },\n\n /**\n * Adds a local directory and all its nested files and directories to the archive\n *\n * @param {object | string} options - options object, if it is string it us used as localPath.\n * @param {string} options.localPath - Local path to the folder.\n * @param {string} [options.zipPath] - optional path inside zip.\n * @param {RegExp|function} [options.filter] - optional RegExp or Function if files match will be included.\n * @param {function|string} [options.namefix] - optional function to help fix filename\n * @param {doneCallback} callback - The callback that handles the response.\n *\n */\n addLocalFolderAsync2: function (options, callback) {\n const self = this;\n options = typeof options === \"object\" ? options : { localPath: options };\n localPath = pth.resolve(fixPath(options.localPath));\n let { zipPath, filter, namefix } = options;\n\n if (filter instanceof RegExp) {\n filter = (function (rx) {\n return function (filename) {\n return rx.test(filename);\n };\n })(filter);\n } else if (\"function\" !== typeof filter) {\n filter = function () {\n return true;\n };\n }\n\n // fix ZipPath\n zipPath = zipPath ? fixPath(zipPath) : \"\";\n\n // Check Namefix function\n if (namefix == \"latin1\") {\n namefix = (str) =>\n str\n .normalize(\"NFD\")\n .replace(/[\\u0300-\\u036f]/g, \"\")\n .replace(/[^\\x20-\\x7E]/g, \"\"); // accent fix (latin1 characers only)\n }\n\n if (typeof namefix !== \"function\") namefix = (str) => str;\n\n // internal, create relative path + fix the name\n const relPathFix = (entry) => pth.join(zipPath, namefix(relativePath(localPath, entry)));\n const fileNameFix = (entry) => pth.win32.basename(pth.win32.normalize(namefix(entry)));\n\n filetools.fs.open(localPath, \"r\", function (err) {\n if (err && err.code === \"ENOENT\") {\n callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath));\n } else if (err) {\n callback(undefined, err);\n } else {\n filetools.findFilesAsync(localPath, function (err, fileEntries) {\n if (err) return callback(err);\n fileEntries = fileEntries.filter((dir) => filter(relPathFix(dir)));\n if (!fileEntries.length) callback(undefined, false);\n\n setImmediate(\n fileEntries.reverse().reduce(function (next, entry) {\n return function (err, done) {\n if (err || done === false) return setImmediate(next, err, false);\n\n self.addLocalFileAsync(\n {\n localPath: entry,\n zipPath: pth.dirname(relPathFix(entry)),\n zipName: fileNameFix(entry)\n },\n next\n );\n };\n }, callback)\n );\n });\n }\n });\n },\n\n /**\n * Adds a local directory and all its nested files and directories to the archive\n *\n * @param {string} localPath - path where files will be extracted\n * @param {object} props - optional properties\n * @param {string} [props.zipPath] - optional path inside zip\n * @param {RegExp|function} [props.filter] - optional RegExp or Function if files match will be included.\n * @param {function|string} [props.namefix] - optional function to help fix filename\n */\n addLocalFolderPromise: function (localPath, props) {\n return new Promise((resolve, reject) => {\n this.addLocalFolderAsync2(Object.assign({ localPath }, props), (err, done) => {\n if (err) reject(err);\n if (done) resolve(this);\n });\n });\n },\n\n /**\n * Allows you to create a entry (file or directory) in the zip file.\n * If you want to create a directory the entryName must end in / and a null buffer should be provided.\n * Comment and attributes are optional\n *\n * @param {string} entryName\n * @param {Buffer | string} content - file content as buffer or utf8 coded string\n * @param {string} [comment] - file comment\n * @param {number | object} [attr] - number as unix file permissions, object as filesystem Stats object\n */\n addFile: function (entryName, content, comment, attr) {\n entryName = zipnamefix(entryName);\n let entry = getEntry(entryName);\n const update = entry != null;\n\n // prepare new entry\n if (!update) {\n entry = new ZipEntry(opts);\n entry.entryName = entryName;\n }\n entry.comment = comment || \"\";\n\n const isStat = \"object\" === typeof attr && attr instanceof filetools.fs.Stats;\n\n // last modification time from file stats\n if (isStat) {\n entry.header.time = attr.mtime;\n }\n\n // Set file attribute\n var fileattr = entry.isDirectory ? 0x10 : 0; // (MS-DOS directory flag)\n\n // extended attributes field for Unix\n // set file type either S_IFDIR / S_IFREG\n let unix = entry.isDirectory ? 0x4000 : 0x8000;\n\n if (isStat) {\n // File attributes from file stats\n unix |= 0xfff & attr.mode;\n } else if (\"number\" === typeof attr) {\n // attr from given attr values\n unix |= 0xfff & attr;\n } else {\n // Default values:\n unix |= entry.isDirectory ? 0o755 : 0o644; // permissions (drwxr-xr-x) or (-r-wr--r--)\n }\n\n fileattr = (fileattr | (unix << 16)) >>> 0; // add attributes\n\n entry.attr = fileattr;\n\n entry.setData(content);\n if (!update) _zip.setEntry(entry);\n\n return entry;\n },\n\n /**\n * Returns an array of ZipEntry objects representing the files and folders inside the archive\n *\n * @param {string} [password]\n * @returns Array\n */\n getEntries: function (password) {\n _zip.password = password;\n return _zip ? _zip.entries : [];\n },\n\n /**\n * Returns a ZipEntry object representing the file or folder specified by ``name``.\n *\n * @param {string} name\n * @return ZipEntry\n */\n getEntry: function (/**String*/ name) {\n return getEntry(name);\n },\n\n getEntryCount: function () {\n return _zip.getEntryCount();\n },\n\n forEach: function (callback) {\n return _zip.forEach(callback);\n },\n\n /**\n * Extracts the given entry to the given targetPath\n * If the entry is a directory inside the archive, the entire directory and it's subdirectories will be extracted\n *\n * @param {string|ZipEntry} entry - ZipEntry object or String with the full path of the entry\n * @param {string} targetPath - Target folder where to write the file\n * @param {boolean} [maintainEntryPath=true] - If maintainEntryPath is true and the entry is inside a folder, the entry folder will be created in targetPath as well. Default is TRUE\n * @param {boolean} [overwrite=false] - If the file already exists at the target path, the file will be overwriten if this is true.\n * @param {boolean} [keepOriginalPermission=false] - The file will be set as the permission from the entry if this is true.\n * @param {string} [outFileName] - String If set will override the filename of the extracted file (Only works if the entry is a file)\n *\n * @return Boolean\n */\n extractEntryTo: function (entry, targetPath, maintainEntryPath, overwrite, keepOriginalPermission, outFileName) {\n overwrite = get_Bool(false, overwrite);\n keepOriginalPermission = get_Bool(false, keepOriginalPermission);\n maintainEntryPath = get_Bool(true, maintainEntryPath);\n outFileName = get_Str(keepOriginalPermission, outFileName);\n\n var item = getEntry(entry);\n if (!item) {\n throw Utils.Errors.NO_ENTRY();\n }\n\n var entryName = canonical(item.entryName);\n\n var target = sanitize(targetPath, outFileName && !item.isDirectory ? outFileName : maintainEntryPath ? entryName : pth.basename(entryName));\n\n if (item.isDirectory) {\n var children = _zip.getEntryChildren(item);\n children.forEach(function (child) {\n if (child.isDirectory) return;\n var content = child.getData();\n if (!content) {\n throw Utils.Errors.CANT_EXTRACT_FILE();\n }\n var name = canonical(child.entryName);\n var childName = sanitize(targetPath, maintainEntryPath ? name : pth.basename(name));\n // The reverse operation for attr depend on method addFile()\n const fileAttr = keepOriginalPermission ? child.header.fileAttr : undefined;\n filetools.writeFileTo(childName, content, overwrite, fileAttr);\n });\n return true;\n }\n\n var content = item.getData(_zip.password);\n if (!content) throw Utils.Errors.CANT_EXTRACT_FILE();\n\n if (filetools.fs.existsSync(target) && !overwrite) {\n throw Utils.Errors.CANT_OVERRIDE();\n }\n // The reverse operation for attr depend on method addFile()\n const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;\n filetools.writeFileTo(target, content, overwrite, fileAttr);\n\n return true;\n },\n\n /**\n * Test the archive\n * @param {string} [pass]\n */\n test: function (pass) {\n if (!_zip) {\n return false;\n }\n\n for (var entry in _zip.entries) {\n try {\n if (entry.isDirectory) {\n continue;\n }\n var content = _zip.entries[entry].getData(pass);\n if (!content) {\n return false;\n }\n } catch (err) {\n return false;\n }\n }\n return true;\n },\n\n /**\n * Extracts the entire archive to the given location\n *\n * @param {string} targetPath Target location\n * @param {boolean} [overwrite=false] If the file already exists at the target path, the file will be overwriten if this is true.\n * Default is FALSE\n * @param {boolean} [keepOriginalPermission=false] The file will be set as the permission from the entry if this is true.\n * Default is FALSE\n * @param {string|Buffer} [pass] password\n */\n extractAllTo: function (targetPath, overwrite, keepOriginalPermission, pass) {\n keepOriginalPermission = get_Bool(false, keepOriginalPermission);\n pass = get_Str(keepOriginalPermission, pass);\n overwrite = get_Bool(false, overwrite);\n if (!_zip) throw Utils.Errors.NO_ZIP();\n\n _zip.entries.forEach(function (entry) {\n var entryName = sanitize(targetPath, canonical(entry.entryName));\n if (entry.isDirectory) {\n filetools.makeDir(entryName);\n return;\n }\n var content = entry.getData(pass);\n if (!content) {\n throw Utils.Errors.CANT_EXTRACT_FILE();\n }\n // The reverse operation for attr depend on method addFile()\n const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;\n filetools.writeFileTo(entryName, content, overwrite, fileAttr);\n try {\n filetools.fs.utimesSync(entryName, entry.header.time, entry.header.time);\n } catch (err) {\n throw Utils.Errors.CANT_EXTRACT_FILE();\n }\n });\n },\n\n /**\n * Asynchronous extractAllTo\n *\n * @param {string} targetPath Target location\n * @param {boolean} [overwrite=false] If the file already exists at the target path, the file will be overwriten if this is true.\n * Default is FALSE\n * @param {boolean} [keepOriginalPermission=false] The file will be set as the permission from the entry if this is true.\n * Default is FALSE\n * @param {function} callback The callback will be executed when all entries are extracted successfully or any error is thrown.\n */\n extractAllToAsync: function (targetPath, overwrite, keepOriginalPermission, callback) {\n callback = get_Fun(overwrite, keepOriginalPermission, callback);\n keepOriginalPermission = get_Bool(false, keepOriginalPermission);\n overwrite = get_Bool(false, overwrite);\n if (!callback) {\n return new Promise((resolve, reject) => {\n this.extractAllToAsync(targetPath, overwrite, keepOriginalPermission, function (err) {\n if (err) {\n reject(err);\n } else {\n resolve(this);\n }\n });\n });\n }\n if (!_zip) {\n callback(Utils.Errors.NO_ZIP());\n return;\n }\n\n targetPath = pth.resolve(targetPath);\n // convert entryName to\n const getPath = (entry) => sanitize(targetPath, pth.normalize(canonical(entry.entryName)));\n const getError = (msg, file) => new Error(msg + ': \"' + file + '\"');\n\n // separate directories from files\n const dirEntries = [];\n const fileEntries = [];\n _zip.entries.forEach((e) => {\n if (e.isDirectory) {\n dirEntries.push(e);\n } else {\n fileEntries.push(e);\n }\n });\n\n // Create directory entries first synchronously\n // this prevents race condition and assures folders are there before writing files\n for (const entry of dirEntries) {\n const dirPath = getPath(entry);\n // The reverse operation for attr depend on method addFile()\n const dirAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;\n try {\n filetools.makeDir(dirPath);\n if (dirAttr) filetools.fs.chmodSync(dirPath, dirAttr);\n // in unix timestamp will change if files are later added to folder, but still\n filetools.fs.utimesSync(dirPath, entry.header.time, entry.header.time);\n } catch (er) {\n callback(getError(\"Unable to create folder\", dirPath));\n }\n }\n\n fileEntries.reverse().reduce(function (next, entry) {\n return function (err) {\n if (err) {\n next(err);\n } else {\n const entryName = pth.normalize(canonical(entry.entryName));\n const filePath = sanitize(targetPath, entryName);\n entry.getDataAsync(function (content, err_1) {\n if (err_1) {\n next(err_1);\n } else if (!content) {\n next(Utils.Errors.CANT_EXTRACT_FILE());\n } else {\n // The reverse operation for attr depend on method addFile()\n const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;\n filetools.writeFileToAsync(filePath, content, overwrite, fileAttr, function (succ) {\n if (!succ) {\n next(getError(\"Unable to write file\", filePath));\n }\n filetools.fs.utimes(filePath, entry.header.time, entry.header.time, function (err_2) {\n if (err_2) {\n next(getError(\"Unable to set times\", filePath));\n } else {\n next();\n }\n });\n });\n }\n });\n }\n };\n }, callback)();\n },\n\n /**\n * Writes the newly created zip file to disk at the specified location or if a zip was opened and no ``targetFileName`` is provided, it will overwrite the opened zip\n *\n * @param {string} targetFileName\n * @param {function} callback\n */\n writeZip: function (targetFileName, callback) {\n if (arguments.length === 1) {\n if (typeof targetFileName === \"function\") {\n callback = targetFileName;\n targetFileName = \"\";\n }\n }\n\n if (!targetFileName && opts.filename) {\n targetFileName = opts.filename;\n }\n if (!targetFileName) return;\n\n var zipData = _zip.compressToBuffer();\n if (zipData) {\n var ok = filetools.writeFileTo(targetFileName, zipData, true);\n if (typeof callback === \"function\") callback(!ok ? new Error(\"failed\") : null, \"\");\n }\n },\n\n /**\n *\n * @param {string} targetFileName\n * @param {object} [props]\n * @param {boolean} [props.overwrite=true] If the file already exists at the target path, the file will be overwriten if this is true.\n * @param {boolean} [props.perm] The file will be set as the permission from the entry if this is true.\n\n * @returns {Promise}\n */\n writeZipPromise: function (/**String*/ targetFileName, /* object */ props) {\n const { overwrite, perm } = Object.assign({ overwrite: true }, props);\n\n return new Promise((resolve, reject) => {\n // find file name\n if (!targetFileName && opts.filename) targetFileName = opts.filename;\n if (!targetFileName) reject(\"ADM-ZIP: ZIP File Name Missing\");\n\n this.toBufferPromise().then((zipData) => {\n const ret = (done) => (done ? resolve(done) : reject(\"ADM-ZIP: Wasn't able to write zip file\"));\n filetools.writeFileToAsync(targetFileName, zipData, overwrite, perm, ret);\n }, reject);\n });\n },\n\n /**\n * @returns {Promise} A promise to the Buffer.\n */\n toBufferPromise: function () {\n return new Promise((resolve, reject) => {\n _zip.toAsyncBuffer(resolve, reject);\n });\n },\n\n /**\n * Returns the content of the entire zip file as a Buffer object\n *\n * @prop {function} [onSuccess]\n * @prop {function} [onFail]\n * @prop {function} [onItemStart]\n * @prop {function} [onItemEnd]\n * @returns {Buffer}\n */\n toBuffer: function (onSuccess, onFail, onItemStart, onItemEnd) {\n if (typeof onSuccess === \"function\") {\n _zip.toAsyncBuffer(onSuccess, onFail, onItemStart, onItemEnd);\n return null;\n }\n return _zip.compressToBuffer();\n }\n };\n};\n","{\n \"name\": \"@actions/artifact\",\n \"version\": \"6.2.1\",\n \"preview\": true,\n \"description\": \"Actions artifact lib\",\n \"keywords\": [\n \"github\",\n \"actions\",\n \"artifact\"\n ],\n \"homepage\": \"https://github.com/actions/toolkit/tree/main/packages/artifact\",\n \"license\": \"MIT\",\n \"type\": \"module\",\n \"main\": \"lib/artifact.js\",\n \"types\": \"lib/artifact.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./lib/artifact.d.ts\",\n \"import\": \"./lib/artifact.js\"\n }\n },\n \"directories\": {\n \"lib\": \"lib\",\n \"test\": \"__tests__\"\n },\n \"files\": [\n \"lib\",\n \"!.DS_Store\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/actions/toolkit.git\",\n \"directory\": \"packages/artifact\"\n },\n \"scripts\": {\n \"audit-moderate\": \"npm install && npm audit --json --audit-level=moderate > audit.json\",\n \"test\": \"cd ../../ && npm run test ./packages/artifact\",\n \"bootstrap\": \"cd ../../ && npm run bootstrap\",\n \"tsc-run\": \"tsc && cp src/internal/shared/package-version.cjs lib/internal/shared/\",\n \"tsc\": \"npm run bootstrap && npm run tsc-run\",\n \"gen:docs\": \"typedoc --plugin typedoc-plugin-markdown --out docs/generated src/artifact.ts --githubPages false --readme none\"\n },\n \"bugs\": {\n \"url\": \"https://github.com/actions/toolkit/issues\"\n },\n \"dependencies\": {\n \"@actions/core\": \"^3.0.0\",\n \"@actions/github\": \"^9.0.0\",\n \"@actions/http-client\": \"^4.0.0\",\n \"@azure/storage-blob\": \"^12.30.0\",\n \"@octokit/core\": \"^7.0.6\",\n \"@octokit/plugin-request-log\": \"^6.0.0\",\n \"@octokit/plugin-retry\": \"^8.0.0\",\n \"@octokit/request\": \"^10.0.7\",\n \"@octokit/request-error\": \"^7.1.0\",\n \"@protobuf-ts/plugin\": \"^2.2.3-alpha.1\",\n \"@protobuf-ts/runtime\": \"^2.9.4\",\n \"archiver\": \"^7.0.1\",\n \"jwt-decode\": \"^4.0.0\",\n \"unzip-stream\": \"^0.3.1\"\n },\n \"devDependencies\": {\n \"@types/archiver\": \"^7.0.0\",\n \"@types/unzip-stream\": \"^0.3.4\",\n \"typedoc\": \"^0.28.16\",\n \"typedoc-plugin-markdown\": \"^4.9.0\",\n \"typescript\": \"^5.9.3\"\n },\n \"overrides\": {\n \"uri-js\": \"npm:uri-js-replace@^1.0.1\",\n \"node-fetch\": \"^3.3.2\"\n }\n}\n","// This file exists as a CommonJS module to read the version from package.json.\n// In an ESM package, using `require()` directly in .ts files requires disabling\n// ESLint rules and doesn't work reliably across all Node.js versions.\n// By keeping this as a .cjs file, we can use require() naturally and export\n// the version for the ESM modules to import.\nconst packageJson = require('../../../package.json')\nmodule.exports = { version: packageJson.version }\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(/\\s+/g, ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","'use strict';\n\nmodule.exports = (flag, argv = process.argv) => {\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst position = argv.indexOf(prefix + flag);\n\tconst terminatorPosition = argv.indexOf('--');\n\treturn position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);\n};\n","'use strict';\nconst os = require('os');\nconst tty = require('tty');\nconst hasFlag = require('has-flag');\n\nconst {env} = process;\n\nlet forceColor;\nif (hasFlag('no-color') ||\n\thasFlag('no-colors') ||\n\thasFlag('color=false') ||\n\thasFlag('color=never')) {\n\tforceColor = 0;\n} else if (hasFlag('color') ||\n\thasFlag('colors') ||\n\thasFlag('color=true') ||\n\thasFlag('color=always')) {\n\tforceColor = 1;\n}\n\nif ('FORCE_COLOR' in env) {\n\tif (env.FORCE_COLOR === 'true') {\n\t\tforceColor = 1;\n\t} else if (env.FORCE_COLOR === 'false') {\n\t\tforceColor = 0;\n\t} else {\n\t\tforceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);\n\t}\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3\n\t};\n}\n\nfunction supportsColor(haveStream, streamIsTTY) {\n\tif (forceColor === 0) {\n\t\treturn 0;\n\t}\n\n\tif (hasFlag('color=16m') ||\n\t\thasFlag('color=full') ||\n\t\thasFlag('color=truecolor')) {\n\t\treturn 3;\n\t}\n\n\tif (hasFlag('color=256')) {\n\t\treturn 2;\n\t}\n\n\tif (haveStream && !streamIsTTY && forceColor === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor || 0;\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\t// Windows 10 build 10586 is the first Windows release that supports 256 colors.\n\t\t// Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(osRelease[0]) >= 10 &&\n\t\t\tNumber(osRelease[2]) >= 10586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app':\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\tcase 'Apple_Terminal':\n\t\t\t\treturn 2;\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\treturn min;\n}\n\nfunction getSupportLevel(stream) {\n\tconst level = supportsColor(stream, stream && stream.isTTY);\n\treturn translateLevel(level);\n}\n\nmodule.exports = {\n\tsupportsColor: getSupportLevel,\n\tstdout: translateLevel(supportsColor(true, tty.isatty(1))),\n\tstderr: translateLevel(supportsColor(true, tty.isatty(2)))\n};\n","/**\n * Module dependencies.\n */\n\nconst tty = require('tty');\nconst util = require('util');\n\n/**\n * This is the Node.js implementation of `debug()`.\n */\n\nexports.init = init;\nexports.log = log;\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.destroy = util.deprecate(\n\t() => {},\n\t'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'\n);\n\n/**\n * Colors.\n */\n\nexports.colors = [6, 2, 3, 4, 5, 1];\n\ntry {\n\t// Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)\n\t// eslint-disable-next-line import/no-extraneous-dependencies\n\tconst supportsColor = require('supports-color');\n\n\tif (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {\n\t\texports.colors = [\n\t\t\t20,\n\t\t\t21,\n\t\t\t26,\n\t\t\t27,\n\t\t\t32,\n\t\t\t33,\n\t\t\t38,\n\t\t\t39,\n\t\t\t40,\n\t\t\t41,\n\t\t\t42,\n\t\t\t43,\n\t\t\t44,\n\t\t\t45,\n\t\t\t56,\n\t\t\t57,\n\t\t\t62,\n\t\t\t63,\n\t\t\t68,\n\t\t\t69,\n\t\t\t74,\n\t\t\t75,\n\t\t\t76,\n\t\t\t77,\n\t\t\t78,\n\t\t\t79,\n\t\t\t80,\n\t\t\t81,\n\t\t\t92,\n\t\t\t93,\n\t\t\t98,\n\t\t\t99,\n\t\t\t112,\n\t\t\t113,\n\t\t\t128,\n\t\t\t129,\n\t\t\t134,\n\t\t\t135,\n\t\t\t148,\n\t\t\t149,\n\t\t\t160,\n\t\t\t161,\n\t\t\t162,\n\t\t\t163,\n\t\t\t164,\n\t\t\t165,\n\t\t\t166,\n\t\t\t167,\n\t\t\t168,\n\t\t\t169,\n\t\t\t170,\n\t\t\t171,\n\t\t\t172,\n\t\t\t173,\n\t\t\t178,\n\t\t\t179,\n\t\t\t184,\n\t\t\t185,\n\t\t\t196,\n\t\t\t197,\n\t\t\t198,\n\t\t\t199,\n\t\t\t200,\n\t\t\t201,\n\t\t\t202,\n\t\t\t203,\n\t\t\t204,\n\t\t\t205,\n\t\t\t206,\n\t\t\t207,\n\t\t\t208,\n\t\t\t209,\n\t\t\t214,\n\t\t\t215,\n\t\t\t220,\n\t\t\t221\n\t\t];\n\t}\n} catch (error) {\n\t// Swallow - we only care if `supports-color` is available; it doesn't have to be.\n}\n\n/**\n * Build up the default `inspectOpts` object from the environment variables.\n *\n * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js\n */\n\nexports.inspectOpts = Object.keys(process.env).filter(key => {\n\treturn /^debug_/i.test(key);\n}).reduce((obj, key) => {\n\t// Camel-case\n\tconst prop = key\n\t\t.substring(6)\n\t\t.toLowerCase()\n\t\t.replace(/_([a-z])/g, (_, k) => {\n\t\t\treturn k.toUpperCase();\n\t\t});\n\n\t// Coerce string value into JS value\n\tlet val = process.env[key];\n\tif (/^(yes|on|true|enabled)$/i.test(val)) {\n\t\tval = true;\n\t} else if (/^(no|off|false|disabled)$/i.test(val)) {\n\t\tval = false;\n\t} else if (val === 'null') {\n\t\tval = null;\n\t} else {\n\t\tval = Number(val);\n\t}\n\n\tobj[prop] = val;\n\treturn obj;\n}, {});\n\n/**\n * Is stdout a TTY? Colored output is enabled when `true`.\n */\n\nfunction useColors() {\n\treturn 'colors' in exports.inspectOpts ?\n\t\tBoolean(exports.inspectOpts.colors) :\n\t\ttty.isatty(process.stderr.fd);\n}\n\n/**\n * Adds ANSI color escape codes if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\tconst {namespace: name, useColors} = this;\n\n\tif (useColors) {\n\t\tconst c = this.color;\n\t\tconst colorCode = '\\u001B[3' + (c < 8 ? c : '8;5;' + c);\n\t\tconst prefix = ` ${colorCode};1m${name} \\u001B[0m`;\n\n\t\targs[0] = prefix + args[0].split('\\n').join('\\n' + prefix);\n\t\targs.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\\u001B[0m');\n\t} else {\n\t\targs[0] = getDate() + name + ' ' + args[0];\n\t}\n}\n\nfunction getDate() {\n\tif (exports.inspectOpts.hideDate) {\n\t\treturn '';\n\t}\n\treturn new Date().toISOString() + ' ';\n}\n\n/**\n * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr.\n */\n\nfunction log(...args) {\n\treturn process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\\n');\n}\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\tif (namespaces) {\n\t\tprocess.env.DEBUG = namespaces;\n\t} else {\n\t\t// If you set a process.env field to null or undefined, it gets cast to the\n\t\t// string 'null' or 'undefined'. Just delete instead.\n\t\tdelete process.env.DEBUG;\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\n\nfunction load() {\n\treturn process.env.DEBUG;\n}\n\n/**\n * Init logic for `debug` instances.\n *\n * Create a new `inspectOpts` object in case `useColors` is set\n * differently for a particular `debug` instance.\n */\n\nfunction init(debug) {\n\tdebug.inspectOpts = {};\n\n\tconst keys = Object.keys(exports.inspectOpts);\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tdebug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %o to `util.inspect()`, all on a single line.\n */\n\nformatters.o = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts)\n\t\t.split('\\n')\n\t\t.map(str => str.trim())\n\t\t.join(' ');\n};\n\n/**\n * Map %O to `util.inspect()`, allowing multiple lines if needed.\n */\n\nformatters.O = function (v) {\n\tthis.inspectOpts.colors = this.useColors;\n\treturn util.inspect(v, this.inspectOpts);\n};\n","/**\n * Detect Electron renderer / nwjs process, which is node, but we should\n * treat as a browser.\n */\n\nif (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {\n\tmodule.exports = require('./browser.js');\n} else {\n\tmodule.exports = require('./node.js');\n}\n",null,null,null,null,null,"// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * @internal\n *\n * Holds the singleton instrumenter, to be shared across CJS and ESM imports.\n */\nexport const state = {\n instrumenterImplementation: undefined,\n};\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * Holds the singleton operationRequestMap, to be shared across CJS and ESM imports.\n */\nexport const state = {\n operationRequestMap: new WeakMap(),\n};\n","'use strict';\n\nconst nameStartChar = ':A-Za-z_\\\\u00C0-\\\\u00D6\\\\u00D8-\\\\u00F6\\\\u00F8-\\\\u02FF\\\\u0370-\\\\u037D\\\\u037F-\\\\u1FFF\\\\u200C-\\\\u200D\\\\u2070-\\\\u218F\\\\u2C00-\\\\u2FEF\\\\u3001-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFFD';\nconst nameChar = nameStartChar + '\\\\-.\\\\d\\\\u00B7\\\\u0300-\\\\u036F\\\\u203F-\\\\u2040';\nexport const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*';\nconst regexName = new RegExp('^' + nameRegexp + '$');\n\nexport function getAllMatches(string, regex) {\n const matches = [];\n let match = regex.exec(string);\n while (match) {\n const allmatches = [];\n allmatches.startIndex = regex.lastIndex - match[0].length;\n const len = match.length;\n for (let index = 0; index < len; index++) {\n allmatches.push(match[index]);\n }\n matches.push(allmatches);\n match = regex.exec(string);\n }\n return matches;\n}\n\nexport const isName = function (string) {\n const match = regexName.exec(string);\n return !(match === null || typeof match === 'undefined');\n}\n\nexport function isExist(v) {\n return typeof v !== 'undefined';\n}\n\nexport function isEmptyObject(obj) {\n return Object.keys(obj).length === 0;\n}\n\nexport function getValue(v) {\n if (exports.isExist(v)) {\n return v;\n } else {\n return '';\n }\n}\n\n/**\n * Dangerous property names that could lead to prototype pollution or security issues\n */\nexport const DANGEROUS_PROPERTY_NAMES = [\n // '__proto__',\n // 'constructor',\n // 'prototype',\n 'hasOwnProperty',\n 'toString',\n 'valueOf',\n '__defineGetter__',\n '__defineSetter__',\n '__lookupGetter__',\n '__lookupSetter__'\n];\n\nexport const criticalProperties = [\"__proto__\", \"constructor\", \"prototype\"];","'use strict';\n\nimport { getAllMatches, isName } from './util.js';\n\nconst defaultOptions = {\n allowBooleanAttributes: false, //A tag can have attributes without any value\n unpairedTags: []\n};\n\n//const tagsPattern = new RegExp(\"<\\\\/?([\\\\w:\\\\-_\\.]+)\\\\s*\\/?>\",\"g\");\nexport function validate(xmlData, options) {\n options = Object.assign({}, defaultOptions, options);\n\n //xmlData = xmlData.replace(/(\\r\\n|\\n|\\r)/gm,\"\");//make it single line\n //xmlData = xmlData.replace(/(^\\s*<\\?xml.*?\\?>)/g,\"\");//Remove XML starting tag\n //xmlData = xmlData.replace(/()/g,\"\");//Remove DOCTYPE\n const tags = [];\n let tagFound = false;\n\n //indicates that the root tag has been closed (aka. depth 0 has been reached)\n let reachedRoot = false;\n\n if (xmlData[0] === '\\ufeff') {\n // check for byte order mark (BOM)\n xmlData = xmlData.substr(1);\n }\n\n for (let i = 0; i < xmlData.length; i++) {\n\n if (xmlData[i] === '<' && xmlData[i + 1] === '?') {\n i += 2;\n i = readPI(xmlData, i);\n if (i.err) return i;\n } else if (xmlData[i] === '<') {\n //starting of tag\n //read until you reach to '>' avoiding any '>' in attribute value\n let tagStartPos = i;\n i++;\n\n if (xmlData[i] === '!') {\n i = readCommentAndCDATA(xmlData, i);\n continue;\n } else {\n let closingTag = false;\n if (xmlData[i] === '/') {\n //closing tag\n closingTag = true;\n i++;\n }\n //read tagname\n let tagName = '';\n for (; i < xmlData.length &&\n xmlData[i] !== '>' &&\n xmlData[i] !== ' ' &&\n xmlData[i] !== '\\t' &&\n xmlData[i] !== '\\n' &&\n xmlData[i] !== '\\r'; i++\n ) {\n tagName += xmlData[i];\n }\n tagName = tagName.trim();\n //console.log(tagName);\n\n if (tagName[tagName.length - 1] === '/') {\n //self closing tag without attributes\n tagName = tagName.substring(0, tagName.length - 1);\n //continue;\n i--;\n }\n if (!validateTagName(tagName)) {\n let msg;\n if (tagName.trim().length === 0) {\n msg = \"Invalid space after '<'.\";\n } else {\n msg = \"Tag '\" + tagName + \"' is an invalid name.\";\n }\n return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i));\n }\n\n const result = readAttributeStr(xmlData, i);\n if (result === false) {\n return getErrorObject('InvalidAttr', \"Attributes for '\" + tagName + \"' have open quote.\", getLineNumberForPosition(xmlData, i));\n }\n let attrStr = result.value;\n i = result.index;\n\n if (attrStr[attrStr.length - 1] === '/') {\n //self closing tag\n const attrStrStart = i - attrStr.length;\n attrStr = attrStr.substring(0, attrStr.length - 1);\n const isValid = validateAttributeString(attrStr, options);\n if (isValid === true) {\n tagFound = true;\n //continue; //text may presents after self closing tag\n } else {\n //the result from the nested function returns the position of the error within the attribute\n //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute\n //this gives us the absolute index in the entire xml, which we can use to find the line at last\n return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));\n }\n } else if (closingTag) {\n if (!result.tagClosed) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' doesn't have proper closing.\", getLineNumberForPosition(xmlData, i));\n } else if (attrStr.trim().length > 0) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' can't have attributes or invalid starting.\", getLineNumberForPosition(xmlData, tagStartPos));\n } else if (tags.length === 0) {\n return getErrorObject('InvalidTag', \"Closing tag '\" + tagName + \"' has not been opened.\", getLineNumberForPosition(xmlData, tagStartPos));\n } else {\n const otg = tags.pop();\n if (tagName !== otg.tagName) {\n let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);\n return getErrorObject('InvalidTag',\n \"Expected closing tag '\" + otg.tagName + \"' (opened in line \" + openPos.line + \", col \" + openPos.col + \") instead of closing tag '\" + tagName + \"'.\",\n getLineNumberForPosition(xmlData, tagStartPos));\n }\n\n //when there are no more tags, we reached the root level.\n if (tags.length == 0) {\n reachedRoot = true;\n }\n }\n } else {\n const isValid = validateAttributeString(attrStr, options);\n if (isValid !== true) {\n //the result from the nested function returns the position of the error within the attribute\n //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute\n //this gives us the absolute index in the entire xml, which we can use to find the line at last\n return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));\n }\n\n //if the root level has been reached before ...\n if (reachedRoot === true) {\n return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i));\n } else if (options.unpairedTags.indexOf(tagName) !== -1) {\n //don't push into stack\n } else {\n tags.push({ tagName, tagStartPos });\n }\n tagFound = true;\n }\n\n //skip tag text value\n //It may include comments and CDATA value\n for (i++; i < xmlData.length; i++) {\n if (xmlData[i] === '<') {\n if (xmlData[i + 1] === '!') {\n //comment or CADATA\n i++;\n i = readCommentAndCDATA(xmlData, i);\n continue;\n } else if (xmlData[i + 1] === '?') {\n i = readPI(xmlData, ++i);\n if (i.err) return i;\n } else {\n break;\n }\n } else if (xmlData[i] === '&') {\n const afterAmp = validateAmpersand(xmlData, i);\n if (afterAmp == -1)\n return getErrorObject('InvalidChar', \"char '&' is not expected.\", getLineNumberForPosition(xmlData, i));\n i = afterAmp;\n } else {\n if (reachedRoot === true && !isWhiteSpace(xmlData[i])) {\n return getErrorObject('InvalidXml', \"Extra text at the end\", getLineNumberForPosition(xmlData, i));\n }\n }\n } //end of reading tag text value\n if (xmlData[i] === '<') {\n i--;\n }\n }\n } else {\n if (isWhiteSpace(xmlData[i])) {\n continue;\n }\n return getErrorObject('InvalidChar', \"char '\" + xmlData[i] + \"' is not expected.\", getLineNumberForPosition(xmlData, i));\n }\n }\n\n if (!tagFound) {\n return getErrorObject('InvalidXml', 'Start tag expected.', 1);\n } else if (tags.length == 1) {\n return getErrorObject('InvalidTag', \"Unclosed tag '\" + tags[0].tagName + \"'.\", getLineNumberForPosition(xmlData, tags[0].tagStartPos));\n } else if (tags.length > 0) {\n return getErrorObject('InvalidXml', \"Invalid '\" +\n JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\\r?\\n/g, '') +\n \"' found.\", { line: 1, col: 1 });\n }\n\n return true;\n};\n\nfunction isWhiteSpace(char) {\n return char === ' ' || char === '\\t' || char === '\\n' || char === '\\r';\n}\n/**\n * Read Processing insstructions and skip\n * @param {*} xmlData\n * @param {*} i\n */\nfunction readPI(xmlData, i) {\n const start = i;\n for (; i < xmlData.length; i++) {\n if (xmlData[i] == '?' || xmlData[i] == ' ') {\n //tagname\n const tagname = xmlData.substr(start, i - start);\n if (i > 5 && tagname === 'xml') {\n return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i));\n } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') {\n //check if valid attribut string\n i++;\n break;\n } else {\n continue;\n }\n }\n }\n return i;\n}\n\nfunction readCommentAndCDATA(xmlData, i) {\n if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') {\n //comment\n for (i += 3; i < xmlData.length; i++) {\n if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') {\n i += 2;\n break;\n }\n }\n } else if (\n xmlData.length > i + 8 &&\n xmlData[i + 1] === 'D' &&\n xmlData[i + 2] === 'O' &&\n xmlData[i + 3] === 'C' &&\n xmlData[i + 4] === 'T' &&\n xmlData[i + 5] === 'Y' &&\n xmlData[i + 6] === 'P' &&\n xmlData[i + 7] === 'E'\n ) {\n let angleBracketsCount = 1;\n for (i += 8; i < xmlData.length; i++) {\n if (xmlData[i] === '<') {\n angleBracketsCount++;\n } else if (xmlData[i] === '>') {\n angleBracketsCount--;\n if (angleBracketsCount === 0) {\n break;\n }\n }\n }\n } else if (\n xmlData.length > i + 9 &&\n xmlData[i + 1] === '[' &&\n xmlData[i + 2] === 'C' &&\n xmlData[i + 3] === 'D' &&\n xmlData[i + 4] === 'A' &&\n xmlData[i + 5] === 'T' &&\n xmlData[i + 6] === 'A' &&\n xmlData[i + 7] === '['\n ) {\n for (i += 8; i < xmlData.length; i++) {\n if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') {\n i += 2;\n break;\n }\n }\n }\n\n return i;\n}\n\nconst doubleQuote = '\"';\nconst singleQuote = \"'\";\n\n/**\n * Keep reading xmlData until '<' is found outside the attribute value.\n * @param {string} xmlData\n * @param {number} i\n */\nfunction readAttributeStr(xmlData, i) {\n let attrStr = '';\n let startChar = '';\n let tagClosed = false;\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) {\n if (startChar === '') {\n startChar = xmlData[i];\n } else if (startChar !== xmlData[i]) {\n //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa\n } else {\n startChar = '';\n }\n } else if (xmlData[i] === '>') {\n if (startChar === '') {\n tagClosed = true;\n break;\n }\n }\n attrStr += xmlData[i];\n }\n if (startChar !== '') {\n return false;\n }\n\n return {\n value: attrStr,\n index: i,\n tagClosed: tagClosed\n };\n}\n\n/**\n * Select all the attributes whether valid or invalid.\n */\nconst validAttrStrRegxp = new RegExp('(\\\\s*)([^\\\\s=]+)(\\\\s*=)?(\\\\s*([\\'\"])(([\\\\s\\\\S])*?)\\\\5)?', 'g');\n\n//attr, =\"sd\", a=\"amit's\", a=\"sd\"b=\"saf\", ab cd=\"\"\n\nfunction validateAttributeString(attrStr, options) {\n //console.log(\"start:\"+attrStr+\":end\");\n\n //if(attrStr.trim().length === 0) return true; //empty string\n\n const matches = getAllMatches(attrStr, validAttrStrRegxp);\n const attrNames = {};\n\n for (let i = 0; i < matches.length; i++) {\n if (matches[i][1].length === 0) {\n //nospace before attribute name: a=\"sd\"b=\"saf\"\n return getErrorObject('InvalidAttr', \"Attribute '\" + matches[i][2] + \"' has no space in starting.\", getPositionFromMatch(matches[i]))\n } else if (matches[i][3] !== undefined && matches[i][4] === undefined) {\n return getErrorObject('InvalidAttr', \"Attribute '\" + matches[i][2] + \"' is without value.\", getPositionFromMatch(matches[i]));\n } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {\n //independent attribute: ab\n return getErrorObject('InvalidAttr', \"boolean attribute '\" + matches[i][2] + \"' is not allowed.\", getPositionFromMatch(matches[i]));\n }\n /* else if(matches[i][6] === undefined){//attribute without value: ab=\n return { err: { code:\"InvalidAttr\",msg:\"attribute \" + matches[i][2] + \" has no value assigned.\"}};\n } */\n const attrName = matches[i][2];\n if (!validateAttrName(attrName)) {\n return getErrorObject('InvalidAttr', \"Attribute '\" + attrName + \"' is an invalid name.\", getPositionFromMatch(matches[i]));\n }\n if (!Object.prototype.hasOwnProperty.call(attrNames, attrName)) {\n //check for duplicate attribute.\n attrNames[attrName] = 1;\n } else {\n return getErrorObject('InvalidAttr', \"Attribute '\" + attrName + \"' is repeated.\", getPositionFromMatch(matches[i]));\n }\n }\n\n return true;\n}\n\nfunction validateNumberAmpersand(xmlData, i) {\n let re = /\\d/;\n if (xmlData[i] === 'x') {\n i++;\n re = /[\\da-fA-F]/;\n }\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === ';')\n return i;\n if (!xmlData[i].match(re))\n break;\n }\n return -1;\n}\n\nfunction validateAmpersand(xmlData, i) {\n // https://www.w3.org/TR/xml/#dt-charref\n i++;\n if (xmlData[i] === ';')\n return -1;\n if (xmlData[i] === '#') {\n i++;\n return validateNumberAmpersand(xmlData, i);\n }\n let count = 0;\n for (; i < xmlData.length; i++, count++) {\n if (xmlData[i].match(/\\w/) && count < 20)\n continue;\n if (xmlData[i] === ';')\n break;\n return -1;\n }\n return i;\n}\n\nfunction getErrorObject(code, message, lineNumber) {\n return {\n err: {\n code: code,\n msg: message,\n line: lineNumber.line || lineNumber,\n col: lineNumber.col,\n },\n };\n}\n\nfunction validateAttrName(attrName) {\n return isName(attrName);\n}\n\n// const startsWithXML = /^xml/i;\n\nfunction validateTagName(tagname) {\n return isName(tagname) /* && !tagname.match(startsWithXML) */;\n}\n\n//this function returns the line number for the character at the given index\nfunction getLineNumberForPosition(xmlData, index) {\n const lines = xmlData.substring(0, index).split(/\\r?\\n/);\n return {\n line: lines.length,\n\n // column number is last line's length + 1, because column numbering starts at 1:\n col: lines[lines.length - 1].length + 1\n };\n}\n\n//this function returns the position of the first character of match within attrStr\nfunction getPositionFromMatch(match) {\n return match.startIndex + match[1].length;\n}\n","// ---------------------------------------------------------------------------\n// Complete HTML5 named entity reference\n// Organized by logical categories for easy maintenance and selective importing\n// ---------------------------------------------------------------------------\n\n/**\n * Basic Latin & Special Characters\n * @type {Record}\n */\nexport const BASIC_LATIN = {\n amp: '&',\n AMP: '&',\n lt: '<',\n LT: '<',\n gt: '>',\n GT: '>',\n quot: '\"',\n QUOT: '\"',\n apos: \"'\",\n lsquo: '‘',\n rsquo: '’',\n ldquo: '“',\n rdquo: '”',\n lsquor: '‚',\n rsquor: '’',\n ldquor: '„',\n bdquo: '„',\n comma: ',',\n period: '.',\n colon: ':',\n semi: ';',\n excl: '!',\n quest: '?',\n num: '#',\n dollar: '$',\n percent: '%',\n amp: '&',\n ast: '*',\n commat: '@',\n lowbar: '_',\n verbar: '|',\n vert: '|',\n sol: '/',\n bsol: '\\\\',\n lbrace: '{',\n rbrace: '}',\n lbrack: '[',\n rbrack: ']',\n lpar: '(',\n rpar: ')',\n nbsp: '\\u00a0',\n iexcl: '¡',\n cent: '¢',\n pound: '£',\n curren: '¤',\n yen: '¥',\n brvbar: '¦',\n sect: '§',\n uml: '¨',\n copy: '©',\n COPY: '©',\n ordf: 'ª',\n laquo: '«',\n not: '¬',\n shy: '\\u00ad',\n reg: '®',\n REG: '®',\n macr: '¯',\n deg: '°',\n plusmn: '±',\n sup2: '²',\n sup3: '³',\n acute: '´',\n micro: 'µ',\n para: '¶',\n middot: '·',\n cedil: '¸',\n sup1: '¹',\n ordm: 'º',\n raquo: '»',\n frac14: '¼',\n frac12: '½',\n half: '½',\n frac34: '¾',\n iquest: '¿',\n times: '×',\n div: '÷',\n divide: '÷',\n};\n\n/**\n * Latin Extended & Accented Letters (A-Z)\n * @type {Record}\n */\nexport const LATIN_ACCENTS = {\n Agrave: 'À',\n agrave: 'à',\n Aacute: 'Á',\n aacute: 'á',\n Acirc: 'Â',\n acirc: 'â',\n Atilde: 'Ã',\n atilde: 'ã',\n Auml: 'Ä',\n auml: 'ä',\n Aring: 'Å',\n aring: 'å',\n AElig: 'Æ',\n aelig: 'æ',\n Ccedil: 'Ç',\n ccedil: 'ç',\n Egrave: 'È',\n egrave: 'è',\n Eacute: 'É',\n eacute: 'é',\n Ecirc: 'Ê',\n ecirc: 'ê',\n Euml: 'Ë',\n euml: 'ë',\n Igrave: 'Ì',\n igrave: 'ì',\n Iacute: 'Í',\n iacute: 'í',\n Icirc: 'Î',\n icirc: 'î',\n Iuml: 'Ï',\n iuml: 'ï',\n ETH: 'Ð',\n eth: 'ð',\n Ntilde: 'Ñ',\n ntilde: 'ñ',\n Ograve: 'Ò',\n ograve: 'ò',\n Oacute: 'Ó',\n oacute: 'ó',\n Ocirc: 'Ô',\n ocirc: 'ô',\n Otilde: 'Õ',\n otilde: 'õ',\n Ouml: 'Ö',\n ouml: 'ö',\n Oslash: 'Ø',\n oslash: 'ø',\n Ugrave: 'Ù',\n ugrave: 'ù',\n Uacute: 'Ú',\n uacute: 'ú',\n Ucirc: 'Û',\n ucirc: 'û',\n Uuml: 'Ü',\n uuml: 'ü',\n Yacute: 'Ý',\n yacute: 'ý',\n THORN: 'Þ',\n thorn: 'þ',\n szlig: 'ß',\n yuml: 'ÿ',\n Yuml: 'Ÿ',\n};\n\n/**\n * Latin Extended (Letters with diacritics)\n * @type {Record}\n */\nexport const LATIN_EXTENDED = {\n Amacr: 'Ā',\n amacr: 'ā',\n Abreve: 'Ă',\n abreve: 'ă',\n Aogon: 'Ą',\n aogon: 'ą',\n Cacute: 'Ć',\n cacute: 'ć',\n Ccirc: 'Ĉ',\n ccirc: 'ĉ',\n Cdot: 'Ċ',\n cdot: 'ċ',\n Ccaron: 'Č',\n ccaron: 'č',\n Dcaron: 'Ď',\n dcaron: 'ď',\n Dstrok: 'Đ',\n dstrok: 'đ',\n Emacr: 'Ē',\n emacr: 'ē',\n Ecaron: 'Ě',\n ecaron: 'ě',\n Edot: 'Ė',\n edot: 'ė',\n Eogon: 'Ę',\n eogon: 'ę',\n Gcirc: 'Ĝ',\n gcirc: 'ĝ',\n Gbreve: 'Ğ',\n gbreve: 'ğ',\n Gdot: 'Ġ',\n gdot: 'ġ',\n Gcedil: 'Ģ',\n Hcirc: 'Ĥ',\n hcirc: 'ĥ',\n Hstrok: 'Ħ',\n hstrok: 'ħ',\n Itilde: 'Ĩ',\n itilde: 'ĩ',\n Imacr: 'Ī',\n imacr: 'ī',\n Iogon: 'Į',\n iogon: 'į',\n Idot: 'İ',\n IJlig: 'IJ',\n ijlig: 'ij',\n Jcirc: 'Ĵ',\n jcirc: 'ĵ',\n Kcedil: 'Ķ',\n kcedil: 'ķ',\n kgreen: 'ĸ',\n Lacute: 'Ĺ',\n lacute: 'ĺ',\n Lcedil: 'Ļ',\n lcedil: 'ļ',\n Lcaron: 'Ľ',\n lcaron: 'ľ',\n Lmidot: 'Ŀ',\n lmidot: 'ŀ',\n Lstrok: 'Ł',\n lstrok: 'ł',\n Nacute: 'Ń',\n nacute: 'ń',\n Ncaron: 'Ň',\n ncaron: 'ň',\n Ncedil: 'Ņ',\n ncedil: 'ņ',\n ENG: 'Ŋ',\n eng: 'ŋ',\n Omacr: 'Ō',\n omacr: 'ō',\n Odblac: 'Ő',\n odblac: 'ő',\n OElig: 'Œ',\n oelig: 'œ',\n Racute: 'Ŕ',\n racute: 'ŕ',\n Rcaron: 'Ř',\n rcaron: 'ř',\n Rcedil: 'Ŗ',\n rcedil: 'ŗ',\n Sacute: 'Ś',\n sacute: 'ś',\n Scirc: 'Ŝ',\n scirc: 'ŝ',\n Scedil: 'Ş',\n scedil: 'ş',\n Scaron: 'Š',\n scaron: 'š',\n Tcedil: 'Ţ',\n tcedil: 'ţ',\n Tcaron: 'Ť',\n tcaron: 'ť',\n Tstrok: 'Ŧ',\n tstrok: 'ŧ',\n Utilde: 'Ũ',\n utilde: 'ũ',\n Umacr: 'Ū',\n umacr: 'ū',\n Ubreve: 'Ŭ',\n ubreve: 'ŭ',\n Uring: 'Ů',\n uring: 'ů',\n Udblac: 'Ű',\n udblac: 'ű',\n Uogon: 'Ų',\n uogon: 'ų',\n Wcirc: 'Ŵ',\n wcirc: 'ŵ',\n Ycirc: 'Ŷ',\n ycirc: 'ŷ',\n Zacute: 'Ź',\n zacute: 'ź',\n Zdot: 'Ż',\n zdot: 'ż',\n Zcaron: 'Ž',\n zcaron: 'ž',\n};\n\n/**\n * Greek Letters\n * @type {Record}\n */\nexport const GREEK = {\n Alpha: 'Α',\n alpha: 'α',\n Beta: 'Β',\n beta: 'β',\n Gamma: 'Γ',\n gamma: 'γ',\n Delta: 'Δ',\n delta: 'δ',\n Epsilon: 'Ε',\n epsilon: 'ε',\n epsiv: 'ϵ',\n varepsilon: 'ϵ',\n Zeta: 'Ζ',\n zeta: 'ζ',\n Eta: 'Η',\n eta: 'η',\n Theta: 'Θ',\n theta: 'θ',\n thetasym: 'ϑ',\n vartheta: 'ϑ',\n Iota: 'Ι',\n iota: 'ι',\n Kappa: 'Κ',\n kappa: 'κ',\n kappav: 'ϰ',\n varkappa: 'ϰ',\n Lambda: 'Λ',\n lambda: 'λ',\n Mu: 'Μ',\n mu: 'μ',\n Nu: 'Ν',\n nu: 'ν',\n Xi: 'Ξ',\n xi: 'ξ',\n Omicron: 'Ο',\n omicron: 'ο',\n Pi: 'Π',\n pi: 'π',\n piv: 'ϖ',\n varpi: 'ϖ',\n Rho: 'Ρ',\n rho: 'ρ',\n rhov: 'ϱ',\n varrho: 'ϱ',\n Sigma: 'Σ',\n sigma: 'σ',\n sigmaf: 'ς',\n sigmav: 'ς',\n varsigma: 'ς',\n Tau: 'Τ',\n tau: 'τ',\n Upsilon: 'Υ',\n upsilon: 'υ',\n upsi: 'υ',\n Upsi: 'ϒ',\n upsih: 'ϒ',\n Phi: 'Φ',\n phi: 'φ',\n phiv: 'ϕ',\n varphi: 'ϕ',\n Chi: 'Χ',\n chi: 'χ',\n Psi: 'Ψ',\n psi: 'ψ',\n Omega: 'Ω',\n omega: 'ω',\n ohm: 'Ω',\n Gammad: 'Ϝ',\n gammad: 'ϝ',\n digamma: 'ϝ',\n};\n\n/**\n * Cyrillic Letters\n * @type {Record}\n */\nexport const CYRILLIC = {\n Afr: '𝔄',\n afr: '𝔞',\n Acy: 'А',\n acy: 'а',\n Bcy: 'Б',\n bcy: 'б',\n Vcy: 'В',\n vcy: 'в',\n Gcy: 'Г',\n gcy: 'г',\n Dcy: 'Д',\n dcy: 'д',\n IEcy: 'Е',\n iecy: 'е',\n IOcy: 'Ё',\n iocy: 'ё',\n ZHcy: 'Ж',\n zhcy: 'ж',\n Zcy: 'З',\n zcy: 'з',\n Icy: 'И',\n icy: 'и',\n Jcy: 'Й',\n jcy: 'й',\n Kcy: 'К',\n kcy: 'к',\n Lcy: 'Л',\n lcy: 'л',\n Mcy: 'М',\n mcy: 'м',\n Ncy: 'Н',\n ncy: 'н',\n Ocy: 'О',\n ocy: 'о',\n Pcy: 'П',\n pcy: 'п',\n Rcy: 'Р',\n rcy: 'р',\n Scy: 'С',\n scy: 'с',\n Tcy: 'Т',\n tcy: 'т',\n Ucy: 'У',\n ucy: 'у',\n Fcy: 'Ф',\n fcy: 'ф',\n KHcy: 'Х',\n khcy: 'х',\n TScy: 'Ц',\n tscy: 'ц',\n CHcy: 'Ч',\n chcy: 'ч',\n SHcy: 'Ш',\n shcy: 'ш',\n SHCHcy: 'Щ',\n shchcy: 'щ',\n HARDcy: 'Ъ',\n hardcy: 'ъ',\n Ycy: 'Ы',\n ycy: 'ы',\n SOFTcy: 'Ь',\n softcy: 'ь',\n Ecy: 'Э',\n ecy: 'э',\n YUcy: 'Ю',\n yucy: 'ю',\n YAcy: 'Я',\n yacy: 'я',\n DJcy: 'Ђ',\n djcy: 'ђ',\n GJcy: 'Ѓ',\n gjcy: 'ѓ',\n Jukcy: 'Є',\n jukcy: 'є',\n DScy: 'Ѕ',\n dscy: 'ѕ',\n Iukcy: 'І',\n iukcy: 'і',\n YIcy: 'Ї',\n yicy: 'ї',\n Jsercy: 'Ј',\n jsercy: 'ј',\n LJcy: 'Љ',\n ljcy: 'љ',\n NJcy: 'Њ',\n njcy: 'њ',\n TSHcy: 'Ћ',\n tshcy: 'ћ',\n KJcy: 'Ќ',\n kjcy: 'ќ',\n Ubrcy: 'Ў',\n ubrcy: 'ў',\n DZcy: 'Џ',\n dzcy: 'џ',\n};\n\n/**\n * Mathematical Operators & Relations\n * @type {Record}\n */\nexport const MATH = {\n plus: '+',\n minus: '−',\n mnplus: '∓',\n mp: '∓',\n pm: '±',\n times: '×',\n div: '÷',\n divide: '÷',\n sdot: '⋅',\n star: '☆',\n starf: '★',\n bigstar: '★',\n lowast: '∗',\n ast: '*',\n midast: '*',\n compfn: '∘',\n smallcircle: '∘',\n bullet: '•',\n bull: '•',\n nbsp: '\\u00a0',\n hellip: '…',\n mldr: '…',\n prime: '′',\n Prime: '″',\n tprime: '‴',\n bprime: '‵',\n backprime: '‵',\n minus: '−',\n minusd: '∸',\n dotminus: '∸',\n plusdo: '∔',\n dotplus: '∔',\n plusmn: '±',\n minusplus: '∓',\n mnplus: '∓',\n mp: '∓',\n setminus: '∖',\n smallsetminus: '∖',\n Backslash: '∖',\n setmn: '∖',\n ssetmn: '∖',\n lowbar: '_',\n verbar: '|',\n vert: '|',\n VerticalLine: '|',\n colon: ':',\n Colon: '∷',\n Proportion: '∷',\n ratio: '∶',\n equals: '=',\n ne: '≠',\n nequiv: '≢',\n equiv: '≡',\n Congruent: '≡',\n sim: '∼',\n thicksim: '∼',\n thksim: '∼',\n sime: '≃',\n simeq: '≃',\n TildeEqual: '≃',\n asymp: '≈',\n approx: '≈',\n thickapprox: '≈',\n thkap: '≈',\n TildeTilde: '≈',\n ncong: '≇',\n cong: '≅',\n TildeFullEqual: '≅',\n asympeq: '≍',\n CupCap: '≍',\n bump: '≎',\n Bumpeq: '≎',\n HumpDownHump: '≎',\n bumpe: '≏',\n bumpeq: '≏',\n HumpEqual: '≏',\n dotminus: '∸',\n minusd: '∸',\n plusdo: '∔',\n dotplus: '∔',\n le: '≤',\n LessEqual: '≤',\n ge: '≥',\n GreaterEqual: '≥',\n lesseqgtr: '⋚',\n lesseqqgtr: '⪋',\n greater: '>',\n less: '<',\n};\n\n/**\n * Mathematical Operators (Advanced)\n * @type {Record}\n */\nexport const MATH_ADVANCED = {\n alefsym: 'ℵ',\n aleph: 'ℵ',\n beth: 'ℶ',\n gimel: 'ℷ',\n daleth: 'ℸ',\n forall: '∀',\n ForAll: '∀',\n part: '∂',\n PartialD: '∂',\n exist: '∃',\n Exists: '∃',\n nexist: '∄',\n nexists: '∄',\n empty: '∅',\n emptyset: '∅',\n emptyv: '∅',\n varnothing: '∅',\n nabla: '∇',\n Del: '∇',\n isin: '∈',\n isinv: '∈',\n in: '∈',\n Element: '∈',\n notin: '∉',\n notinva: '∉',\n ni: '∋',\n niv: '∋',\n SuchThat: '∋',\n ReverseElement: '∋',\n notni: '∌',\n notniva: '∌',\n prod: '∏',\n Product: '∏',\n coprod: '∐',\n Coproduct: '∐',\n sum: '∑',\n Sum: '∑',\n minus: '−',\n mp: '∓',\n plusdo: '∔',\n dotplus: '∔',\n setminus: '∖',\n lowast: '∗',\n radic: '√',\n Sqrt: '√',\n prop: '∝',\n propto: '∝',\n Proportional: '∝',\n varpropto: '∝',\n infin: '∞',\n infintie: '⧝',\n ang: '∠',\n angle: '∠',\n angmsd: '∡',\n measuredangle: '∡',\n angsph: '∢',\n mid: '∣',\n VerticalBar: '∣',\n nmid: '∤',\n nsmid: '∤',\n npar: '∦',\n parallel: '∥',\n spar: '∥',\n nparallel: '∦',\n nspar: '∦',\n and: '∧',\n wedge: '∧',\n or: '∨',\n vee: '∨',\n cap: '∩',\n cup: '∪',\n int: '∫',\n Integral: '∫',\n conint: '∮',\n ContourIntegral: '∮',\n Conint: '∯',\n DoubleContourIntegral: '∯',\n Cconint: '∰',\n there4: '∴',\n therefore: '∴',\n Therefore: '∴',\n becaus: '∵',\n because: '∵',\n Because: '∵',\n ratio: '∶',\n Proportion: '∷',\n minusd: '∸',\n dotminus: '∸',\n mDDot: '∺',\n homtht: '∻',\n sim: '∼',\n bsimg: '∽',\n backsim: '∽',\n ac: '∾',\n mstpos: '∾',\n acd: '∿',\n VerticalTilde: '≀',\n wr: '≀',\n wreath: '≀',\n nsime: '≄',\n nsimeq: '≄',\n nsimeq: '≄',\n ncong: '≇',\n simne: '≆',\n ncongdot: '⩭̸',\n ngsim: '≵',\n nsim: '≁',\n napprox: '≉',\n nap: '≉',\n ngeq: '≱',\n nge: '≱',\n nleq: '≰',\n nle: '≰',\n ngtr: '≯',\n ngt: '≯',\n nless: '≮',\n nlt: '≮',\n nprec: '⊀',\n npr: '⊀',\n nsucc: '⊁',\n nsc: '⊁',\n};\n\n/**\n * Arrows\n * @type {Record}\n */\nexport const ARROWS = {\n larr: '←',\n leftarrow: '←',\n LeftArrow: '←',\n uarr: '↑',\n uparrow: '↑',\n UpArrow: '↑',\n rarr: '→',\n rightarrow: '→',\n RightArrow: '→',\n darr: '↓',\n downarrow: '↓',\n DownArrow: '↓',\n harr: '↔',\n leftrightarrow: '↔',\n LeftRightArrow: '↔',\n varr: '↕',\n updownarrow: '↕',\n UpDownArrow: '↕',\n nwarr: '↖',\n nwarrow: '↖',\n UpperLeftArrow: '↖',\n nearr: '↗',\n nearrow: '↗',\n UpperRightArrow: '↗',\n searr: '↘',\n searrow: '↘',\n LowerRightArrow: '↘',\n swarr: '↙',\n swarrow: '↙',\n LowerLeftArrow: '↙',\n lArr: '⇐',\n Leftarrow: '⇐',\n uArr: '⇑',\n Uparrow: '⇑',\n rArr: '⇒',\n Rightarrow: '⇒',\n dArr: '⇓',\n Downarrow: '⇓',\n hArr: '⇔',\n Leftrightarrow: '⇔',\n iff: '⇔',\n vArr: '⇕',\n Updownarrow: '⇕',\n lAarr: '⇚',\n Lleftarrow: '⇚',\n rAarr: '⇛',\n Rrightarrow: '⇛',\n lrarr: '⇆',\n leftrightarrows: '⇆',\n rlarr: '⇄',\n rightleftarrows: '⇄',\n lrhar: '⇋',\n leftrightharpoons: '⇋',\n ReverseEquilibrium: '⇋',\n rlhar: '⇌',\n rightleftharpoons: '⇌',\n Equilibrium: '⇌',\n udarr: '⇅',\n UpArrowDownArrow: '⇅',\n duarr: '⇵',\n DownArrowUpArrow: '⇵',\n llarr: '⇇',\n leftleftarrows: '⇇',\n rrarr: '⇉',\n rightrightarrows: '⇉',\n ddarr: '⇊',\n downdownarrows: '⇊',\n har: '↽',\n lhard: '↽',\n leftharpoondown: '↽',\n lharu: '↼',\n leftharpoonup: '↼',\n rhard: '⇁',\n rightharpoondown: '⇁',\n rharu: '⇀',\n rightharpoonup: '⇀',\n lsh: '↰',\n Lsh: '↰',\n rsh: '↱',\n Rsh: '↱',\n ldsh: '↲',\n rdsh: '↳',\n hookleftarrow: '↩',\n hookrightarrow: '↪',\n mapstoleft: '↤',\n mapstoup: '↥',\n map: '↦',\n mapsto: '↦',\n mapstodown: '↧',\n crarr: '↵',\n nwarrow: '↖',\n nearrow: '↗',\n searrow: '↘',\n swarrow: '↙',\n nleftarrow: '↚',\n nleftrightarrow: '↮',\n nrightarrow: '↛',\n nrarr: '↛',\n larrtl: '↢',\n rarrtl: '↣',\n leftarrowtail: '↢',\n rightarrowtail: '↣',\n twoheadleftarrow: '↞',\n twoheadrightarrow: '↠',\n Larr: '↞',\n Rarr: '↠',\n larrhk: '↩',\n rarrhk: '↪',\n larrlp: '↫',\n looparrowleft: '↫',\n rarrlp: '↬',\n looparrowright: '↬',\n harrw: '↭',\n leftrightsquigarrow: '↭',\n nrarrw: '↝̸',\n rarrw: '↝',\n rightsquigarrow: '↝',\n larrbfs: '⤟',\n rarrbfs: '⤠',\n nvHarr: '⤄',\n nvlArr: '⤂',\n nvrArr: '⤃',\n larrfs: '⤝',\n rarrfs: '⤞',\n Map: '⤅',\n larrsim: '⥳',\n rarrsim: '⥴',\n harrcir: '⥈',\n Uarrocir: '⥉',\n lurdshar: '⥊',\n ldrdhar: '⥧',\n ldrushar: '⥋',\n rdldhar: '⥩',\n lrhard: '⥭',\n rlhar: '⇌',\n uharr: '↾',\n uharl: '↿',\n dharr: '⇂',\n dharl: '⇃',\n Uarr: '↟',\n Darr: '↡',\n zigrarr: '⇝',\n nwArr: '⇖',\n neArr: '⇗',\n seArr: '⇘',\n swArr: '⇙',\n nharr: '↮',\n nhArr: '⇎',\n nlarr: '↚',\n nlArr: '⇍',\n nrarr: '↛',\n nrArr: '⇏',\n larrb: '⇤',\n LeftArrowBar: '⇤',\n rarrb: '⇥',\n RightArrowBar: '⇥',\n};\n\n/**\n * Geometric Shapes\n * @type {Record}\n */\nexport const SHAPES = {\n square: '□',\n Square: '□',\n squ: '□',\n squf: '▪',\n squarf: '▪',\n blacksquar: '▪',\n blacksquare: '▪',\n FilledVerySmallSquare: '▪',\n blk34: '▓',\n blk12: '▒',\n blk14: '░',\n block: '█',\n srect: '▭',\n rect: '▭',\n sdot: '⋅',\n sdotb: '⊡',\n dotsquare: '⊡',\n triangle: '▵',\n tri: '▵',\n trine: '▵',\n utri: '▵',\n triangledown: '▿',\n dtri: '▿',\n tridown: '▿',\n triangleleft: '◃',\n ltri: '◃',\n triangleright: '▹',\n rtri: '▹',\n blacktriangle: '▴',\n utrif: '▴',\n blacktriangledown: '▾',\n dtrif: '▾',\n blacktriangleleft: '◂',\n ltrif: '◂',\n blacktriangleright: '▸',\n rtrif: '▸',\n loz: '◊',\n lozenge: '◊',\n blacklozenge: '⧫',\n lozf: '⧫',\n bigcirc: '◯',\n xcirc: '◯',\n circ: 'ˆ',\n Circle: '○',\n cir: '○',\n o: '○',\n bullet: '•',\n bull: '•',\n hellip: '…',\n mldr: '…',\n nldr: '‥',\n boxh: '─',\n HorizontalLine: '─',\n boxv: '│',\n boxdr: '┌',\n boxdl: '┐',\n boxur: '└',\n boxul: '┘',\n boxvr: '├',\n boxvl: '┤',\n boxhd: '┬',\n boxhu: '┴',\n boxvh: '┼',\n boxH: '═',\n boxV: '║',\n boxdR: '╒',\n boxDr: '╓',\n boxDR: '╔',\n boxDl: '╕',\n boxdL: '╖',\n boxDL: '╗',\n boxuR: '╘',\n boxUr: '╙',\n boxUR: '╚',\n boxUl: '╜',\n boxuL: '╛',\n boxUL: '╝',\n boxvR: '╞',\n boxVr: '╟',\n boxVR: '╠',\n boxVl: '╢',\n boxvL: '╡',\n boxVL: '╣',\n boxHd: '╤',\n boxhD: '╥',\n boxHD: '╦',\n boxHu: '╧',\n boxhU: '╨',\n boxHU: '╩',\n boxvH: '╪',\n boxVh: '╫',\n boxVH: '╬',\n};\n\n/**\n * Punctuation & Diacritics\n * @type {Record}\n */\nexport const PUNCTUATION = {\n excl: '!',\n iexcl: '¡',\n brvbar: '¦',\n sect: '§',\n uml: '¨',\n copy: '©',\n ordf: 'ª',\n laquo: '«',\n not: '¬',\n shy: '\\u00ad',\n reg: '®',\n macr: '¯',\n deg: '°',\n plusmn: '±',\n sup2: '²',\n sup3: '³',\n acute: '´',\n micro: 'µ',\n para: '¶',\n middot: '·',\n cedil: '¸',\n sup1: '¹',\n ordm: 'º',\n raquo: '»',\n frac14: '¼',\n frac12: '½',\n frac34: '¾',\n iquest: '¿',\n nbsp: '\\u00a0',\n comma: ',',\n period: '.',\n colon: ':',\n semi: ';',\n vert: '|',\n Verbar: '‖',\n verbar: '|',\n dblac: '˝',\n circ: 'ˆ',\n caron: 'ˇ',\n breve: '˘',\n dot: '˙',\n ring: '˚',\n ogon: '˛',\n tilde: '˜',\n DiacriticalGrave: '`',\n DiacriticalAcute: '´',\n DiacriticalTilde: '˜',\n DiacriticalDot: '˙',\n DiacriticalDoubleAcute: '˝',\n grave: '`',\n acute: '´',\n};\n\n/**\n * Currency Symbols\n * @type {Record}\n */\nexport const CURRENCY = {\n cent: '¢',\n pound: '£',\n curren: '¤',\n yen: '¥',\n euro: '€',\n dollar: '$',\n euro: '€',\n fnof: 'ƒ',\n inr: '₹',\n af: '؋',\n birr: 'ብር',\n peso: '₱',\n rub: '₽',\n won: '₩',\n yuan: '¥',\n cedil: '¸',\n};\n\n/**\n * Fractions\n * @type {Record}\n */\nexport const FRACTIONS = {\n frac12: '½',\n half: '½',\n frac13: '⅓',\n frac14: '¼',\n frac15: '⅕',\n frac16: '⅙',\n frac18: '⅛',\n frac23: '⅔',\n frac25: '⅖',\n frac34: '¾',\n frac35: '⅗',\n frac38: '⅜',\n frac45: '⅘',\n frac56: '⅚',\n frac58: '⅝',\n frac78: '⅞',\n frasl: '⁄',\n};\n\n/**\n * Miscellaneous Symbols\n * @type {Record}\n */\nexport const MISC_SYMBOLS = {\n trade: '™',\n TRADE: '™',\n telrec: '⌕',\n target: '⌖',\n ulcorn: '⌜',\n ulcorner: '⌜',\n urcorn: '⌝',\n urcorner: '⌝',\n dlcorn: '⌞',\n llcorner: '⌞',\n drcorn: '⌟',\n lrcorner: '⌟',\n intercal: '⊺',\n intcal: '⊺',\n oplus: '⊕',\n CirclePlus: '⊕',\n ominus: '⊖',\n CircleMinus: '⊖',\n otimes: '⊗',\n CircleTimes: '⊗',\n osol: '⊘',\n odot: '⊙',\n CircleDot: '⊙',\n oast: '⊛',\n circledast: '⊛',\n odash: '⊝',\n circleddash: '⊝',\n ocirc: '⊚',\n circledcirc: '⊚',\n boxplus: '⊞',\n plusb: '⊞',\n boxminus: '⊟',\n minusb: '⊟',\n boxtimes: '⊠',\n timesb: '⊠',\n boxdot: '⊡',\n sdotb: '⊡',\n veebar: '⊻',\n vee: '∨',\n barvee: '⊽',\n and: '∧',\n wedge: '∧',\n Cap: '⋒',\n Cup: '⋓',\n Fork: '⋔',\n pitchfork: '⋔',\n epar: '⋕',\n ltlarr: '⥶',\n nvap: '≍⃒',\n nvsim: '∼⃒',\n nvge: '≥⃒',\n nvle: '≤⃒',\n nvlt: '<⃒',\n nvgt: '>⃒',\n nvltrie: '⊴⃒',\n nvrtrie: '⊵⃒',\n Vdash: '⊩',\n dashv: '⊣',\n vDash: '⊨',\n Vdash: '⊩',\n Vvdash: '⊪',\n nvdash: '⊬',\n nvDash: '⊭',\n nVdash: '⊮',\n nVDash: '⊯',\n};\n\n/**\n * All entities combined (if you need everything)\n * @type {Record}\n */\nexport const ALL_ENTITIES = {\n ...BASIC_LATIN,\n ...LATIN_ACCENTS,\n ...LATIN_EXTENDED,\n ...GREEK,\n ...CYRILLIC,\n ...MATH,\n ...MATH_ADVANCED,\n ...ARROWS,\n ...SHAPES,\n ...PUNCTUATION,\n ...CURRENCY,\n ...FRACTIONS,\n ...MISC_SYMBOLS,\n};\n\nexport const XML = {\n amp: \"&\",\n apos: \"'\",\n gt: \">\",\n lt: \"<\",\n quot: \"\\\"\"\n}\nexport const COMMON_HTML = {\n nbsp: '\\u00a0',\n copy: '\\u00a9',\n reg: '\\u00ae',\n trade: '\\u2122',\n mdash: '\\u2014',\n ndash: '\\u2013',\n hellip: '\\u2026',\n laquo: '\\u00ab',\n raquo: '\\u00bb',\n lsquo: '\\u2018',\n rsquo: '\\u2019',\n ldquo: '\\u201c',\n rdquo: '\\u201d',\n bull: '\\u2022',\n para: '\\u00b6',\n sect: '\\u00a7',\n deg: '\\u00b0',\n frac12: '\\u00bd',\n frac14: '\\u00bc',\n frac34: '\\u00be',\n}\n// ---------------------------------------------------------------------------\n// Note: NUMERIC_ENTITIES (&#NNN; / &#xHH;) are handled by the scanner directly\n// via String.fromCodePoint() without any map lookup.\n// ---------------------------------------------------------------------------","// ---------------------------------------------------------------------------\n// Built-in named entity map (name → replacement string)\n// No regex, no {regex,val} objects — just flat key/value pairs.\n// ---------------------------------------------------------------------------\n\nimport { XML as DEFAULT_XML_ENTITIES } from \"./entities.js\"\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst SPECIAL_CHARS = new Set('!?\\\\\\\\/[]$%{}^&*()<>|+');\n\n/**\n * Validate that an entity name contains no dangerous characters.\n * @param {string} name\n * @returns {string} the name, unchanged\n * @throws {Error} on invalid characters\n */\nfunction validateEntityName(name) {\n if (name[0] === '#') {\n throw new Error(`[EntityReplacer] Invalid character '#' in entity name: \"${name}\"`);\n }\n for (const ch of name) {\n if (SPECIAL_CHARS.has(ch)) {\n throw new Error(`[EntityReplacer] Invalid character '${ch}' in entity name: \"${name}\"`);\n }\n }\n return name;\n}\n\n/**\n * Merge one or more entity maps into a flat name→string map.\n * Accepts either:\n * - plain string values: { amp: '&' }\n * - legacy {regex,val} / {regx,val}: { lt: { regex: /.../, val: '<' } }\n *\n * Values containing '&' are skipped (recursive expansion risk).\n *\n * @param {...object} maps\n * @returns {Record}\n */\nfunction mergeEntityMaps(...maps) {\n const out = Object.create(null);\n for (const map of maps) {\n if (!map) continue;\n for (const key of Object.keys(map)) {\n const raw = map[key];\n if (typeof raw === 'string') {\n out[key] = raw;\n } else if (raw && typeof raw === 'object' && raw.val !== undefined) {\n // Legacy {regex,val} or {regx,val} — extract the string val only\n const val = raw.val;\n if (typeof val === 'string') {\n out[key] = val;\n }\n // function vals are not supported in the scanner — skip\n }\n }\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// applyLimitsTo helpers\n// ---------------------------------------------------------------------------\n\nconst LIMIT_TIER_EXTERNAL = 'external'; // input/runtime + persistent external maps\nconst LIMIT_TIER_BASE = 'base'; // DEFAULT_XML_ENTITIES + namedEntities (system) maps\nconst LIMIT_TIER_ALL = 'all'; // every entity regardless of tier\n\n/**\n * Resolve `applyLimitsTo` option into a normalised Set of tier strings.\n * Accepted values: 'external' | 'base' | 'all' | string[]\n * Default: 'external' (only untrusted injected entities are counted).\n * @param {string|string[]|undefined} raw\n * @returns {Set}\n */\nfunction parseLimitTiers(raw) {\n if (!raw || raw === LIMIT_TIER_EXTERNAL) return new Set([LIMIT_TIER_EXTERNAL]);\n if (raw === LIMIT_TIER_ALL) return new Set([LIMIT_TIER_ALL]);\n if (raw === LIMIT_TIER_BASE) return new Set([LIMIT_TIER_BASE]);\n if (Array.isArray(raw)) return new Set(raw);\n return new Set([LIMIT_TIER_EXTERNAL]); // safe default for unrecognised values\n}\n\n// ---------------------------------------------------------------------------\n// NCR (Numeric Character Reference) classification\n// ---------------------------------------------------------------------------\n\n// Severity order — higher number = stricter action.\n// Used to enforce minimum action levels for specific codepoint ranges.\nconst NCR_LEVEL = Object.freeze({ allow: 0, leave: 1, remove: 2, throw: 3 });\n\n// XML 1.0 §2.2: allowed chars are #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]\n// Restricted C0: U+0001–U+001F excluding U+0009, U+000A, U+000D\nconst XML10_ALLOWED_C0 = new Set([0x09, 0x0A, 0x0D]);\n\n/**\n * Parse the `ncr` constructor option into flat, hot-path-friendly fields.\n * @param {object|undefined} ncr\n * @returns {{ xmlVersion: number, onLevel: number, nullLevel: number }}\n */\nfunction parseNCRConfig(ncr) {\n if (!ncr) {\n return { xmlVersion: 1.0, onLevel: NCR_LEVEL.allow, nullLevel: NCR_LEVEL.remove };\n }\n const xmlVersion = ncr.xmlVersion === 1.1 ? 1.1 : 1.0;\n const onLevel = NCR_LEVEL[ncr.onNCR] ?? NCR_LEVEL.allow;\n const nullLevel = NCR_LEVEL[ncr.nullNCR] ?? NCR_LEVEL.remove;\n // 'allow' is not meaningful for null — clamp to at least 'remove'\n const clampedNull = Math.max(nullLevel, NCR_LEVEL.remove);\n return { xmlVersion, onLevel, nullLevel: clampedNull };\n}\n\n// ---------------------------------------------------------------------------\n// EntityReplacer\n// ---------------------------------------------------------------------------\n\n/**\n * Single-pass, zero-regex entity replacer for XML/HTML content.\n *\n * Algorithm: scan the string once for '&', read to ';', resolve via map\n * or direct codepoint conversion, build output chunks, join once at the end.\n *\n * Entity lookup priority (highest → lowest):\n * 1. input / runtime (DOCTYPE entities for current document)\n * 2. persistent external (survive across documents)\n * 3. base named map (DEFAULT_XML_ENTITIES + user-supplied namedEntities)\n *\n * Both input and external resolve as the 'external' tier for limit purposes.\n * Base map entities resolve as the 'base' tier.\n *\n * Numeric / hex references (&#NNN; / &#xHH;) are resolved directly via\n * String.fromCodePoint() — no map needed. They count as 'base' tier.\n *\n * @example\n * const replacer = new EntityReplacer({ namedEntities: COMMON_HTML });\n * replacer.setExternalEntities({ brand: 'Acme' });\n *\n * const instance = replacer.reset();\n * instance.addInputEntities({ version: '1.0' });\n * instance.encode('&brand; v&version; <'); // 'Acme v1.0 <'\n */\nexport default class EntityDecoder {\n /**\n * @param {object} [options]\n * @param {object|null} [options.namedEntities] — extra named entities merged into base map\n * @param {object} [options.limit] — security limits\n * @param {number} [options.limit.maxTotalExpansions=0] — 0 = unlimited\n * @param {number} [options.limit.maxExpandedLength=0] — 0 = unlimited\n * @param {'external'|'base'|'all'|string[]} [options.limit.applyLimitsTo='external']\n * Which entity tiers count against the security limits:\n * - 'external' (default) — only input/runtime + persistent external entities\n * - 'base' — only DEFAULT_XML_ENTITIES + namedEntities\n * - 'all' — every entity regardless of tier\n * - string[] — explicit combination, e.g. ['external', 'base']\n * @param {((resolved: string, original: string) => string)|null} [options.postCheck=null]\n * @param {string[]} [options.remove=[]] — entity names (e.g. ['nbsp', '#13']) to delete (replace with empty string)\n * @param {string[]} [options.leave=[]] — entity names to keep as literal (unchanged in output)\n * @param {object} [options.ncr] — Numeric Character Reference controls\n * @param {1.0|1.1} [options.ncr.xmlVersion=1.0]\n * XML version governing which codepoint ranges are restricted:\n * - 1.0 — C0 controls U+0001–U+001F (except U+0009/000A/000D) are prohibited\n * - 1.1 — C0 controls are allowed when written as NCRs; C1 (U+007F–U+009F) decoded as-is\n * @param {'allow'|'leave'|'remove'|'throw'} [options.ncr.onNCR='allow']\n * Base action for numeric references. Severity order: allow < leave < remove < throw.\n * For codepoint ranges that carry a minimum level (surrogates → remove, XML 1.0 C0 → remove),\n * the effective action is max(onNCR, rangeMinimum).\n * @param {'remove'|'throw'} [options.ncr.nullNCR='remove']\n * Action for U+0000 (null). 'allow' and 'leave' are clamped to 'remove' since null is never safe.\n */\n constructor(options = {}) {\n this._limit = options.limit || {};\n this._maxTotalExpansions = this._limit.maxTotalExpansions || 0;\n this._maxExpandedLength = this._limit.maxExpandedLength || 0;\n this._postCheck = typeof options.postCheck === 'function' ? options.postCheck : r => r;\n this._limitTiers = parseLimitTiers(this._limit.applyLimitsTo ?? LIMIT_TIER_EXTERNAL);\n this._numericAllowed = options.numericAllowed ?? true;\n // Base map: DEFAULT_XML_ENTITIES + user-supplied extras. Immutable after construction.\n this._baseMap = mergeEntityMaps(DEFAULT_XML_ENTITIES, options.namedEntities || null);\n\n // Persistent external entities — survive across documents.\n // Stored as a separate map so reset() never touches them.\n /** @type {Record} */\n this._externalMap = Object.create(null);\n\n // Input / runtime entities — current document only, wiped on reset().\n /** @type {Record} */\n this._inputMap = Object.create(null);\n\n // Per-document counters\n this._totalExpansions = 0;\n this._expandedLength = 0;\n\n // --- New: remove / leave sets ---\n /** @type {Set} */\n this._removeSet = new Set(options.remove && Array.isArray(options.remove) ? options.remove : []);\n /** @type {Set} */\n this._leaveSet = new Set(options.leave && Array.isArray(options.leave) ? options.leave : []);\n\n // --- NCR config (parsed into flat fields for hot-path speed) ---\n const ncrCfg = parseNCRConfig(options.ncr);\n this._ncrXmlVersion = ncrCfg.xmlVersion;\n this._ncrOnLevel = ncrCfg.onLevel;\n this._ncrNullLevel = ncrCfg.nullLevel;\n }\n\n // -------------------------------------------------------------------------\n // Persistent external entity registration\n // -------------------------------------------------------------------------\n\n /**\n * Replace the full set of persistent external entities.\n * All keys are validated — throws on invalid characters.\n * @param {Record} map\n */\n setExternalEntities(map) {\n if (map) {\n for (const key of Object.keys(map)) {\n validateEntityName(key);\n }\n }\n this._externalMap = mergeEntityMaps(map);\n }\n\n /**\n * Add a single persistent external entity.\n * @param {string} key\n * @param {string} value\n */\n addExternalEntity(key, value) {\n validateEntityName(key);\n if (typeof value === 'string' && value.indexOf('&') === -1) {\n this._externalMap[key] = value;\n }\n }\n\n // -------------------------------------------------------------------------\n // Input / runtime entity registration (per document)\n // -------------------------------------------------------------------------\n\n /**\n * Inject DOCTYPE entities for the current document.\n * Also resets per-document expansion counters.\n * @param {Record} map\n */\n addInputEntities(map) {\n this._totalExpansions = 0;\n this._expandedLength = 0;\n this._inputMap = mergeEntityMaps(map);\n }\n\n // -------------------------------------------------------------------------\n // Per-document reset\n // -------------------------------------------------------------------------\n\n /**\n * Wipe input/runtime entities and reset counters.\n * Call this before processing each new document.\n * @returns {this}\n */\n reset() {\n this._inputMap = Object.create(null);\n this._totalExpansions = 0;\n this._expandedLength = 0;\n return this;\n }\n\n // -------------------------------------------------------------------------\n // XML version (can be set after construction, e.g. once parser reads )\n // -------------------------------------------------------------------------\n\n /**\n * Update the XML version used for NCR classification.\n * Call this as soon as the document's `` declaration is parsed.\n * @param {1.0|1.1|number} version\n */\n setXmlVersion(version) {\n this._ncrXmlVersion = version === 1.1 ? 1.1 : 1.0;\n }\n\n // -------------------------------------------------------------------------\n // Primary API\n // -------------------------------------------------------------------------\n\n /**\n * Replace all entity references in `str` in a single pass.\n *\n * @param {string} str\n * @returns {string}\n */\n decode(str) {\n if (typeof str !== 'string' || str.length === 0) return str;\n //TODO: check if needed\n //if (str.indexOf('&') === -1) return str; // fast path — no entities at all\n\n const original = str;\n const chunks = [];\n const len = str.length;\n let last = 0; // start of next unprocessed literal chunk\n let i = 0;\n\n const limitExpansions = this._maxTotalExpansions > 0;\n const limitLength = this._maxExpandedLength > 0;\n const checkLimits = limitExpansions || limitLength;\n\n while (i < len) {\n // Scan forward to next '&'\n if (str.charCodeAt(i) !== 38 /* '&' */) { i++; continue; }\n\n // --- Found '&' at position i ---\n\n // Scan forward to ';'\n let j = i + 1;\n while (j < len && str.charCodeAt(j) !== 59 /* ';' */ && (j - i) <= 32) j++;\n\n if (j >= len || str.charCodeAt(j) !== 59) {\n // No closing ';' within window — treat '&' as literal\n i++;\n continue;\n }\n\n // Raw token between '&' and ';' (exclusive)\n const token = str.slice(i + 1, j);\n if (token.length === 0) { i++; continue; }\n\n let replacement;\n let tier; // which limit tier this entity belongs to\n\n if (this._removeSet.has(token)) {\n // Remove entity: replace with empty string\n replacement = '';\n // If entity was unknown (replacement undefined), we still need a tier for limits.\n // Treat as external tier because it's user-directed removal of an unknown reference.\n if (tier === undefined) {\n tier = LIMIT_TIER_EXTERNAL;\n }\n } else if (this._leaveSet.has(token)) {\n // Do not replace — keep original &token; as literal\n i++;\n continue;\n } else if (token.charCodeAt(0) === 35 /* '#' */) {\n // ---- Numeric / NCR reference ----\n // NCR classification always runs first — prohibited codepoints must be\n // caught regardless of numericAllowed.\n const ncrResult = this._resolveNCR(token);\n if (ncrResult === undefined) {\n // 'leave' action — keep original &token; as-is\n i++;\n continue;\n }\n replacement = ncrResult; // '' for remove, char string for allow\n tier = LIMIT_TIER_BASE;\n } else {\n // ---- Named reference ----\n const resolved = this._resolveName(token);\n replacement = resolved?.value;\n tier = resolved?.tier;\n }\n\n if (replacement === undefined) {\n // Unknown entity — leave as-is, advance past '&' only\n i++;\n continue;\n }\n\n // Flush literal chunk before this entity\n if (i > last) chunks.push(str.slice(last, i));\n chunks.push(replacement);\n last = j + 1; // skip past ';'\n i = last;\n\n // Apply expansion limits only if this tier is being tracked\n if (checkLimits && this._tierCounts(tier)) {\n if (limitExpansions) {\n this._totalExpansions++;\n if (this._totalExpansions > this._maxTotalExpansions) {\n throw new Error(\n `[EntityReplacer] Entity expansion count limit exceeded: ` +\n `${this._totalExpansions} > ${this._maxTotalExpansions}`\n );\n }\n }\n if (limitLength) {\n // delta: replacement.length minus the raw &token; length (token.length + 2 for '&' and ';')\n const delta = replacement.length - (token.length + 2);\n if (delta > 0) {\n this._expandedLength += delta;\n if (this._expandedLength > this._maxExpandedLength) {\n throw new Error(\n `[EntityReplacer] Expanded content length limit exceeded: ` +\n `${this._expandedLength} > ${this._maxExpandedLength}`\n );\n }\n }\n }\n }\n }\n\n // Flush trailing literal\n if (last < len) chunks.push(str.slice(last));\n\n // If nothing was replaced, chunks is empty — return original\n const result = chunks.length === 0 ? str : chunks.join('');\n\n return this._postCheck(result, original);\n }\n\n // -------------------------------------------------------------------------\n // Private: limit tier check\n // -------------------------------------------------------------------------\n\n /**\n * Returns true if a resolved entity of the given tier should count\n * against the expansion/length limits.\n * @param {string} tier — LIMIT_TIER_EXTERNAL | LIMIT_TIER_BASE\n * @returns {boolean}\n */\n _tierCounts(tier) {\n if (this._limitTiers.has(LIMIT_TIER_ALL)) return true;\n return this._limitTiers.has(tier);\n }\n\n // -------------------------------------------------------------------------\n // Private: entity resolution\n // -------------------------------------------------------------------------\n\n /**\n * Resolve a named entity token (without & and ;).\n * Priority: inputMap > externalMap > baseMap\n * Returns the resolved value tagged with its limit tier.\n *\n * @param {string} name\n * @returns {{ value: string, tier: string }|undefined}\n */\n _resolveName(name) {\n // input and external both count as 'external' tier for limit purposes —\n // they are injected at runtime and are the untrusted surface.\n if (name in this._inputMap) return { value: this._inputMap[name], tier: LIMIT_TIER_EXTERNAL };\n if (name in this._externalMap) return { value: this._externalMap[name], tier: LIMIT_TIER_EXTERNAL };\n if (name in this._baseMap) return { value: this._baseMap[name], tier: LIMIT_TIER_BASE };\n return undefined;\n }\n\n /**\n * Classify a codepoint and return the minimum action level that must be applied.\n * Returns -1 when no minimum is imposed (normal allow path).\n *\n * Ranges checked (in priority order):\n * 1. U+0000 — null, governed by nullNCR (always ≥ remove)\n * 2. U+D800–U+DFFF — surrogates, always prohibited (min: remove)\n * 3. U+0001–U+001F \\ {0x09,0x0A,0x0D} — XML 1.0 restricted C0 (min: remove)\n * (skipped in XML 1.1 — C0 controls are allowed when written as NCRs)\n *\n * @param {number} cp — codepoint\n * @returns {number} — minimum NCR_LEVEL value, or -1 for no restriction\n */\n _classifyNCR(cp) {\n // 1. Null\n if (cp === 0) return this._ncrNullLevel;\n\n // 2. Surrogates — always prohibited, minimum 'remove'\n if (cp >= 0xD800 && cp <= 0xDFFF) return NCR_LEVEL.remove;\n\n // 3. XML 1.0 restricted C0 controls\n if (this._ncrXmlVersion === 1.0) {\n if (cp >= 0x01 && cp <= 0x1F && !XML10_ALLOWED_C0.has(cp)) return NCR_LEVEL.remove;\n }\n\n return -1; // no restriction\n }\n\n /**\n * Execute a resolved NCR action.\n *\n * @param {number} action — NCR_LEVEL value\n * @param {string} token — raw token (e.g. '#38') for error messages\n * @param {number} cp — codepoint, used only for error messages\n * @returns {string|undefined}\n * - decoded character string → 'allow'\n * - '' → 'remove'\n * - undefined → 'leave' (caller must skip past '&' only)\n * - throws Error → 'throw'\n */\n _applyNCRAction(action, token, cp) {\n switch (action) {\n case NCR_LEVEL.allow: return String.fromCodePoint(cp);\n case NCR_LEVEL.remove: return '';\n case NCR_LEVEL.leave: return undefined; // signal: keep literal\n case NCR_LEVEL.throw:\n throw new Error(\n `[EntityDecoder] Prohibited numeric character reference ` +\n `&${token}; (U+${cp.toString(16).toUpperCase().padStart(4, '0')})`\n );\n default: return String.fromCodePoint(cp);\n }\n }\n\n /**\n * Full NCR resolution pipeline for a numeric token.\n *\n * Steps:\n * 1. Parse the codepoint (decimal or hex).\n * 2. Validate the raw codepoint range (NaN, <0, >0x10FFFF).\n * 3. If numericAllowed is false and no minimum restriction applies → leave as-is.\n * 4. Classify the codepoint to find the minimum required action level.\n * 5. Resolve effective action = max(onNCR, minimum).\n * 6. Apply and return.\n *\n * @param {string} token — e.g. '#38', '#x26', '#X26'\n * @returns {string|undefined}\n * - string (incl. '') — replacement ('' = remove)\n * - undefined — leave original &token; as-is\n */\n _resolveNCR(token) {\n // Step 1: parse codepoint\n const second = token.charCodeAt(1);\n let cp;\n if (second === 120 /* x */ || second === 88 /* X */) {\n cp = parseInt(token.slice(2), 16);\n } else {\n cp = parseInt(token.slice(1), 10);\n }\n\n // Step 2: out-of-range → leave as-is unconditionally\n if (Number.isNaN(cp) || cp < 0 || cp > 0x10FFFF) return undefined;\n\n // Step 3: classify to get minimum action level\n const minimum = this._classifyNCR(cp);\n\n // Step 4: if numericAllowed is false and no hard minimum → leave\n if (!this._numericAllowed && minimum < NCR_LEVEL.remove) return undefined;\n\n // Step 5: effective action = max(configured onNCR, range minimum)\n const effective = minimum === -1\n ? this._ncrOnLevel\n : Math.max(this._ncrOnLevel, minimum);\n\n // Step 6: apply\n return this._applyNCRAction(effective, token, cp);\n }\n}","/**\n * @nodable/entities\n *\n * Standalone, zero-dependency XML/HTML entity replacement.\n *\n\n */\n\nexport { default as EntityDecoder } from './EntityDecoder.js';\nexport {\n COMMON_HTML,\n XML,\n ALL_ENTITIES,\n ARROWS,\n BASIC_LATIN,\n CURRENCY,\n MATH,\n MATH_ADVANCED,\n CYRILLIC,\n FRACTIONS,\n GREEK,\n LATIN_ACCENTS,\n LATIN_EXTENDED,\n MISC_SYMBOLS,\n PUNCTUATION,\n SHAPES,\n} from './entities.js';\n\nexport { default as EntityEncoder } from './EntityEncoder.js';","import { DANGEROUS_PROPERTY_NAMES, criticalProperties } from \"../util.js\";\nimport { COMMON_HTML, CURRENCY } from '@nodable/entities';\n\nconst defaultOnDangerousProperty = (name) => {\n if (DANGEROUS_PROPERTY_NAMES.includes(name)) {\n return \"__\" + name;\n }\n return name;\n};\n\n\nexport const defaultOptions = {\n preserveOrder: false,\n attributeNamePrefix: '@_',\n attributesGroupName: false,\n textNodeName: '#text',\n ignoreAttributes: true,\n removeNSPrefix: false, // remove NS from tag name or attribute name if true\n allowBooleanAttributes: false, //a tag can have attributes without any value\n //ignoreRootElement : false,\n parseTagValue: true,\n parseAttributeValue: false,\n trimValues: true, //Trim string values of tag and attributes\n cdataPropName: false,\n numberParseOptions: {\n hex: true,\n leadingZeros: true,\n eNotation: true\n },\n tagValueProcessor: function (tagName, val) {\n return val;\n },\n attributeValueProcessor: function (attrName, val) {\n return val;\n },\n stopNodes: [], //nested tags will not be parsed even for errors\n alwaysCreateTextNode: false,\n isArray: () => false,\n commentPropName: false,\n unpairedTags: [],\n processEntities: true,\n htmlEntities: false,\n entityDecoder: null,\n ignoreDeclaration: false,\n ignorePiTags: false,\n transformTagName: false,\n transformAttributeName: false,\n updateTag: function (tagName, jPath, attrs) {\n return tagName\n },\n // skipEmptyListItem: false\n captureMetaData: false,\n maxNestedTags: 100,\n strictReservedNames: true,\n jPath: true, // if true, pass jPath string to callbacks; if false, pass matcher instance\n onDangerousProperty: defaultOnDangerousProperty\n};\n\n\n/**\n * Validates that a property name is safe to use\n * @param {string} propertyName - The property name to validate\n * @param {string} optionName - The option field name (for error message)\n * @throws {Error} If property name is dangerous\n */\nfunction validatePropertyName(propertyName, optionName) {\n if (typeof propertyName !== 'string') {\n return; // Only validate string property names\n }\n\n const normalized = propertyName.toLowerCase();\n if (DANGEROUS_PROPERTY_NAMES.some(dangerous => normalized === dangerous.toLowerCase())) {\n throw new Error(\n `[SECURITY] Invalid ${optionName}: \"${propertyName}\" is a reserved JavaScript keyword that could cause prototype pollution`\n );\n }\n\n if (criticalProperties.some(dangerous => normalized === dangerous.toLowerCase())) {\n throw new Error(\n `[SECURITY] Invalid ${optionName}: \"${propertyName}\" is a reserved JavaScript keyword that could cause prototype pollution`\n );\n }\n}\n\n/**\n * Normalizes processEntities option for backward compatibility\n * @param {boolean|object} value \n * @returns {object} Always returns normalized object\n */\nfunction normalizeProcessEntities(value, htmlEntities) {\n // Boolean backward compatibility\n if (typeof value === 'boolean') {\n return {\n enabled: value, // true or false\n maxEntitySize: 10000,\n maxExpansionDepth: 10000,\n maxTotalExpansions: Infinity,\n maxExpandedLength: 100000,\n maxEntityCount: 1000,\n allowedTags: null,\n tagFilter: null,\n appliesTo: \"all\",\n };\n }\n\n // Object config - merge with defaults\n if (typeof value === 'object' && value !== null) {\n return {\n enabled: value.enabled !== false,\n maxEntitySize: Math.max(1, value.maxEntitySize ?? 10000),\n maxExpansionDepth: Math.max(1, value.maxExpansionDepth ?? 10000),\n maxTotalExpansions: Math.max(1, value.maxTotalExpansions ?? Infinity),\n maxExpandedLength: Math.max(1, value.maxExpandedLength ?? 100000),\n maxEntityCount: Math.max(1, value.maxEntityCount ?? 1000),\n allowedTags: value.allowedTags ?? null,\n tagFilter: value.tagFilter ?? null,\n appliesTo: value.appliesTo ?? \"all\",\n };\n }\n\n // Default to enabled with limits\n return normalizeProcessEntities(true);\n}\n\nexport const buildOptions = function (options) {\n const built = Object.assign({}, defaultOptions, options);\n\n // Validate property names to prevent prototype pollution\n const propertyNameOptions = [\n { value: built.attributeNamePrefix, name: 'attributeNamePrefix' },\n { value: built.attributesGroupName, name: 'attributesGroupName' },\n { value: built.textNodeName, name: 'textNodeName' },\n { value: built.cdataPropName, name: 'cdataPropName' },\n { value: built.commentPropName, name: 'commentPropName' }\n ];\n\n for (const { value, name } of propertyNameOptions) {\n if (value) {\n validatePropertyName(value, name);\n }\n }\n\n if (built.onDangerousProperty === null) {\n built.onDangerousProperty = defaultOnDangerousProperty;\n }\n\n // Always normalize processEntities for backward compatibility and validation\n built.processEntities = normalizeProcessEntities(built.processEntities, built.htmlEntities);\n built.unpairedTagsSet = new Set(built.unpairedTags);\n // Convert old-style stopNodes for backward compatibility\n if (built.stopNodes && Array.isArray(built.stopNodes)) {\n built.stopNodes = built.stopNodes.map(node => {\n if (typeof node === 'string' && node.startsWith('*.')) {\n // Old syntax: *.tagname meant \"tagname anywhere\"\n // Convert to new syntax: ..tagname\n return '..' + node.substring(2);\n }\n return node;\n });\n }\n //console.debug(built.processEntities)\n return built;\n};","'use strict';\n\nlet METADATA_SYMBOL;\n\nif (typeof Symbol !== \"function\") {\n METADATA_SYMBOL = \"@@xmlMetadata\";\n} else {\n METADATA_SYMBOL = Symbol(\"XML Node Metadata\");\n}\n\nexport default class XmlNode {\n constructor(tagname) {\n this.tagname = tagname;\n this.child = []; //nested tags, text, cdata, comments in order\n this[\":@\"] = Object.create(null); //attributes map\n }\n add(key, val) {\n // this.child.push( {name : key, val: val, isCdata: isCdata });\n if (key === \"__proto__\") key = \"#__proto__\";\n this.child.push({ [key]: val });\n }\n addChild(node, startIndex) {\n if (node.tagname === \"__proto__\") node.tagname = \"#__proto__\";\n if (node[\":@\"] && Object.keys(node[\":@\"]).length > 0) {\n this.child.push({ [node.tagname]: node.child, [\":@\"]: node[\":@\"] });\n } else {\n this.child.push({ [node.tagname]: node.child });\n }\n // if requested, add the startIndex\n if (startIndex !== undefined) {\n // Note: for now we just overwrite the metadata. If we had more complex metadata,\n // we might need to do an object append here: metadata = { ...metadata, startIndex }\n this.child[this.child.length - 1][METADATA_SYMBOL] = { startIndex };\n }\n }\n /** symbol used for metadata */\n static getMetaDataSymbol() {\n return METADATA_SYMBOL;\n }\n}\n","import { isName } from '../util.js';\n\nexport default class DocTypeReader {\n constructor(options) {\n this.suppressValidationErr = !options;\n this.options = options;\n }\n\n readDocType(xmlData, i) {\n const entities = Object.create(null);\n let entityCount = 0;\n\n if (xmlData[i + 3] === 'O' &&\n xmlData[i + 4] === 'C' &&\n xmlData[i + 5] === 'T' &&\n xmlData[i + 6] === 'Y' &&\n xmlData[i + 7] === 'P' &&\n xmlData[i + 8] === 'E') {\n i = i + 9;\n let angleBracketsCount = 1;\n let hasBody = false, comment = false;\n let exp = \"\";\n for (; i < xmlData.length; i++) {\n if (xmlData[i] === '<' && !comment) { //Determine the tag type\n if (hasBody && hasSeq(xmlData, \"!ENTITY\", i)) {\n i += 7;\n let entityName, val;\n [entityName, val, i] = this.readEntityExp(xmlData, i + 1, this.suppressValidationErr);\n if (val.indexOf(\"&\") === -1) { //Parameter entities are not supported\n if (this.options.enabled !== false &&\n this.options.maxEntityCount != null &&\n entityCount >= this.options.maxEntityCount) {\n throw new Error(\n `Entity count (${entityCount + 1}) exceeds maximum allowed (${this.options.maxEntityCount})`\n );\n }\n //const escaped = entityName.replace(/[.\\-+*:]/g, '\\\\.');\n //const escaped = entityName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n entities[entityName] = val;\n entityCount++;\n }\n }\n else if (hasBody && hasSeq(xmlData, \"!ELEMENT\", i)) {\n i += 8;//Not supported\n const { index } = this.readElementExp(xmlData, i + 1);\n i = index;\n } else if (hasBody && hasSeq(xmlData, \"!ATTLIST\", i)) {\n i += 8;//Not supported\n // const {index} = this.readAttlistExp(xmlData,i+1);\n // i = index;\n } else if (hasBody && hasSeq(xmlData, \"!NOTATION\", i)) {\n i += 9;//Not supported\n const { index } = this.readNotationExp(xmlData, i + 1, this.suppressValidationErr);\n i = index;\n } else if (hasSeq(xmlData, \"!--\", i)) comment = true;\n else throw new Error(`Invalid DOCTYPE`);\n\n angleBracketsCount++;\n exp = \"\";\n } else if (xmlData[i] === '>') { //Read tag content\n if (comment) {\n if (xmlData[i - 1] === \"-\" && xmlData[i - 2] === \"-\") {\n comment = false;\n angleBracketsCount--;\n }\n } else {\n angleBracketsCount--;\n }\n if (angleBracketsCount === 0) {\n break;\n }\n } else if (xmlData[i] === '[') {\n hasBody = true;\n } else {\n exp += xmlData[i];\n }\n }\n if (angleBracketsCount !== 0) {\n throw new Error(`Unclosed DOCTYPE`);\n }\n } else {\n throw new Error(`Invalid Tag instead of DOCTYPE`);\n }\n return { entities, i };\n }\n readEntityExp(xmlData, i) {\n //External entities are not supported\n // \n\n //Parameter entities are not supported\n // \n\n //Internal entities are supported\n // \n\n // Skip leading whitespace after this.options.maxEntitySize) {\n throw new Error(\n `Entity \"${entityName}\" size (${entityValue.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`\n );\n }\n\n i--;\n return [entityName, entityValue, i];\n }\n\n readNotationExp(xmlData, i) {\n // Skip leading whitespace after \n // \n // \n // \n // \n\n // Skip leading whitespace after {\n while (index < data.length && /\\s/.test(data[index])) {\n index++;\n }\n return index;\n};\n\n\n\nfunction hasSeq(data, seq, i) {\n for (let j = 0; j < seq.length; j++) {\n if (seq[j] !== data[i + j + 1]) return false;\n }\n return true;\n}\n\nfunction validateEntityName(name) {\n if (isName(name))\n return name;\n else\n throw new Error(`Invalid entity name ${name}`);\n}","const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;\nconst numRegex = /^([\\-\\+])?(0*)([0-9]*(\\.[0-9]*)?)$/;\n// const octRegex = /^0x[a-z0-9]+/;\n// const binRegex = /0x[a-z0-9]+/;\n\n\nconst consider = {\n hex: true,\n // oct: false,\n leadingZeros: true,\n decimalPoint: \"\\.\",\n eNotation: true,\n //skipLike: /regex/,\n infinity: \"original\", // \"null\", \"infinity\" (Infinity type), \"string\" (\"Infinity\" (the string literal))\n};\n\nexport default function toNumber(str, options = {}) {\n options = Object.assign({}, consider, options);\n if (!str || typeof str !== \"string\") return str;\n\n let trimmedStr = str.trim();\n\n if (trimmedStr.length === 0) return str;\n else if (options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str;\n else if (trimmedStr === \"0\") return 0;\n else if (options.hex && hexRegex.test(trimmedStr)) {\n return parse_int(trimmedStr, 16);\n // }else if (options.oct && octRegex.test(str)) {\n // return Number.parseInt(val, 8);\n } else if (!isFinite(trimmedStr)) { //Infinity\n return handleInfinity(str, Number(trimmedStr), options);\n } else if (trimmedStr.includes('e') || trimmedStr.includes('E')) { //eNotation\n return resolveEnotation(str, trimmedStr, options);\n // }else if (options.parseBin && binRegex.test(str)) {\n // return Number.parseInt(val, 2);\n } else {\n //separate negative sign, leading zeros, and rest number\n const match = numRegex.exec(trimmedStr);\n // +00.123 => [ , '+', '00', '.123', ..\n if (match) {\n const sign = match[1] || \"\";\n const leadingZeros = match[2];\n let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros\n const decimalAdjacentToLeadingZeros = sign ? // 0., -00., 000.\n str[leadingZeros.length + 1] === \".\"\n : str[leadingZeros.length] === \".\";\n\n //trim ending zeros for floating number\n if (!options.leadingZeros //leading zeros are not allowed\n && (leadingZeros.length > 1\n || (leadingZeros.length === 1 && !decimalAdjacentToLeadingZeros))) {\n // 00, 00.3, +03.24, 03, 03.24\n return str;\n }\n else {//no leading zeros or leading zeros are allowed\n const num = Number(trimmedStr);\n const parsedStr = String(num);\n\n if (num === 0) return num;\n if (parsedStr.search(/[eE]/) !== -1) { //given number is long and parsed to eNotation\n if (options.eNotation) return num;\n else return str;\n } else if (trimmedStr.indexOf(\".\") !== -1) { //floating number\n if (parsedStr === \"0\") return num; //0.0\n else if (parsedStr === numTrimmedByZeros) return num; //0.456. 0.79000\n else if (parsedStr === `${sign}${numTrimmedByZeros}`) return num;\n else return str;\n }\n\n let n = leadingZeros ? numTrimmedByZeros : trimmedStr;\n if (leadingZeros) {\n // -009 => -9\n return (n === parsedStr) || (sign + n === parsedStr) ? num : str\n } else {\n // +9\n return (n === parsedStr) || (n === sign + parsedStr) ? num : str\n }\n }\n } else { //non-numeric string\n return str;\n }\n }\n}\n\nconst eNotationRegx = /^([-+])?(0*)(\\d*(\\.\\d*)?[eE][-\\+]?\\d+)$/;\nfunction resolveEnotation(str, trimmedStr, options) {\n if (!options.eNotation) return str;\n const notation = trimmedStr.match(eNotationRegx);\n if (notation) {\n let sign = notation[1] || \"\";\n const eChar = notation[3].indexOf(\"e\") === -1 ? \"E\" : \"e\";\n const leadingZeros = notation[2];\n const eAdjacentToLeadingZeros = sign ? // 0E.\n str[leadingZeros.length + 1] === eChar\n : str[leadingZeros.length] === eChar;\n\n if (leadingZeros.length > 1 && eAdjacentToLeadingZeros) return str;\n else if (leadingZeros.length === 1\n && (notation[3].startsWith(`.${eChar}`) || notation[3][0] === eChar)) {\n return Number(trimmedStr);\n } else if (leadingZeros.length > 0) {\n // Has leading zeros — only accept if leadingZeros option allows it\n if (options.leadingZeros && !eAdjacentToLeadingZeros) {\n trimmedStr = (notation[1] || \"\") + notation[3];\n return Number(trimmedStr);\n } else return str;\n } else {\n // No leading zeros — always valid e-notation, parse it\n return Number(trimmedStr);\n }\n } else {\n return str;\n }\n}\n\n/**\n * \n * @param {string} numStr without leading zeros\n * @returns \n */\nfunction trimZeros(numStr) {\n if (numStr && numStr.indexOf(\".\") !== -1) {//float\n numStr = numStr.replace(/0+$/, \"\"); //remove ending zeros\n if (numStr === \".\") numStr = \"0\";\n else if (numStr[0] === \".\") numStr = \"0\" + numStr;\n else if (numStr[numStr.length - 1] === \".\") numStr = numStr.substring(0, numStr.length - 1);\n return numStr;\n }\n return numStr;\n}\n\nfunction parse_int(numStr, base) {\n //polyfill\n if (parseInt) return parseInt(numStr, base);\n else if (Number.parseInt) return Number.parseInt(numStr, base);\n else if (window && window.parseInt) return window.parseInt(numStr, base);\n else throw new Error(\"parseInt, Number.parseInt, window.parseInt are not supported\")\n}\n\n/**\n * Handle infinite values based on user option\n * @param {string} str - original input string\n * @param {number} num - parsed number (Infinity or -Infinity)\n * @param {object} options - user options\n * @returns {string|number|null} based on infinity option\n */\nfunction handleInfinity(str, num, options) {\n const isPositive = num === Infinity;\n\n switch (options.infinity.toLowerCase()) {\n case \"null\":\n return null;\n case \"infinity\":\n return num; // Return Infinity or -Infinity\n case \"string\":\n return isPositive ? \"Infinity\" : \"-Infinity\";\n case \"original\":\n default:\n return str; // Return original string like \"1e1000\"\n }\n}","export default function getIgnoreAttributesFn(ignoreAttributes) {\n if (typeof ignoreAttributes === 'function') {\n return ignoreAttributes\n }\n if (Array.isArray(ignoreAttributes)) {\n return (attrName) => {\n for (const pattern of ignoreAttributes) {\n if (typeof pattern === 'string' && attrName === pattern) {\n return true\n }\n if (pattern instanceof RegExp && pattern.test(attrName)) {\n return true\n }\n }\n }\n }\n return () => false\n}","/**\n * Expression - Parses and stores a tag pattern expression\n * \n * Patterns are parsed once and stored in an optimized structure for fast matching.\n * \n * @example\n * const expr = new Expression(\"root.users.user\");\n * const expr2 = new Expression(\"..user[id]:first\");\n * const expr3 = new Expression(\"root/users/user\", { separator: '/' });\n */\nexport default class Expression {\n /**\n * Create a new Expression\n * @param {string} pattern - Pattern string (e.g., \"root.users.user\", \"..user[id]\")\n * @param {Object} options - Configuration options\n * @param {string} options.separator - Path separator (default: '.')\n */\n constructor(pattern, options = {}, data) {\n this.pattern = pattern;\n this.separator = options.separator || '.';\n this.segments = this._parse(pattern);\n this.data = data;\n // Cache expensive checks for performance (O(1) instead of O(n))\n this._hasDeepWildcard = this.segments.some(seg => seg.type === 'deep-wildcard');\n this._hasAttributeCondition = this.segments.some(seg => seg.attrName !== undefined);\n this._hasPositionSelector = this.segments.some(seg => seg.position !== undefined);\n }\n\n /**\n * Parse pattern string into segments\n * @private\n * @param {string} pattern - Pattern to parse\n * @returns {Array} Array of segment objects\n */\n _parse(pattern) {\n const segments = [];\n\n // Split by separator but handle \"..\" specially\n let i = 0;\n let currentPart = '';\n\n while (i < pattern.length) {\n if (pattern[i] === this.separator) {\n // Check if next char is also separator (deep wildcard)\n if (i + 1 < pattern.length && pattern[i + 1] === this.separator) {\n // Flush current part if any\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n currentPart = '';\n }\n // Add deep wildcard\n segments.push({ type: 'deep-wildcard' });\n i += 2; // Skip both separators\n } else {\n // Regular separator\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n }\n currentPart = '';\n i++;\n }\n } else {\n currentPart += pattern[i];\n i++;\n }\n }\n\n // Flush remaining part\n if (currentPart.trim()) {\n segments.push(this._parseSegment(currentPart.trim()));\n }\n\n return segments;\n }\n\n /**\n * Parse a single segment\n * @private\n * @param {string} part - Segment string (e.g., \"user\", \"ns::user\", \"user[id]\", \"ns::user:first\")\n * @returns {Object} Segment object\n */\n _parseSegment(part) {\n const segment = { type: 'tag' };\n\n // NEW NAMESPACE SYNTAX (v2.0):\n // ============================\n // Namespace uses DOUBLE colon (::)\n // Position uses SINGLE colon (:)\n // \n // Examples:\n // \"user\" → tag\n // \"user:first\" → tag + position\n // \"user[id]\" → tag + attribute\n // \"user[id]:first\" → tag + attribute + position\n // \"ns::user\" → namespace + tag\n // \"ns::user:first\" → namespace + tag + position\n // \"ns::user[id]\" → namespace + tag + attribute\n // \"ns::user[id]:first\" → namespace + tag + attribute + position\n // \"ns::first\" → namespace + tag named \"first\" (NO ambiguity!)\n //\n // This eliminates all ambiguity:\n // :: = namespace separator\n // : = position selector\n // [] = attributes\n\n // Step 1: Extract brackets [attr] or [attr=value]\n let bracketContent = null;\n let withoutBrackets = part;\n\n const bracketMatch = part.match(/^([^\\[]+)(\\[[^\\]]*\\])(.*)$/);\n if (bracketMatch) {\n withoutBrackets = bracketMatch[1] + bracketMatch[3];\n if (bracketMatch[2]) {\n const content = bracketMatch[2].slice(1, -1);\n if (content) {\n bracketContent = content;\n }\n }\n }\n\n // Step 2: Check for namespace (double colon ::)\n let namespace = undefined;\n let tagAndPosition = withoutBrackets;\n\n if (withoutBrackets.includes('::')) {\n const nsIndex = withoutBrackets.indexOf('::');\n namespace = withoutBrackets.substring(0, nsIndex).trim();\n tagAndPosition = withoutBrackets.substring(nsIndex + 2).trim(); // Skip ::\n\n if (!namespace) {\n throw new Error(`Invalid namespace in pattern: ${part}`);\n }\n }\n\n // Step 3: Parse tag and position (single colon :)\n let tag = undefined;\n let positionMatch = null;\n\n if (tagAndPosition.includes(':')) {\n const colonIndex = tagAndPosition.lastIndexOf(':'); // Use last colon for position\n const tagPart = tagAndPosition.substring(0, colonIndex).trim();\n const posPart = tagAndPosition.substring(colonIndex + 1).trim();\n\n // Verify position is a valid keyword\n const isPositionKeyword = ['first', 'last', 'odd', 'even'].includes(posPart) ||\n /^nth\\(\\d+\\)$/.test(posPart);\n\n if (isPositionKeyword) {\n tag = tagPart;\n positionMatch = posPart;\n } else {\n // Not a valid position keyword, treat whole thing as tag\n tag = tagAndPosition;\n }\n } else {\n tag = tagAndPosition;\n }\n\n if (!tag) {\n throw new Error(`Invalid segment pattern: ${part}`);\n }\n\n segment.tag = tag;\n if (namespace) {\n segment.namespace = namespace;\n }\n\n // Step 4: Parse attributes\n if (bracketContent) {\n if (bracketContent.includes('=')) {\n const eqIndex = bracketContent.indexOf('=');\n segment.attrName = bracketContent.substring(0, eqIndex).trim();\n segment.attrValue = bracketContent.substring(eqIndex + 1).trim();\n } else {\n segment.attrName = bracketContent.trim();\n }\n }\n\n // Step 5: Parse position selector\n if (positionMatch) {\n const nthMatch = positionMatch.match(/^nth\\((\\d+)\\)$/);\n if (nthMatch) {\n segment.position = 'nth';\n segment.positionValue = parseInt(nthMatch[1], 10);\n } else {\n segment.position = positionMatch;\n }\n }\n\n return segment;\n }\n\n /**\n * Get the number of segments\n * @returns {number}\n */\n get length() {\n return this.segments.length;\n }\n\n /**\n * Check if expression contains deep wildcard\n * @returns {boolean}\n */\n hasDeepWildcard() {\n return this._hasDeepWildcard;\n }\n\n /**\n * Check if expression has attribute conditions\n * @returns {boolean}\n */\n hasAttributeCondition() {\n return this._hasAttributeCondition;\n }\n\n /**\n * Check if expression has position selectors\n * @returns {boolean}\n */\n hasPositionSelector() {\n return this._hasPositionSelector;\n }\n\n /**\n * Get string representation\n * @returns {string}\n */\n toString() {\n return this.pattern;\n }\n}","/**\n * ExpressionSet - An indexed collection of Expressions for efficient bulk matching\n *\n * Instead of iterating all expressions on every tag, ExpressionSet pre-indexes\n * them at insertion time by depth and terminal tag name. At match time, only\n * the relevant bucket is evaluated — typically reducing checks from O(E) to O(1)\n * lookup plus O(small bucket) matches.\n *\n * Three buckets are maintained:\n * - `_byDepthAndTag` — exact depth + exact tag name (tightest, used first)\n * - `_wildcardByDepth` — exact depth + wildcard tag `*` (depth-matched only)\n * - `_deepWildcards` — expressions containing `..` (cannot be depth-indexed)\n *\n * @example\n * import { Expression, ExpressionSet } from 'fast-xml-tagger';\n *\n * // Build once at config time\n * const stopNodes = new ExpressionSet();\n * stopNodes.add(new Expression('root.users.user'));\n * stopNodes.add(new Expression('root.config.setting'));\n * stopNodes.add(new Expression('..script'));\n *\n * // Query on every tag — hot path\n * if (stopNodes.matchesAny(matcher)) { ... }\n */\nexport default class ExpressionSet {\n constructor() {\n /** @type {Map} depth:tag → expressions */\n this._byDepthAndTag = new Map();\n\n /** @type {Map} depth → wildcard-tag expressions */\n this._wildcardByDepth = new Map();\n\n /** @type {import('./Expression.js').default[]} expressions containing deep wildcard (..) */\n this._deepWildcards = [];\n\n /** @type {Set} pattern strings already added — used for deduplication */\n this._patterns = new Set();\n\n /** @type {boolean} whether the set is sealed against further additions */\n this._sealed = false;\n }\n\n /**\n * Add an Expression to the set.\n * Duplicate patterns (same pattern string) are silently ignored.\n *\n * @param {import('./Expression.js').default} expression - A pre-constructed Expression instance\n * @returns {this} for chaining\n * @throws {TypeError} if called after seal()\n *\n * @example\n * set.add(new Expression('root.users.user'));\n * set.add(new Expression('..script'));\n */\n add(expression) {\n if (this._sealed) {\n throw new TypeError(\n 'ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.'\n );\n }\n\n // Deduplicate by pattern string\n if (this._patterns.has(expression.pattern)) return this;\n this._patterns.add(expression.pattern);\n\n if (expression.hasDeepWildcard()) {\n this._deepWildcards.push(expression);\n return this;\n }\n\n const depth = expression.length;\n const lastSeg = expression.segments[expression.segments.length - 1];\n const tag = lastSeg?.tag;\n\n if (!tag || tag === '*') {\n // Can index by depth but not by tag\n if (!this._wildcardByDepth.has(depth)) this._wildcardByDepth.set(depth, []);\n this._wildcardByDepth.get(depth).push(expression);\n } else {\n // Tightest bucket: depth + tag\n const key = `${depth}:${tag}`;\n if (!this._byDepthAndTag.has(key)) this._byDepthAndTag.set(key, []);\n this._byDepthAndTag.get(key).push(expression);\n }\n\n return this;\n }\n\n /**\n * Add multiple expressions at once.\n *\n * @param {import('./Expression.js').default[]} expressions - Array of Expression instances\n * @returns {this} for chaining\n *\n * @example\n * set.addAll([\n * new Expression('root.users.user'),\n * new Expression('root.config.setting'),\n * ]);\n */\n addAll(expressions) {\n for (const expr of expressions) this.add(expr);\n return this;\n }\n\n /**\n * Check whether a pattern string is already present in the set.\n *\n * @param {import('./Expression.js').default} expression\n * @returns {boolean}\n */\n has(expression) {\n return this._patterns.has(expression.pattern);\n }\n\n /**\n * Number of expressions in the set.\n * @type {number}\n */\n get size() {\n return this._patterns.size;\n }\n\n /**\n * Seal the set against further modifications.\n * Useful to prevent accidental mutations after config is built.\n * Calling add() or addAll() on a sealed set throws a TypeError.\n *\n * @returns {this}\n */\n seal() {\n this._sealed = true;\n return this;\n }\n\n /**\n * Whether the set has been sealed.\n * @type {boolean}\n */\n get isSealed() {\n return this._sealed;\n }\n\n /**\n * Test whether the matcher's current path matches any expression in the set.\n *\n * Evaluation order (cheapest → most expensive):\n * 1. Exact depth + tag bucket — O(1) lookup, typically 0–2 expressions\n * 2. Depth-only wildcard bucket — O(1) lookup, rare\n * 3. Deep-wildcard list — always checked, but usually small\n *\n * @param {import('./Matcher.js').default} matcher - Matcher instance (or readOnly view)\n * @returns {boolean} true if any expression matches the current path\n *\n * @example\n * if (stopNodes.matchesAny(matcher)) {\n * // handle stop node\n * }\n */\n matchesAny(matcher) {\n return this.findMatch(matcher) !== null;\n }\n /**\n * Find and return the first Expression that matches the matcher's current path.\n *\n * Uses the same evaluation order as matchesAny (cheapest → most expensive):\n * 1. Exact depth + tag bucket\n * 2. Depth-only wildcard bucket\n * 3. Deep-wildcard list\n *\n * @param {import('./Matcher.js').default} matcher - Matcher instance (or readOnly view)\n * @returns {import('./Expression.js').default | null} the first matching Expression, or null\n *\n * @example\n * const expr = stopNodes.findMatch(matcher);\n * if (expr) {\n * // access expr.config, expr.pattern, etc.\n * }\n */\n findMatch(matcher) {\n const depth = matcher.getDepth();\n const tag = matcher.getCurrentTag();\n\n // 1. Tightest bucket — most expressions live here\n const exactKey = `${depth}:${tag}`;\n const exactBucket = this._byDepthAndTag.get(exactKey);\n if (exactBucket) {\n for (let i = 0; i < exactBucket.length; i++) {\n if (matcher.matches(exactBucket[i])) return exactBucket[i];\n }\n }\n\n // 2. Depth-matched wildcard-tag expressions\n const wildcardBucket = this._wildcardByDepth.get(depth);\n if (wildcardBucket) {\n for (let i = 0; i < wildcardBucket.length; i++) {\n if (matcher.matches(wildcardBucket[i])) return wildcardBucket[i];\n }\n }\n\n // 3. Deep wildcards — cannot be pre-filtered by depth or tag\n for (let i = 0; i < this._deepWildcards.length; i++) {\n if (matcher.matches(this._deepWildcards[i])) return this._deepWildcards[i];\n }\n\n return null;\n }\n}\n","import ExpressionSet from \"./ExpressionSet.js\";\n\n/**\n * MatcherView - A lightweight read-only view over a Matcher's internal state.\n *\n * Created once by Matcher and reused across all callbacks. Holds a direct\n * reference to the parent Matcher so it always reflects current parser state\n * with zero copying or freezing overhead.\n *\n * Users receive this via {@link Matcher#readOnly} or directly from parser\n * callbacks. It exposes all query and matching methods but has no mutation\n * methods — misuse is caught at the TypeScript level rather than at runtime.\n *\n * @example\n * const matcher = new Matcher();\n * const view = matcher.readOnly();\n *\n * matcher.push(\"root\", {});\n * view.getCurrentTag(); // \"root\"\n * view.getDepth(); // 1\n */\nexport class MatcherView {\n /**\n * @param {Matcher} matcher - The parent Matcher instance to read from.\n */\n constructor(matcher) {\n this._matcher = matcher;\n }\n\n /**\n * Get the path separator used by the parent matcher.\n * @returns {string}\n */\n get separator() {\n return this._matcher.separator;\n }\n\n /**\n * Get current tag name.\n * @returns {string|undefined}\n */\n getCurrentTag() {\n const path = this._matcher.path;\n return path.length > 0 ? path[path.length - 1].tag : undefined;\n }\n\n /**\n * Get current namespace.\n * @returns {string|undefined}\n */\n getCurrentNamespace() {\n const path = this._matcher.path;\n return path.length > 0 ? path[path.length - 1].namespace : undefined;\n }\n\n /**\n * Get current node's attribute value.\n * @param {string} attrName\n * @returns {*}\n */\n getAttrValue(attrName) {\n const path = this._matcher.path;\n if (path.length === 0) return undefined;\n return path[path.length - 1].values?.[attrName];\n }\n\n /**\n * Check if current node has an attribute.\n * @param {string} attrName\n * @returns {boolean}\n */\n hasAttr(attrName) {\n const path = this._matcher.path;\n if (path.length === 0) return false;\n const current = path[path.length - 1];\n return current.values !== undefined && attrName in current.values;\n }\n\n /**\n * Get current node's sibling position (child index in parent).\n * @returns {number}\n */\n getPosition() {\n const path = this._matcher.path;\n if (path.length === 0) return -1;\n return path[path.length - 1].position ?? 0;\n }\n\n /**\n * Get current node's repeat counter (occurrence count of this tag name).\n * @returns {number}\n */\n getCounter() {\n const path = this._matcher.path;\n if (path.length === 0) return -1;\n return path[path.length - 1].counter ?? 0;\n }\n\n /**\n * Get current node's sibling index (alias for getPosition).\n * @returns {number}\n * @deprecated Use getPosition() or getCounter() instead\n */\n getIndex() {\n return this.getPosition();\n }\n\n /**\n * Get current path depth.\n * @returns {number}\n */\n getDepth() {\n return this._matcher.path.length;\n }\n\n /**\n * Get path as string.\n * @param {string} [separator] - Optional separator (uses default if not provided)\n * @param {boolean} [includeNamespace=true]\n * @returns {string}\n */\n toString(separator, includeNamespace = true) {\n return this._matcher.toString(separator, includeNamespace);\n }\n\n /**\n * Get path as array of tag names.\n * @returns {string[]}\n */\n toArray() {\n return this._matcher.path.map(n => n.tag);\n }\n\n /**\n * Match current path against an Expression.\n * @param {Expression} expression\n * @returns {boolean}\n */\n matches(expression) {\n return this._matcher.matches(expression);\n }\n\n /**\n * Match any expression in the given set against the current path.\n * @param {ExpressionSet} exprSet\n * @returns {boolean}\n */\n matchesAny(exprSet) {\n return exprSet.matchesAny(this._matcher);\n }\n}\n\n/**\n * Matcher - Tracks current path in XML/JSON tree and matches against Expressions.\n *\n * The matcher maintains a stack of nodes representing the current path from root to\n * current tag. It only stores attribute values for the current (top) node to minimize\n * memory usage. Sibling tracking is used to auto-calculate position and counter.\n *\n * Use {@link Matcher#readOnly} to obtain a {@link MatcherView} safe to pass to\n * user callbacks — it always reflects current state with no Proxy overhead.\n *\n * @example\n * const matcher = new Matcher();\n * matcher.push(\"root\", {});\n * matcher.push(\"users\", {});\n * matcher.push(\"user\", { id: \"123\", type: \"admin\" });\n *\n * const expr = new Expression(\"root.users.user\");\n * matcher.matches(expr); // true\n */\nexport default class Matcher {\n /**\n * Create a new Matcher.\n * @param {Object} [options={}]\n * @param {string} [options.separator='.'] - Default path separator\n */\n constructor(options = {}) {\n this.separator = options.separator || '.';\n this.path = [];\n this.siblingStacks = [];\n // Each path node: { tag, values, position, counter, namespace? }\n // values only present for current (last) node\n // Each siblingStacks entry: Map tracking occurrences at each level\n this._pathStringCache = null;\n this._view = new MatcherView(this);\n }\n\n /**\n * Push a new tag onto the path.\n * @param {string} tagName\n * @param {Object|null} [attrValues=null]\n * @param {string|null} [namespace=null]\n */\n push(tagName, attrValues = null, namespace = null) {\n this._pathStringCache = null;\n\n // Remove values from previous current node (now becoming ancestor)\n if (this.path.length > 0) {\n this.path[this.path.length - 1].values = undefined;\n }\n\n // Get or create sibling tracking for current level\n const currentLevel = this.path.length;\n if (!this.siblingStacks[currentLevel]) {\n this.siblingStacks[currentLevel] = new Map();\n }\n\n const siblings = this.siblingStacks[currentLevel];\n\n // Create a unique key for sibling tracking that includes namespace\n const siblingKey = namespace ? `${namespace}:${tagName}` : tagName;\n\n // Calculate counter (how many times this tag appeared at this level)\n const counter = siblings.get(siblingKey) || 0;\n\n // Calculate position (total children at this level so far)\n let position = 0;\n for (const count of siblings.values()) {\n position += count;\n }\n\n // Update sibling count for this tag\n siblings.set(siblingKey, counter + 1);\n\n // Create new node\n const node = {\n tag: tagName,\n position: position,\n counter: counter\n };\n\n if (namespace !== null && namespace !== undefined) {\n node.namespace = namespace;\n }\n\n if (attrValues !== null && attrValues !== undefined) {\n node.values = attrValues;\n }\n\n this.path.push(node);\n }\n\n /**\n * Pop the last tag from the path.\n * @returns {Object|undefined} The popped node\n */\n pop() {\n if (this.path.length === 0) return undefined;\n this._pathStringCache = null;\n\n const node = this.path.pop();\n\n if (this.siblingStacks.length > this.path.length + 1) {\n this.siblingStacks.length = this.path.length + 1;\n }\n\n return node;\n }\n\n /**\n * Update current node's attribute values.\n * Useful when attributes are parsed after push.\n * @param {Object} attrValues\n */\n updateCurrent(attrValues) {\n if (this.path.length > 0) {\n const current = this.path[this.path.length - 1];\n if (attrValues !== null && attrValues !== undefined) {\n current.values = attrValues;\n }\n }\n }\n\n /**\n * Get current tag name.\n * @returns {string|undefined}\n */\n getCurrentTag() {\n return this.path.length > 0 ? this.path[this.path.length - 1].tag : undefined;\n }\n\n /**\n * Get current namespace.\n * @returns {string|undefined}\n */\n getCurrentNamespace() {\n return this.path.length > 0 ? this.path[this.path.length - 1].namespace : undefined;\n }\n\n /**\n * Get current node's attribute value.\n * @param {string} attrName\n * @returns {*}\n */\n getAttrValue(attrName) {\n if (this.path.length === 0) return undefined;\n return this.path[this.path.length - 1].values?.[attrName];\n }\n\n /**\n * Check if current node has an attribute.\n * @param {string} attrName\n * @returns {boolean}\n */\n hasAttr(attrName) {\n if (this.path.length === 0) return false;\n const current = this.path[this.path.length - 1];\n return current.values !== undefined && attrName in current.values;\n }\n\n /**\n * Get current node's sibling position (child index in parent).\n * @returns {number}\n */\n getPosition() {\n if (this.path.length === 0) return -1;\n return this.path[this.path.length - 1].position ?? 0;\n }\n\n /**\n * Get current node's repeat counter (occurrence count of this tag name).\n * @returns {number}\n */\n getCounter() {\n if (this.path.length === 0) return -1;\n return this.path[this.path.length - 1].counter ?? 0;\n }\n\n /**\n * Get current node's sibling index (alias for getPosition).\n * @returns {number}\n * @deprecated Use getPosition() or getCounter() instead\n */\n getIndex() {\n return this.getPosition();\n }\n\n /**\n * Get current path depth.\n * @returns {number}\n */\n getDepth() {\n return this.path.length;\n }\n\n /**\n * Get path as string.\n * @param {string} [separator] - Optional separator (uses default if not provided)\n * @param {boolean} [includeNamespace=true]\n * @returns {string}\n */\n toString(separator, includeNamespace = true) {\n const sep = separator || this.separator;\n const isDefault = (sep === this.separator && includeNamespace === true);\n\n if (isDefault) {\n if (this._pathStringCache !== null) {\n return this._pathStringCache;\n }\n const result = this.path.map(n =>\n (n.namespace) ? `${n.namespace}:${n.tag}` : n.tag\n ).join(sep);\n this._pathStringCache = result;\n return result;\n }\n\n return this.path.map(n =>\n (includeNamespace && n.namespace) ? `${n.namespace}:${n.tag}` : n.tag\n ).join(sep);\n }\n\n /**\n * Get path as array of tag names.\n * @returns {string[]}\n */\n toArray() {\n return this.path.map(n => n.tag);\n }\n\n /**\n * Reset the path to empty.\n */\n reset() {\n this._pathStringCache = null;\n this.path = [];\n this.siblingStacks = [];\n }\n\n /**\n * Match current path against an Expression.\n * @param {Expression} expression\n * @returns {boolean}\n */\n matches(expression) {\n const segments = expression.segments;\n\n if (segments.length === 0) {\n return false;\n }\n\n if (expression.hasDeepWildcard()) {\n return this._matchWithDeepWildcard(segments);\n }\n\n return this._matchSimple(segments);\n }\n\n /**\n * @private\n */\n _matchSimple(segments) {\n if (this.path.length !== segments.length) {\n return false;\n }\n\n for (let i = 0; i < segments.length; i++) {\n if (!this._matchSegment(segments[i], this.path[i], i === this.path.length - 1)) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * @private\n */\n _matchWithDeepWildcard(segments) {\n let pathIdx = this.path.length - 1;\n let segIdx = segments.length - 1;\n\n while (segIdx >= 0 && pathIdx >= 0) {\n const segment = segments[segIdx];\n\n if (segment.type === 'deep-wildcard') {\n segIdx--;\n\n if (segIdx < 0) {\n return true;\n }\n\n const nextSeg = segments[segIdx];\n let found = false;\n\n for (let i = pathIdx; i >= 0; i--) {\n if (this._matchSegment(nextSeg, this.path[i], i === this.path.length - 1)) {\n pathIdx = i - 1;\n segIdx--;\n found = true;\n break;\n }\n }\n\n if (!found) {\n return false;\n }\n } else {\n if (!this._matchSegment(segment, this.path[pathIdx], pathIdx === this.path.length - 1)) {\n return false;\n }\n pathIdx--;\n segIdx--;\n }\n }\n\n return segIdx < 0;\n }\n\n /**\n * @private\n */\n _matchSegment(segment, node, isCurrentNode) {\n if (segment.tag !== '*' && segment.tag !== node.tag) {\n return false;\n }\n\n if (segment.namespace !== undefined) {\n if (segment.namespace !== '*' && segment.namespace !== node.namespace) {\n return false;\n }\n }\n\n if (segment.attrName !== undefined) {\n if (!isCurrentNode) {\n return false;\n }\n\n if (!node.values || !(segment.attrName in node.values)) {\n return false;\n }\n\n if (segment.attrValue !== undefined) {\n if (String(node.values[segment.attrName]) !== String(segment.attrValue)) {\n return false;\n }\n }\n }\n\n if (segment.position !== undefined) {\n if (!isCurrentNode) {\n return false;\n }\n\n const counter = node.counter ?? 0;\n\n if (segment.position === 'first' && counter !== 0) {\n return false;\n } else if (segment.position === 'odd' && counter % 2 !== 1) {\n return false;\n } else if (segment.position === 'even' && counter % 2 !== 0) {\n return false;\n } else if (segment.position === 'nth' && counter !== segment.positionValue) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Match any expression in the given set against the current path.\n * @param {ExpressionSet} exprSet\n * @returns {boolean}\n */\n matchesAny(exprSet) {\n return exprSet.matchesAny(this);\n }\n\n /**\n * Create a snapshot of current state.\n * @returns {Object}\n */\n snapshot() {\n return {\n path: this.path.map(node => ({ ...node })),\n siblingStacks: this.siblingStacks.map(map => new Map(map))\n };\n }\n\n /**\n * Restore state from snapshot.\n * @param {Object} snapshot\n */\n restore(snapshot) {\n this._pathStringCache = null;\n this.path = snapshot.path.map(node => ({ ...node }));\n this.siblingStacks = snapshot.siblingStacks.map(map => new Map(map));\n }\n\n /**\n * Return the read-only {@link MatcherView} for this matcher.\n *\n * The same instance is returned on every call — no allocation occurs.\n * It always reflects the current parser state and is safe to pass to\n * user callbacks without risk of accidental mutation.\n *\n * @returns {MatcherView}\n *\n * @example\n * const view = matcher.readOnly();\n * // pass view to callbacks — it stays in sync automatically\n * view.matches(expr); // ✓\n * view.getCurrentTag(); // ✓\n * // view.push(...) // ✗ method does not exist — caught by TypeScript\n */\n readOnly() {\n return this._view;\n }\n}","/**\n * fast-xml-tagger - XML/JSON path matching library\n * \n * Provides efficient path tracking and pattern matching for XML/JSON parsers.\n * \n * @example\n * import { Expression, Matcher } from 'fast-xml-tagger';\n * \n * // Create expression (parse once)\n * const expr = new Expression(\"root.users.user[id]\");\n * \n * // Create matcher (track path)\n * const matcher = new Matcher();\n * matcher.push(\"root\", [], {}, 0);\n * matcher.push(\"users\", [], {}, 0);\n * matcher.push(\"user\", [\"id\", \"type\"], { id: \"123\", type: \"admin\" }, 0);\n * \n * // Match\n * if (matcher.matches(expr)) {\n * console.log(\"Match found!\");\n * }\n */\n\nimport Expression from './Expression.js';\nimport Matcher from './Matcher.js';\nimport ExpressionSet from './ExpressionSet.js';\n\nexport { Expression, Matcher, ExpressionSet };\nexport default { Expression, Matcher, ExpressionSet };\n","'use strict';\n///@ts-check\n\nimport { getAllMatches, isExist, DANGEROUS_PROPERTY_NAMES, criticalProperties } from '../util.js';\nimport xmlNode from './xmlNode.js';\nimport DocTypeReader from './DocTypeReader.js';\nimport toNumber from \"strnum\";\nimport getIgnoreAttributesFn from \"../ignoreAttributes.js\";\nimport { Expression, Matcher } from 'path-expression-matcher';\nimport { ExpressionSet } from 'path-expression-matcher';\nimport { EntityDecoder, XML, CURRENCY, COMMON_HTML } from '@nodable/entities';\n\n// const regx =\n// '<((!\\\\[CDATA\\\\[([\\\\s\\\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\\\/)(NAME)\\\\s*>))([^<]*)'\n// .replace(/NAME/g, util.nameRegexp);\n\n//const tagsRegx = new RegExp(\"<(\\\\/?[\\\\w:\\\\-\\._]+)([^>]*)>(\\\\s*\"+cdataRegx+\")*([^<]+)?\",\"g\");\n//const tagsRegx = new RegExp(\"<(\\\\/?)((\\\\w*:)?([\\\\w:\\\\-\\._]+))([^>]*)>([^<]*)(\"+cdataRegx+\"([^<]*))*([^<]+)?\",\"g\");\n\n// Helper functions for attribute and namespace handling\n\n/**\n * Extract raw attributes (without prefix) from prefixed attribute map\n * @param {object} prefixedAttrs - Attributes with prefix from buildAttributesMap\n * @param {object} options - Parser options containing attributeNamePrefix\n * @returns {object} Raw attributes for matcher\n */\nfunction extractRawAttributes(prefixedAttrs, options) {\n if (!prefixedAttrs) return {};\n\n // Handle attributesGroupName option\n const attrs = options.attributesGroupName\n ? prefixedAttrs[options.attributesGroupName]\n : prefixedAttrs;\n\n if (!attrs) return {};\n\n const rawAttrs = {};\n for (const key in attrs) {\n // Remove the attribute prefix to get raw name\n if (key.startsWith(options.attributeNamePrefix)) {\n const rawName = key.substring(options.attributeNamePrefix.length);\n rawAttrs[rawName] = attrs[key];\n } else {\n // Attribute without prefix (shouldn't normally happen, but be safe)\n rawAttrs[key] = attrs[key];\n }\n }\n return rawAttrs;\n}\n\n/**\n * Extract namespace from raw tag name\n * @param {string} rawTagName - Tag name possibly with namespace (e.g., \"soap:Envelope\")\n * @returns {string|undefined} Namespace or undefined\n */\nfunction extractNamespace(rawTagName) {\n if (!rawTagName || typeof rawTagName !== 'string') return undefined;\n\n const colonIndex = rawTagName.indexOf(':');\n if (colonIndex !== -1 && colonIndex > 0) {\n const ns = rawTagName.substring(0, colonIndex);\n // Don't treat xmlns as a namespace\n if (ns !== 'xmlns') {\n return ns;\n }\n }\n return undefined;\n}\n\nexport default class OrderedObjParser {\n constructor(options, externalEntities) {\n this.options = options;\n this.currentNode = null;\n this.tagsNodeStack = [];\n this.parseXml = parseXml;\n this.parseTextData = parseTextData;\n this.resolveNameSpace = resolveNameSpace;\n this.buildAttributesMap = buildAttributesMap;\n this.isItStopNode = isItStopNode;\n this.replaceEntitiesValue = replaceEntitiesValue;\n this.readStopNodeData = readStopNodeData;\n this.saveTextToParentTag = saveTextToParentTag;\n this.addChild = addChild;\n this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)\n this.entityExpansionCount = 0;\n this.currentExpandedLength = 0;\n let namedEntities = { ...XML };\n if (this.options.entityDecoder) {\n this.entityDecoder = this.options.entityDecoder\n } else {\n if (typeof this.options.htmlEntities === \"object\") namedEntities = this.options.htmlEntities;\n else if (this.options.htmlEntities === true) namedEntities = { ...COMMON_HTML, ...CURRENCY };\n this.entityDecoder = new EntityDecoder({\n namedEntities: { ...namedEntities, ...externalEntities },\n numericAllowed: this.options.htmlEntities,\n limit: {\n maxTotalExpansions: this.options.processEntities.maxTotalExpansions,\n maxExpandedLength: this.options.processEntities.maxExpandedLength,\n applyLimitsTo: this.options.processEntities.appliesTo,\n }\n //postCheck: resolved => resolved\n });\n }\n\n // Initialize path matcher for path-expression-matcher\n this.matcher = new Matcher();\n\n // Live read-only proxy of matcher — PEM creates and caches this internally.\n // All user callbacks receive this instead of the mutable matcher.\n this.readonlyMatcher = this.matcher.readOnly();\n\n // Flag to track if current node is a stop node (optimization)\n this.isCurrentNodeStopNode = false;\n\n // Pre-compile stopNodes expressions\n this.stopNodeExpressionsSet = new ExpressionSet();\n const stopNodesOpts = this.options.stopNodes;\n if (stopNodesOpts && stopNodesOpts.length > 0) {\n for (let i = 0; i < stopNodesOpts.length; i++) {\n const stopNodeExp = stopNodesOpts[i];\n if (typeof stopNodeExp === 'string') {\n // Convert string to Expression object\n this.stopNodeExpressionsSet.add(new Expression(stopNodeExp));\n } else if (stopNodeExp instanceof Expression) {\n // Already an Expression object\n this.stopNodeExpressionsSet.add(stopNodeExp);\n }\n }\n this.stopNodeExpressionsSet.seal();\n }\n }\n\n}\n\n\n/**\n * @param {string} val\n * @param {string} tagName\n * @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath\n * @param {boolean} dontTrim\n * @param {boolean} hasAttributes\n * @param {boolean} isLeafNode\n * @param {boolean} escapeEntities\n */\nfunction parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {\n const options = this.options;\n if (val !== undefined) {\n if (options.trimValues && !dontTrim) {\n val = val.trim();\n }\n if (val.length > 0) {\n if (!escapeEntities) val = this.replaceEntitiesValue(val, tagName, jPath);\n\n // Pass jPath string or matcher based on options.jPath setting\n const jPathOrMatcher = options.jPath ? jPath.toString() : jPath;\n const newval = options.tagValueProcessor(tagName, val, jPathOrMatcher, hasAttributes, isLeafNode);\n if (newval === null || newval === undefined) {\n //don't parse\n return val;\n } else if (typeof newval !== typeof val || newval !== val) {\n //overwrite\n return newval;\n } else if (options.trimValues) {\n return parseValue(val, options.parseTagValue, options.numberParseOptions);\n } else {\n const trimmedVal = val.trim();\n if (trimmedVal === val) {\n return parseValue(val, options.parseTagValue, options.numberParseOptions);\n } else {\n return val;\n }\n }\n }\n }\n}\n\nfunction resolveNameSpace(tagname) {\n if (this.options.removeNSPrefix) {\n const tags = tagname.split(':');\n const prefix = tagname.charAt(0) === '/' ? '/' : '';\n if (tags[0] === 'xmlns') {\n return '';\n }\n if (tags.length === 2) {\n tagname = prefix + tags[1];\n }\n }\n return tagname;\n}\n\n//TODO: change regex to capture NS\n//const attrsRegx = new RegExp(\"([\\\\w\\\\-\\\\.\\\\:]+)\\\\s*=\\\\s*(['\\\"])((.|\\n)*?)\\\\2\",\"gm\");\nconst attrsRegx = new RegExp('([^\\\\s=]+)\\\\s*(=\\\\s*([\\'\"])([\\\\s\\\\S]*?)\\\\3)?', 'gm');\n\nfunction buildAttributesMap(attrStr, jPath, tagName, force = false) {\n const options = this.options;\n if (force === true || (options.ignoreAttributes !== true && typeof attrStr === 'string')) {\n // attrStr = attrStr.replace(/\\r?\\n/g, ' ');\n //attrStr = attrStr || attrStr.trim();\n\n const matches = getAllMatches(attrStr, attrsRegx);\n const len = matches.length; //don't make it inline\n const attrs = {};\n\n // Pre-process values once: trim + entity replacement\n // Reused in both matcher update and second pass\n const processedVals = new Array(len);\n let hasRawAttrs = false;\n const rawAttrsForMatcher = {};\n\n for (let i = 0; i < len; i++) {\n const attrName = this.resolveNameSpace(matches[i][1]);\n const oldVal = matches[i][4];\n\n if (attrName.length && oldVal !== undefined) {\n let val = oldVal;\n if (options.trimValues) val = val.trim();\n val = this.replaceEntitiesValue(val, tagName, this.readonlyMatcher);\n processedVals[i] = val;\n\n rawAttrsForMatcher[attrName] = val;\n hasRawAttrs = true;\n }\n }\n\n // Update matcher ONCE before second pass, if applicable\n if (hasRawAttrs && typeof jPath === 'object' && jPath.updateCurrent) {\n jPath.updateCurrent(rawAttrsForMatcher);\n }\n\n // Hoist toString() once — path doesn't change during attribute processing\n const jPathStr = options.jPath ? jPath.toString() : this.readonlyMatcher;\n\n // Second pass: apply processors, build final attrs\n let hasAttrs = false;\n for (let i = 0; i < len; i++) {\n const attrName = this.resolveNameSpace(matches[i][1]);\n\n if (this.ignoreAttributesFn(attrName, jPathStr)) continue;\n\n let aName = options.attributeNamePrefix + attrName;\n\n if (attrName.length) {\n if (options.transformAttributeName) {\n aName = options.transformAttributeName(aName);\n }\n aName = sanitizeName(aName, options);\n\n if (matches[i][4] !== undefined) {\n // Reuse already-processed value — no double entity replacement\n const oldVal = processedVals[i];\n\n const newVal = options.attributeValueProcessor(attrName, oldVal, jPathStr);\n if (newVal === null || newVal === undefined) {\n attrs[aName] = oldVal;\n } else if (typeof newVal !== typeof oldVal || newVal !== oldVal) {\n attrs[aName] = newVal;\n } else {\n attrs[aName] = parseValue(oldVal, options.parseAttributeValue, options.numberParseOptions);\n }\n hasAttrs = true;\n } else if (options.allowBooleanAttributes) {\n attrs[aName] = true;\n hasAttrs = true;\n }\n }\n }\n\n if (!hasAttrs) return;\n\n if (options.attributesGroupName && !options.preserveOrder) {\n const attrCollection = {};\n attrCollection[options.attributesGroupName] = attrs;\n return attrCollection;\n }\n return attrs;\n }\n}\nconst parseXml = function (xmlData) {\n xmlData = xmlData.replace(/\\r\\n?/g, \"\\n\"); //TODO: remove this line\n const xmlObj = new xmlNode('!xml');\n let currentNode = xmlObj;\n let textData = \"\";\n\n // Reset matcher for new document\n this.matcher.reset();\n this.entityDecoder.reset();\n\n // Reset entity expansion counters for this document\n this.entityExpansionCount = 0;\n this.currentExpandedLength = 0;\n const options = this.options;\n const docTypeReader = new DocTypeReader(options.processEntities);\n const xmlLen = xmlData.length;\n for (let i = 0; i < xmlLen; i++) {//for each char in XML data\n const ch = xmlData[i];\n if (ch === '<') {\n // const nextIndex = i+1;\n // const _2ndChar = xmlData[nextIndex];\n const c1 = xmlData.charCodeAt(i + 1);\n if (c1 === 47) {//Closing Tag '/'\n const closeIndex = findClosingIndex(xmlData, \">\", i, \"Closing Tag is not closed.\")\n let tagName = xmlData.substring(i + 2, closeIndex).trim();\n\n if (options.removeNSPrefix) {\n const colonIndex = tagName.indexOf(\":\");\n if (colonIndex !== -1) {\n tagName = tagName.substr(colonIndex + 1);\n }\n }\n\n tagName = transformTagName(options.transformTagName, tagName, \"\", options).tagName;\n\n if (currentNode) {\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n }\n\n //check if last tag of nested tag was unpaired tag\n const lastTagName = this.matcher.getCurrentTag();\n if (tagName && options.unpairedTagsSet.has(tagName)) {\n throw new Error(`Unpaired tag can not be used as closing tag: `);\n }\n if (lastTagName && options.unpairedTagsSet.has(lastTagName)) {\n // Pop the unpaired tag\n this.matcher.pop();\n this.tagsNodeStack.pop();\n }\n // Pop the closing tag\n this.matcher.pop();\n this.isCurrentNodeStopNode = false; // Reset flag when closing tag\n\n currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope\n textData = \"\";\n i = closeIndex;\n } else if (c1 === 63) { //'?'\n\n let tagData = readTagExp(xmlData, i, false, \"?>\");\n if (!tagData) throw new Error(\"Pi Tag is not closed.\");\n\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n const attsMap = this.buildAttributesMap(tagData.tagExp, this.matcher, tagData.tagName, true);\n if (attsMap) {\n const ver = attsMap[this.options.attributeNamePrefix + \"version\"];\n this.entityDecoder.setXmlVersion(Number(ver) || 1.0);\n }\n if ((options.ignoreDeclaration && tagData.tagName === \"?xml\") || options.ignorePiTags) {\n //do nothing\n } else {\n\n const childNode = new xmlNode(tagData.tagName);\n childNode.add(options.textNodeName, \"\");\n\n if (tagData.tagName !== tagData.tagExp && tagData.attrExpPresent && options.ignoreAttributes !== true) {\n childNode[\":@\"] = attsMap\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, i);\n }\n\n\n i = tagData.closeIndex + 1;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 45\n && xmlData.charCodeAt(i + 3) === 45) { //'!--'\n const endIndex = findClosingIndex(xmlData, \"-->\", i + 4, \"Comment is not closed.\")\n if (options.commentPropName) {\n const comment = xmlData.substring(i + 4, endIndex - 2);\n\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n\n currentNode.add(options.commentPropName, [{ [options.textNodeName]: comment }]);\n }\n i = endIndex;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 68) { //'!D'\n const result = docTypeReader.readDocType(xmlData, i);\n this.entityDecoder.addInputEntities(result.entities);\n i = result.i;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 91) { // '!['\n const closeIndex = findClosingIndex(xmlData, \"]]>\", i, \"CDATA is not closed.\") - 2;\n const tagExp = xmlData.substring(i + 9, closeIndex);\n\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher);\n\n let val = this.parseTextData(tagExp, currentNode.tagname, this.readonlyMatcher, true, false, true, true);\n if (val == undefined) val = \"\";\n\n //cdata should be set even if it is 0 length string\n if (options.cdataPropName) {\n currentNode.add(options.cdataPropName, [{ [options.textNodeName]: tagExp }]);\n } else {\n currentNode.add(options.textNodeName, val);\n }\n\n i = closeIndex + 2;\n } else {//Opening tag\n let result = readTagExp(xmlData, i, options.removeNSPrefix);\n\n // Safety check: readTagExp can return undefined\n if (!result) {\n // Log context for debugging\n const context = xmlData.substring(Math.max(0, i - 50), Math.min(xmlLen, i + 50));\n throw new Error(`readTagExp returned undefined at position ${i}. Context: \"${context}\"`);\n }\n\n let tagName = result.tagName;\n const rawTagName = result.rawTagName;\n let tagExp = result.tagExp;\n let attrExpPresent = result.attrExpPresent;\n let closeIndex = result.closeIndex;\n\n ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));\n\n if (options.strictReservedNames &&\n (tagName === options.commentPropName\n || tagName === options.cdataPropName\n || tagName === options.textNodeName\n || tagName === options.attributesGroupName\n )) {\n throw new Error(`Invalid tag name: ${tagName}`);\n }\n\n //save text as child node\n if (currentNode && textData) {\n if (currentNode.tagname !== '!xml') {\n //when nested tag is found\n textData = this.saveTextToParentTag(textData, currentNode, this.readonlyMatcher, false);\n }\n }\n\n //check if last tag was unpaired tag\n const lastTag = currentNode;\n if (lastTag && options.unpairedTagsSet.has(lastTag.tagname)) {\n currentNode = this.tagsNodeStack.pop();\n this.matcher.pop();\n }\n\n // Clean up self-closing syntax BEFORE processing attributes\n // This is where tagExp gets the trailing / removed\n let isSelfClosing = false;\n if (tagExp.length > 0 && tagExp.lastIndexOf(\"/\") === tagExp.length - 1) {\n isSelfClosing = true;\n if (tagName[tagName.length - 1] === \"/\") {\n tagName = tagName.substr(0, tagName.length - 1);\n tagExp = tagName;\n } else {\n tagExp = tagExp.substr(0, tagExp.length - 1);\n }\n\n // Re-check attrExpPresent after cleaning\n attrExpPresent = (tagName !== tagExp);\n }\n\n // Now process attributes with CLEAN tagExp (no trailing /)\n let prefixedAttrs = null;\n let rawAttrs = {};\n let namespace = undefined;\n\n // Extract namespace from rawTagName\n namespace = extractNamespace(rawTagName);\n\n // Push tag to matcher FIRST (with empty attrs for now) so callbacks see correct path\n if (tagName !== xmlObj.tagname) {\n this.matcher.push(tagName, {}, namespace);\n }\n\n // Now build attributes - callbacks will see correct matcher state\n if (tagName !== tagExp && attrExpPresent) {\n // Build attributes (returns prefixed attributes for the tree)\n // Note: buildAttributesMap now internally updates the matcher with raw attributes\n prefixedAttrs = this.buildAttributesMap(tagExp, this.matcher, tagName);\n\n if (prefixedAttrs) {\n // Extract raw attributes (without prefix) for our use\n //TODO: seems a performance overhead\n rawAttrs = extractRawAttributes(prefixedAttrs, options);\n }\n }\n\n // Now check if this is a stop node (after attributes are set)\n if (tagName !== xmlObj.tagname) {\n this.isCurrentNodeStopNode = this.isItStopNode();\n }\n\n const startIndex = i;\n if (this.isCurrentNodeStopNode) {\n let tagContent = \"\";\n\n // For self-closing tags, content is empty\n if (isSelfClosing) {\n i = result.closeIndex;\n }\n //unpaired tag\n else if (options.unpairedTagsSet.has(tagName)) {\n i = result.closeIndex;\n }\n //normal tag\n else {\n //read until closing tag is found\n const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);\n if (!result) throw new Error(`Unexpected end of ${rawTagName}`);\n i = result.i;\n tagContent = result.tagContent;\n }\n\n const childNode = new xmlNode(tagName);\n\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n\n // For stop nodes, store raw content as-is without any processing\n childNode.add(options.textNodeName, tagContent);\n\n this.matcher.pop(); // Pop the stop node tag\n this.isCurrentNodeStopNode = false; // Reset flag\n\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n } else {\n //selfClosing tag\n if (isSelfClosing) {\n ({ tagName, tagExp } = transformTagName(options.transformTagName, tagName, tagExp, options));\n\n const childNode = new xmlNode(tagName);\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n this.matcher.pop(); // Pop self-closing tag\n this.isCurrentNodeStopNode = false; // Reset flag\n }\n else if (options.unpairedTagsSet.has(tagName)) {//unpaired tag\n const childNode = new xmlNode(tagName);\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n this.matcher.pop(); // Pop unpaired tag\n this.isCurrentNodeStopNode = false; // Reset flag\n i = result.closeIndex;\n // Continue to next iteration without changing currentNode\n continue;\n }\n //opening tag\n else {\n const childNode = new xmlNode(tagName);\n if (this.tagsNodeStack.length > options.maxNestedTags) {\n throw new Error(\"Maximum nested tags exceeded\");\n }\n this.tagsNodeStack.push(currentNode);\n\n if (prefixedAttrs) {\n childNode[\":@\"] = prefixedAttrs;\n }\n this.addChild(currentNode, childNode, this.readonlyMatcher, startIndex);\n currentNode = childNode;\n }\n textData = \"\";\n i = closeIndex;\n }\n }\n } else {\n textData += xmlData[i];\n }\n }\n return xmlObj.child;\n}\n\nfunction addChild(currentNode, childNode, matcher, startIndex) {\n // unset startIndex if not requested\n if (!this.options.captureMetaData) startIndex = undefined;\n\n // Pass jPath string or matcher based on options.jPath setting\n const jPathOrMatcher = this.options.jPath ? matcher.toString() : matcher;\n const result = this.options.updateTag(childNode.tagname, jPathOrMatcher, childNode[\":@\"])\n if (result === false) {\n //do nothing\n } else if (typeof result === \"string\") {\n childNode.tagname = result\n currentNode.addChild(childNode, startIndex);\n } else {\n currentNode.addChild(childNode, startIndex);\n }\n}\n\n/**\n * @param {object} val - Entity object with regex and val properties\n * @param {string} tagName - Tag name\n * @param {string|Matcher} jPath - jPath string or Matcher instance based on options.jPath\n */\nfunction replaceEntitiesValue(val, tagName, jPath) {\n const entityConfig = this.options.processEntities;\n\n if (!entityConfig || !entityConfig.enabled) {\n return val;\n }\n\n // Check if tag is allowed to contain entities\n if (entityConfig.allowedTags) {\n const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;\n const allowed = Array.isArray(entityConfig.allowedTags)\n ? entityConfig.allowedTags.includes(tagName)\n : entityConfig.allowedTags(tagName, jPathOrMatcher);\n\n if (!allowed) {\n return val;\n }\n }\n\n // Apply custom tag filter if provided\n if (entityConfig.tagFilter) {\n const jPathOrMatcher = this.options.jPath ? jPath.toString() : jPath;\n if (!entityConfig.tagFilter(tagName, jPathOrMatcher)) {\n return val; // Skip based on custom filter\n }\n }\n\n return this.entityDecoder.decode(val);\n}\n\n\nfunction saveTextToParentTag(textData, parentNode, matcher, isLeafNode) {\n if (textData) { //store previously collected data as textNode\n if (isLeafNode === undefined) isLeafNode = parentNode.child.length === 0\n\n textData = this.parseTextData(textData,\n parentNode.tagname,\n matcher,\n false,\n parentNode[\":@\"] ? Object.keys(parentNode[\":@\"]).length !== 0 : false,\n isLeafNode);\n\n if (textData !== undefined && textData !== \"\")\n parentNode.add(this.options.textNodeName, textData);\n textData = \"\";\n }\n return textData;\n}\n\n/**\n * @param {Array} stopNodeExpressions - Array of compiled Expression objects\n * @param {Matcher} matcher - Current path matcher\n */\nfunction isItStopNode() {\n if (this.stopNodeExpressionsSet.size === 0) return false;\n\n return this.matcher.matchesAny(this.stopNodeExpressionsSet);\n}\n\n/**\n * Returns the tag Expression and where it is ending handling single-double quotes situation\n * @param {string} xmlData \n * @param {number} i starting index\n * @returns \n */\nfunction tagExpWithClosingIndex(xmlData, i, closingChar = \">\") {\n //TODO: ignore boolean attributes in tag expression\n //TODO: if ignore attributes, dont read full attribute expression but the end. But read for xml declaration\n let attrBoundary = 0;\n const len = xmlData.length;\n const closeCode0 = closingChar.charCodeAt(0);\n const closeCode1 = closingChar.length > 1 ? closingChar.charCodeAt(1) : -1;\n\n let result = '';\n let segmentStart = i;\n\n for (let index = i; index < len; index++) {\n const code = xmlData.charCodeAt(index);\n\n if (attrBoundary) {\n if (code === attrBoundary) attrBoundary = 0;\n } else if (code === 34 || code === 39) { // \" or '\n attrBoundary = code;\n } else if (code === closeCode0) {\n if (closeCode1 !== -1) {\n if (xmlData.charCodeAt(index + 1) === closeCode1) {\n result += xmlData.substring(segmentStart, index);\n return { data: result, index };\n }\n } else {\n result += xmlData.substring(segmentStart, index);\n return { data: result, index };\n }\n } else if (code === 9 && !attrBoundary) { // \\t - only replace with space outside attribute values\n // Flush accumulated segment, add space, start new segment\n result += xmlData.substring(segmentStart, index) + ' ';\n segmentStart = index + 1;\n }\n }\n}\n\nfunction findClosingIndex(xmlData, str, i, errMsg) {\n const closingIndex = xmlData.indexOf(str, i);\n if (closingIndex === -1) {\n throw new Error(errMsg)\n } else {\n return closingIndex + str.length - 1;\n }\n}\n\nfunction findClosingChar(xmlData, char, i, errMsg) {\n const closingIndex = xmlData.indexOf(char, i);\n if (closingIndex === -1) throw new Error(errMsg);\n return closingIndex; // no offset needed\n}\n\nfunction readTagExp(xmlData, i, removeNSPrefix, closingChar = \">\") {\n const result = tagExpWithClosingIndex(xmlData, i + 1, closingChar);\n if (!result) return;\n let tagExp = result.data;\n const closeIndex = result.index;\n const separatorIndex = tagExp.search(/\\s/);\n let tagName = tagExp;\n let attrExpPresent = true;\n if (separatorIndex !== -1) {//separate tag name and attributes expression\n tagName = tagExp.substring(0, separatorIndex);\n tagExp = tagExp.substring(separatorIndex + 1).trimStart();\n }\n\n const rawTagName = tagName;\n if (removeNSPrefix) {\n const colonIndex = tagName.indexOf(\":\");\n if (colonIndex !== -1) {\n tagName = tagName.substr(colonIndex + 1);\n attrExpPresent = tagName !== result.data.substr(colonIndex + 1);\n }\n }\n\n return {\n tagName: tagName,\n tagExp: tagExp,\n closeIndex: closeIndex,\n attrExpPresent: attrExpPresent,\n rawTagName: rawTagName,\n }\n}\n/**\n * find paired tag for a stop node\n * @param {string} xmlData \n * @param {string} tagName \n * @param {number} i \n */\nfunction readStopNodeData(xmlData, tagName, i) {\n const startIndex = i;\n // Starting at 1 since we already have an open tag\n let openTagCount = 1;\n\n const xmllen = xmlData.length;\n for (; i < xmllen; i++) {\n if (xmlData[i] === \"<\") {\n const c1 = xmlData.charCodeAt(i + 1);\n if (c1 === 47) {//close tag '/'\n const closeIndex = findClosingChar(xmlData, \">\", i, `${tagName} is not closed`);\n let closeTagName = xmlData.substring(i + 2, closeIndex).trim();\n if (closeTagName === tagName) {\n openTagCount--;\n if (openTagCount === 0) {\n return {\n tagContent: xmlData.substring(startIndex, i),\n i: closeIndex\n }\n }\n }\n i = closeIndex;\n } else if (c1 === 63) { //?\n const closeIndex = findClosingIndex(xmlData, \"?>\", i + 1, \"StopNode is not closed.\")\n i = closeIndex;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 45\n && xmlData.charCodeAt(i + 3) === 45) { // '!--'\n const closeIndex = findClosingIndex(xmlData, \"-->\", i + 3, \"StopNode is not closed.\")\n i = closeIndex;\n } else if (c1 === 33\n && xmlData.charCodeAt(i + 2) === 91) { // '!['\n const closeIndex = findClosingIndex(xmlData, \"]]>\", i, \"StopNode is not closed.\") - 2;\n i = closeIndex;\n } else {\n const tagData = readTagExp(xmlData, i, '>')\n\n if (tagData) {\n const openTagName = tagData && tagData.tagName;\n if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length - 1] !== \"/\") {\n openTagCount++;\n }\n i = tagData.closeIndex;\n }\n }\n }\n }//end for loop\n}\n\nfunction parseValue(val, shouldParse, options) {\n if (shouldParse && typeof val === 'string') {\n //console.log(options)\n const newval = val.trim();\n if (newval === 'true') return true;\n else if (newval === 'false') return false;\n else return toNumber(val, options);\n } else {\n if (isExist(val)) {\n return val;\n } else {\n return '';\n }\n }\n}\n\nfunction fromCodePoint(str, base, prefix) {\n const codePoint = Number.parseInt(str, base);\n\n if (codePoint >= 0 && codePoint <= 0x10FFFF) {\n return String.fromCodePoint(codePoint);\n } else {\n return prefix + str + \";\";\n }\n}\n\nfunction transformTagName(fn, tagName, tagExp, options) {\n if (fn) {\n const newTagName = fn(tagName);\n if (tagExp === tagName) {\n tagExp = newTagName\n }\n tagName = newTagName;\n }\n tagName = sanitizeName(tagName, options);\n return { tagName, tagExp };\n}\n\n\n\nfunction sanitizeName(name, options) {\n if (criticalProperties.includes(name)) {\n throw new Error(`[SECURITY] Invalid name: \"${name}\" is a reserved JavaScript keyword that could cause prototype pollution`);\n } else if (DANGEROUS_PROPERTY_NAMES.includes(name)) {\n return options.onDangerousProperty(name);\n }\n return name;\n}","'use strict';\n\nimport XmlNode from './xmlNode.js';\nimport { Matcher } from 'path-expression-matcher';\n\nconst METADATA_SYMBOL = XmlNode.getMetaDataSymbol();\n\n/**\n * Helper function to strip attribute prefix from attribute map\n * @param {object} attrs - Attributes with prefix (e.g., {\"@_class\": \"code\"})\n * @param {string} prefix - Attribute prefix to remove (e.g., \"@_\")\n * @returns {object} Attributes without prefix (e.g., {\"class\": \"code\"})\n */\nfunction stripAttributePrefix(attrs, prefix) {\n if (!attrs || typeof attrs !== 'object') return {};\n if (!prefix) return attrs;\n\n const rawAttrs = {};\n for (const key in attrs) {\n if (key.startsWith(prefix)) {\n const rawName = key.substring(prefix.length);\n rawAttrs[rawName] = attrs[key];\n } else {\n // Attribute without prefix (shouldn't normally happen, but be safe)\n rawAttrs[key] = attrs[key];\n }\n }\n return rawAttrs;\n}\n\n/**\n * \n * @param {array} node \n * @param {any} options \n * @param {Matcher} matcher - Path matcher instance\n * @returns \n */\nexport default function prettify(node, options, matcher, readonlyMatcher) {\n return compress(node, options, matcher, readonlyMatcher);\n}\n\n/**\n * @param {array} arr \n * @param {object} options \n * @param {Matcher} matcher - Path matcher instance\n * @returns object\n */\nfunction compress(arr, options, matcher, readonlyMatcher) {\n let text;\n const compressedObj = {}; //This is intended to be a plain object\n for (let i = 0; i < arr.length; i++) {\n const tagObj = arr[i];\n const property = propName(tagObj);\n\n // Push current property to matcher WITH RAW ATTRIBUTES (no prefix)\n if (property !== undefined && property !== options.textNodeName) {\n const rawAttrs = stripAttributePrefix(\n tagObj[\":@\"] || {},\n options.attributeNamePrefix\n );\n matcher.push(property, rawAttrs);\n }\n\n if (property === options.textNodeName) {\n if (text === undefined) text = tagObj[property];\n else text += \"\" + tagObj[property];\n } else if (property === undefined) {\n continue;\n } else if (tagObj[property]) {\n\n let val = compress(tagObj[property], options, matcher, readonlyMatcher);\n const isLeaf = isLeafTag(val, options);\n\n if (tagObj[\":@\"]) {\n assignAttributes(val, tagObj[\":@\"], readonlyMatcher, options);\n } else if (Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode) {\n val = val[options.textNodeName];\n } else if (Object.keys(val).length === 0) {\n if (options.alwaysCreateTextNode) val[options.textNodeName] = \"\";\n else val = \"\";\n }\n\n if (tagObj[METADATA_SYMBOL] !== undefined && typeof val === \"object\" && val !== null) {\n val[METADATA_SYMBOL] = tagObj[METADATA_SYMBOL]; // copy over metadata\n }\n\n\n if (compressedObj[property] !== undefined && Object.prototype.hasOwnProperty.call(compressedObj, property)) {\n if (!Array.isArray(compressedObj[property])) {\n compressedObj[property] = [compressedObj[property]];\n }\n compressedObj[property].push(val);\n } else {\n //TODO: if a node is not an array, then check if it should be an array\n //also determine if it is a leaf node\n\n // Pass jPath string or readonlyMatcher based on options.jPath setting\n const jPathOrMatcher = options.jPath ? readonlyMatcher.toString() : readonlyMatcher;\n if (options.isArray(property, jPathOrMatcher, isLeaf)) {\n compressedObj[property] = [val];\n } else {\n compressedObj[property] = val;\n }\n }\n\n // Pop property from matcher after processing\n if (property !== undefined && property !== options.textNodeName) {\n matcher.pop();\n }\n }\n\n }\n // if(text && text.length > 0) compressedObj[options.textNodeName] = text;\n if (typeof text === \"string\") {\n if (text.length > 0) compressedObj[options.textNodeName] = text;\n } else if (text !== undefined) compressedObj[options.textNodeName] = text;\n\n\n return compressedObj;\n}\n\nfunction propName(obj) {\n const keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if (key !== \":@\") return key;\n }\n}\n\nfunction assignAttributes(obj, attrMap, readonlyMatcher, options) {\n if (attrMap) {\n const keys = Object.keys(attrMap);\n const len = keys.length; //don't make it inline\n for (let i = 0; i < len; i++) {\n const atrrName = keys[i]; // This is the PREFIXED name (e.g., \"@_class\")\n\n // Strip prefix for matcher path (for isArray callback)\n const rawAttrName = atrrName.startsWith(options.attributeNamePrefix)\n ? atrrName.substring(options.attributeNamePrefix.length)\n : atrrName;\n\n // For attributes, we need to create a temporary path\n // Pass jPath string or matcher based on options.jPath setting\n const jPathOrMatcher = options.jPath\n ? readonlyMatcher.toString() + \".\" + rawAttrName\n : readonlyMatcher;\n\n if (options.isArray(atrrName, jPathOrMatcher, true, true)) {\n obj[atrrName] = [attrMap[atrrName]];\n } else {\n obj[atrrName] = attrMap[atrrName];\n }\n }\n }\n}\n\nfunction isLeafTag(obj, options) {\n const { textNodeName } = options;\n const propCount = Object.keys(obj).length;\n\n if (propCount === 0) {\n return true;\n }\n\n if (\n propCount === 1 &&\n (obj[textNodeName] || typeof obj[textNodeName] === \"boolean\" || obj[textNodeName] === 0)\n ) {\n return true;\n }\n\n return false;\n}","import { buildOptions } from './OptionsBuilder.js';\nimport OrderedObjParser from './OrderedObjParser.js';\nimport prettify from './node2json.js';\nimport { validate } from \"../validator.js\";\nimport XmlNode from './xmlNode.js';\n\nexport default class XMLParser {\n\n constructor(options) {\n this.externalEntities = {};\n this.options = buildOptions(options);\n\n }\n /**\n * Parse XML dats to JS object \n * @param {string|Uint8Array} xmlData \n * @param {boolean|Object} validationOption \n */\n parse(xmlData, validationOption) {\n if (typeof xmlData !== \"string\" && xmlData.toString) {\n xmlData = xmlData.toString();\n } else if (typeof xmlData !== \"string\") {\n throw new Error(\"XML data is accepted in String or Bytes[] form.\")\n }\n\n if (validationOption) {\n if (validationOption === true) validationOption = {}; //validate with default options\n\n const result = validate(xmlData, validationOption);\n if (result !== true) {\n throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`)\n }\n }\n const orderedObjParser = new OrderedObjParser(this.options, this.externalEntities);\n // orderedObjParser.entityDecoder.setExternalEntities(this.externalEntities);\n const orderedResult = orderedObjParser.parseXml(xmlData);\n if (this.options.preserveOrder || orderedResult === undefined) return orderedResult;\n else return prettify(orderedResult, this.options, orderedObjParser.matcher, orderedObjParser.readonlyMatcher);\n }\n\n /**\n * Add Entity which is not by default supported by this library\n * @param {string} key \n * @param {string} value \n */\n addEntity(key, value) {\n if (value.indexOf(\"&\") !== -1) {\n throw new Error(\"Entity value can't have '&'\")\n } else if (key.indexOf(\"&\") !== -1 || key.indexOf(\";\") !== -1) {\n throw new Error(\"An entity must be set without '&' and ';'. Eg. use '#xD' for ' '\")\n } else if (value === \"&\") {\n throw new Error(\"An entity with value '&' is not permitted\");\n } else {\n this.externalEntities[key] = value;\n }\n }\n\n /**\n * Returns a Symbol that can be used to access the metadata\n * property on a node.\n * \n * If Symbol is not available in the environment, an ordinary property is used\n * and the name of the property is here returned.\n * \n * The XMLMetaData property is only present when `captureMetaData`\n * is true in the options.\n */\n static getMetaDataSymbol() {\n return XmlNode.getMetaDataSymbol();\n }\n}","import { Expression, Matcher } from 'path-expression-matcher';\n\nconst EOL = \"\\n\";\n\n/**\n * \n * @param {array} jArray \n * @param {any} options \n * @returns \n */\nexport default function toXml(jArray, options) {\n let indentation = \"\";\n if (options.format && options.indentBy.length > 0) {\n indentation = EOL;\n }\n\n // Pre-compile stopNode expressions for pattern matching\n const stopNodeExpressions = [];\n if (options.stopNodes && Array.isArray(options.stopNodes)) {\n for (let i = 0; i < options.stopNodes.length; i++) {\n const node = options.stopNodes[i];\n if (typeof node === 'string') {\n stopNodeExpressions.push(new Expression(node));\n } else if (node instanceof Expression) {\n stopNodeExpressions.push(node);\n }\n }\n }\n\n // Initialize matcher for path tracking\n const matcher = new Matcher();\n\n return arrToStr(jArray, options, indentation, matcher, stopNodeExpressions);\n}\n\nfunction arrToStr(arr, options, indentation, matcher, stopNodeExpressions) {\n let xmlStr = \"\";\n let isPreviousElementTag = false;\n\n if (options.maxNestedTags && matcher.getDepth() > options.maxNestedTags) {\n throw new Error(\"Maximum nested tags exceeded\");\n }\n\n if (!Array.isArray(arr)) {\n // Non-array values (e.g. string tag values) should be treated as text content\n if (arr !== undefined && arr !== null) {\n let text = arr.toString();\n text = replaceEntitiesValue(text, options);\n return text;\n }\n return \"\";\n }\n\n for (let i = 0; i < arr.length; i++) {\n const tagObj = arr[i];\n const tagName = propName(tagObj);\n if (tagName === undefined) continue;\n\n // Extract attributes from \":@\" property\n const attrValues = extractAttributeValues(tagObj[\":@\"], options);\n\n // Push tag to matcher WITH attributes\n matcher.push(tagName, attrValues);\n\n // Check if this is a stop node using Expression matching\n const isStopNode = checkStopNode(matcher, stopNodeExpressions);\n\n if (tagName === options.textNodeName) {\n let tagText = tagObj[tagName];\n if (!isStopNode) {\n tagText = options.tagValueProcessor(tagName, tagText);\n tagText = replaceEntitiesValue(tagText, options);\n }\n if (isPreviousElementTag) {\n xmlStr += indentation;\n }\n xmlStr += tagText;\n isPreviousElementTag = false;\n matcher.pop();\n continue;\n } else if (tagName === options.cdataPropName) {\n if (isPreviousElementTag) {\n xmlStr += indentation;\n }\n const val = tagObj[tagName][0][options.textNodeName];\n const safeVal = String(val).replace(/\\]\\]>/g, ']]]]>');\n xmlStr += ``;\n isPreviousElementTag = false;\n matcher.pop();\n continue;\n } else if (tagName === options.commentPropName) {\n const val = tagObj[tagName][0][options.textNodeName]\n const safeVal = String(val)\n .replace(/--/g, '- -') // -- is illegal anywhere in comment content\n .replace(/-$/, '- '); // trailing - would form -- with the closing -->\n xmlStr += indentation + ``;\n isPreviousElementTag = true;\n matcher.pop();\n continue;\n } else if (tagName[0] === \"?\") {\n const attStr = attr_to_str(tagObj[\":@\"], options, isStopNode);\n const tempInd = tagName === \"?xml\" ? \"\" : indentation;\n let piTextNodeName = tagObj[tagName][0][options.textNodeName];\n piTextNodeName = piTextNodeName.length !== 0 ? \" \" + piTextNodeName : \"\"; //remove extra spacing\n xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`;\n isPreviousElementTag = true;\n matcher.pop();\n continue;\n }\n\n let newIdentation = indentation;\n if (newIdentation !== \"\") {\n newIdentation += options.indentBy;\n }\n\n // Pass isStopNode to attr_to_str so attributes are also not processed for stopNodes\n const attStr = attr_to_str(tagObj[\":@\"], options, isStopNode);\n const tagStart = indentation + `<${tagName}${attStr}`;\n\n // If this is a stopNode, get raw content without processing\n let tagValue;\n if (isStopNode) {\n tagValue = getRawContent(tagObj[tagName], options);\n } else {\n\n tagValue = arrToStr(tagObj[tagName], options, newIdentation, matcher, stopNodeExpressions);\n }\n\n if (options.unpairedTags.indexOf(tagName) !== -1) {\n if (options.suppressUnpairedNode) xmlStr += tagStart + \">\";\n else xmlStr += tagStart + \"/>\";\n } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {\n xmlStr += tagStart + \"/>\";\n } else if (tagValue && tagValue.endsWith(\">\")) {\n xmlStr += tagStart + `>${tagValue}${indentation}`;\n } else {\n xmlStr += tagStart + \">\";\n if (tagValue && indentation !== \"\" && (tagValue.includes(\"/>\") || tagValue.includes(\"`;\n }\n isPreviousElementTag = true;\n\n // Pop tag from matcher\n matcher.pop();\n }\n\n return xmlStr;\n}\n\n/**\n * Extract attribute values from the \":@\" object and return as plain object\n * for passing to matcher.push()\n */\nfunction extractAttributeValues(attrMap, options) {\n if (!attrMap || options.ignoreAttributes) return null;\n\n const attrValues = {};\n let hasAttrs = false;\n\n for (let attr in attrMap) {\n if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;\n // Remove the attribute prefix to get clean attribute name\n const cleanAttrName = attr.startsWith(options.attributeNamePrefix)\n ? attr.substr(options.attributeNamePrefix.length)\n : attr;\n attrValues[cleanAttrName] = attrMap[attr];\n hasAttrs = true;\n }\n\n return hasAttrs ? attrValues : null;\n}\n\n/**\n * Extract raw content from a stopNode without any processing\n * This preserves the content exactly as-is, including special characters\n */\nfunction getRawContent(arr, options) {\n if (!Array.isArray(arr)) {\n // Non-array values return as-is\n if (arr !== undefined && arr !== null) {\n return arr.toString();\n }\n return \"\";\n }\n\n let content = \"\";\n for (let i = 0; i < arr.length; i++) {\n const item = arr[i];\n const tagName = propName(item);\n\n if (tagName === options.textNodeName) {\n // Raw text content - NO processing, NO entity replacement\n content += item[tagName];\n } else if (tagName === options.cdataPropName) {\n // CDATA content\n content += item[tagName][0][options.textNodeName];\n } else if (tagName === options.commentPropName) {\n // Comment content\n content += item[tagName][0][options.textNodeName];\n } else if (tagName && tagName[0] === \"?\") {\n // Processing instruction - skip for stopNodes\n continue;\n } else if (tagName) {\n // Nested tags within stopNode\n // Recursively get raw content and reconstruct the tag\n // For stopNodes, we don't process attributes either\n const attStr = attr_to_str_raw(item[\":@\"], options);\n const nestedContent = getRawContent(item[tagName], options);\n\n if (!nestedContent || nestedContent.length === 0) {\n content += `<${tagName}${attStr}/>`;\n } else {\n content += `<${tagName}${attStr}>${nestedContent}`;\n }\n }\n }\n return content;\n}\n\n/**\n * Build attribute string for stopNodes - NO entity replacement\n */\nfunction attr_to_str_raw(attrMap, options) {\n let attrStr = \"\";\n if (attrMap && !options.ignoreAttributes) {\n for (let attr in attrMap) {\n if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;\n // For stopNodes, use raw value without processing\n let attrVal = attrMap[attr];\n if (attrVal === true && options.suppressBooleanAttributes) {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;\n } else {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}=\"${attrVal}\"`;\n }\n }\n }\n return attrStr;\n}\n\nfunction propName(obj) {\n const keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;\n if (key !== \":@\") return key;\n }\n}\n\nfunction attr_to_str(attrMap, options, isStopNode) {\n let attrStr = \"\";\n if (attrMap && !options.ignoreAttributes) {\n for (let attr in attrMap) {\n if (!Object.prototype.hasOwnProperty.call(attrMap, attr)) continue;\n let attrVal;\n\n if (isStopNode) {\n // For stopNodes, use raw value without any processing\n attrVal = attrMap[attr];\n } else {\n // Normal processing: apply attributeValueProcessor and entity replacement\n attrVal = options.attributeValueProcessor(attr, attrMap[attr]);\n attrVal = replaceEntitiesValue(attrVal, options);\n }\n\n if (attrVal === true && options.suppressBooleanAttributes) {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;\n } else {\n attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}=\"${attrVal}\"`;\n }\n }\n }\n return attrStr;\n}\n\nfunction checkStopNode(matcher, stopNodeExpressions) {\n if (!stopNodeExpressions || stopNodeExpressions.length === 0) return false;\n\n for (let i = 0; i < stopNodeExpressions.length; i++) {\n if (matcher.matches(stopNodeExpressions[i])) {\n return true;\n }\n }\n return false;\n}\n\nfunction replaceEntitiesValue(textValue, options) {\n if (textValue && textValue.length > 0 && options.processEntities) {\n for (let i = 0; i < options.entities.length; i++) {\n const entity = options.entities[i];\n textValue = textValue.replace(entity.regex, entity.val);\n }\n }\n return textValue;\n}\n\nfunction cdataVal(val) {\n\n}\n\nfunction commentVal(val) {\n\n}","export default function getIgnoreAttributesFn(ignoreAttributes) {\n if (typeof ignoreAttributes === 'function') {\n return ignoreAttributes\n }\n if (Array.isArray(ignoreAttributes)) {\n return (attrName) => {\n for (const pattern of ignoreAttributes) {\n if (typeof pattern === 'string' && attrName === pattern) {\n return true\n }\n if (pattern instanceof RegExp && pattern.test(attrName)) {\n return true\n }\n }\n }\n }\n return () => false\n}","'use strict';\n//parse Empty Node as self closing node\nimport buildFromOrderedJs from './orderedJs2Xml.js';\nimport getIgnoreAttributesFn from \"./ignoreAttributes.js\";\nimport { Expression, Matcher } from 'path-expression-matcher';\n\nconst defaultOptions = {\n attributeNamePrefix: '@_',\n attributesGroupName: false,\n textNodeName: '#text',\n ignoreAttributes: true,\n cdataPropName: false,\n format: false,\n indentBy: ' ',\n suppressEmptyNode: false,\n suppressUnpairedNode: true,\n suppressBooleanAttributes: true,\n tagValueProcessor: function (key, a) {\n return a;\n },\n attributeValueProcessor: function (attrName, a) {\n return a;\n },\n preserveOrder: false,\n commentPropName: false,\n unpairedTags: [],\n entities: [\n { regex: new RegExp(\"&\", \"g\"), val: \"&\" },//it must be on top\n { regex: new RegExp(\">\", \"g\"), val: \">\" },\n { regex: new RegExp(\"<\", \"g\"), val: \"<\" },\n { regex: new RegExp(\"\\'\", \"g\"), val: \"'\" },\n { regex: new RegExp(\"\\\"\", \"g\"), val: \""\" }\n ],\n processEntities: true,\n stopNodes: [],\n // transformTagName: false,\n // transformAttributeName: false,\n oneListGroup: false,\n maxNestedTags: 100,\n jPath: true // When true, callbacks receive string jPath; when false, receive Matcher instance\n};\n\nexport default function Builder(options) {\n this.options = Object.assign({}, defaultOptions, options);\n\n // Convert old-style stopNodes for backward compatibility\n // Old syntax: \"*.tag\" meant \"tag anywhere in tree\"\n // New syntax: \"..tag\" means \"tag anywhere in tree\"\n if (this.options.stopNodes && Array.isArray(this.options.stopNodes)) {\n this.options.stopNodes = this.options.stopNodes.map(node => {\n if (typeof node === 'string' && node.startsWith('*.')) {\n // Convert old wildcard syntax to deep wildcard\n return '..' + node.substring(2);\n }\n return node;\n });\n }\n\n // Pre-compile stopNode expressions for pattern matching\n this.stopNodeExpressions = [];\n if (this.options.stopNodes && Array.isArray(this.options.stopNodes)) {\n for (let i = 0; i < this.options.stopNodes.length; i++) {\n const node = this.options.stopNodes[i];\n if (typeof node === 'string') {\n this.stopNodeExpressions.push(new Expression(node));\n } else if (node instanceof Expression) {\n this.stopNodeExpressions.push(node);\n }\n }\n }\n\n if (this.options.ignoreAttributes === true || this.options.attributesGroupName) {\n this.isAttribute = function (/*a*/) {\n return false;\n };\n } else {\n this.ignoreAttributesFn = getIgnoreAttributesFn(this.options.ignoreAttributes)\n this.attrPrefixLen = this.options.attributeNamePrefix.length;\n this.isAttribute = isAttribute;\n }\n\n this.processTextOrObjNode = processTextOrObjNode\n\n if (this.options.format) {\n this.indentate = indentate;\n this.tagEndChar = '>\\n';\n this.newLine = '\\n';\n } else {\n this.indentate = function () {\n return '';\n };\n this.tagEndChar = '>';\n this.newLine = '';\n }\n}\n\nBuilder.prototype.build = function (jObj) {\n if (this.options.preserveOrder) {\n return buildFromOrderedJs(jObj, this.options);\n } else {\n if (Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1) {\n jObj = {\n [this.options.arrayNodeName]: jObj\n }\n }\n // Initialize matcher for path tracking\n const matcher = new Matcher();\n return this.j2x(jObj, 0, matcher).val;\n }\n};\n\nBuilder.prototype.j2x = function (jObj, level, matcher) {\n let attrStr = '';\n let val = '';\n if (this.options.maxNestedTags && matcher.getDepth() >= this.options.maxNestedTags) {\n throw new Error(\"Maximum nested tags exceeded\");\n }\n // Get jPath based on option: string for backward compatibility, or Matcher for new features\n const jPath = this.options.jPath ? matcher.toString() : matcher;\n\n // Check if current node is a stopNode (will be used for attribute encoding)\n const isCurrentStopNode = this.checkStopNode(matcher);\n\n for (let key in jObj) {\n if (!Object.prototype.hasOwnProperty.call(jObj, key)) continue;\n if (typeof jObj[key] === 'undefined') {\n // supress undefined node only if it is not an attribute\n if (this.isAttribute(key)) {\n val += '';\n }\n } else if (jObj[key] === null) {\n // null attribute should be ignored by the attribute list, but should not cause the tag closing\n if (this.isAttribute(key)) {\n val += '';\n } else if (key === this.options.cdataPropName) {\n val += '';\n } else if (key[0] === '?') {\n val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;\n } else {\n val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;\n }\n // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;\n } else if (jObj[key] instanceof Date) {\n val += this.buildTextValNode(jObj[key], key, '', level, matcher);\n } else if (typeof jObj[key] !== 'object') {\n //premitive type\n const attr = this.isAttribute(key);\n if (attr && !this.ignoreAttributesFn(attr, jPath)) {\n attrStr += this.buildAttrPairStr(attr, '' + jObj[key], isCurrentStopNode);\n } else if (!attr) {\n //tag value\n if (key === this.options.textNodeName) {\n let newval = this.options.tagValueProcessor(key, '' + jObj[key]);\n val += this.replaceEntitiesValue(newval);\n } else {\n // Check if this is a stopNode before building\n matcher.push(key);\n const isStopNode = this.checkStopNode(matcher);\n matcher.pop();\n\n if (isStopNode) {\n // Build as raw content without encoding\n const textValue = '' + jObj[key];\n if (textValue === '') {\n val += this.indentate(level) + '<' + key + this.closeTag(key) + this.tagEndChar;\n } else {\n val += this.indentate(level) + '<' + key + '>' + textValue + '' + textValue + '${item}`;\n } else if (typeof item === 'object' && item !== null) {\n const nestedContent = this.buildRawContent(item);\n const nestedAttrs = this.buildAttributesForStopNode(item);\n if (nestedContent === '') {\n content += `<${key}${nestedAttrs}/>`;\n } else {\n content += `<${key}${nestedAttrs}>${nestedContent}`;\n }\n }\n }\n } else if (typeof value === 'object' && value !== null) {\n // Nested object\n const nestedContent = this.buildRawContent(value);\n const nestedAttrs = this.buildAttributesForStopNode(value);\n if (nestedContent === '') {\n content += `<${key}${nestedAttrs}/>`;\n } else {\n content += `<${key}${nestedAttrs}>${nestedContent}`;\n }\n } else {\n // Primitive value\n content += `<${key}>${value}`;\n }\n }\n\n return content;\n};\n\n// Build attribute string for stopNode (no entity encoding)\nBuilder.prototype.buildAttributesForStopNode = function (obj) {\n if (!obj || typeof obj !== 'object') return '';\n\n let attrStr = '';\n\n // Check for attributesGroupName (when attributes are grouped)\n if (this.options.attributesGroupName && obj[this.options.attributesGroupName]) {\n const attrGroup = obj[this.options.attributesGroupName];\n for (let attrKey in attrGroup) {\n if (!Object.prototype.hasOwnProperty.call(attrGroup, attrKey)) continue;\n const cleanKey = attrKey.startsWith(this.options.attributeNamePrefix)\n ? attrKey.substring(this.options.attributeNamePrefix.length)\n : attrKey;\n const val = attrGroup[attrKey];\n if (val === true && this.options.suppressBooleanAttributes) {\n attrStr += ' ' + cleanKey;\n } else {\n attrStr += ' ' + cleanKey + '=\"' + val + '\"'; // No encoding for stopNode\n }\n }\n } else {\n // Look for individual attributes\n for (let key in obj) {\n if (!Object.prototype.hasOwnProperty.call(obj, key)) continue;\n const attr = this.isAttribute(key);\n if (attr) {\n const val = obj[key];\n if (val === true && this.options.suppressBooleanAttributes) {\n attrStr += ' ' + attr;\n } else {\n attrStr += ' ' + attr + '=\"' + val + '\"'; // No encoding for stopNode\n }\n }\n }\n }\n\n return attrStr;\n};\n\nBuilder.prototype.buildObjectNode = function (val, key, attrStr, level) {\n if (val === \"\") {\n if (key[0] === \"?\") return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;\n else {\n return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;\n }\n } else {\n\n let tagEndExp = '' + val + tagEndExp);\n } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {\n return this.indentate(level) + `` + this.newLine;\n } else {\n return (\n this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar +\n val +\n this.indentate(level) + tagEndExp);\n }\n }\n}\n\nBuilder.prototype.closeTag = function (key) {\n let closeTag = \"\";\n if (this.options.unpairedTags.indexOf(key) !== -1) { //unpaired\n if (!this.options.suppressUnpairedNode) closeTag = \"/\"\n } else if (this.options.suppressEmptyNode) { //empty\n closeTag = \"/\";\n } else {\n closeTag = `>/g, ']]]]>');\n return this.indentate(level) + `` + this.newLine;\n } else if (this.options.commentPropName !== false && key === this.options.commentPropName) {\n const safeVal = String(val)\n .replace(/--/g, '- -') // -- is illegal anywhere in comment content\n .replace(/-$/, '- '); // trailing - would form -- with the closing -->\n return this.indentate(level) + `` + this.newLine;\n } else if (key[0] === \"?\") {//PI tag\n return this.indentate(level) + '<' + key + attrStr + '?' + this.tagEndChar;\n } else {\n // Normal processing: apply tagValueProcessor and entity replacement\n let textValue = this.options.tagValueProcessor(key, val);\n textValue = this.replaceEntitiesValue(textValue);\n\n if (textValue === '') {\n return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;\n } else {\n return this.indentate(level) + '<' + key + attrStr + '>' +\n textValue +\n ' 0 && this.options.processEntities) {\n for (let i = 0; i < this.options.entities.length; i++) {\n const entity = this.options.entities[i];\n textValue = textValue.replace(entity.regex, entity.val);\n }\n }\n return textValue;\n}\n\nfunction indentate(level) {\n return this.options.indentBy.repeat(level);\n}\n\nfunction isAttribute(name /*, options*/) {\n if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) {\n return name.substr(this.attrPrefixLen);\n } else {\n return false;\n }\n}","// Re-export from fast-xml-builder for backward compatibility\nimport XMLBuilder from 'fast-xml-builder';\nexport default XMLBuilder;\n\n// If there are any named exports you also want to re-export:\nexport * from 'fast-xml-builder';","'use strict';\n\nimport { validate } from './validator.js';\nimport XMLParser from './xmlparser/XMLParser.js';\nimport XMLBuilder from './xmlbuilder/json2xml.js';\n\nconst XMLValidator = {\n validate: validate\n}\nexport {\n XMLParser,\n XMLValidator,\n XMLBuilder\n};","const isWindows = typeof process === 'object' &&\n process &&\n process.platform === 'win32'\nmodule.exports = isWindows ? { sep: '\\\\' } : { sep: '/' }\n","'use strict';\nmodule.exports = balanced;\nfunction balanced(a, b, str) {\n if (a instanceof RegExp) a = maybeMatch(a, str);\n if (b instanceof RegExp) b = maybeMatch(b, str);\n\n var r = range(a, b, str);\n\n return r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + a.length, r[1]),\n post: str.slice(r[1] + b.length)\n };\n}\n\nfunction maybeMatch(reg, str) {\n var m = str.match(reg);\n return m ? m[0] : null;\n}\n\nbalanced.range = range;\nfunction range(a, b, str) {\n var begs, beg, left, right, result;\n var ai = str.indexOf(a);\n var bi = str.indexOf(b, ai + 1);\n var i = ai;\n\n if (ai >= 0 && bi > 0) {\n if(a===b) {\n return [ai, bi];\n }\n begs = [];\n left = str.length;\n\n while (i >= 0 && !result) {\n if (i == ai) {\n begs.push(i);\n ai = str.indexOf(a, i + 1);\n } else if (begs.length == 1) {\n result = [ begs.pop(), bi ];\n } else {\n beg = begs.pop();\n if (beg < left) {\n left = beg;\n right = bi;\n }\n\n bi = str.indexOf(b, i + 1);\n }\n\n i = ai < bi && ai >= 0 ? ai : bi;\n }\n\n if (begs.length) {\n result = [ left, right ];\n }\n }\n\n return result;\n}\n","var balanced = require('balanced-match');\n\nmodule.exports = expandTop;\n\nvar escSlash = '\\0SLASH'+Math.random()+'\\0';\nvar escOpen = '\\0OPEN'+Math.random()+'\\0';\nvar escClose = '\\0CLOSE'+Math.random()+'\\0';\nvar escComma = '\\0COMMA'+Math.random()+'\\0';\nvar escPeriod = '\\0PERIOD'+Math.random()+'\\0';\n\nfunction numeric(str) {\n return parseInt(str, 10) == str\n ? parseInt(str, 10)\n : str.charCodeAt(0);\n}\n\nfunction escapeBraces(str) {\n return str.split('\\\\\\\\').join(escSlash)\n .split('\\\\{').join(escOpen)\n .split('\\\\}').join(escClose)\n .split('\\\\,').join(escComma)\n .split('\\\\.').join(escPeriod);\n}\n\nfunction unescapeBraces(str) {\n return str.split(escSlash).join('\\\\')\n .split(escOpen).join('{')\n .split(escClose).join('}')\n .split(escComma).join(',')\n .split(escPeriod).join('.');\n}\n\n\n// Basically just str.split(\",\"), but handling cases\n// where we have nested braced sections, which should be\n// treated as individual members, like {a,{b,c},d}\nfunction parseCommaParts(str) {\n if (!str)\n return [''];\n\n var parts = [];\n var m = balanced('{', '}', str);\n\n if (!m)\n return str.split(',');\n\n var pre = m.pre;\n var body = m.body;\n var post = m.post;\n var p = pre.split(',');\n\n p[p.length-1] += '{' + body + '}';\n var postParts = parseCommaParts(post);\n if (post.length) {\n p[p.length-1] += postParts.shift();\n p.push.apply(p, postParts);\n }\n\n parts.push.apply(parts, p);\n\n return parts;\n}\n\nfunction expandTop(str, options) {\n if (!str)\n return [];\n\n options = options || {};\n var max = options.max == null ? Infinity : options.max;\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.substr(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.substr(2);\n }\n\n return expand(escapeBraces(str), max, true).map(unescapeBraces);\n}\n\nfunction embrace(str) {\n return '{' + str + '}';\n}\nfunction isPadded(el) {\n return /^-?0\\d/.test(el);\n}\n\nfunction lte(i, y) {\n return i <= y;\n}\nfunction gte(i, y) {\n return i >= y;\n}\n\nfunction expand(str, max, isTop) {\n var expansions = [];\n\n var m = balanced('{', '}', str);\n if (!m) return [str];\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n var pre = m.pre;\n var post = m.post.length\n ? expand(m.post, max, false)\n : [''];\n\n if (/\\$$/.test(m.pre)) { \n for (var k = 0; k < post.length && k < max; k++) {\n var expansion = pre+ '{' + m.body + '}' + post[k];\n expansions.push(expansion);\n }\n } else {\n var isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body);\n var isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(m.body);\n var isSequence = isNumericSequence || isAlphaSequence;\n var isOptions = m.body.indexOf(',') >= 0;\n if (!isSequence && !isOptions) {\n // {a},b}\n if (m.post.match(/,(?!,).*\\}/)) {\n str = m.pre + '{' + m.body + escClose + m.post;\n return expand(str, max, true);\n }\n return [str];\n }\n\n var n;\n if (isSequence) {\n n = m.body.split(/\\.\\./);\n } else {\n n = parseCommaParts(m.body);\n if (n.length === 1) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand(n[0], max, false).map(embrace);\n if (n.length === 1) {\n return post.map(function(p) {\n return m.pre + n[0] + p;\n });\n }\n }\n }\n\n // at this point, n is the parts, and we know it's not a comma set\n // with a single entry.\n var N;\n\n if (isSequence) {\n var x = numeric(n[0]);\n var y = numeric(n[1]);\n var width = Math.max(n[0].length, n[1].length)\n var incr = n.length == 3\n ? Math.max(Math.abs(numeric(n[2])), 1)\n : 1;\n var test = lte;\n var reverse = y < x;\n if (reverse) {\n incr *= -1;\n test = gte;\n }\n var pad = n.some(isPadded);\n\n N = [];\n\n for (var i = x; test(i, y); i += incr) {\n var c;\n if (isAlphaSequence) {\n c = String.fromCharCode(i);\n if (c === '\\\\')\n c = '';\n } else {\n c = String(i);\n if (pad) {\n var need = width - c.length;\n if (need > 0) {\n var z = new Array(need + 1).join('0');\n if (i < 0)\n c = '-' + z + c.slice(1);\n else\n c = z + c;\n }\n }\n }\n N.push(c);\n }\n } else {\n N = [];\n\n for (var j = 0; j < n.length; j++) {\n N.push.apply(N, expand(n[j], max, false));\n }\n }\n\n for (var j = 0; j < N.length; j++) {\n for (var k = 0; k < post.length && expansions.length < max; k++) {\n var expansion = pre + N[j] + post[k];\n if (!isTop || isSequence || expansion)\n expansions.push(expansion);\n }\n }\n }\n\n return expansions;\n}\n","const minimatch = module.exports = (p, pattern, options = {}) => {\n assertValidPattern(pattern)\n\n // shortcut: comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n return false\n }\n\n return new Minimatch(pattern, options).match(p)\n}\n\nmodule.exports = minimatch\n\nconst path = require('./lib/path.js')\nminimatch.sep = path.sep\n\nconst GLOBSTAR = Symbol('globstar **')\nminimatch.GLOBSTAR = GLOBSTAR\nconst expand = require('brace-expansion')\n\nconst plTypes = {\n '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},\n '?': { open: '(?:', close: ')?' },\n '+': { open: '(?:', close: ')+' },\n '*': { open: '(?:', close: ')*' },\n '@': { open: '(?:', close: ')' }\n}\n\n// any single thing other than /\n// don't need to escape / when using new RegExp()\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n\n// ** when dots are allowed. Anything goes, except .. and .\n// not (^ or / followed by one or two dots followed by $ or /),\n// followed by anything, any number of times.\nconst twoStarDot = '(?:(?!(?:\\\\\\/|^)(?:\\\\.{1,2})($|\\\\\\/)).)*?'\n\n// not a ^ or / followed by a dot,\n// followed by anything, any number of times.\nconst twoStarNoDot = '(?:(?!(?:\\\\\\/|^)\\\\.).)*?'\n\n// \"abc\" -> { a:true, b:true, c:true }\nconst charSet = s => s.split('').reduce((set, c) => {\n set[c] = true\n return set\n}, {})\n\n// characters that need to be escaped in RegExp.\nconst reSpecials = charSet('().*{}+?[]^$\\\\!')\n\n// characters that indicate we have to add the pattern start\nconst addPatternStartSet = charSet('[.(')\n\n// normalizes slashes.\nconst slashSplit = /\\/+/\n\nminimatch.filter = (pattern, options = {}) =>\n (p, i, list) => minimatch(p, pattern, options)\n\nconst ext = (a, b = {}) => {\n const t = {}\n Object.keys(a).forEach(k => t[k] = a[k])\n Object.keys(b).forEach(k => t[k] = b[k])\n return t\n}\n\nminimatch.defaults = def => {\n if (!def || typeof def !== 'object' || !Object.keys(def).length) {\n return minimatch\n }\n\n const orig = minimatch\n\n const m = (p, pattern, options) => orig(p, pattern, ext(def, options))\n m.Minimatch = class Minimatch extends orig.Minimatch {\n constructor (pattern, options) {\n super(pattern, ext(def, options))\n }\n }\n m.Minimatch.defaults = options => orig.defaults(ext(def, options)).Minimatch\n m.filter = (pattern, options) => orig.filter(pattern, ext(def, options))\n m.defaults = options => orig.defaults(ext(def, options))\n m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options))\n m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options))\n m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options))\n\n return m\n}\n\n\n\n\n\n// Brace expansion:\n// a{b,c}d -> abd acd\n// a{b,}c -> abc ac\n// a{0..3}d -> a0d a1d a2d a3d\n// a{b,c{d,e}f}g -> abg acdfg acefg\n// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg\n//\n// Invalid sets are not expanded.\n// a{2..}b -> a{2..}b\n// a{b}c -> a{b}c\nminimatch.braceExpand = (pattern, options) => braceExpand(pattern, options)\n\nconst braceExpand = (pattern, options = {}) => {\n assertValidPattern(pattern)\n\n // Thanks to Yeting Li for\n // improving this regexp to avoid a ReDOS vulnerability.\n if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n // shortcut. no need to expand.\n return [pattern]\n }\n\n return expand(pattern)\n}\n\nconst MAX_PATTERN_LENGTH = 1024 * 64\nconst assertValidPattern = pattern => {\n if (typeof pattern !== 'string') {\n throw new TypeError('invalid pattern')\n }\n\n if (pattern.length > MAX_PATTERN_LENGTH) {\n throw new TypeError('pattern is too long')\n }\n}\n\n// parse a component of the expanded set.\n// At this point, no pattern may contain \"/\" in it\n// so we're going to return a 2d array, where each entry is the full\n// pattern, split on '/', and then turned into a regular expression.\n// A regexp is made at the end which joins each array with an\n// escaped /, and another full one which joins each regexp with |.\n//\n// Following the lead of Bash 4.1, note that \"**\" only has special meaning\n// when it is the *only* thing in a path portion. Otherwise, any series\n// of * is equivalent to a single *. Globstar behavior is enabled by\n// default, and can be disabled by setting options.noglobstar.\nconst SUBPARSE = Symbol('subparse')\n\nminimatch.makeRe = (pattern, options) =>\n new Minimatch(pattern, options || {}).makeRe()\n\nminimatch.match = (list, pattern, options = {}) => {\n const mm = new Minimatch(pattern, options)\n list = list.filter(f => mm.match(f))\n if (mm.options.nonull && !list.length) {\n list.push(pattern)\n }\n return list\n}\n\n// replace stuff like \\* with *\nconst globUnescape = s => s.replace(/\\\\(.)/g, '$1')\nconst charUnescape = s => s.replace(/\\\\([^-\\]])/g, '$1')\nconst regExpEscape = s => s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\nconst braExpEscape = s => s.replace(/[[\\]\\\\]/g, '\\\\$&')\n\nclass Minimatch {\n constructor (pattern, options) {\n assertValidPattern(pattern)\n\n if (!options) options = {}\n\n this.options = options\n this.maxGlobstarRecursion = options.maxGlobstarRecursion !== undefined\n ? options.maxGlobstarRecursion : 200\n this.set = []\n this.pattern = pattern\n this.windowsPathsNoEscape = !!options.windowsPathsNoEscape ||\n options.allowWindowsEscape === false\n if (this.windowsPathsNoEscape) {\n this.pattern = this.pattern.replace(/\\\\/g, '/')\n }\n this.regexp = null\n this.negate = false\n this.comment = false\n this.empty = false\n this.partial = !!options.partial\n\n // make the set of regexps etc.\n this.make()\n }\n\n debug () {}\n\n make () {\n const pattern = this.pattern\n const options = this.options\n\n // empty patterns and comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n this.comment = true\n return\n }\n if (!pattern) {\n this.empty = true\n return\n }\n\n // step 1: figure out negation, etc.\n this.parseNegate()\n\n // step 2: expand braces\n let set = this.globSet = this.braceExpand()\n\n if (options.debug) this.debug = (...args) => console.error(...args)\n\n this.debug(this.pattern, set)\n\n // step 3: now we have a set, so turn each one into a series of path-portion\n // matching patterns.\n // These will be regexps, except in the case of \"**\", which is\n // set to the GLOBSTAR object for globstar behavior,\n // and will not contain any / characters\n set = this.globParts = set.map(s => s.split(slashSplit))\n\n this.debug(this.pattern, set)\n\n // glob --> regexps\n set = set.map((s, si, set) => s.map(this.parse, this))\n\n this.debug(this.pattern, set)\n\n // filter out everything that didn't compile properly.\n set = set.filter(s => s.indexOf(false) === -1)\n\n this.debug(this.pattern, set)\n\n this.set = set\n }\n\n parseNegate () {\n if (this.options.nonegate) return\n\n const pattern = this.pattern\n let negate = false\n let negateOffset = 0\n\n for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {\n negate = !negate\n negateOffset++\n }\n\n if (negateOffset) this.pattern = pattern.slice(negateOffset)\n this.negate = negate\n }\n\n // set partial to true to test if, for example,\n // \"/a/b\" matches the start of \"/*/b/*/d\"\n // Partial means, if you run out of file before you run\n // out of pattern, then that's fine, as long as all\n // the parts match.\n matchOne (file, pattern, partial) {\n if (pattern.indexOf(GLOBSTAR) !== -1) {\n return this._matchGlobstar(file, pattern, partial, 0, 0)\n }\n return this._matchOne(file, pattern, partial, 0, 0)\n }\n\n _matchGlobstar (file, pattern, partial, fileIndex, patternIndex) {\n // find first globstar from patternIndex\n let firstgs = -1\n for (let i = patternIndex; i < pattern.length; i++) {\n if (pattern[i] === GLOBSTAR) { firstgs = i; break }\n }\n\n // find last globstar\n let lastgs = -1\n for (let i = pattern.length - 1; i >= 0; i--) {\n if (pattern[i] === GLOBSTAR) { lastgs = i; break }\n }\n\n const head = pattern.slice(patternIndex, firstgs)\n const body = partial ? pattern.slice(firstgs + 1) : pattern.slice(firstgs + 1, lastgs)\n const tail = partial ? [] : pattern.slice(lastgs + 1)\n\n // check the head\n if (head.length) {\n const fileHead = file.slice(fileIndex, fileIndex + head.length)\n if (!this._matchOne(fileHead, head, partial, 0, 0)) {\n return false\n }\n fileIndex += head.length\n }\n\n // check the tail\n let fileTailMatch = 0\n if (tail.length) {\n if (tail.length + fileIndex > file.length) return false\n\n const tailStart = file.length - tail.length\n if (this._matchOne(file, tail, partial, tailStart, 0)) {\n fileTailMatch = tail.length\n } else {\n // affordance for stuff like a/**/* matching a/b/\n if (file[file.length - 1] !== '' ||\n fileIndex + tail.length === file.length) {\n return false\n }\n if (!this._matchOne(file, tail, partial, tailStart - 1, 0)) {\n return false\n }\n fileTailMatch = tail.length + 1\n }\n }\n\n // if body is empty (single ** between head and tail)\n if (!body.length) {\n let sawSome = !!fileTailMatch\n for (let i = fileIndex; i < file.length - fileTailMatch; i++) {\n const f = String(file[i])\n sawSome = true\n if (f === '.' || f === '..' ||\n (!this.options.dot && f.charAt(0) === '.')) {\n return false\n }\n }\n return partial || sawSome\n }\n\n // split body into segments at each GLOBSTAR\n const bodySegments = [[[], 0]]\n let currentBody = bodySegments[0]\n let nonGsParts = 0\n const nonGsPartsSums = [0]\n for (const b of body) {\n if (b === GLOBSTAR) {\n nonGsPartsSums.push(nonGsParts)\n currentBody = [[], 0]\n bodySegments.push(currentBody)\n } else {\n currentBody[0].push(b)\n nonGsParts++\n }\n }\n\n let idx = bodySegments.length - 1\n const fileLength = file.length - fileTailMatch\n for (const b of bodySegments) {\n b[1] = fileLength - (nonGsPartsSums[idx--] + b[0].length)\n }\n\n return !!this._matchGlobStarBodySections(\n file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch\n )\n }\n\n // return false for \"nope, not matching\"\n // return null for \"not matching, cannot keep trying\"\n _matchGlobStarBodySections (\n file, bodySegments, fileIndex, bodyIndex, partial, globStarDepth, sawTail\n ) {\n const bs = bodySegments[bodyIndex]\n if (!bs) {\n // just make sure there are no bad dots\n for (let i = fileIndex; i < file.length; i++) {\n sawTail = true\n const f = file[i]\n if (f === '.' || f === '..' ||\n (!this.options.dot && f.charAt(0) === '.')) {\n return false\n }\n }\n return sawTail\n }\n\n const [body, after] = bs\n while (fileIndex <= after) {\n const m = this._matchOne(\n file.slice(0, fileIndex + body.length),\n body,\n partial,\n fileIndex,\n 0\n )\n // if limit exceeded, no match. intentional false negative,\n // acceptable break in correctness for security.\n if (m && globStarDepth < this.maxGlobstarRecursion) {\n const sub = this._matchGlobStarBodySections(\n file, bodySegments,\n fileIndex + body.length, bodyIndex + 1,\n partial, globStarDepth + 1, sawTail\n )\n if (sub !== false) {\n return sub\n }\n }\n const f = file[fileIndex]\n if (f === '.' || f === '..' ||\n (!this.options.dot && f.charAt(0) === '.')) {\n return false\n }\n fileIndex++\n }\n return partial || null\n }\n\n _matchOne (file, pattern, partial, fileIndex, patternIndex) {\n let fi, pi, fl, pl\n for (\n fi = fileIndex, pi = patternIndex, fl = file.length, pl = pattern.length\n ; (fi < fl) && (pi < pl)\n ; fi++, pi++\n ) {\n this.debug('matchOne loop')\n const p = pattern[pi]\n const f = file[fi]\n\n this.debug(pattern, p, f)\n\n // should be impossible.\n // some invalid regexp stuff in the set.\n /* istanbul ignore if */\n if (p === false || p === GLOBSTAR) return false\n\n // something other than **\n // non-magic patterns just have to match exactly\n // patterns with magic have been turned into regexps.\n let hit\n if (typeof p === 'string') {\n hit = f === p\n this.debug('string match', p, f, hit)\n } else {\n hit = f.match(p)\n this.debug('pattern match', p, f, hit)\n }\n\n if (!hit) return false\n }\n\n // now either we fell off the end of the pattern, or we're done.\n if (fi === fl && pi === pl) {\n // ran out of pattern and filename at the same time.\n // an exact hit!\n return true\n } else if (fi === fl) {\n // ran out of file, but still had pattern left.\n // this is ok if we're doing the match as part of\n // a glob fs traversal.\n return partial\n } else /* istanbul ignore else */ if (pi === pl) {\n // ran out of pattern, still have file left.\n // this is only acceptable if we're on the very last\n // empty segment of a file with a trailing slash.\n // a/* should match a/b/\n return (fi === fl - 1) && (file[fi] === '')\n }\n\n // should be unreachable.\n /* istanbul ignore next */\n throw new Error('wtf?')\n }\n\n braceExpand () {\n return braceExpand(this.pattern, this.options)\n }\n\n parse (pattern, isSub) {\n assertValidPattern(pattern)\n\n const options = this.options\n\n // shortcuts\n if (pattern === '**') {\n if (!options.noglobstar)\n return GLOBSTAR\n else\n pattern = '*'\n }\n if (pattern === '') return ''\n\n let re = ''\n let hasMagic = false\n let escaping = false\n // ? => one single character\n const patternListStack = []\n const negativeLists = []\n let stateChar\n let inClass = false\n let reClassStart = -1\n let classStart = -1\n let cs\n let pl\n let sp\n // . and .. never match anything that doesn't start with .,\n // even when options.dot is set. However, if the pattern\n // starts with ., then traversal patterns can match.\n let dotTravAllowed = pattern.charAt(0) === '.'\n let dotFileAllowed = options.dot || dotTravAllowed\n const patternStart = () =>\n dotTravAllowed\n ? ''\n : dotFileAllowed\n ? '(?!(?:^|\\\\/)\\\\.{1,2}(?:$|\\\\/))'\n : '(?!\\\\.)'\n const subPatternStart = (p) =>\n p.charAt(0) === '.'\n ? ''\n : options.dot\n ? '(?!(?:^|\\\\/)\\\\.{1,2}(?:$|\\\\/))'\n : '(?!\\\\.)'\n\n\n const clearStateChar = () => {\n if (stateChar) {\n // we had some state-tracking character\n // that wasn't consumed by this pass.\n switch (stateChar) {\n case '*':\n re += star\n hasMagic = true\n break\n case '?':\n re += qmark\n hasMagic = true\n break\n default:\n re += '\\\\' + stateChar\n break\n }\n this.debug('clearStateChar %j %j', stateChar, re)\n stateChar = false\n }\n }\n\n for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) {\n this.debug('%s\\t%s %s %j', pattern, i, re, c)\n\n // skip over any that are escaped.\n if (escaping) {\n /* istanbul ignore next - completely not allowed, even escaped. */\n if (c === '/') {\n return false\n }\n\n if (reSpecials[c]) {\n re += '\\\\'\n }\n re += c\n escaping = false\n continue\n }\n\n switch (c) {\n /* istanbul ignore next */\n case '/': {\n // Should already be path-split by now.\n return false\n }\n\n case '\\\\':\n if (inClass && pattern.charAt(i + 1) === '-') {\n re += c\n continue\n }\n\n clearStateChar()\n escaping = true\n continue\n\n // the various stateChar values\n // for the \"extglob\" stuff.\n case '?':\n case '*':\n case '+':\n case '@':\n case '!':\n this.debug('%s\\t%s %s %j <-- stateChar', pattern, i, re, c)\n\n // all of those are literals inside a class, except that\n // the glob [!a] means [^a] in regexp\n if (inClass) {\n this.debug(' in class')\n if (c === '!' && i === classStart + 1) c = '^'\n re += c\n continue\n }\n\n // coalesce consecutive non-globstar * characters\n if (c === '*' && stateChar === '*') continue\n\n // if we already have a stateChar, then it means\n // that there was something like ** or +? in there.\n // Handle the stateChar, then proceed with this one.\n this.debug('call clearStateChar %j', stateChar)\n clearStateChar()\n stateChar = c\n // if extglob is disabled, then +(asdf|foo) isn't a thing.\n // just clear the statechar *now*, rather than even diving into\n // the patternList stuff.\n if (options.noext) clearStateChar()\n continue\n\n case '(': {\n if (inClass) {\n re += '('\n continue\n }\n\n if (!stateChar) {\n re += '\\\\('\n continue\n }\n\n const plEntry = {\n type: stateChar,\n start: i - 1,\n reStart: re.length,\n open: plTypes[stateChar].open,\n close: plTypes[stateChar].close,\n }\n this.debug(this.pattern, '\\t', plEntry)\n patternListStack.push(plEntry)\n // negation is (?:(?!(?:js)(?:))[^/]*)\n re += plEntry.open\n // next entry starts with a dot maybe?\n if (plEntry.start === 0 && plEntry.type !== '!') {\n dotTravAllowed = true\n re += subPatternStart(pattern.slice(i + 1))\n }\n this.debug('plType %j %j', stateChar, re)\n stateChar = false\n continue\n }\n\n case ')': {\n const plEntry = patternListStack[patternListStack.length - 1]\n if (inClass || !plEntry) {\n re += '\\\\)'\n continue\n }\n patternListStack.pop()\n\n // closing an extglob\n clearStateChar()\n hasMagic = true\n pl = plEntry\n // negation is (?:(?!js)[^/]*)\n // The others are (?:)\n re += pl.close\n if (pl.type === '!') {\n negativeLists.push(Object.assign(pl, { reEnd: re.length }))\n }\n continue\n }\n\n case '|': {\n const plEntry = patternListStack[patternListStack.length - 1]\n if (inClass || !plEntry) {\n re += '\\\\|'\n continue\n }\n\n clearStateChar()\n re += '|'\n // next subpattern can start with a dot?\n if (plEntry.start === 0 && plEntry.type !== '!') {\n dotTravAllowed = true\n re += subPatternStart(pattern.slice(i + 1))\n }\n continue\n }\n\n // these are mostly the same in regexp and glob\n case '[':\n // swallow any state-tracking char before the [\n clearStateChar()\n\n if (inClass) {\n re += '\\\\' + c\n continue\n }\n\n inClass = true\n classStart = i\n reClassStart = re.length\n re += c\n continue\n\n case ']':\n // a right bracket shall lose its special\n // meaning and represent itself in\n // a bracket expression if it occurs\n // first in the list. -- POSIX.2 2.8.3.2\n if (i === classStart + 1 || !inClass) {\n re += '\\\\' + c\n continue\n }\n\n // split where the last [ was, make sure we don't have\n // an invalid re. if so, re-walk the contents of the\n // would-be class to re-translate any characters that\n // were passed through as-is\n // TODO: It would probably be faster to determine this\n // without a try/catch and a new RegExp, but it's tricky\n // to do safely. For now, this is safe and works.\n cs = pattern.substring(classStart + 1, i)\n try {\n RegExp('[' + braExpEscape(charUnescape(cs)) + ']')\n // looks good, finish up the class.\n re += c\n } catch (er) {\n // out of order ranges in JS are errors, but in glob syntax,\n // they're just a range that matches nothing.\n re = re.substring(0, reClassStart) + '(?:$.)' // match nothing ever\n }\n hasMagic = true\n inClass = false\n continue\n\n default:\n // swallow any state char that wasn't consumed\n clearStateChar()\n\n if (reSpecials[c] && !(c === '^' && inClass)) {\n re += '\\\\'\n }\n\n re += c\n break\n\n } // switch\n } // for\n\n // handle the case where we left a class open.\n // \"[abc\" is valid, equivalent to \"\\[abc\"\n if (inClass) {\n // split where the last [ was, and escape it\n // this is a huge pita. We now have to re-walk\n // the contents of the would-be class to re-translate\n // any characters that were passed through as-is\n cs = pattern.slice(classStart + 1)\n sp = this.parse(cs, SUBPARSE)\n re = re.substring(0, reClassStart) + '\\\\[' + sp[0]\n hasMagic = hasMagic || sp[1]\n }\n\n // handle the case where we had a +( thing at the *end*\n // of the pattern.\n // each pattern list stack adds 3 chars, and we need to go through\n // and escape any | chars that were passed through as-is for the regexp.\n // Go through and escape them, taking care not to double-escape any\n // | chars that were already escaped.\n for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {\n let tail\n tail = re.slice(pl.reStart + pl.open.length)\n this.debug('setting tail', re, pl)\n // maybe some even number of \\, then maybe 1 \\, followed by a |\n tail = tail.replace(/((?:\\\\{2}){0,64})(\\\\?)\\|/g, (_, $1, $2) => {\n /* istanbul ignore else - should already be done */\n if (!$2) {\n // the | isn't already escaped, so escape it.\n $2 = '\\\\'\n }\n\n // need to escape all those slashes *again*, without escaping the\n // one that we need for escaping the | character. As it works out,\n // escaping an even number of slashes can be done by simply repeating\n // it exactly after itself. That's why this trick works.\n //\n // I am sorry that you have to see this.\n return $1 + $1 + $2 + '|'\n })\n\n this.debug('tail=%j\\n %s', tail, tail, pl, re)\n const t = pl.type === '*' ? star\n : pl.type === '?' ? qmark\n : '\\\\' + pl.type\n\n hasMagic = true\n re = re.slice(0, pl.reStart) + t + '\\\\(' + tail\n }\n\n // handle trailing things that only matter at the very end.\n clearStateChar()\n if (escaping) {\n // trailing \\\\\n re += '\\\\\\\\'\n }\n\n // only need to apply the nodot start if the re starts with\n // something that could conceivably capture a dot\n const addPatternStart = addPatternStartSet[re.charAt(0)]\n\n // Hack to work around lack of negative lookbehind in JS\n // A pattern like: *.!(x).!(y|z) needs to ensure that a name\n // like 'a.xyz.yz' doesn't match. So, the first negative\n // lookahead, has to look ALL the way ahead, to the end of\n // the pattern.\n for (let n = negativeLists.length - 1; n > -1; n--) {\n const nl = negativeLists[n]\n\n const nlBefore = re.slice(0, nl.reStart)\n const nlFirst = re.slice(nl.reStart, nl.reEnd - 8)\n let nlAfter = re.slice(nl.reEnd)\n const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter\n\n // Handle nested stuff like *(*.js|!(*.json)), where open parens\n // mean that we should *not* include the ) in the bit that is considered\n // \"after\" the negated section.\n const closeParensBefore = nlBefore.split(')').length\n const openParensBefore = nlBefore.split('(').length - closeParensBefore\n let cleanAfter = nlAfter\n for (let i = 0; i < openParensBefore; i++) {\n cleanAfter = cleanAfter.replace(/\\)[+*?]?/, '')\n }\n nlAfter = cleanAfter\n\n const dollar = nlAfter === '' && isSub !== SUBPARSE ? '(?:$|\\\\/)' : ''\n\n re = nlBefore + nlFirst + nlAfter + dollar + nlLast\n }\n\n // if the re is not \"\" at this point, then we need to make sure\n // it doesn't match against an empty path part.\n // Otherwise a/* will match a/, which it should not.\n if (re !== '' && hasMagic) {\n re = '(?=.)' + re\n }\n\n if (addPatternStart) {\n re = patternStart() + re\n }\n\n // parsing just a piece of a larger pattern.\n if (isSub === SUBPARSE) {\n return [re, hasMagic]\n }\n\n // if it's nocase, and the lcase/uppercase don't match, it's magic\n if (options.nocase && !hasMagic) {\n hasMagic = pattern.toUpperCase() !== pattern.toLowerCase()\n }\n\n // skip the regexp for non-magical patterns\n // unescape anything in it, though, so that it'll be\n // an exact match against a file etc.\n if (!hasMagic) {\n return globUnescape(pattern)\n }\n\n const flags = options.nocase ? 'i' : ''\n try {\n return Object.assign(new RegExp('^' + re + '$', flags), {\n _glob: pattern,\n _src: re,\n })\n } catch (er) /* istanbul ignore next - should be impossible */ {\n // If it was an invalid regular expression, then it can't match\n // anything. This trick looks for a character after the end of\n // the string, which is of course impossible, except in multi-line\n // mode, but it's not a /m regex.\n return new RegExp('$.')\n }\n }\n\n makeRe () {\n if (this.regexp || this.regexp === false) return this.regexp\n\n // at this point, this.set is a 2d array of partial\n // pattern strings, or \"**\".\n //\n // It's better to use .match(). This function shouldn't\n // be used, really, but it's pretty convenient sometimes,\n // when you just want to work with a regex.\n const set = this.set\n\n if (!set.length) {\n this.regexp = false\n return this.regexp\n }\n const options = this.options\n\n const twoStar = options.noglobstar ? star\n : options.dot ? twoStarDot\n : twoStarNoDot\n const flags = options.nocase ? 'i' : ''\n\n // coalesce globstars and regexpify non-globstar patterns\n // if it's the only item, then we just do one twoStar\n // if it's the first, and there are more, prepend (\\/|twoStar\\/)? to next\n // if it's the last, append (\\/twoStar|) to previous\n // if it's in the middle, append (\\/|\\/twoStar\\/) to previous\n // then filter out GLOBSTAR symbols\n let re = set.map(pattern => {\n pattern = pattern.map(p =>\n typeof p === 'string' ? regExpEscape(p)\n : p === GLOBSTAR ? GLOBSTAR\n : p._src\n ).reduce((set, p) => {\n if (!(set[set.length - 1] === GLOBSTAR && p === GLOBSTAR)) {\n set.push(p)\n }\n return set\n }, [])\n pattern.forEach((p, i) => {\n if (p !== GLOBSTAR || pattern[i-1] === GLOBSTAR) {\n return\n }\n if (i === 0) {\n if (pattern.length > 1) {\n pattern[i+1] = '(?:\\\\\\/|' + twoStar + '\\\\\\/)?' + pattern[i+1]\n } else {\n pattern[i] = twoStar\n }\n } else if (i === pattern.length - 1) {\n pattern[i-1] += '(?:\\\\\\/|' + twoStar + ')?'\n } else {\n pattern[i-1] += '(?:\\\\\\/|\\\\\\/' + twoStar + '\\\\\\/)' + pattern[i+1]\n pattern[i+1] = GLOBSTAR\n }\n })\n return pattern.filter(p => p !== GLOBSTAR).join('/')\n }).join('|')\n\n // must match entire pattern\n // ending in a * or ** will make it less strict.\n re = '^(?:' + re + ')$'\n\n // can match anything, as long as it's not this.\n if (this.negate) re = '^(?!' + re + ').*$'\n\n try {\n this.regexp = new RegExp(re, flags)\n } catch (ex) /* istanbul ignore next - should be impossible */ {\n this.regexp = false\n }\n return this.regexp\n }\n\n match (f, partial = this.partial) {\n this.debug('match', f, this.pattern)\n // short-circuit in the case of busted things.\n // comments, etc.\n if (this.comment) return false\n if (this.empty) return f === ''\n\n if (f === '/' && partial) return true\n\n const options = this.options\n\n // windows: need to use /, not \\\n if (path.sep !== '/') {\n f = f.split(path.sep).join('/')\n }\n\n // treat the test path as a set of pathparts.\n f = f.split(slashSplit)\n this.debug(this.pattern, 'split', f)\n\n // just ONE of the pattern sets in this.set needs to match\n // in order for it to be valid. If negating, then just one\n // match means that we have failed.\n // Either way, return on the first hit.\n\n const set = this.set\n this.debug(this.pattern, 'set', set)\n\n // Find the basename of the path by looking for the last non-empty segment\n let filename\n for (let i = f.length - 1; i >= 0; i--) {\n filename = f[i]\n if (filename) break\n }\n\n for (let i = 0; i < set.length; i++) {\n const pattern = set[i]\n let file = f\n if (options.matchBase && pattern.length === 1) {\n file = [filename]\n }\n const hit = this.matchOne(file, pattern, partial)\n if (hit) {\n if (options.flipNegate) return true\n return !this.negate\n }\n }\n\n // didn't get any hits. this is success if it's a negative\n // pattern, failure otherwise.\n if (options.flipNegate) return false\n return this.negate\n }\n\n static defaults (def) {\n return minimatch.defaults(def).Minimatch\n }\n}\n\nminimatch.Minimatch = Minimatch\n","module.exports = readdirGlob;\n\nconst fs = require('fs');\nconst { EventEmitter } = require('events');\nconst { Minimatch } = require('minimatch');\nconst { resolve } = require('path');\n\nfunction readdir(dir, strict) {\n return new Promise((resolve, reject) => {\n fs.readdir(dir, {withFileTypes: true} ,(err, files) => {\n if(err) {\n switch (err.code) {\n case 'ENOTDIR': // Not a directory\n if(strict) {\n reject(err);\n } else {\n resolve([]);\n }\n break;\n case 'ENOTSUP': // Operation not supported\n case 'ENOENT': // No such file or directory\n case 'ENAMETOOLONG': // Filename too long\n case 'UNKNOWN':\n resolve([]);\n break;\n case 'ELOOP': // Too many levels of symbolic links\n default:\n reject(err);\n break;\n }\n } else {\n resolve(files);\n }\n });\n });\n}\nfunction stat(file, followSymlinks) {\n return new Promise((resolve, reject) => {\n const statFunc = followSymlinks ? fs.stat : fs.lstat;\n statFunc(file, (err, stats) => {\n if(err) {\n switch (err.code) {\n case 'ENOENT':\n if(followSymlinks) {\n // Fallback to lstat to handle broken links as files\n resolve(stat(file, false)); \n } else {\n resolve(null);\n }\n break;\n default:\n resolve(null);\n break;\n }\n } else {\n resolve(stats);\n }\n });\n });\n}\n\nasync function* exploreWalkAsync(dir, path, followSymlinks, useStat, shouldSkip, strict) {\n let files = await readdir(path + dir, strict);\n for(const file of files) {\n let name = file.name;\n if(name === undefined) {\n // undefined file.name means the `withFileTypes` options is not supported by node\n // we have to call the stat function to know if file is directory or not.\n name = file;\n useStat = true;\n }\n const filename = dir + '/' + name;\n const relative = filename.slice(1); // Remove the leading /\n const absolute = path + '/' + relative;\n let stats = null;\n if(useStat || followSymlinks) {\n stats = await stat(absolute, followSymlinks);\n }\n if(!stats && file.name !== undefined) {\n stats = file;\n }\n if(stats === null) {\n stats = { isDirectory: () => false };\n }\n\n if(stats.isDirectory()) {\n if(!shouldSkip(relative)) {\n yield {relative, absolute, stats};\n yield* exploreWalkAsync(filename, path, followSymlinks, useStat, shouldSkip, false);\n }\n } else {\n yield {relative, absolute, stats};\n }\n }\n}\nasync function* explore(path, followSymlinks, useStat, shouldSkip) {\n yield* exploreWalkAsync('', path, followSymlinks, useStat, shouldSkip, true);\n}\n\n\nfunction readOptions(options) {\n return {\n pattern: options.pattern,\n dot: !!options.dot,\n noglobstar: !!options.noglobstar,\n matchBase: !!options.matchBase,\n nocase: !!options.nocase,\n ignore: options.ignore,\n skip: options.skip,\n\n follow: !!options.follow,\n stat: !!options.stat,\n nodir: !!options.nodir,\n mark: !!options.mark,\n silent: !!options.silent,\n absolute: !!options.absolute\n };\n}\n\nclass ReaddirGlob extends EventEmitter {\n constructor(cwd, options, cb) {\n super();\n if(typeof options === 'function') {\n cb = options;\n options = null;\n }\n\n this.options = readOptions(options || {});\n \n this.matchers = [];\n if(this.options.pattern) {\n const matchers = Array.isArray(this.options.pattern) ? this.options.pattern : [this.options.pattern];\n this.matchers = matchers.map( m =>\n new Minimatch(m, {\n dot: this.options.dot,\n noglobstar:this.options.noglobstar,\n matchBase:this.options.matchBase,\n nocase:this.options.nocase\n })\n );\n }\n \n this.ignoreMatchers = [];\n if(this.options.ignore) {\n const ignorePatterns = Array.isArray(this.options.ignore) ? this.options.ignore : [this.options.ignore];\n this.ignoreMatchers = ignorePatterns.map( ignore =>\n new Minimatch(ignore, {dot: true})\n );\n }\n \n this.skipMatchers = [];\n if(this.options.skip) {\n const skipPatterns = Array.isArray(this.options.skip) ? this.options.skip : [this.options.skip];\n this.skipMatchers = skipPatterns.map( skip =>\n new Minimatch(skip, {dot: true})\n );\n }\n\n this.iterator = explore(resolve(cwd || '.'), this.options.follow, this.options.stat, this._shouldSkipDirectory.bind(this));\n this.paused = false;\n this.inactive = false;\n this.aborted = false;\n \n if(cb) {\n this._matches = []; \n this.on('match', match => this._matches.push(this.options.absolute ? match.absolute : match.relative));\n this.on('error', err => cb(err));\n this.on('end', () => cb(null, this._matches));\n }\n\n setTimeout( () => this._next(), 0);\n }\n\n _shouldSkipDirectory(relative) {\n //console.log(relative, this.skipMatchers.some(m => m.match(relative)));\n return this.skipMatchers.some(m => m.match(relative));\n }\n\n _fileMatches(relative, isDirectory) {\n const file = relative + (isDirectory ? '/' : '');\n return (this.matchers.length === 0 || this.matchers.some(m => m.match(file)))\n && !this.ignoreMatchers.some(m => m.match(file))\n && (!this.options.nodir || !isDirectory);\n }\n\n _next() {\n if(!this.paused && !this.aborted) {\n this.iterator.next()\n .then((obj)=> {\n if(!obj.done) {\n const isDirectory = obj.value.stats.isDirectory();\n if(this._fileMatches(obj.value.relative, isDirectory )) {\n let relative = obj.value.relative;\n let absolute = obj.value.absolute;\n if(this.options.mark && isDirectory) {\n relative += '/';\n absolute += '/';\n }\n if(this.options.stat) {\n this.emit('match', {relative, absolute, stat:obj.value.stats});\n } else {\n this.emit('match', {relative, absolute});\n }\n }\n this._next(this.iterator);\n } else {\n this.emit('end');\n }\n })\n .catch((err) => {\n this.abort();\n this.emit('error', err);\n if(!err.code && !this.options.silent) {\n console.error(err);\n }\n });\n } else {\n this.inactive = true;\n }\n }\n\n abort() {\n this.aborted = true;\n }\n\n pause() {\n this.paused = true;\n }\n\n resume() {\n this.paused = false;\n if(this.inactive) {\n this.inactive = false;\n this._next();\n }\n }\n}\n\n\nfunction readdirGlob(pattern, options, cb) {\n return new ReaddirGlob(pattern, options, cb);\n}\nreaddirGlob.ReaddirGlob = ReaddirGlob;","/**\n * Creates a continuation function with some arguments already applied.\n *\n * Useful as a shorthand when combined with other control flow functions. Any\n * arguments passed to the returned function are added to the arguments\n * originally passed to apply.\n *\n * @name apply\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {Function} fn - The function you want to eventually apply all\n * arguments to. Invokes with (arguments...).\n * @param {...*} arguments... - Any number of arguments to automatically apply\n * when the continuation is called.\n * @returns {Function} the partially-applied function\n * @example\n *\n * // using apply\n * async.parallel([\n * async.apply(fs.writeFile, 'testfile1', 'test1'),\n * async.apply(fs.writeFile, 'testfile2', 'test2')\n * ]);\n *\n *\n * // the same process without using apply\n * async.parallel([\n * function(callback) {\n * fs.writeFile('testfile1', 'test1', callback);\n * },\n * function(callback) {\n * fs.writeFile('testfile2', 'test2', callback);\n * }\n * ]);\n *\n * // It's possible to pass any number of additional arguments when calling the\n * // continuation:\n *\n * node> var fn = async.apply(sys.puts, 'one');\n * node> fn('two', 'three');\n * one\n * two\n * three\n */\nfunction apply(fn, ...args) {\n return (...callArgs) => fn(...args,...callArgs);\n}\n\nfunction initialParams (fn) {\n return function (...args/*, callback*/) {\n var callback = args.pop();\n return fn.call(this, args, callback);\n };\n}\n\n/* istanbul ignore file */\n\nvar hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask;\nvar hasSetImmediate = typeof setImmediate === 'function' && setImmediate;\nvar hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';\n\nfunction fallback(fn) {\n setTimeout(fn, 0);\n}\n\nfunction wrap(defer) {\n return (fn, ...args) => defer(() => fn(...args));\n}\n\nvar _defer$1;\n\nif (hasQueueMicrotask) {\n _defer$1 = queueMicrotask;\n} else if (hasSetImmediate) {\n _defer$1 = setImmediate;\n} else if (hasNextTick) {\n _defer$1 = process.nextTick;\n} else {\n _defer$1 = fallback;\n}\n\nvar setImmediate$1 = wrap(_defer$1);\n\n/**\n * Take a sync function and make it async, passing its return value to a\n * callback. This is useful for plugging sync functions into a waterfall,\n * series, or other async functions. Any arguments passed to the generated\n * function will be passed to the wrapped function (except for the final\n * callback argument). Errors thrown will be passed to the callback.\n *\n * If the function passed to `asyncify` returns a Promise, that promises's\n * resolved/rejected state will be used to call the callback, rather than simply\n * the synchronous return value.\n *\n * This also means you can asyncify ES2017 `async` functions.\n *\n * @name asyncify\n * @static\n * @memberOf module:Utils\n * @method\n * @alias wrapSync\n * @category Util\n * @param {Function} func - The synchronous function, or Promise-returning\n * function to convert to an {@link AsyncFunction}.\n * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be\n * invoked with `(args..., callback)`.\n * @example\n *\n * // passing a regular synchronous function\n * async.waterfall([\n * async.apply(fs.readFile, filename, \"utf8\"),\n * async.asyncify(JSON.parse),\n * function (data, next) {\n * // data is the result of parsing the text.\n * // If there was a parsing error, it would have been caught.\n * }\n * ], callback);\n *\n * // passing a function returning a promise\n * async.waterfall([\n * async.apply(fs.readFile, filename, \"utf8\"),\n * async.asyncify(function (contents) {\n * return db.model.create(contents);\n * }),\n * function (model, next) {\n * // `model` is the instantiated model object.\n * // If there was an error, this function would be skipped.\n * }\n * ], callback);\n *\n * // es2017 example, though `asyncify` is not needed if your JS environment\n * // supports async functions out of the box\n * var q = async.queue(async.asyncify(async function(file) {\n * var intermediateStep = await processFile(file);\n * return await somePromise(intermediateStep)\n * }));\n *\n * q.push(files);\n */\nfunction asyncify(func) {\n if (isAsync(func)) {\n return function (...args/*, callback*/) {\n const callback = args.pop();\n const promise = func.apply(this, args);\n return handlePromise(promise, callback)\n }\n }\n\n return initialParams(function (args, callback) {\n var result;\n try {\n result = func.apply(this, args);\n } catch (e) {\n return callback(e);\n }\n // if result is Promise object\n if (result && typeof result.then === 'function') {\n return handlePromise(result, callback)\n } else {\n callback(null, result);\n }\n });\n}\n\nfunction handlePromise(promise, callback) {\n return promise.then(value => {\n invokeCallback(callback, null, value);\n }, err => {\n invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err));\n });\n}\n\nfunction invokeCallback(callback, error, value) {\n try {\n callback(error, value);\n } catch (err) {\n setImmediate$1(e => { throw e }, err);\n }\n}\n\nfunction isAsync(fn) {\n return fn[Symbol.toStringTag] === 'AsyncFunction';\n}\n\nfunction isAsyncGenerator(fn) {\n return fn[Symbol.toStringTag] === 'AsyncGenerator';\n}\n\nfunction isAsyncIterable(obj) {\n return typeof obj[Symbol.asyncIterator] === 'function';\n}\n\nfunction wrapAsync(asyncFn) {\n if (typeof asyncFn !== 'function') throw new Error('expected a function')\n return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn;\n}\n\n// conditionally promisify a function.\n// only return a promise if a callback is omitted\nfunction awaitify (asyncFn, arity) {\n if (!arity) arity = asyncFn.length;\n if (!arity) throw new Error('arity is undefined')\n function awaitable (...args) {\n if (typeof args[arity - 1] === 'function') {\n return asyncFn.apply(this, args)\n }\n\n return new Promise((resolve, reject) => {\n args[arity - 1] = (err, ...cbArgs) => {\n if (err) return reject(err)\n resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]);\n };\n asyncFn.apply(this, args);\n })\n }\n\n return awaitable\n}\n\nfunction applyEach$1 (eachfn) {\n return function applyEach(fns, ...callArgs) {\n const go = awaitify(function (callback) {\n var that = this;\n return eachfn(fns, (fn, cb) => {\n wrapAsync(fn).apply(that, callArgs.concat(cb));\n }, callback);\n });\n return go;\n };\n}\n\nfunction _asyncMap(eachfn, arr, iteratee, callback) {\n arr = arr || [];\n var results = [];\n var counter = 0;\n var _iteratee = wrapAsync(iteratee);\n\n return eachfn(arr, (value, _, iterCb) => {\n var index = counter++;\n _iteratee(value, (err, v) => {\n results[index] = v;\n iterCb(err);\n });\n }, err => {\n callback(err, results);\n });\n}\n\nfunction isArrayLike(value) {\n return value &&\n typeof value.length === 'number' &&\n value.length >= 0 &&\n value.length % 1 === 0;\n}\n\n// A temporary value used to identify if the loop should be broken.\n// See #1064, #1293\nconst breakLoop = {};\n\nfunction once(fn) {\n function wrapper (...args) {\n if (fn === null) return;\n var callFn = fn;\n fn = null;\n callFn.apply(this, args);\n }\n Object.assign(wrapper, fn);\n return wrapper\n}\n\nfunction getIterator (coll) {\n return coll[Symbol.iterator] && coll[Symbol.iterator]();\n}\n\nfunction createArrayIterator(coll) {\n var i = -1;\n var len = coll.length;\n return function next() {\n return ++i < len ? {value: coll[i], key: i} : null;\n }\n}\n\nfunction createES2015Iterator(iterator) {\n var i = -1;\n return function next() {\n var item = iterator.next();\n if (item.done)\n return null;\n i++;\n return {value: item.value, key: i};\n }\n}\n\nfunction createObjectIterator(obj) {\n var okeys = obj ? Object.keys(obj) : [];\n var i = -1;\n var len = okeys.length;\n return function next() {\n var key = okeys[++i];\n if (key === '__proto__') {\n return next();\n }\n return i < len ? {value: obj[key], key} : null;\n };\n}\n\nfunction createIterator(coll) {\n if (isArrayLike(coll)) {\n return createArrayIterator(coll);\n }\n\n var iterator = getIterator(coll);\n return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);\n}\n\nfunction onlyOnce(fn) {\n return function (...args) {\n if (fn === null) throw new Error(\"Callback was already called.\");\n var callFn = fn;\n fn = null;\n callFn.apply(this, args);\n };\n}\n\n// for async generators\nfunction asyncEachOfLimit(generator, limit, iteratee, callback) {\n let done = false;\n let canceled = false;\n let awaiting = false;\n let running = 0;\n let idx = 0;\n\n function replenish() {\n //console.log('replenish')\n if (running >= limit || awaiting || done) return\n //console.log('replenish awaiting')\n awaiting = true;\n generator.next().then(({value, done: iterDone}) => {\n //console.log('got value', value)\n if (canceled || done) return\n awaiting = false;\n if (iterDone) {\n done = true;\n if (running <= 0) {\n //console.log('done nextCb')\n callback(null);\n }\n return;\n }\n running++;\n iteratee(value, idx, iterateeCallback);\n idx++;\n replenish();\n }).catch(handleError);\n }\n\n function iterateeCallback(err, result) {\n //console.log('iterateeCallback')\n running -= 1;\n if (canceled) return\n if (err) return handleError(err)\n\n if (err === false) {\n done = true;\n canceled = true;\n return\n }\n\n if (result === breakLoop || (done && running <= 0)) {\n done = true;\n //console.log('done iterCb')\n return callback(null);\n }\n replenish();\n }\n\n function handleError(err) {\n if (canceled) return\n awaiting = false;\n done = true;\n callback(err);\n }\n\n replenish();\n}\n\nvar eachOfLimit$2 = (limit) => {\n return (obj, iteratee, callback) => {\n callback = once(callback);\n if (limit <= 0) {\n throw new RangeError('concurrency limit cannot be less than 1')\n }\n if (!obj) {\n return callback(null);\n }\n if (isAsyncGenerator(obj)) {\n return asyncEachOfLimit(obj, limit, iteratee, callback)\n }\n if (isAsyncIterable(obj)) {\n return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback)\n }\n var nextElem = createIterator(obj);\n var done = false;\n var canceled = false;\n var running = 0;\n var looping = false;\n\n function iterateeCallback(err, value) {\n if (canceled) return\n running -= 1;\n if (err) {\n done = true;\n callback(err);\n }\n else if (err === false) {\n done = true;\n canceled = true;\n }\n else if (value === breakLoop || (done && running <= 0)) {\n done = true;\n return callback(null);\n }\n else if (!looping) {\n replenish();\n }\n }\n\n function replenish () {\n looping = true;\n while (running < limit && !done) {\n var elem = nextElem();\n if (elem === null) {\n done = true;\n if (running <= 0) {\n callback(null);\n }\n return;\n }\n running += 1;\n iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));\n }\n looping = false;\n }\n\n replenish();\n };\n};\n\n/**\n * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name eachOfLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.eachOf]{@link module:Collections.eachOf}\n * @alias forEachOfLimit\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - An async function to apply to each\n * item in `coll`. The `key` is the item's key, or index in the case of an\n * array.\n * Invoked with (item, key, callback).\n * @param {Function} [callback] - A callback which is called when all\n * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n * @returns {Promise} a promise, if a callback is omitted\n */\nfunction eachOfLimit(coll, limit, iteratee, callback) {\n return eachOfLimit$2(limit)(coll, wrapAsync(iteratee), callback);\n}\n\nvar eachOfLimit$1 = awaitify(eachOfLimit, 4);\n\n// eachOf implementation optimized for array-likes\nfunction eachOfArrayLike(coll, iteratee, callback) {\n callback = once(callback);\n var index = 0,\n completed = 0,\n {length} = coll,\n canceled = false;\n if (length === 0) {\n callback(null);\n }\n\n function iteratorCallback(err, value) {\n if (err === false) {\n canceled = true;\n }\n if (canceled === true) return\n if (err) {\n callback(err);\n } else if ((++completed === length) || value === breakLoop) {\n callback(null);\n }\n }\n\n for (; index < length; index++) {\n iteratee(coll[index], index, onlyOnce(iteratorCallback));\n }\n}\n\n// a generic version of eachOf which can handle array, object, and iterator cases.\nfunction eachOfGeneric (coll, iteratee, callback) {\n return eachOfLimit$1(coll, Infinity, iteratee, callback);\n}\n\n/**\n * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument\n * to the iteratee.\n *\n * @name eachOf\n * @static\n * @memberOf module:Collections\n * @method\n * @alias forEachOf\n * @category Collection\n * @see [async.each]{@link module:Collections.each}\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A function to apply to each\n * item in `coll`.\n * The `key` is the item's key, or index in the case of an array.\n * Invoked with (item, key, callback).\n * @param {Function} [callback] - A callback which is called when all\n * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n * @returns {Promise} a promise, if a callback is omitted\n * @example\n *\n * // dev.json is a file containing a valid json object config for dev environment\n * // dev.json is a file containing a valid json object config for test environment\n * // prod.json is a file containing a valid json object config for prod environment\n * // invalid.json is a file with a malformed json object\n *\n * let configs = {}; //global variable\n * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'};\n * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'};\n *\n * // asynchronous function that reads a json file and parses the contents as json object\n * function parseFile(file, key, callback) {\n * fs.readFile(file, \"utf8\", function(err, data) {\n * if (err) return calback(err);\n * try {\n * configs[key] = JSON.parse(data);\n * } catch (e) {\n * return callback(e);\n * }\n * callback();\n * });\n * }\n *\n * // Using callbacks\n * async.forEachOf(validConfigFileMap, parseFile, function (err) {\n * if (err) {\n * console.error(err);\n * } else {\n * console.log(configs);\n * // configs is now a map of JSON data, e.g.\n * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}\n * }\n * });\n *\n * //Error handing\n * async.forEachOf(invalidConfigFileMap, parseFile, function (err) {\n * if (err) {\n * console.error(err);\n * // JSON parse error exception\n * } else {\n * console.log(configs);\n * }\n * });\n *\n * // Using Promises\n * async.forEachOf(validConfigFileMap, parseFile)\n * .then( () => {\n * console.log(configs);\n * // configs is now a map of JSON data, e.g.\n * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}\n * }).catch( err => {\n * console.error(err);\n * });\n *\n * //Error handing\n * async.forEachOf(invalidConfigFileMap, parseFile)\n * .then( () => {\n * console.log(configs);\n * }).catch( err => {\n * console.error(err);\n * // JSON parse error exception\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let result = await async.forEachOf(validConfigFileMap, parseFile);\n * console.log(configs);\n * // configs is now a map of JSON data, e.g.\n * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json}\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n * //Error handing\n * async () => {\n * try {\n * let result = await async.forEachOf(invalidConfigFileMap, parseFile);\n * console.log(configs);\n * }\n * catch (err) {\n * console.log(err);\n * // JSON parse error exception\n * }\n * }\n *\n */\nfunction eachOf(coll, iteratee, callback) {\n var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;\n return eachOfImplementation(coll, wrapAsync(iteratee), callback);\n}\n\nvar eachOf$1 = awaitify(eachOf, 3);\n\n/**\n * Produces a new collection of values by mapping each value in `coll` through\n * the `iteratee` function. The `iteratee` is called with an item from `coll`\n * and a callback for when it has finished processing. Each of these callbacks\n * takes 2 arguments: an `error`, and the transformed item from `coll`. If\n * `iteratee` passes an error to its callback, the main `callback` (for the\n * `map` function) is immediately called with the error.\n *\n * Note, that since this function applies the `iteratee` to each item in\n * parallel, there is no guarantee that the `iteratee` functions will complete\n * in order. However, the results array will be in the same order as the\n * original `coll`.\n *\n * If `map` is passed an Object, the results will be an Array. The results\n * will roughly be in the order of the original Objects' keys (but this can\n * vary across JavaScript engines).\n *\n * @name map\n * @static\n * @memberOf module:Collections\n * @method\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with the transformed item.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Results is an Array of the\n * transformed items from the `coll`. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback is passed\n * @example\n *\n * // file1.txt is a file that is 1000 bytes in size\n * // file2.txt is a file that is 2000 bytes in size\n * // file3.txt is a file that is 3000 bytes in size\n * // file4.txt does not exist\n *\n * const fileList = ['file1.txt','file2.txt','file3.txt'];\n * const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];\n *\n * // asynchronous function that returns the file size in bytes\n * function getFileSizeInBytes(file, callback) {\n * fs.stat(file, function(err, stat) {\n * if (err) {\n * return callback(err);\n * }\n * callback(null, stat.size);\n * });\n * }\n *\n * // Using callbacks\n * async.map(fileList, getFileSizeInBytes, function(err, results) {\n * if (err) {\n * console.log(err);\n * } else {\n * console.log(results);\n * // results is now an array of the file size in bytes for each file, e.g.\n * // [ 1000, 2000, 3000]\n * }\n * });\n *\n * // Error Handling\n * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) {\n * if (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * } else {\n * console.log(results);\n * }\n * });\n *\n * // Using Promises\n * async.map(fileList, getFileSizeInBytes)\n * .then( results => {\n * console.log(results);\n * // results is now an array of the file size in bytes for each file, e.g.\n * // [ 1000, 2000, 3000]\n * }).catch( err => {\n * console.log(err);\n * });\n *\n * // Error Handling\n * async.map(withMissingFileList, getFileSizeInBytes)\n * .then( results => {\n * console.log(results);\n * }).catch( err => {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let results = await async.map(fileList, getFileSizeInBytes);\n * console.log(results);\n * // results is now an array of the file size in bytes for each file, e.g.\n * // [ 1000, 2000, 3000]\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n * // Error Handling\n * async () => {\n * try {\n * let results = await async.map(withMissingFileList, getFileSizeInBytes);\n * console.log(results);\n * }\n * catch (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * }\n * }\n *\n */\nfunction map (coll, iteratee, callback) {\n return _asyncMap(eachOf$1, coll, iteratee, callback)\n}\nvar map$1 = awaitify(map, 3);\n\n/**\n * Applies the provided arguments to each function in the array, calling\n * `callback` after all functions have completed. If you only provide the first\n * argument, `fns`, then it will return a function which lets you pass in the\n * arguments as if it were a single function call. If more arguments are\n * provided, `callback` is required while `args` is still optional. The results\n * for each of the applied async functions are passed to the final callback\n * as an array.\n *\n * @name applyEach\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s\n * to all call with the same arguments\n * @param {...*} [args] - any number of separate arguments to pass to the\n * function.\n * @param {Function} [callback] - the final argument should be the callback,\n * called when all functions have completed processing.\n * @returns {AsyncFunction} - Returns a function that takes no args other than\n * an optional callback, that is the result of applying the `args` to each\n * of the functions.\n * @example\n *\n * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket')\n *\n * appliedFn((err, results) => {\n * // results[0] is the results for `enableSearch`\n * // results[1] is the results for `updateSchema`\n * });\n *\n * // partial application example:\n * async.each(\n * buckets,\n * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(),\n * callback\n * );\n */\nvar applyEach = applyEach$1(map$1);\n\n/**\n * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.\n *\n * @name eachOfSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.eachOf]{@link module:Collections.eachOf}\n * @alias forEachOfSeries\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * Invoked with (item, key, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Invoked with (err).\n * @returns {Promise} a promise, if a callback is omitted\n */\nfunction eachOfSeries(coll, iteratee, callback) {\n return eachOfLimit$1(coll, 1, iteratee, callback)\n}\nvar eachOfSeries$1 = awaitify(eachOfSeries, 3);\n\n/**\n * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.\n *\n * @name mapSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.map]{@link module:Collections.map}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with the transformed item.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Results is an array of the\n * transformed items from the `coll`. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction mapSeries (coll, iteratee, callback) {\n return _asyncMap(eachOfSeries$1, coll, iteratee, callback)\n}\nvar mapSeries$1 = awaitify(mapSeries, 3);\n\n/**\n * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time.\n *\n * @name applyEachSeries\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.applyEach]{@link module:ControlFlow.applyEach}\n * @category Control Flow\n * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all\n * call with the same arguments\n * @param {...*} [args] - any number of separate arguments to pass to the\n * function.\n * @param {Function} [callback] - the final argument should be the callback,\n * called when all functions have completed processing.\n * @returns {AsyncFunction} - A function, that when called, is the result of\n * appling the `args` to the list of functions. It takes no args, other than\n * a callback.\n */\nvar applyEachSeries = applyEach$1(mapSeries$1);\n\nconst PROMISE_SYMBOL = Symbol('promiseCallback');\n\nfunction promiseCallback () {\n let resolve, reject;\n function callback (err, ...args) {\n if (err) return reject(err)\n resolve(args.length > 1 ? args : args[0]);\n }\n\n callback[PROMISE_SYMBOL] = new Promise((res, rej) => {\n resolve = res,\n reject = rej;\n });\n\n return callback\n}\n\n/**\n * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on\n * their requirements. Each function can optionally depend on other functions\n * being completed first, and each function is run as soon as its requirements\n * are satisfied.\n *\n * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence\n * will stop. Further tasks will not execute (so any other functions depending\n * on it will not run), and the main `callback` is immediately called with the\n * error.\n *\n * {@link AsyncFunction}s also receive an object containing the results of functions which\n * have completed so far as the first argument, if they have dependencies. If a\n * task function has no dependencies, it will only be passed a callback.\n *\n * @name auto\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Object} tasks - An object. Each of its properties is either a\n * function or an array of requirements, with the {@link AsyncFunction} itself the last item\n * in the array. The object's key of a property serves as the name of the task\n * defined by that property, i.e. can be used when specifying requirements for\n * other tasks. The function receives one or two arguments:\n * * a `results` object, containing the results of the previously executed\n * functions, only passed if the task has any dependencies,\n * * a `callback(err, result)` function, which must be called when finished,\n * passing an `error` (which can be `null`) and the result of the function's\n * execution.\n * @param {number} [concurrency=Infinity] - An optional `integer` for\n * determining the maximum number of tasks that can be run in parallel. By\n * default, as many as possible.\n * @param {Function} [callback] - An optional callback which is called when all\n * the tasks have been completed. It receives the `err` argument if any `tasks`\n * pass an error to their callback. Results are always returned; however, if an\n * error occurs, no further `tasks` will be performed, and the results object\n * will only contain partial results. Invoked with (err, results).\n * @returns {Promise} a promise, if a callback is not passed\n * @example\n *\n * //Using Callbacks\n * async.auto({\n * get_data: function(callback) {\n * // async code to get some data\n * callback(null, 'data', 'converted to array');\n * },\n * make_folder: function(callback) {\n * // async code to create a directory to store a file in\n * // this is run at the same time as getting the data\n * callback(null, 'folder');\n * },\n * write_file: ['get_data', 'make_folder', function(results, callback) {\n * // once there is some data and the directory exists,\n * // write the data to a file in the directory\n * callback(null, 'filename');\n * }],\n * email_link: ['write_file', function(results, callback) {\n * // once the file is written let's email a link to it...\n * callback(null, {'file':results.write_file, 'email':'user@example.com'});\n * }]\n * }, function(err, results) {\n * if (err) {\n * console.log('err = ', err);\n * }\n * console.log('results = ', results);\n * // results = {\n * // get_data: ['data', 'converted to array']\n * // make_folder; 'folder',\n * // write_file: 'filename'\n * // email_link: { file: 'filename', email: 'user@example.com' }\n * // }\n * });\n *\n * //Using Promises\n * async.auto({\n * get_data: function(callback) {\n * console.log('in get_data');\n * // async code to get some data\n * callback(null, 'data', 'converted to array');\n * },\n * make_folder: function(callback) {\n * console.log('in make_folder');\n * // async code to create a directory to store a file in\n * // this is run at the same time as getting the data\n * callback(null, 'folder');\n * },\n * write_file: ['get_data', 'make_folder', function(results, callback) {\n * // once there is some data and the directory exists,\n * // write the data to a file in the directory\n * callback(null, 'filename');\n * }],\n * email_link: ['write_file', function(results, callback) {\n * // once the file is written let's email a link to it...\n * callback(null, {'file':results.write_file, 'email':'user@example.com'});\n * }]\n * }).then(results => {\n * console.log('results = ', results);\n * // results = {\n * // get_data: ['data', 'converted to array']\n * // make_folder; 'folder',\n * // write_file: 'filename'\n * // email_link: { file: 'filename', email: 'user@example.com' }\n * // }\n * }).catch(err => {\n * console.log('err = ', err);\n * });\n *\n * //Using async/await\n * async () => {\n * try {\n * let results = await async.auto({\n * get_data: function(callback) {\n * // async code to get some data\n * callback(null, 'data', 'converted to array');\n * },\n * make_folder: function(callback) {\n * // async code to create a directory to store a file in\n * // this is run at the same time as getting the data\n * callback(null, 'folder');\n * },\n * write_file: ['get_data', 'make_folder', function(results, callback) {\n * // once there is some data and the directory exists,\n * // write the data to a file in the directory\n * callback(null, 'filename');\n * }],\n * email_link: ['write_file', function(results, callback) {\n * // once the file is written let's email a link to it...\n * callback(null, {'file':results.write_file, 'email':'user@example.com'});\n * }]\n * });\n * console.log('results = ', results);\n * // results = {\n * // get_data: ['data', 'converted to array']\n * // make_folder; 'folder',\n * // write_file: 'filename'\n * // email_link: { file: 'filename', email: 'user@example.com' }\n * // }\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n */\nfunction auto(tasks, concurrency, callback) {\n if (typeof concurrency !== 'number') {\n // concurrency is optional, shift the args.\n callback = concurrency;\n concurrency = null;\n }\n callback = once(callback || promiseCallback());\n var numTasks = Object.keys(tasks).length;\n if (!numTasks) {\n return callback(null);\n }\n if (!concurrency) {\n concurrency = numTasks;\n }\n\n var results = {};\n var runningTasks = 0;\n var canceled = false;\n var hasError = false;\n\n var listeners = Object.create(null);\n\n var readyTasks = [];\n\n // for cycle detection:\n var readyToCheck = []; // tasks that have been identified as reachable\n // without the possibility of returning to an ancestor task\n var uncheckedDependencies = {};\n\n Object.keys(tasks).forEach(key => {\n var task = tasks[key];\n if (!Array.isArray(task)) {\n // no dependencies\n enqueueTask(key, [task]);\n readyToCheck.push(key);\n return;\n }\n\n var dependencies = task.slice(0, task.length - 1);\n var remainingDependencies = dependencies.length;\n if (remainingDependencies === 0) {\n enqueueTask(key, task);\n readyToCheck.push(key);\n return;\n }\n uncheckedDependencies[key] = remainingDependencies;\n\n dependencies.forEach(dependencyName => {\n if (!tasks[dependencyName]) {\n throw new Error('async.auto task `' + key +\n '` has a non-existent dependency `' +\n dependencyName + '` in ' +\n dependencies.join(', '));\n }\n addListener(dependencyName, () => {\n remainingDependencies--;\n if (remainingDependencies === 0) {\n enqueueTask(key, task);\n }\n });\n });\n });\n\n checkForDeadlocks();\n processQueue();\n\n function enqueueTask(key, task) {\n readyTasks.push(() => runTask(key, task));\n }\n\n function processQueue() {\n if (canceled) return\n if (readyTasks.length === 0 && runningTasks === 0) {\n return callback(null, results);\n }\n while(readyTasks.length && runningTasks < concurrency) {\n var run = readyTasks.shift();\n run();\n }\n\n }\n\n function addListener(taskName, fn) {\n var taskListeners = listeners[taskName];\n if (!taskListeners) {\n taskListeners = listeners[taskName] = [];\n }\n\n taskListeners.push(fn);\n }\n\n function taskComplete(taskName) {\n var taskListeners = listeners[taskName] || [];\n taskListeners.forEach(fn => fn());\n processQueue();\n }\n\n\n function runTask(key, task) {\n if (hasError) return;\n\n var taskCallback = onlyOnce((err, ...result) => {\n runningTasks--;\n if (err === false) {\n canceled = true;\n return\n }\n if (result.length < 2) {\n [result] = result;\n }\n if (err) {\n var safeResults = {};\n Object.keys(results).forEach(rkey => {\n safeResults[rkey] = results[rkey];\n });\n safeResults[key] = result;\n hasError = true;\n listeners = Object.create(null);\n if (canceled) return\n callback(err, safeResults);\n } else {\n results[key] = result;\n taskComplete(key);\n }\n });\n\n runningTasks++;\n var taskFn = wrapAsync(task[task.length - 1]);\n if (task.length > 1) {\n taskFn(results, taskCallback);\n } else {\n taskFn(taskCallback);\n }\n }\n\n function checkForDeadlocks() {\n // Kahn's algorithm\n // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm\n // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html\n var currentTask;\n var counter = 0;\n while (readyToCheck.length) {\n currentTask = readyToCheck.pop();\n counter++;\n getDependents(currentTask).forEach(dependent => {\n if (--uncheckedDependencies[dependent] === 0) {\n readyToCheck.push(dependent);\n }\n });\n }\n\n if (counter !== numTasks) {\n throw new Error(\n 'async.auto cannot execute tasks due to a recursive dependency'\n );\n }\n }\n\n function getDependents(taskName) {\n var result = [];\n Object.keys(tasks).forEach(key => {\n const task = tasks[key];\n if (Array.isArray(task) && task.indexOf(taskName) >= 0) {\n result.push(key);\n }\n });\n return result;\n }\n\n return callback[PROMISE_SYMBOL]\n}\n\nvar FN_ARGS = /^(?:async\\s)?(?:function)?\\s*(?:\\w+\\s*)?\\(([^)]+)\\)(?:\\s*{)/;\nvar ARROW_FN_ARGS = /^(?:async\\s)?\\s*(?:\\(\\s*)?((?:[^)=\\s]\\s*)*)(?:\\)\\s*)?=>/;\nvar FN_ARG_SPLIT = /,/;\nvar FN_ARG = /(=.+)?(\\s*)$/;\n\nfunction stripComments(string) {\n let stripped = '';\n let index = 0;\n let endBlockComment = string.indexOf('*/');\n while (index < string.length) {\n if (string[index] === '/' && string[index+1] === '/') {\n // inline comment\n let endIndex = string.indexOf('\\n', index);\n index = (endIndex === -1) ? string.length : endIndex;\n } else if ((endBlockComment !== -1) && (string[index] === '/') && (string[index+1] === '*')) {\n // block comment\n let endIndex = string.indexOf('*/', index);\n if (endIndex !== -1) {\n index = endIndex + 2;\n endBlockComment = string.indexOf('*/', index);\n } else {\n stripped += string[index];\n index++;\n }\n } else {\n stripped += string[index];\n index++;\n }\n }\n return stripped;\n}\n\nfunction parseParams(func) {\n const src = stripComments(func.toString());\n let match = src.match(FN_ARGS);\n if (!match) {\n match = src.match(ARROW_FN_ARGS);\n }\n if (!match) throw new Error('could not parse args in autoInject\\nSource:\\n' + src)\n let [, args] = match;\n return args\n .replace(/\\s/g, '')\n .split(FN_ARG_SPLIT)\n .map((arg) => arg.replace(FN_ARG, '').trim());\n}\n\n/**\n * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent\n * tasks are specified as parameters to the function, after the usual callback\n * parameter, with the parameter names matching the names of the tasks it\n * depends on. This can provide even more readable task graphs which can be\n * easier to maintain.\n *\n * If a final callback is specified, the task results are similarly injected,\n * specified as named parameters after the initial error parameter.\n *\n * The autoInject function is purely syntactic sugar and its semantics are\n * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}.\n *\n * @name autoInject\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.auto]{@link module:ControlFlow.auto}\n * @category Control Flow\n * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of\n * the form 'func([dependencies...], callback). The object's key of a property\n * serves as the name of the task defined by that property, i.e. can be used\n * when specifying requirements for other tasks.\n * * The `callback` parameter is a `callback(err, result)` which must be called\n * when finished, passing an `error` (which can be `null`) and the result of\n * the function's execution. The remaining parameters name other tasks on\n * which the task is dependent, and the results from those tasks are the\n * arguments of those parameters.\n * @param {Function} [callback] - An optional callback which is called when all\n * the tasks have been completed. It receives the `err` argument if any `tasks`\n * pass an error to their callback, and a `results` object with any completed\n * task results, similar to `auto`.\n * @returns {Promise} a promise, if no callback is passed\n * @example\n *\n * // The example from `auto` can be rewritten as follows:\n * async.autoInject({\n * get_data: function(callback) {\n * // async code to get some data\n * callback(null, 'data', 'converted to array');\n * },\n * make_folder: function(callback) {\n * // async code to create a directory to store a file in\n * // this is run at the same time as getting the data\n * callback(null, 'folder');\n * },\n * write_file: function(get_data, make_folder, callback) {\n * // once there is some data and the directory exists,\n * // write the data to a file in the directory\n * callback(null, 'filename');\n * },\n * email_link: function(write_file, callback) {\n * // once the file is written let's email a link to it...\n * // write_file contains the filename returned by write_file.\n * callback(null, {'file':write_file, 'email':'user@example.com'});\n * }\n * }, function(err, results) {\n * console.log('err = ', err);\n * console.log('email_link = ', results.email_link);\n * });\n *\n * // If you are using a JS minifier that mangles parameter names, `autoInject`\n * // will not work with plain functions, since the parameter names will be\n * // collapsed to a single letter identifier. To work around this, you can\n * // explicitly specify the names of the parameters your task function needs\n * // in an array, similar to Angular.js dependency injection.\n *\n * // This still has an advantage over plain `auto`, since the results a task\n * // depends on are still spread into arguments.\n * async.autoInject({\n * //...\n * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) {\n * callback(null, 'filename');\n * }],\n * email_link: ['write_file', function(write_file, callback) {\n * callback(null, {'file':write_file, 'email':'user@example.com'});\n * }]\n * //...\n * }, function(err, results) {\n * console.log('err = ', err);\n * console.log('email_link = ', results.email_link);\n * });\n */\nfunction autoInject(tasks, callback) {\n var newTasks = {};\n\n Object.keys(tasks).forEach(key => {\n var taskFn = tasks[key];\n var params;\n var fnIsAsync = isAsync(taskFn);\n var hasNoDeps =\n (!fnIsAsync && taskFn.length === 1) ||\n (fnIsAsync && taskFn.length === 0);\n\n if (Array.isArray(taskFn)) {\n params = [...taskFn];\n taskFn = params.pop();\n\n newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn);\n } else if (hasNoDeps) {\n // no dependencies, use the function as-is\n newTasks[key] = taskFn;\n } else {\n params = parseParams(taskFn);\n if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) {\n throw new Error(\"autoInject task functions require explicit parameters.\");\n }\n\n // remove callback param\n if (!fnIsAsync) params.pop();\n\n newTasks[key] = params.concat(newTask);\n }\n\n function newTask(results, taskCb) {\n var newArgs = params.map(name => results[name]);\n newArgs.push(taskCb);\n wrapAsync(taskFn)(...newArgs);\n }\n });\n\n return auto(newTasks, callback);\n}\n\n// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation\n// used for queues. This implementation assumes that the node provided by the user can be modified\n// to adjust the next and last properties. We implement only the minimal functionality\n// for queue support.\nclass DLL {\n constructor() {\n this.head = this.tail = null;\n this.length = 0;\n }\n\n removeLink(node) {\n if (node.prev) node.prev.next = node.next;\n else this.head = node.next;\n if (node.next) node.next.prev = node.prev;\n else this.tail = node.prev;\n\n node.prev = node.next = null;\n this.length -= 1;\n return node;\n }\n\n empty () {\n while(this.head) this.shift();\n return this;\n }\n\n insertAfter(node, newNode) {\n newNode.prev = node;\n newNode.next = node.next;\n if (node.next) node.next.prev = newNode;\n else this.tail = newNode;\n node.next = newNode;\n this.length += 1;\n }\n\n insertBefore(node, newNode) {\n newNode.prev = node.prev;\n newNode.next = node;\n if (node.prev) node.prev.next = newNode;\n else this.head = newNode;\n node.prev = newNode;\n this.length += 1;\n }\n\n unshift(node) {\n if (this.head) this.insertBefore(this.head, node);\n else setInitial(this, node);\n }\n\n push(node) {\n if (this.tail) this.insertAfter(this.tail, node);\n else setInitial(this, node);\n }\n\n shift() {\n return this.head && this.removeLink(this.head);\n }\n\n pop() {\n return this.tail && this.removeLink(this.tail);\n }\n\n toArray() {\n return [...this]\n }\n\n *[Symbol.iterator] () {\n var cur = this.head;\n while (cur) {\n yield cur.data;\n cur = cur.next;\n }\n }\n\n remove (testFn) {\n var curr = this.head;\n while(curr) {\n var {next} = curr;\n if (testFn(curr)) {\n this.removeLink(curr);\n }\n curr = next;\n }\n return this;\n }\n}\n\nfunction setInitial(dll, node) {\n dll.length = 1;\n dll.head = dll.tail = node;\n}\n\nfunction queue$1(worker, concurrency, payload) {\n if (concurrency == null) {\n concurrency = 1;\n }\n else if(concurrency === 0) {\n throw new RangeError('Concurrency must not be zero');\n }\n\n var _worker = wrapAsync(worker);\n var numRunning = 0;\n var workersList = [];\n const events = {\n error: [],\n drain: [],\n saturated: [],\n unsaturated: [],\n empty: []\n };\n\n function on (event, handler) {\n events[event].push(handler);\n }\n\n function once (event, handler) {\n const handleAndRemove = (...args) => {\n off(event, handleAndRemove);\n handler(...args);\n };\n events[event].push(handleAndRemove);\n }\n\n function off (event, handler) {\n if (!event) return Object.keys(events).forEach(ev => events[ev] = [])\n if (!handler) return events[event] = []\n events[event] = events[event].filter(ev => ev !== handler);\n }\n\n function trigger (event, ...args) {\n events[event].forEach(handler => handler(...args));\n }\n\n var processingScheduled = false;\n function _insert(data, insertAtFront, rejectOnError, callback) {\n if (callback != null && typeof callback !== 'function') {\n throw new Error('task callback must be a function');\n }\n q.started = true;\n\n var res, rej;\n function promiseCallback (err, ...args) {\n // we don't care about the error, let the global error handler\n // deal with it\n if (err) return rejectOnError ? rej(err) : res()\n if (args.length <= 1) return res(args[0])\n res(args);\n }\n\n var item = q._createTaskItem(\n data,\n rejectOnError ? promiseCallback :\n (callback || promiseCallback)\n );\n\n if (insertAtFront) {\n q._tasks.unshift(item);\n } else {\n q._tasks.push(item);\n }\n\n if (!processingScheduled) {\n processingScheduled = true;\n setImmediate$1(() => {\n processingScheduled = false;\n q.process();\n });\n }\n\n if (rejectOnError || !callback) {\n return new Promise((resolve, reject) => {\n res = resolve;\n rej = reject;\n })\n }\n }\n\n function _createCB(tasks) {\n return function (err, ...args) {\n numRunning -= 1;\n\n for (var i = 0, l = tasks.length; i < l; i++) {\n var task = tasks[i];\n\n var index = workersList.indexOf(task);\n if (index === 0) {\n workersList.shift();\n } else if (index > 0) {\n workersList.splice(index, 1);\n }\n\n task.callback(err, ...args);\n\n if (err != null) {\n trigger('error', err, task.data);\n }\n }\n\n if (numRunning <= (q.concurrency - q.buffer) ) {\n trigger('unsaturated');\n }\n\n if (q.idle()) {\n trigger('drain');\n }\n q.process();\n };\n }\n\n function _maybeDrain(data) {\n if (data.length === 0 && q.idle()) {\n // call drain immediately if there are no tasks\n setImmediate$1(() => trigger('drain'));\n return true\n }\n return false\n }\n\n const eventMethod = (name) => (handler) => {\n if (!handler) {\n return new Promise((resolve, reject) => {\n once(name, (err, data) => {\n if (err) return reject(err)\n resolve(data);\n });\n })\n }\n off(name);\n on(name, handler);\n\n };\n\n var isProcessing = false;\n var q = {\n _tasks: new DLL(),\n _createTaskItem (data, callback) {\n return {\n data,\n callback\n };\n },\n *[Symbol.iterator] () {\n yield* q._tasks[Symbol.iterator]();\n },\n concurrency,\n payload,\n buffer: concurrency / 4,\n started: false,\n paused: false,\n push (data, callback) {\n if (Array.isArray(data)) {\n if (_maybeDrain(data)) return\n return data.map(datum => _insert(datum, false, false, callback))\n }\n return _insert(data, false, false, callback);\n },\n pushAsync (data, callback) {\n if (Array.isArray(data)) {\n if (_maybeDrain(data)) return\n return data.map(datum => _insert(datum, false, true, callback))\n }\n return _insert(data, false, true, callback);\n },\n kill () {\n off();\n q._tasks.empty();\n },\n unshift (data, callback) {\n if (Array.isArray(data)) {\n if (_maybeDrain(data)) return\n return data.map(datum => _insert(datum, true, false, callback))\n }\n return _insert(data, true, false, callback);\n },\n unshiftAsync (data, callback) {\n if (Array.isArray(data)) {\n if (_maybeDrain(data)) return\n return data.map(datum => _insert(datum, true, true, callback))\n }\n return _insert(data, true, true, callback);\n },\n remove (testFn) {\n q._tasks.remove(testFn);\n },\n process () {\n // Avoid trying to start too many processing operations. This can occur\n // when callbacks resolve synchronously (#1267).\n if (isProcessing) {\n return;\n }\n isProcessing = true;\n while(!q.paused && numRunning < q.concurrency && q._tasks.length){\n var tasks = [], data = [];\n var l = q._tasks.length;\n if (q.payload) l = Math.min(l, q.payload);\n for (var i = 0; i < l; i++) {\n var node = q._tasks.shift();\n tasks.push(node);\n workersList.push(node);\n data.push(node.data);\n }\n\n numRunning += 1;\n\n if (q._tasks.length === 0) {\n trigger('empty');\n }\n\n if (numRunning === q.concurrency) {\n trigger('saturated');\n }\n\n var cb = onlyOnce(_createCB(tasks));\n _worker(data, cb);\n }\n isProcessing = false;\n },\n length () {\n return q._tasks.length;\n },\n running () {\n return numRunning;\n },\n workersList () {\n return workersList;\n },\n idle() {\n return q._tasks.length + numRunning === 0;\n },\n pause () {\n q.paused = true;\n },\n resume () {\n if (q.paused === false) { return; }\n q.paused = false;\n setImmediate$1(q.process);\n }\n };\n // define these as fixed properties, so people get useful errors when updating\n Object.defineProperties(q, {\n saturated: {\n writable: false,\n value: eventMethod('saturated')\n },\n unsaturated: {\n writable: false,\n value: eventMethod('unsaturated')\n },\n empty: {\n writable: false,\n value: eventMethod('empty')\n },\n drain: {\n writable: false,\n value: eventMethod('drain')\n },\n error: {\n writable: false,\n value: eventMethod('error')\n },\n });\n return q;\n}\n\n/**\n * Creates a `cargo` object with the specified payload. Tasks added to the\n * cargo will be processed altogether (up to the `payload` limit). If the\n * `worker` is in progress, the task is queued until it becomes available. Once\n * the `worker` has completed some tasks, each callback of those tasks is\n * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)\n * for how `cargo` and `queue` work.\n *\n * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers\n * at a time, cargo passes an array of tasks to a single worker, repeating\n * when the worker is finished.\n *\n * @name cargo\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.queue]{@link module:ControlFlow.queue}\n * @category Control Flow\n * @param {AsyncFunction} worker - An asynchronous function for processing an array\n * of queued tasks. Invoked with `(tasks, callback)`.\n * @param {number} [payload=Infinity] - An optional `integer` for determining\n * how many tasks should be processed per round; if omitted, the default is\n * unlimited.\n * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can\n * attached as certain properties to listen for specific events during the\n * lifecycle of the cargo and inner queue.\n * @example\n *\n * // create a cargo object with payload 2\n * var cargo = async.cargo(function(tasks, callback) {\n * for (var i=0; i {\n * console.log(result);\n * // 6000\n * // which is the sum of the file sizes of the three files\n * }).catch( err => {\n * console.log(err);\n * });\n *\n * // Error Handling\n * async.reduce(withMissingFileList, 0, getFileSizeInBytes)\n * .then( result => {\n * console.log(result);\n * }).catch( err => {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let result = await async.reduce(fileList, 0, getFileSizeInBytes);\n * console.log(result);\n * // 6000\n * // which is the sum of the file sizes of the three files\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n * // Error Handling\n * async () => {\n * try {\n * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes);\n * console.log(result);\n * }\n * catch (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * }\n * }\n *\n */\nfunction reduce(coll, memo, iteratee, callback) {\n callback = once(callback);\n var _iteratee = wrapAsync(iteratee);\n return eachOfSeries$1(coll, (x, i, iterCb) => {\n _iteratee(memo, x, (err, v) => {\n memo = v;\n iterCb(err);\n });\n }, err => callback(err, memo));\n}\nvar reduce$1 = awaitify(reduce, 4);\n\n/**\n * Version of the compose function that is more natural to read. Each function\n * consumes the return value of the previous function. It is the equivalent of\n * [compose]{@link module:ControlFlow.compose} with the arguments reversed.\n *\n * Each function is executed with the `this` binding of the composed function.\n *\n * @name seq\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.compose]{@link module:ControlFlow.compose}\n * @category Control Flow\n * @param {...AsyncFunction} functions - the asynchronous functions to compose\n * @returns {Function} a function that composes the `functions` in order\n * @example\n *\n * // Requires lodash (or underscore), express3 and dresende's orm2.\n * // Part of an app, that fetches cats of the logged user.\n * // This example uses `seq` function to avoid overnesting and error\n * // handling clutter.\n * app.get('/cats', function(request, response) {\n * var User = request.models.User;\n * async.seq(\n * User.get.bind(User), // 'User.get' has signature (id, callback(err, data))\n * function(user, fn) {\n * user.getCats(fn); // 'getCats' has signature (callback(err, data))\n * }\n * )(req.session.user_id, function (err, cats) {\n * if (err) {\n * console.error(err);\n * response.json({ status: 'error', message: err.message });\n * } else {\n * response.json({ status: 'ok', message: 'Cats found', data: cats });\n * }\n * });\n * });\n */\nfunction seq(...functions) {\n var _functions = functions.map(wrapAsync);\n return function (...args) {\n var that = this;\n\n var cb = args[args.length - 1];\n if (typeof cb == 'function') {\n args.pop();\n } else {\n cb = promiseCallback();\n }\n\n reduce$1(_functions, args, (newargs, fn, iterCb) => {\n fn.apply(that, newargs.concat((err, ...nextargs) => {\n iterCb(err, nextargs);\n }));\n },\n (err, results) => cb(err, ...results));\n\n return cb[PROMISE_SYMBOL]\n };\n}\n\n/**\n * Creates a function which is a composition of the passed asynchronous\n * functions. Each function consumes the return value of the function that\n * follows. Composing functions `f()`, `g()`, and `h()` would produce the result\n * of `f(g(h()))`, only this version uses callbacks to obtain the return values.\n *\n * If the last argument to the composed function is not a function, a promise\n * is returned when you call it.\n *\n * Each function is executed with the `this` binding of the composed function.\n *\n * @name compose\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {...AsyncFunction} functions - the asynchronous functions to compose\n * @returns {Function} an asynchronous function that is the composed\n * asynchronous `functions`\n * @example\n *\n * function add1(n, callback) {\n * setTimeout(function () {\n * callback(null, n + 1);\n * }, 10);\n * }\n *\n * function mul3(n, callback) {\n * setTimeout(function () {\n * callback(null, n * 3);\n * }, 10);\n * }\n *\n * var add1mul3 = async.compose(mul3, add1);\n * add1mul3(4, function (err, result) {\n * // result now equals 15\n * });\n */\nfunction compose(...args) {\n return seq(...args.reverse());\n}\n\n/**\n * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time.\n *\n * @name mapLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.map]{@link module:Collections.map}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with the transformed item.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Results is an array of the\n * transformed items from the `coll`. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction mapLimit (coll, limit, iteratee, callback) {\n return _asyncMap(eachOfLimit$2(limit), coll, iteratee, callback)\n}\nvar mapLimit$1 = awaitify(mapLimit, 4);\n\n/**\n * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time.\n *\n * @name concatLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.concat]{@link module:Collections.concat}\n * @category Collection\n * @alias flatMapLimit\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,\n * which should use an array as its result. Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished, or an error occurs. Results is an array\n * containing the concatenated results of the `iteratee` function. Invoked with\n * (err, results).\n * @returns A Promise, if no callback is passed\n */\nfunction concatLimit(coll, limit, iteratee, callback) {\n var _iteratee = wrapAsync(iteratee);\n return mapLimit$1(coll, limit, (val, iterCb) => {\n _iteratee(val, (err, ...args) => {\n if (err) return iterCb(err);\n return iterCb(err, args);\n });\n }, (err, mapResults) => {\n var result = [];\n for (var i = 0; i < mapResults.length; i++) {\n if (mapResults[i]) {\n result = result.concat(...mapResults[i]);\n }\n }\n\n return callback(err, result);\n });\n}\nvar concatLimit$1 = awaitify(concatLimit, 4);\n\n/**\n * Applies `iteratee` to each item in `coll`, concatenating the results. Returns\n * the concatenated list. The `iteratee`s are called in parallel, and the\n * results are concatenated as they return. The results array will be returned in\n * the original order of `coll` passed to the `iteratee` function.\n *\n * @name concat\n * @static\n * @memberOf module:Collections\n * @method\n * @category Collection\n * @alias flatMap\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,\n * which should use an array as its result. Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished, or an error occurs. Results is an array\n * containing the concatenated results of the `iteratee` function. Invoked with\n * (err, results).\n * @returns A Promise, if no callback is passed\n * @example\n *\n * // dir1 is a directory that contains file1.txt, file2.txt\n * // dir2 is a directory that contains file3.txt, file4.txt\n * // dir3 is a directory that contains file5.txt\n * // dir4 does not exist\n *\n * let directoryList = ['dir1','dir2','dir3'];\n * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4'];\n *\n * // Using callbacks\n * async.concat(directoryList, fs.readdir, function(err, results) {\n * if (err) {\n * console.log(err);\n * } else {\n * console.log(results);\n * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]\n * }\n * });\n *\n * // Error Handling\n * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) {\n * if (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * // since dir4 does not exist\n * } else {\n * console.log(results);\n * }\n * });\n *\n * // Using Promises\n * async.concat(directoryList, fs.readdir)\n * .then(results => {\n * console.log(results);\n * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]\n * }).catch(err => {\n * console.log(err);\n * });\n *\n * // Error Handling\n * async.concat(withMissingDirectoryList, fs.readdir)\n * .then(results => {\n * console.log(results);\n * }).catch(err => {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * // since dir4 does not exist\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let results = await async.concat(directoryList, fs.readdir);\n * console.log(results);\n * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ]\n * } catch (err) {\n * console.log(err);\n * }\n * }\n *\n * // Error Handling\n * async () => {\n * try {\n * let results = await async.concat(withMissingDirectoryList, fs.readdir);\n * console.log(results);\n * } catch (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * // since dir4 does not exist\n * }\n * }\n *\n */\nfunction concat(coll, iteratee, callback) {\n return concatLimit$1(coll, Infinity, iteratee, callback)\n}\nvar concat$1 = awaitify(concat, 3);\n\n/**\n * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time.\n *\n * @name concatSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.concat]{@link module:Collections.concat}\n * @category Collection\n * @alias flatMapSeries\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`.\n * The iteratee should complete with an array an array of results.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished, or an error occurs. Results is an array\n * containing the concatenated results of the `iteratee` function. Invoked with\n * (err, results).\n * @returns A Promise, if no callback is passed\n */\nfunction concatSeries(coll, iteratee, callback) {\n return concatLimit$1(coll, 1, iteratee, callback)\n}\nvar concatSeries$1 = awaitify(concatSeries, 3);\n\n/**\n * Returns a function that when called, calls-back with the values provided.\n * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to\n * [`auto`]{@link module:ControlFlow.auto}.\n *\n * @name constant\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {...*} arguments... - Any number of arguments to automatically invoke\n * callback with.\n * @returns {AsyncFunction} Returns a function that when invoked, automatically\n * invokes the callback with the previous given arguments.\n * @example\n *\n * async.waterfall([\n * async.constant(42),\n * function (value, next) {\n * // value === 42\n * },\n * //...\n * ], callback);\n *\n * async.waterfall([\n * async.constant(filename, \"utf8\"),\n * fs.readFile,\n * function (fileData, next) {\n * //...\n * }\n * //...\n * ], callback);\n *\n * async.auto({\n * hostname: async.constant(\"https://server.net/\"),\n * port: findFreePort,\n * launchServer: [\"hostname\", \"port\", function (options, cb) {\n * startServer(options, cb);\n * }],\n * //...\n * }, callback);\n */\nfunction constant$1(...args) {\n return function (...ignoredArgs/*, callback*/) {\n var callback = ignoredArgs.pop();\n return callback(null, ...args);\n };\n}\n\nfunction _createTester(check, getResult) {\n return (eachfn, arr, _iteratee, cb) => {\n var testPassed = false;\n var testResult;\n const iteratee = wrapAsync(_iteratee);\n eachfn(arr, (value, _, callback) => {\n iteratee(value, (err, result) => {\n if (err || err === false) return callback(err);\n\n if (check(result) && !testResult) {\n testPassed = true;\n testResult = getResult(true, value);\n return callback(null, breakLoop);\n }\n callback();\n });\n }, err => {\n if (err) return cb(err);\n cb(null, testPassed ? testResult : getResult(false));\n });\n };\n}\n\n/**\n * Returns the first value in `coll` that passes an async truth test. The\n * `iteratee` is applied in parallel, meaning the first iteratee to return\n * `true` will fire the detect `callback` with that result. That means the\n * result might not be the first item in the original `coll` (in terms of order)\n * that passes the test.\n\n * If order within the original `coll` is important, then look at\n * [`detectSeries`]{@link module:Collections.detectSeries}.\n *\n * @name detect\n * @static\n * @memberOf module:Collections\n * @method\n * @alias find\n * @category Collections\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.\n * The iteratee must complete with a boolean value as its result.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called as soon as any\n * iteratee returns `true`, or after all the `iteratee` functions have finished.\n * Result will be the first item in the array that passes the truth test\n * (iteratee) or the value `undefined` if none passed. Invoked with\n * (err, result).\n * @returns {Promise} a promise, if a callback is omitted\n * @example\n *\n * // dir1 is a directory that contains file1.txt, file2.txt\n * // dir2 is a directory that contains file3.txt, file4.txt\n * // dir3 is a directory that contains file5.txt\n *\n * // asynchronous function that checks if a file exists\n * function fileExists(file, callback) {\n * fs.access(file, fs.constants.F_OK, (err) => {\n * callback(null, !err);\n * });\n * }\n *\n * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists,\n * function(err, result) {\n * console.log(result);\n * // dir1/file1.txt\n * // result now equals the first file in the list that exists\n * }\n *);\n *\n * // Using Promises\n * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists)\n * .then(result => {\n * console.log(result);\n * // dir1/file1.txt\n * // result now equals the first file in the list that exists\n * }).catch(err => {\n * console.log(err);\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists);\n * console.log(result);\n * // dir1/file1.txt\n * // result now equals the file in the list that exists\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n */\nfunction detect(coll, iteratee, callback) {\n return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback)\n}\nvar detect$1 = awaitify(detect, 3);\n\n/**\n * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name detectLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.detect]{@link module:Collections.detect}\n * @alias findLimit\n * @category Collections\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.\n * The iteratee must complete with a boolean value as its result.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called as soon as any\n * iteratee returns `true`, or after all the `iteratee` functions have finished.\n * Result will be the first item in the array that passes the truth test\n * (iteratee) or the value `undefined` if none passed. Invoked with\n * (err, result).\n * @returns {Promise} a promise, if a callback is omitted\n */\nfunction detectLimit(coll, limit, iteratee, callback) {\n return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(limit), coll, iteratee, callback)\n}\nvar detectLimit$1 = awaitify(detectLimit, 4);\n\n/**\n * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time.\n *\n * @name detectSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.detect]{@link module:Collections.detect}\n * @alias findSeries\n * @category Collections\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.\n * The iteratee must complete with a boolean value as its result.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called as soon as any\n * iteratee returns `true`, or after all the `iteratee` functions have finished.\n * Result will be the first item in the array that passes the truth test\n * (iteratee) or the value `undefined` if none passed. Invoked with\n * (err, result).\n * @returns {Promise} a promise, if a callback is omitted\n */\nfunction detectSeries(coll, iteratee, callback) {\n return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(1), coll, iteratee, callback)\n}\n\nvar detectSeries$1 = awaitify(detectSeries, 3);\n\nfunction consoleFunc(name) {\n return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => {\n /* istanbul ignore else */\n if (typeof console === 'object') {\n /* istanbul ignore else */\n if (err) {\n /* istanbul ignore else */\n if (console.error) {\n console.error(err);\n }\n } else if (console[name]) { /* istanbul ignore else */\n resultArgs.forEach(x => console[name](x));\n }\n }\n })\n}\n\n/**\n * Logs the result of an [`async` function]{@link AsyncFunction} to the\n * `console` using `console.dir` to display the properties of the resulting object.\n * Only works in Node.js or in browsers that support `console.dir` and\n * `console.error` (such as FF and Chrome).\n * If multiple arguments are returned from the async function,\n * `console.dir` is called on each argument in order.\n *\n * @name dir\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {AsyncFunction} function - The function you want to eventually apply\n * all arguments to.\n * @param {...*} arguments... - Any number of arguments to apply to the function.\n * @example\n *\n * // in a module\n * var hello = function(name, callback) {\n * setTimeout(function() {\n * callback(null, {hello: name});\n * }, 1000);\n * };\n *\n * // in the node repl\n * node> async.dir(hello, 'world');\n * {hello: 'world'}\n */\nvar dir = consoleFunc('dir');\n\n/**\n * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in\n * the order of operations, the arguments `test` and `iteratee` are switched.\n *\n * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.\n *\n * @name doWhilst\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.whilst]{@link module:ControlFlow.whilst}\n * @category Control Flow\n * @param {AsyncFunction} iteratee - A function which is called each time `test`\n * passes. Invoked with (callback).\n * @param {AsyncFunction} test - asynchronous truth test to perform after each\n * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the\n * non-error args from the previous callback of `iteratee`.\n * @param {Function} [callback] - A callback which is called after the test\n * function has failed and repeated execution of `iteratee` has stopped.\n * `callback` will be passed an error and any arguments passed to the final\n * `iteratee`'s callback. Invoked with (err, [results]);\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction doWhilst(iteratee, test, callback) {\n callback = onlyOnce(callback);\n var _fn = wrapAsync(iteratee);\n var _test = wrapAsync(test);\n var results;\n\n function next(err, ...args) {\n if (err) return callback(err);\n if (err === false) return;\n results = args;\n _test(...args, check);\n }\n\n function check(err, truth) {\n if (err) return callback(err);\n if (err === false) return;\n if (!truth) return callback(null, ...results);\n _fn(next);\n }\n\n return check(null, true);\n}\n\nvar doWhilst$1 = awaitify(doWhilst, 3);\n\n/**\n * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the\n * argument ordering differs from `until`.\n *\n * @name doUntil\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.doWhilst]{@link module:ControlFlow.doWhilst}\n * @category Control Flow\n * @param {AsyncFunction} iteratee - An async function which is called each time\n * `test` fails. Invoked with (callback).\n * @param {AsyncFunction} test - asynchronous truth test to perform after each\n * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the\n * non-error args from the previous callback of `iteratee`\n * @param {Function} [callback] - A callback which is called after the test\n * function has passed and repeated execution of `iteratee` has stopped. `callback`\n * will be passed an error and any arguments passed to the final `iteratee`'s\n * callback. Invoked with (err, [results]);\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction doUntil(iteratee, test, callback) {\n const _test = wrapAsync(test);\n return doWhilst$1(iteratee, (...args) => {\n const cb = args.pop();\n _test(...args, (err, truth) => cb (err, !truth));\n }, callback);\n}\n\nfunction _withoutIndex(iteratee) {\n return (value, index, callback) => iteratee(value, callback);\n}\n\n/**\n * Applies the function `iteratee` to each item in `coll`, in parallel.\n * The `iteratee` is called with an item from the list, and a callback for when\n * it has finished. If the `iteratee` passes an error to its `callback`, the\n * main `callback` (for the `each` function) is immediately called with the\n * error.\n *\n * Note, that since this function applies `iteratee` to each item in parallel,\n * there is no guarantee that the iteratee functions will complete in order.\n *\n * @name each\n * @static\n * @memberOf module:Collections\n * @method\n * @alias forEach\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to\n * each item in `coll`. Invoked with (item, callback).\n * The array index is not passed to the iteratee.\n * If you need the index, use `eachOf`.\n * @param {Function} [callback] - A callback which is called when all\n * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n * @returns {Promise} a promise, if a callback is omitted\n * @example\n *\n * // dir1 is a directory that contains file1.txt, file2.txt\n * // dir2 is a directory that contains file3.txt, file4.txt\n * // dir3 is a directory that contains file5.txt\n * // dir4 does not exist\n *\n * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt'];\n * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt'];\n *\n * // asynchronous function that deletes a file\n * const deleteFile = function(file, callback) {\n * fs.unlink(file, callback);\n * };\n *\n * // Using callbacks\n * async.each(fileList, deleteFile, function(err) {\n * if( err ) {\n * console.log(err);\n * } else {\n * console.log('All files have been deleted successfully');\n * }\n * });\n *\n * // Error Handling\n * async.each(withMissingFileList, deleteFile, function(err){\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * // since dir4/file2.txt does not exist\n * // dir1/file1.txt could have been deleted\n * });\n *\n * // Using Promises\n * async.each(fileList, deleteFile)\n * .then( () => {\n * console.log('All files have been deleted successfully');\n * }).catch( err => {\n * console.log(err);\n * });\n *\n * // Error Handling\n * async.each(fileList, deleteFile)\n * .then( () => {\n * console.log('All files have been deleted successfully');\n * }).catch( err => {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * // since dir4/file2.txt does not exist\n * // dir1/file1.txt could have been deleted\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * await async.each(files, deleteFile);\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n * // Error Handling\n * async () => {\n * try {\n * await async.each(withMissingFileList, deleteFile);\n * }\n * catch (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * // since dir4/file2.txt does not exist\n * // dir1/file1.txt could have been deleted\n * }\n * }\n *\n */\nfunction eachLimit$2(coll, iteratee, callback) {\n return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback);\n}\n\nvar each = awaitify(eachLimit$2, 3);\n\n/**\n * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.\n *\n * @name eachLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.each]{@link module:Collections.each}\n * @alias forEachLimit\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The array index is not passed to the iteratee.\n * If you need the index, use `eachOfLimit`.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called when all\n * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n * @returns {Promise} a promise, if a callback is omitted\n */\nfunction eachLimit(coll, limit, iteratee, callback) {\n return eachOfLimit$2(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback);\n}\nvar eachLimit$1 = awaitify(eachLimit, 4);\n\n/**\n * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time.\n *\n * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item\n * in series and therefore the iteratee functions will complete in order.\n\n * @name eachSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.each]{@link module:Collections.each}\n * @alias forEachSeries\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each\n * item in `coll`.\n * The array index is not passed to the iteratee.\n * If you need the index, use `eachOfSeries`.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called when all\n * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n * @returns {Promise} a promise, if a callback is omitted\n */\nfunction eachSeries(coll, iteratee, callback) {\n return eachLimit$1(coll, 1, iteratee, callback)\n}\nvar eachSeries$1 = awaitify(eachSeries, 3);\n\n/**\n * Wrap an async function and ensure it calls its callback on a later tick of\n * the event loop. If the function already calls its callback on a next tick,\n * no extra deferral is added. This is useful for preventing stack overflows\n * (`RangeError: Maximum call stack size exceeded`) and generally keeping\n * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony)\n * contained. ES2017 `async` functions are returned as-is -- they are immune\n * to Zalgo's corrupting influences, as they always resolve on a later tick.\n *\n * @name ensureAsync\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {AsyncFunction} fn - an async function, one that expects a node-style\n * callback as its last argument.\n * @returns {AsyncFunction} Returns a wrapped function with the exact same call\n * signature as the function passed in.\n * @example\n *\n * function sometimesAsync(arg, callback) {\n * if (cache[arg]) {\n * return callback(null, cache[arg]); // this would be synchronous!!\n * } else {\n * doSomeIO(arg, callback); // this IO would be asynchronous\n * }\n * }\n *\n * // this has a risk of stack overflows if many results are cached in a row\n * async.mapSeries(args, sometimesAsync, done);\n *\n * // this will defer sometimesAsync's callback if necessary,\n * // preventing stack overflows\n * async.mapSeries(args, async.ensureAsync(sometimesAsync), done);\n */\nfunction ensureAsync(fn) {\n if (isAsync(fn)) return fn;\n return function (...args/*, callback*/) {\n var callback = args.pop();\n var sync = true;\n args.push((...innerArgs) => {\n if (sync) {\n setImmediate$1(() => callback(...innerArgs));\n } else {\n callback(...innerArgs);\n }\n });\n fn.apply(this, args);\n sync = false;\n };\n}\n\n/**\n * Returns `true` if every element in `coll` satisfies an async test. If any\n * iteratee call returns `false`, the main `callback` is immediately called.\n *\n * @name every\n * @static\n * @memberOf module:Collections\n * @method\n * @alias all\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async truth test to apply to each item\n * in the collection in parallel.\n * The iteratee must complete with a boolean result value.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Result will be either `true` or `false`\n * depending on the values of the async tests. Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n * @example\n *\n * // dir1 is a directory that contains file1.txt, file2.txt\n * // dir2 is a directory that contains file3.txt, file4.txt\n * // dir3 is a directory that contains file5.txt\n * // dir4 does not exist\n *\n * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt'];\n * const withMissingFileList = ['file1.txt','file2.txt','file4.txt'];\n *\n * // asynchronous function that checks if a file exists\n * function fileExists(file, callback) {\n * fs.access(file, fs.constants.F_OK, (err) => {\n * callback(null, !err);\n * });\n * }\n *\n * // Using callbacks\n * async.every(fileList, fileExists, function(err, result) {\n * console.log(result);\n * // true\n * // result is true since every file exists\n * });\n *\n * async.every(withMissingFileList, fileExists, function(err, result) {\n * console.log(result);\n * // false\n * // result is false since NOT every file exists\n * });\n *\n * // Using Promises\n * async.every(fileList, fileExists)\n * .then( result => {\n * console.log(result);\n * // true\n * // result is true since every file exists\n * }).catch( err => {\n * console.log(err);\n * });\n *\n * async.every(withMissingFileList, fileExists)\n * .then( result => {\n * console.log(result);\n * // false\n * // result is false since NOT every file exists\n * }).catch( err => {\n * console.log(err);\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let result = await async.every(fileList, fileExists);\n * console.log(result);\n * // true\n * // result is true since every file exists\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n * async () => {\n * try {\n * let result = await async.every(withMissingFileList, fileExists);\n * console.log(result);\n * // false\n * // result is false since NOT every file exists\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n */\nfunction every(coll, iteratee, callback) {\n return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback)\n}\nvar every$1 = awaitify(every, 3);\n\n/**\n * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time.\n *\n * @name everyLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.every]{@link module:Collections.every}\n * @alias allLimit\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - An async truth test to apply to each item\n * in the collection in parallel.\n * The iteratee must complete with a boolean result value.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Result will be either `true` or `false`\n * depending on the values of the async tests. Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n */\nfunction everyLimit(coll, limit, iteratee, callback) {\n return _createTester(bool => !bool, res => !res)(eachOfLimit$2(limit), coll, iteratee, callback)\n}\nvar everyLimit$1 = awaitify(everyLimit, 4);\n\n/**\n * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time.\n *\n * @name everySeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.every]{@link module:Collections.every}\n * @alias allSeries\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async truth test to apply to each item\n * in the collection in series.\n * The iteratee must complete with a boolean result value.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Result will be either `true` or `false`\n * depending on the values of the async tests. Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n */\nfunction everySeries(coll, iteratee, callback) {\n return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback)\n}\nvar everySeries$1 = awaitify(everySeries, 3);\n\nfunction filterArray(eachfn, arr, iteratee, callback) {\n var truthValues = new Array(arr.length);\n eachfn(arr, (x, index, iterCb) => {\n iteratee(x, (err, v) => {\n truthValues[index] = !!v;\n iterCb(err);\n });\n }, err => {\n if (err) return callback(err);\n var results = [];\n for (var i = 0; i < arr.length; i++) {\n if (truthValues[i]) results.push(arr[i]);\n }\n callback(null, results);\n });\n}\n\nfunction filterGeneric(eachfn, coll, iteratee, callback) {\n var results = [];\n eachfn(coll, (x, index, iterCb) => {\n iteratee(x, (err, v) => {\n if (err) return iterCb(err);\n if (v) {\n results.push({index, value: x});\n }\n iterCb(err);\n });\n }, err => {\n if (err) return callback(err);\n callback(null, results\n .sort((a, b) => a.index - b.index)\n .map(v => v.value));\n });\n}\n\nfunction _filter(eachfn, coll, iteratee, callback) {\n var filter = isArrayLike(coll) ? filterArray : filterGeneric;\n return filter(eachfn, coll, wrapAsync(iteratee), callback);\n}\n\n/**\n * Returns a new array of all the values in `coll` which pass an async truth\n * test. This operation is performed in parallel, but the results array will be\n * in the same order as the original.\n *\n * @name filter\n * @static\n * @memberOf module:Collections\n * @method\n * @alias select\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {Function} iteratee - A truth test to apply to each item in `coll`.\n * The `iteratee` is passed a `callback(err, truthValue)`, which must be called\n * with a boolean argument once it has completed. Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback provided\n * @example\n *\n * // dir1 is a directory that contains file1.txt, file2.txt\n * // dir2 is a directory that contains file3.txt, file4.txt\n * // dir3 is a directory that contains file5.txt\n *\n * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];\n *\n * // asynchronous function that checks if a file exists\n * function fileExists(file, callback) {\n * fs.access(file, fs.constants.F_OK, (err) => {\n * callback(null, !err);\n * });\n * }\n *\n * // Using callbacks\n * async.filter(files, fileExists, function(err, results) {\n * if(err) {\n * console.log(err);\n * } else {\n * console.log(results);\n * // [ 'dir1/file1.txt', 'dir2/file3.txt' ]\n * // results is now an array of the existing files\n * }\n * });\n *\n * // Using Promises\n * async.filter(files, fileExists)\n * .then(results => {\n * console.log(results);\n * // [ 'dir1/file1.txt', 'dir2/file3.txt' ]\n * // results is now an array of the existing files\n * }).catch(err => {\n * console.log(err);\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let results = await async.filter(files, fileExists);\n * console.log(results);\n * // [ 'dir1/file1.txt', 'dir2/file3.txt' ]\n * // results is now an array of the existing files\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n */\nfunction filter (coll, iteratee, callback) {\n return _filter(eachOf$1, coll, iteratee, callback)\n}\nvar filter$1 = awaitify(filter, 3);\n\n/**\n * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name filterLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.filter]{@link module:Collections.filter}\n * @alias selectLimit\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {Function} iteratee - A truth test to apply to each item in `coll`.\n * The `iteratee` is passed a `callback(err, truthValue)`, which must be called\n * with a boolean argument once it has completed. Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback provided\n */\nfunction filterLimit (coll, limit, iteratee, callback) {\n return _filter(eachOfLimit$2(limit), coll, iteratee, callback)\n}\nvar filterLimit$1 = awaitify(filterLimit, 4);\n\n/**\n * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time.\n *\n * @name filterSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.filter]{@link module:Collections.filter}\n * @alias selectSeries\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {Function} iteratee - A truth test to apply to each item in `coll`.\n * The `iteratee` is passed a `callback(err, truthValue)`, which must be called\n * with a boolean argument once it has completed. Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Invoked with (err, results)\n * @returns {Promise} a promise, if no callback provided\n */\nfunction filterSeries (coll, iteratee, callback) {\n return _filter(eachOfSeries$1, coll, iteratee, callback)\n}\nvar filterSeries$1 = awaitify(filterSeries, 3);\n\n/**\n * Calls the asynchronous function `fn` with a callback parameter that allows it\n * to call itself again, in series, indefinitely.\n\n * If an error is passed to the callback then `errback` is called with the\n * error, and execution stops, otherwise it will never be called.\n *\n * @name forever\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {AsyncFunction} fn - an async function to call repeatedly.\n * Invoked with (next).\n * @param {Function} [errback] - when `fn` passes an error to it's callback,\n * this function will be called, and execution stops. Invoked with (err).\n * @returns {Promise} a promise that rejects if an error occurs and an errback\n * is not passed\n * @example\n *\n * async.forever(\n * function(next) {\n * // next is suitable for passing to things that need a callback(err [, whatever]);\n * // it will result in this function being called again.\n * },\n * function(err) {\n * // if next is called with a value in its first parameter, it will appear\n * // in here as 'err', and execution will stop.\n * }\n * );\n */\nfunction forever(fn, errback) {\n var done = onlyOnce(errback);\n var task = wrapAsync(ensureAsync(fn));\n\n function next(err) {\n if (err) return done(err);\n if (err === false) return;\n task(next);\n }\n return next();\n}\nvar forever$1 = awaitify(forever, 2);\n\n/**\n * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time.\n *\n * @name groupByLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.groupBy]{@link module:Collections.groupBy}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with a `key` to group the value under.\n * Invoked with (value, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Result is an `Object` whoses\n * properties are arrays of values which returned the corresponding key.\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction groupByLimit(coll, limit, iteratee, callback) {\n var _iteratee = wrapAsync(iteratee);\n return mapLimit$1(coll, limit, (val, iterCb) => {\n _iteratee(val, (err, key) => {\n if (err) return iterCb(err);\n return iterCb(err, {key, val});\n });\n }, (err, mapResults) => {\n var result = {};\n // from MDN, handle object having an `hasOwnProperty` prop\n var {hasOwnProperty} = Object.prototype;\n\n for (var i = 0; i < mapResults.length; i++) {\n if (mapResults[i]) {\n var {key} = mapResults[i];\n var {val} = mapResults[i];\n\n if (hasOwnProperty.call(result, key)) {\n result[key].push(val);\n } else {\n result[key] = [val];\n }\n }\n }\n\n return callback(err, result);\n });\n}\n\nvar groupByLimit$1 = awaitify(groupByLimit, 4);\n\n/**\n * Returns a new object, where each value corresponds to an array of items, from\n * `coll`, that returned the corresponding key. That is, the keys of the object\n * correspond to the values passed to the `iteratee` callback.\n *\n * Note: Since this function applies the `iteratee` to each item in parallel,\n * there is no guarantee that the `iteratee` functions will complete in order.\n * However, the values for each key in the `result` will be in the same order as\n * the original `coll`. For Objects, the values will roughly be in the order of\n * the original Objects' keys (but this can vary across JavaScript engines).\n *\n * @name groupBy\n * @static\n * @memberOf module:Collections\n * @method\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with a `key` to group the value under.\n * Invoked with (value, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Result is an `Object` whoses\n * properties are arrays of values which returned the corresponding key.\n * @returns {Promise} a promise, if no callback is passed\n * @example\n *\n * // dir1 is a directory that contains file1.txt, file2.txt\n * // dir2 is a directory that contains file3.txt, file4.txt\n * // dir3 is a directory that contains file5.txt\n * // dir4 does not exist\n *\n * const files = ['dir1/file1.txt','dir2','dir4']\n *\n * // asynchronous function that detects file type as none, file, or directory\n * function detectFile(file, callback) {\n * fs.stat(file, function(err, stat) {\n * if (err) {\n * return callback(null, 'none');\n * }\n * callback(null, stat.isDirectory() ? 'directory' : 'file');\n * });\n * }\n *\n * //Using callbacks\n * async.groupBy(files, detectFile, function(err, result) {\n * if(err) {\n * console.log(err);\n * } else {\n *\t console.log(result);\n * // {\n * // file: [ 'dir1/file1.txt' ],\n * // none: [ 'dir4' ],\n * // directory: [ 'dir2']\n * // }\n * // result is object containing the files grouped by type\n * }\n * });\n *\n * // Using Promises\n * async.groupBy(files, detectFile)\n * .then( result => {\n * console.log(result);\n * // {\n * // file: [ 'dir1/file1.txt' ],\n * // none: [ 'dir4' ],\n * // directory: [ 'dir2']\n * // }\n * // result is object containing the files grouped by type\n * }).catch( err => {\n * console.log(err);\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let result = await async.groupBy(files, detectFile);\n * console.log(result);\n * // {\n * // file: [ 'dir1/file1.txt' ],\n * // none: [ 'dir4' ],\n * // directory: [ 'dir2']\n * // }\n * // result is object containing the files grouped by type\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n */\nfunction groupBy (coll, iteratee, callback) {\n return groupByLimit$1(coll, Infinity, iteratee, callback)\n}\n\n/**\n * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time.\n *\n * @name groupBySeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.groupBy]{@link module:Collections.groupBy}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with a `key` to group the value under.\n * Invoked with (value, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Result is an `Object` whose\n * properties are arrays of values which returned the corresponding key.\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction groupBySeries (coll, iteratee, callback) {\n return groupByLimit$1(coll, 1, iteratee, callback)\n}\n\n/**\n * Logs the result of an `async` function to the `console`. Only works in\n * Node.js or in browsers that support `console.log` and `console.error` (such\n * as FF and Chrome). If multiple arguments are returned from the async\n * function, `console.log` is called on each argument in order.\n *\n * @name log\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {AsyncFunction} function - The function you want to eventually apply\n * all arguments to.\n * @param {...*} arguments... - Any number of arguments to apply to the function.\n * @example\n *\n * // in a module\n * var hello = function(name, callback) {\n * setTimeout(function() {\n * callback(null, 'hello ' + name);\n * }, 1000);\n * };\n *\n * // in the node repl\n * node> async.log(hello, 'world');\n * 'hello world'\n */\nvar log = consoleFunc('log');\n\n/**\n * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name mapValuesLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.mapValues]{@link module:Collections.mapValues}\n * @category Collection\n * @param {Object} obj - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - A function to apply to each value and key\n * in `coll`.\n * The iteratee should complete with the transformed value as its result.\n * Invoked with (value, key, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. `result` is a new object consisting\n * of each key from `obj`, with each transformed value on the right-hand side.\n * Invoked with (err, result).\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction mapValuesLimit(obj, limit, iteratee, callback) {\n callback = once(callback);\n var newObj = {};\n var _iteratee = wrapAsync(iteratee);\n return eachOfLimit$2(limit)(obj, (val, key, next) => {\n _iteratee(val, key, (err, result) => {\n if (err) return next(err);\n newObj[key] = result;\n next(err);\n });\n }, err => callback(err, newObj));\n}\n\nvar mapValuesLimit$1 = awaitify(mapValuesLimit, 4);\n\n/**\n * A relative of [`map`]{@link module:Collections.map}, designed for use with objects.\n *\n * Produces a new Object by mapping each value of `obj` through the `iteratee`\n * function. The `iteratee` is called each `value` and `key` from `obj` and a\n * callback for when it has finished processing. Each of these callbacks takes\n * two arguments: an `error`, and the transformed item from `obj`. If `iteratee`\n * passes an error to its callback, the main `callback` (for the `mapValues`\n * function) is immediately called with the error.\n *\n * Note, the order of the keys in the result is not guaranteed. The keys will\n * be roughly in the order they complete, (but this is very engine-specific)\n *\n * @name mapValues\n * @static\n * @memberOf module:Collections\n * @method\n * @category Collection\n * @param {Object} obj - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A function to apply to each value and key\n * in `coll`.\n * The iteratee should complete with the transformed value as its result.\n * Invoked with (value, key, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. `result` is a new object consisting\n * of each key from `obj`, with each transformed value on the right-hand side.\n * Invoked with (err, result).\n * @returns {Promise} a promise, if no callback is passed\n * @example\n *\n * // file1.txt is a file that is 1000 bytes in size\n * // file2.txt is a file that is 2000 bytes in size\n * // file3.txt is a file that is 3000 bytes in size\n * // file4.txt does not exist\n *\n * const fileMap = {\n * f1: 'file1.txt',\n * f2: 'file2.txt',\n * f3: 'file3.txt'\n * };\n *\n * const withMissingFileMap = {\n * f1: 'file1.txt',\n * f2: 'file2.txt',\n * f3: 'file4.txt'\n * };\n *\n * // asynchronous function that returns the file size in bytes\n * function getFileSizeInBytes(file, key, callback) {\n * fs.stat(file, function(err, stat) {\n * if (err) {\n * return callback(err);\n * }\n * callback(null, stat.size);\n * });\n * }\n *\n * // Using callbacks\n * async.mapValues(fileMap, getFileSizeInBytes, function(err, result) {\n * if (err) {\n * console.log(err);\n * } else {\n * console.log(result);\n * // result is now a map of file size in bytes for each file, e.g.\n * // {\n * // f1: 1000,\n * // f2: 2000,\n * // f3: 3000\n * // }\n * }\n * });\n *\n * // Error handling\n * async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) {\n * if (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * } else {\n * console.log(result);\n * }\n * });\n *\n * // Using Promises\n * async.mapValues(fileMap, getFileSizeInBytes)\n * .then( result => {\n * console.log(result);\n * // result is now a map of file size in bytes for each file, e.g.\n * // {\n * // f1: 1000,\n * // f2: 2000,\n * // f3: 3000\n * // }\n * }).catch (err => {\n * console.log(err);\n * });\n *\n * // Error Handling\n * async.mapValues(withMissingFileMap, getFileSizeInBytes)\n * .then( result => {\n * console.log(result);\n * }).catch (err => {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let result = await async.mapValues(fileMap, getFileSizeInBytes);\n * console.log(result);\n * // result is now a map of file size in bytes for each file, e.g.\n * // {\n * // f1: 1000,\n * // f2: 2000,\n * // f3: 3000\n * // }\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n * // Error Handling\n * async () => {\n * try {\n * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes);\n * console.log(result);\n * }\n * catch (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * }\n * }\n *\n */\nfunction mapValues(obj, iteratee, callback) {\n return mapValuesLimit$1(obj, Infinity, iteratee, callback)\n}\n\n/**\n * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time.\n *\n * @name mapValuesSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.mapValues]{@link module:Collections.mapValues}\n * @category Collection\n * @param {Object} obj - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A function to apply to each value and key\n * in `coll`.\n * The iteratee should complete with the transformed value as its result.\n * Invoked with (value, key, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. `result` is a new object consisting\n * of each key from `obj`, with each transformed value on the right-hand side.\n * Invoked with (err, result).\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction mapValuesSeries(obj, iteratee, callback) {\n return mapValuesLimit$1(obj, 1, iteratee, callback)\n}\n\n/**\n * Caches the results of an async function. When creating a hash to store\n * function results against, the callback is omitted from the hash and an\n * optional hash function can be used.\n *\n * **Note: if the async function errs, the result will not be cached and\n * subsequent calls will call the wrapped function.**\n *\n * If no hash function is specified, the first argument is used as a hash key,\n * which may work reasonably if it is a string or a data type that converts to a\n * distinct string. Note that objects and arrays will not behave reasonably.\n * Neither will cases where the other arguments are significant. In such cases,\n * specify your own hash function.\n *\n * The cache of results is exposed as the `memo` property of the function\n * returned by `memoize`.\n *\n * @name memoize\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {AsyncFunction} fn - The async function to proxy and cache results from.\n * @param {Function} hasher - An optional function for generating a custom hash\n * for storing results. It has all the arguments applied to it apart from the\n * callback, and must be synchronous.\n * @returns {AsyncFunction} a memoized version of `fn`\n * @example\n *\n * var slow_fn = function(name, callback) {\n * // do something\n * callback(null, result);\n * };\n * var fn = async.memoize(slow_fn);\n *\n * // fn can now be used as if it were slow_fn\n * fn('some name', function() {\n * // callback\n * });\n */\nfunction memoize(fn, hasher = v => v) {\n var memo = Object.create(null);\n var queues = Object.create(null);\n var _fn = wrapAsync(fn);\n var memoized = initialParams((args, callback) => {\n var key = hasher(...args);\n if (key in memo) {\n setImmediate$1(() => callback(null, ...memo[key]));\n } else if (key in queues) {\n queues[key].push(callback);\n } else {\n queues[key] = [callback];\n _fn(...args, (err, ...resultArgs) => {\n // #1465 don't memoize if an error occurred\n if (!err) {\n memo[key] = resultArgs;\n }\n var q = queues[key];\n delete queues[key];\n for (var i = 0, l = q.length; i < l; i++) {\n q[i](err, ...resultArgs);\n }\n });\n }\n });\n memoized.memo = memo;\n memoized.unmemoized = fn;\n return memoized;\n}\n\n/* istanbul ignore file */\n\n/**\n * Calls `callback` on a later loop around the event loop. In Node.js this just\n * calls `process.nextTick`. In the browser it will use `setImmediate` if\n * available, otherwise `setTimeout(callback, 0)`, which means other higher\n * priority events may precede the execution of `callback`.\n *\n * This is used internally for browser-compatibility purposes.\n *\n * @name nextTick\n * @static\n * @memberOf module:Utils\n * @method\n * @see [async.setImmediate]{@link module:Utils.setImmediate}\n * @category Util\n * @param {Function} callback - The function to call on a later loop around\n * the event loop. Invoked with (args...).\n * @param {...*} args... - any number of additional arguments to pass to the\n * callback on the next tick.\n * @example\n *\n * var call_order = [];\n * async.nextTick(function() {\n * call_order.push('two');\n * // call_order now equals ['one','two']\n * });\n * call_order.push('one');\n *\n * async.setImmediate(function (a, b, c) {\n * // a, b, and c equal 1, 2, and 3\n * }, 1, 2, 3);\n */\nvar _defer;\n\nif (hasNextTick) {\n _defer = process.nextTick;\n} else if (hasSetImmediate) {\n _defer = setImmediate;\n} else {\n _defer = fallback;\n}\n\nvar nextTick = wrap(_defer);\n\nvar _parallel = awaitify((eachfn, tasks, callback) => {\n var results = isArrayLike(tasks) ? [] : {};\n\n eachfn(tasks, (task, key, taskCb) => {\n wrapAsync(task)((err, ...result) => {\n if (result.length < 2) {\n [result] = result;\n }\n results[key] = result;\n taskCb(err);\n });\n }, err => callback(err, results));\n}, 3);\n\n/**\n * Run the `tasks` collection of functions in parallel, without waiting until\n * the previous function has completed. If any of the functions pass an error to\n * its callback, the main `callback` is immediately called with the value of the\n * error. Once the `tasks` have completed, the results are passed to the final\n * `callback` as an array.\n *\n * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about\n * parallel execution of code. If your tasks do not use any timers or perform\n * any I/O, they will actually be executed in series. Any synchronous setup\n * sections for each task will happen one after the other. JavaScript remains\n * single-threaded.\n *\n * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the\n * execution of other tasks when a task fails.\n *\n * It is also possible to use an object instead of an array. Each property will\n * be run as a function and the results will be passed to the final `callback`\n * as an object instead of an array. This can be a more readable way of handling\n * results from {@link async.parallel}.\n *\n * @name parallel\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of\n * [async functions]{@link AsyncFunction} to run.\n * Each async function can complete with any number of optional `result` values.\n * @param {Function} [callback] - An optional callback to run once all the\n * functions have completed successfully. This function gets a results array\n * (or object) containing all the result arguments passed to the task callbacks.\n * Invoked with (err, results).\n * @returns {Promise} a promise, if a callback is not passed\n *\n * @example\n *\n * //Using Callbacks\n * async.parallel([\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'one');\n * }, 200);\n * },\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'two');\n * }, 100);\n * }\n * ], function(err, results) {\n * console.log(results);\n * // results is equal to ['one','two'] even though\n * // the second function had a shorter timeout.\n * });\n *\n * // an example using an object instead of an array\n * async.parallel({\n * one: function(callback) {\n * setTimeout(function() {\n * callback(null, 1);\n * }, 200);\n * },\n * two: function(callback) {\n * setTimeout(function() {\n * callback(null, 2);\n * }, 100);\n * }\n * }, function(err, results) {\n * console.log(results);\n * // results is equal to: { one: 1, two: 2 }\n * });\n *\n * //Using Promises\n * async.parallel([\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'one');\n * }, 200);\n * },\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'two');\n * }, 100);\n * }\n * ]).then(results => {\n * console.log(results);\n * // results is equal to ['one','two'] even though\n * // the second function had a shorter timeout.\n * }).catch(err => {\n * console.log(err);\n * });\n *\n * // an example using an object instead of an array\n * async.parallel({\n * one: function(callback) {\n * setTimeout(function() {\n * callback(null, 1);\n * }, 200);\n * },\n * two: function(callback) {\n * setTimeout(function() {\n * callback(null, 2);\n * }, 100);\n * }\n * }).then(results => {\n * console.log(results);\n * // results is equal to: { one: 1, two: 2 }\n * }).catch(err => {\n * console.log(err);\n * });\n *\n * //Using async/await\n * async () => {\n * try {\n * let results = await async.parallel([\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'one');\n * }, 200);\n * },\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'two');\n * }, 100);\n * }\n * ]);\n * console.log(results);\n * // results is equal to ['one','two'] even though\n * // the second function had a shorter timeout.\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n * // an example using an object instead of an array\n * async () => {\n * try {\n * let results = await async.parallel({\n * one: function(callback) {\n * setTimeout(function() {\n * callback(null, 1);\n * }, 200);\n * },\n * two: function(callback) {\n * setTimeout(function() {\n * callback(null, 2);\n * }, 100);\n * }\n * });\n * console.log(results);\n * // results is equal to: { one: 1, two: 2 }\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n */\nfunction parallel(tasks, callback) {\n return _parallel(eachOf$1, tasks, callback);\n}\n\n/**\n * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name parallelLimit\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.parallel]{@link module:ControlFlow.parallel}\n * @category Control Flow\n * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of\n * [async functions]{@link AsyncFunction} to run.\n * Each async function can complete with any number of optional `result` values.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {Function} [callback] - An optional callback to run once all the\n * functions have completed successfully. This function gets a results array\n * (or object) containing all the result arguments passed to the task callbacks.\n * Invoked with (err, results).\n * @returns {Promise} a promise, if a callback is not passed\n */\nfunction parallelLimit(tasks, limit, callback) {\n return _parallel(eachOfLimit$2(limit), tasks, callback);\n}\n\n/**\n * A queue of tasks for the worker function to complete.\n * @typedef {Iterable} QueueObject\n * @memberOf module:ControlFlow\n * @property {Function} length - a function returning the number of items\n * waiting to be processed. Invoke with `queue.length()`.\n * @property {boolean} started - a boolean indicating whether or not any\n * items have been pushed and processed by the queue.\n * @property {Function} running - a function returning the number of items\n * currently being processed. Invoke with `queue.running()`.\n * @property {Function} workersList - a function returning the array of items\n * currently being processed. Invoke with `queue.workersList()`.\n * @property {Function} idle - a function returning false if there are items\n * waiting or being processed, or true if not. Invoke with `queue.idle()`.\n * @property {number} concurrency - an integer for determining how many `worker`\n * functions should be run in parallel. This property can be changed after a\n * `queue` is created to alter the concurrency on-the-fly.\n * @property {number} payload - an integer that specifies how many items are\n * passed to the worker function at a time. only applies if this is a\n * [cargo]{@link module:ControlFlow.cargo} object\n * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback`\n * once the `worker` has finished processing the task. Instead of a single task,\n * a `tasks` array can be submitted. The respective callback is used for every\n * task in the list. Invoke with `queue.push(task, [callback])`,\n * @property {AsyncFunction} unshift - add a new task to the front of the `queue`.\n * Invoke with `queue.unshift(task, [callback])`.\n * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns\n * a promise that rejects if an error occurs.\n * @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns\n * a promise that rejects if an error occurs.\n * @property {Function} remove - remove items from the queue that match a test\n * function. The test function will be passed an object with a `data` property,\n * and a `priority` property, if this is a\n * [priorityQueue]{@link module:ControlFlow.priorityQueue} object.\n * Invoked with `queue.remove(testFn)`, where `testFn` is of the form\n * `function ({data, priority}) {}` and returns a Boolean.\n * @property {Function} saturated - a function that sets a callback that is\n * called when the number of running workers hits the `concurrency` limit, and\n * further tasks will be queued. If the callback is omitted, `q.saturated()`\n * returns a promise for the next occurrence.\n * @property {Function} unsaturated - a function that sets a callback that is\n * called when the number of running workers is less than the `concurrency` &\n * `buffer` limits, and further tasks will not be queued. If the callback is\n * omitted, `q.unsaturated()` returns a promise for the next occurrence.\n * @property {number} buffer - A minimum threshold buffer in order to say that\n * the `queue` is `unsaturated`.\n * @property {Function} empty - a function that sets a callback that is called\n * when the last item from the `queue` is given to a `worker`. If the callback\n * is omitted, `q.empty()` returns a promise for the next occurrence.\n * @property {Function} drain - a function that sets a callback that is called\n * when the last item from the `queue` has returned from the `worker`. If the\n * callback is omitted, `q.drain()` returns a promise for the next occurrence.\n * @property {Function} error - a function that sets a callback that is called\n * when a task errors. Has the signature `function(error, task)`. If the\n * callback is omitted, `error()` returns a promise that rejects on the next\n * error.\n * @property {boolean} paused - a boolean for determining whether the queue is\n * in a paused state.\n * @property {Function} pause - a function that pauses the processing of tasks\n * until `resume()` is called. Invoke with `queue.pause()`.\n * @property {Function} resume - a function that resumes the processing of\n * queued tasks when the queue is paused. Invoke with `queue.resume()`.\n * @property {Function} kill - a function that removes the `drain` callback and\n * empties remaining tasks from the queue forcing it to go idle. No more tasks\n * should be pushed to the queue after calling this function. Invoke with `queue.kill()`.\n *\n * @example\n * const q = async.queue(worker, 2)\n * q.push(item1)\n * q.push(item2)\n * q.push(item3)\n * // queues are iterable, spread into an array to inspect\n * const items = [...q] // [item1, item2, item3]\n * // or use for of\n * for (let item of q) {\n * console.log(item)\n * }\n *\n * q.drain(() => {\n * console.log('all done')\n * })\n * // or\n * await q.drain()\n */\n\n/**\n * Creates a `queue` object with the specified `concurrency`. Tasks added to the\n * `queue` are processed in parallel (up to the `concurrency` limit). If all\n * `worker`s are in progress, the task is queued until one becomes available.\n * Once a `worker` completes a `task`, that `task`'s callback is called.\n *\n * @name queue\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {AsyncFunction} worker - An async function for processing a queued task.\n * If you want to handle errors from an individual task, pass a callback to\n * `q.push()`. Invoked with (task, callback).\n * @param {number} [concurrency=1] - An `integer` for determining how many\n * `worker` functions should be run in parallel. If omitted, the concurrency\n * defaults to `1`. If the concurrency is `0`, an error is thrown.\n * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be\n * attached as certain properties to listen for specific events during the\n * lifecycle of the queue.\n * @example\n *\n * // create a queue object with concurrency 2\n * var q = async.queue(function(task, callback) {\n * console.log('hello ' + task.name);\n * callback();\n * }, 2);\n *\n * // assign a callback\n * q.drain(function() {\n * console.log('all items have been processed');\n * });\n * // or await the end\n * await q.drain()\n *\n * // assign an error callback\n * q.error(function(err, task) {\n * console.error('task experienced an error');\n * });\n *\n * // add some items to the queue\n * q.push({name: 'foo'}, function(err) {\n * console.log('finished processing foo');\n * });\n * // callback is optional\n * q.push({name: 'bar'});\n *\n * // add some items to the queue (batch-wise)\n * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {\n * console.log('finished processing item');\n * });\n *\n * // add some items to the front of the queue\n * q.unshift({name: 'bar'}, function (err) {\n * console.log('finished processing bar');\n * });\n */\nfunction queue (worker, concurrency) {\n var _worker = wrapAsync(worker);\n return queue$1((items, cb) => {\n _worker(items[0], cb);\n }, concurrency, 1);\n}\n\n// Binary min-heap implementation used for priority queue.\n// Implementation is stable, i.e. push time is considered for equal priorities\nclass Heap {\n constructor() {\n this.heap = [];\n this.pushCount = Number.MIN_SAFE_INTEGER;\n }\n\n get length() {\n return this.heap.length;\n }\n\n empty () {\n this.heap = [];\n return this;\n }\n\n percUp(index) {\n let p;\n\n while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) {\n let t = this.heap[index];\n this.heap[index] = this.heap[p];\n this.heap[p] = t;\n\n index = p;\n }\n }\n\n percDown(index) {\n let l;\n\n while ((l=leftChi(index)) < this.heap.length) {\n if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) {\n l = l+1;\n }\n\n if (smaller(this.heap[index], this.heap[l])) {\n break;\n }\n\n let t = this.heap[index];\n this.heap[index] = this.heap[l];\n this.heap[l] = t;\n\n index = l;\n }\n }\n\n push(node) {\n node.pushCount = ++this.pushCount;\n this.heap.push(node);\n this.percUp(this.heap.length-1);\n }\n\n unshift(node) {\n return this.heap.push(node);\n }\n\n shift() {\n let [top] = this.heap;\n\n this.heap[0] = this.heap[this.heap.length-1];\n this.heap.pop();\n this.percDown(0);\n\n return top;\n }\n\n toArray() {\n return [...this];\n }\n\n *[Symbol.iterator] () {\n for (let i = 0; i < this.heap.length; i++) {\n yield this.heap[i].data;\n }\n }\n\n remove (testFn) {\n let j = 0;\n for (let i = 0; i < this.heap.length; i++) {\n if (!testFn(this.heap[i])) {\n this.heap[j] = this.heap[i];\n j++;\n }\n }\n\n this.heap.splice(j);\n\n for (let i = parent(this.heap.length-1); i >= 0; i--) {\n this.percDown(i);\n }\n\n return this;\n }\n}\n\nfunction leftChi(i) {\n return (i<<1)+1;\n}\n\nfunction parent(i) {\n return ((i+1)>>1)-1;\n}\n\nfunction smaller(x, y) {\n if (x.priority !== y.priority) {\n return x.priority < y.priority;\n }\n else {\n return x.pushCount < y.pushCount;\n }\n}\n\n/**\n * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and\n * completed in ascending priority order.\n *\n * @name priorityQueue\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.queue]{@link module:ControlFlow.queue}\n * @category Control Flow\n * @param {AsyncFunction} worker - An async function for processing a queued task.\n * If you want to handle errors from an individual task, pass a callback to\n * `q.push()`.\n * Invoked with (task, callback).\n * @param {number} concurrency - An `integer` for determining how many `worker`\n * functions should be run in parallel. If omitted, the concurrency defaults to\n * `1`. If the concurrency is `0`, an error is thrown.\n * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are three\n * differences between `queue` and `priorityQueue` objects:\n * * `push(task, priority, [callback])` - `priority` should be a number. If an\n * array of `tasks` is given, all tasks will be assigned the same priority.\n * * `pushAsync(task, priority, [callback])` - the same as `priorityQueue.push`,\n * except this returns a promise that rejects if an error occurs.\n * * The `unshift` and `unshiftAsync` methods were removed.\n */\nfunction priorityQueue(worker, concurrency) {\n // Start with a normal queue\n var q = queue(worker, concurrency);\n\n var {\n push,\n pushAsync\n } = q;\n\n q._tasks = new Heap();\n q._createTaskItem = ({data, priority}, callback) => {\n return {\n data,\n priority,\n callback\n };\n };\n\n function createDataItems(tasks, priority) {\n if (!Array.isArray(tasks)) {\n return {data: tasks, priority};\n }\n return tasks.map(data => { return {data, priority}; });\n }\n\n // Override push to accept second parameter representing priority\n q.push = function(data, priority = 0, callback) {\n return push(createDataItems(data, priority), callback);\n };\n\n q.pushAsync = function(data, priority = 0, callback) {\n return pushAsync(createDataItems(data, priority), callback);\n };\n\n // Remove unshift functions\n delete q.unshift;\n delete q.unshiftAsync;\n\n return q;\n}\n\n/**\n * Runs the `tasks` array of functions in parallel, without waiting until the\n * previous function has completed. Once any of the `tasks` complete or pass an\n * error to its callback, the main `callback` is immediately called. It's\n * equivalent to `Promise.race()`.\n *\n * @name race\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction}\n * to run. Each function can complete with an optional `result` value.\n * @param {Function} callback - A callback to run once any of the functions have\n * completed. This function gets an error or result from the first function that\n * completed. Invoked with (err, result).\n * @returns {Promise} a promise, if a callback is omitted\n * @example\n *\n * async.race([\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'one');\n * }, 200);\n * },\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'two');\n * }, 100);\n * }\n * ],\n * // main callback\n * function(err, result) {\n * // the result will be equal to 'two' as it finishes earlier\n * });\n */\nfunction race(tasks, callback) {\n callback = once(callback);\n if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions'));\n if (!tasks.length) return callback();\n for (var i = 0, l = tasks.length; i < l; i++) {\n wrapAsync(tasks[i])(callback);\n }\n}\n\nvar race$1 = awaitify(race, 2);\n\n/**\n * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order.\n *\n * @name reduceRight\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.reduce]{@link module:Collections.reduce}\n * @alias foldr\n * @category Collection\n * @param {Array} array - A collection to iterate over.\n * @param {*} memo - The initial state of the reduction.\n * @param {AsyncFunction} iteratee - A function applied to each item in the\n * array to produce the next step in the reduction.\n * The `iteratee` should complete with the next state of the reduction.\n * If the iteratee completes with an error, the reduction is stopped and the\n * main `callback` is immediately called with the error.\n * Invoked with (memo, item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Result is the reduced value. Invoked with\n * (err, result).\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction reduceRight (array, memo, iteratee, callback) {\n var reversed = [...array].reverse();\n return reduce$1(reversed, memo, iteratee, callback);\n}\n\n/**\n * Wraps the async function in another function that always completes with a\n * result object, even when it errors.\n *\n * The result object has either the property `error` or `value`.\n *\n * @name reflect\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {AsyncFunction} fn - The async function you want to wrap\n * @returns {Function} - A function that always passes null to it's callback as\n * the error. The second argument to the callback will be an `object` with\n * either an `error` or a `value` property.\n * @example\n *\n * async.parallel([\n * async.reflect(function(callback) {\n * // do some stuff ...\n * callback(null, 'one');\n * }),\n * async.reflect(function(callback) {\n * // do some more stuff but error ...\n * callback('bad stuff happened');\n * }),\n * async.reflect(function(callback) {\n * // do some more stuff ...\n * callback(null, 'two');\n * })\n * ],\n * // optional callback\n * function(err, results) {\n * // values\n * // results[0].value = 'one'\n * // results[1].error = 'bad stuff happened'\n * // results[2].value = 'two'\n * });\n */\nfunction reflect(fn) {\n var _fn = wrapAsync(fn);\n return initialParams(function reflectOn(args, reflectCallback) {\n args.push((error, ...cbArgs) => {\n let retVal = {};\n if (error) {\n retVal.error = error;\n }\n if (cbArgs.length > 0){\n var value = cbArgs;\n if (cbArgs.length <= 1) {\n [value] = cbArgs;\n }\n retVal.value = value;\n }\n reflectCallback(null, retVal);\n });\n\n return _fn.apply(this, args);\n });\n}\n\n/**\n * A helper function that wraps an array or an object of functions with `reflect`.\n *\n * @name reflectAll\n * @static\n * @memberOf module:Utils\n * @method\n * @see [async.reflect]{@link module:Utils.reflect}\n * @category Util\n * @param {Array|Object|Iterable} tasks - The collection of\n * [async functions]{@link AsyncFunction} to wrap in `async.reflect`.\n * @returns {Array} Returns an array of async functions, each wrapped in\n * `async.reflect`\n * @example\n *\n * let tasks = [\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'one');\n * }, 200);\n * },\n * function(callback) {\n * // do some more stuff but error ...\n * callback(new Error('bad stuff happened'));\n * },\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'two');\n * }, 100);\n * }\n * ];\n *\n * async.parallel(async.reflectAll(tasks),\n * // optional callback\n * function(err, results) {\n * // values\n * // results[0].value = 'one'\n * // results[1].error = Error('bad stuff happened')\n * // results[2].value = 'two'\n * });\n *\n * // an example using an object instead of an array\n * let tasks = {\n * one: function(callback) {\n * setTimeout(function() {\n * callback(null, 'one');\n * }, 200);\n * },\n * two: function(callback) {\n * callback('two');\n * },\n * three: function(callback) {\n * setTimeout(function() {\n * callback(null, 'three');\n * }, 100);\n * }\n * };\n *\n * async.parallel(async.reflectAll(tasks),\n * // optional callback\n * function(err, results) {\n * // values\n * // results.one.value = 'one'\n * // results.two.error = 'two'\n * // results.three.value = 'three'\n * });\n */\nfunction reflectAll(tasks) {\n var results;\n if (Array.isArray(tasks)) {\n results = tasks.map(reflect);\n } else {\n results = {};\n Object.keys(tasks).forEach(key => {\n results[key] = reflect.call(this, tasks[key]);\n });\n }\n return results;\n}\n\nfunction reject$2(eachfn, arr, _iteratee, callback) {\n const iteratee = wrapAsync(_iteratee);\n return _filter(eachfn, arr, (value, cb) => {\n iteratee(value, (err, v) => {\n cb(err, !v);\n });\n }, callback);\n}\n\n/**\n * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test.\n *\n * @name reject\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.filter]{@link module:Collections.filter}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {Function} iteratee - An async truth test to apply to each item in\n * `coll`.\n * The should complete with a boolean value as its `result`.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback is passed\n * @example\n *\n * // dir1 is a directory that contains file1.txt, file2.txt\n * // dir2 is a directory that contains file3.txt, file4.txt\n * // dir3 is a directory that contains file5.txt\n *\n * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];\n *\n * // asynchronous function that checks if a file exists\n * function fileExists(file, callback) {\n * fs.access(file, fs.constants.F_OK, (err) => {\n * callback(null, !err);\n * });\n * }\n *\n * // Using callbacks\n * async.reject(fileList, fileExists, function(err, results) {\n * // [ 'dir3/file6.txt' ]\n * // results now equals an array of the non-existing files\n * });\n *\n * // Using Promises\n * async.reject(fileList, fileExists)\n * .then( results => {\n * console.log(results);\n * // [ 'dir3/file6.txt' ]\n * // results now equals an array of the non-existing files\n * }).catch( err => {\n * console.log(err);\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let results = await async.reject(fileList, fileExists);\n * console.log(results);\n * // [ 'dir3/file6.txt' ]\n * // results now equals an array of the non-existing files\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n */\nfunction reject (coll, iteratee, callback) {\n return reject$2(eachOf$1, coll, iteratee, callback)\n}\nvar reject$1 = awaitify(reject, 3);\n\n/**\n * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name rejectLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.reject]{@link module:Collections.reject}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {Function} iteratee - An async truth test to apply to each item in\n * `coll`.\n * The should complete with a boolean value as its `result`.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction rejectLimit (coll, limit, iteratee, callback) {\n return reject$2(eachOfLimit$2(limit), coll, iteratee, callback)\n}\nvar rejectLimit$1 = awaitify(rejectLimit, 4);\n\n/**\n * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time.\n *\n * @name rejectSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.reject]{@link module:Collections.reject}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {Function} iteratee - An async truth test to apply to each item in\n * `coll`.\n * The should complete with a boolean value as its `result`.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback is passed\n */\nfunction rejectSeries (coll, iteratee, callback) {\n return reject$2(eachOfSeries$1, coll, iteratee, callback)\n}\nvar rejectSeries$1 = awaitify(rejectSeries, 3);\n\nfunction constant(value) {\n return function () {\n return value;\n }\n}\n\n/**\n * Attempts to get a successful response from `task` no more than `times` times\n * before returning an error. If the task is successful, the `callback` will be\n * passed the result of the successful task. If all attempts fail, the callback\n * will be passed the error and result (if any) of the final attempt.\n *\n * @name retry\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @see [async.retryable]{@link module:ControlFlow.retryable}\n * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an\n * object with `times` and `interval` or a number.\n * * `times` - The number of attempts to make before giving up. The default\n * is `5`.\n * * `interval` - The time to wait between retries, in milliseconds. The\n * default is `0`. The interval may also be specified as a function of the\n * retry count (see example).\n * * `errorFilter` - An optional synchronous function that is invoked on\n * erroneous result. If it returns `true` the retry attempts will continue;\n * if the function returns `false` the retry flow is aborted with the current\n * attempt's error and result being returned to the final callback.\n * Invoked with (err).\n * * If `opts` is a number, the number specifies the number of times to retry,\n * with the default interval of `0`.\n * @param {AsyncFunction} task - An async function to retry.\n * Invoked with (callback).\n * @param {Function} [callback] - An optional callback which is called when the\n * task has succeeded, or after the final failed attempt. It receives the `err`\n * and `result` arguments of the last attempt at completing the `task`. Invoked\n * with (err, results).\n * @returns {Promise} a promise if no callback provided\n *\n * @example\n *\n * // The `retry` function can be used as a stand-alone control flow by passing\n * // a callback, as shown below:\n *\n * // try calling apiMethod 3 times\n * async.retry(3, apiMethod, function(err, result) {\n * // do something with the result\n * });\n *\n * // try calling apiMethod 3 times, waiting 200 ms between each retry\n * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {\n * // do something with the result\n * });\n *\n * // try calling apiMethod 10 times with exponential backoff\n * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds)\n * async.retry({\n * times: 10,\n * interval: function(retryCount) {\n * return 50 * Math.pow(2, retryCount);\n * }\n * }, apiMethod, function(err, result) {\n * // do something with the result\n * });\n *\n * // try calling apiMethod the default 5 times no delay between each retry\n * async.retry(apiMethod, function(err, result) {\n * // do something with the result\n * });\n *\n * // try calling apiMethod only when error condition satisfies, all other\n * // errors will abort the retry control flow and return to final callback\n * async.retry({\n * errorFilter: function(err) {\n * return err.message === 'Temporary error'; // only retry on a specific error\n * }\n * }, apiMethod, function(err, result) {\n * // do something with the result\n * });\n *\n * // to retry individual methods that are not as reliable within other\n * // control flow functions, use the `retryable` wrapper:\n * async.auto({\n * users: api.getUsers.bind(api),\n * payments: async.retryable(3, api.getPayments.bind(api))\n * }, function(err, results) {\n * // do something with the results\n * });\n *\n */\nconst DEFAULT_TIMES = 5;\nconst DEFAULT_INTERVAL = 0;\n\nfunction retry(opts, task, callback) {\n var options = {\n times: DEFAULT_TIMES,\n intervalFunc: constant(DEFAULT_INTERVAL)\n };\n\n if (arguments.length < 3 && typeof opts === 'function') {\n callback = task || promiseCallback();\n task = opts;\n } else {\n parseTimes(options, opts);\n callback = callback || promiseCallback();\n }\n\n if (typeof task !== 'function') {\n throw new Error(\"Invalid arguments for async.retry\");\n }\n\n var _task = wrapAsync(task);\n\n var attempt = 1;\n function retryAttempt() {\n _task((err, ...args) => {\n if (err === false) return\n if (err && attempt++ < options.times &&\n (typeof options.errorFilter != 'function' ||\n options.errorFilter(err))) {\n setTimeout(retryAttempt, options.intervalFunc(attempt - 1));\n } else {\n callback(err, ...args);\n }\n });\n }\n\n retryAttempt();\n return callback[PROMISE_SYMBOL]\n}\n\nfunction parseTimes(acc, t) {\n if (typeof t === 'object') {\n acc.times = +t.times || DEFAULT_TIMES;\n\n acc.intervalFunc = typeof t.interval === 'function' ?\n t.interval :\n constant(+t.interval || DEFAULT_INTERVAL);\n\n acc.errorFilter = t.errorFilter;\n } else if (typeof t === 'number' || typeof t === 'string') {\n acc.times = +t || DEFAULT_TIMES;\n } else {\n throw new Error(\"Invalid arguments for async.retry\");\n }\n}\n\n/**\n * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method\n * wraps a task and makes it retryable, rather than immediately calling it\n * with retries.\n *\n * @name retryable\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.retry]{@link module:ControlFlow.retry}\n * @category Control Flow\n * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional\n * options, exactly the same as from `retry`, except for a `opts.arity` that\n * is the arity of the `task` function, defaulting to `task.length`\n * @param {AsyncFunction} task - the asynchronous function to wrap.\n * This function will be passed any arguments passed to the returned wrapper.\n * Invoked with (...args, callback).\n * @returns {AsyncFunction} The wrapped function, which when invoked, will\n * retry on an error, based on the parameters specified in `opts`.\n * This function will accept the same parameters as `task`.\n * @example\n *\n * async.auto({\n * dep1: async.retryable(3, getFromFlakyService),\n * process: [\"dep1\", async.retryable(3, function (results, cb) {\n * maybeProcessData(results.dep1, cb);\n * })]\n * }, callback);\n */\nfunction retryable (opts, task) {\n if (!task) {\n task = opts;\n opts = null;\n }\n let arity = (opts && opts.arity) || task.length;\n if (isAsync(task)) {\n arity += 1;\n }\n var _task = wrapAsync(task);\n return initialParams((args, callback) => {\n if (args.length < arity - 1 || callback == null) {\n args.push(callback);\n callback = promiseCallback();\n }\n function taskFn(cb) {\n _task(...args, cb);\n }\n\n if (opts) retry(opts, taskFn, callback);\n else retry(taskFn, callback);\n\n return callback[PROMISE_SYMBOL]\n });\n}\n\n/**\n * Run the functions in the `tasks` collection in series, each one running once\n * the previous function has completed. If any functions in the series pass an\n * error to its callback, no more functions are run, and `callback` is\n * immediately called with the value of the error. Otherwise, `callback`\n * receives an array of results when `tasks` have completed.\n *\n * It is also possible to use an object instead of an array. Each property will\n * be run as a function, and the results will be passed to the final `callback`\n * as an object instead of an array. This can be a more readable way of handling\n * results from {@link async.series}.\n *\n * **Note** that while many implementations preserve the order of object\n * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)\n * explicitly states that\n *\n * > The mechanics and order of enumerating the properties is not specified.\n *\n * So if you rely on the order in which your series of functions are executed,\n * and want this to work on all platforms, consider using an array.\n *\n * @name series\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing\n * [async functions]{@link AsyncFunction} to run in series.\n * Each function can complete with any number of optional `result` values.\n * @param {Function} [callback] - An optional callback to run once all the\n * functions have completed. This function gets a results array (or object)\n * containing all the result arguments passed to the `task` callbacks. Invoked\n * with (err, result).\n * @return {Promise} a promise, if no callback is passed\n * @example\n *\n * //Using Callbacks\n * async.series([\n * function(callback) {\n * setTimeout(function() {\n * // do some async task\n * callback(null, 'one');\n * }, 200);\n * },\n * function(callback) {\n * setTimeout(function() {\n * // then do another async task\n * callback(null, 'two');\n * }, 100);\n * }\n * ], function(err, results) {\n * console.log(results);\n * // results is equal to ['one','two']\n * });\n *\n * // an example using objects instead of arrays\n * async.series({\n * one: function(callback) {\n * setTimeout(function() {\n * // do some async task\n * callback(null, 1);\n * }, 200);\n * },\n * two: function(callback) {\n * setTimeout(function() {\n * // then do another async task\n * callback(null, 2);\n * }, 100);\n * }\n * }, function(err, results) {\n * console.log(results);\n * // results is equal to: { one: 1, two: 2 }\n * });\n *\n * //Using Promises\n * async.series([\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'one');\n * }, 200);\n * },\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'two');\n * }, 100);\n * }\n * ]).then(results => {\n * console.log(results);\n * // results is equal to ['one','two']\n * }).catch(err => {\n * console.log(err);\n * });\n *\n * // an example using an object instead of an array\n * async.series({\n * one: function(callback) {\n * setTimeout(function() {\n * // do some async task\n * callback(null, 1);\n * }, 200);\n * },\n * two: function(callback) {\n * setTimeout(function() {\n * // then do another async task\n * callback(null, 2);\n * }, 100);\n * }\n * }).then(results => {\n * console.log(results);\n * // results is equal to: { one: 1, two: 2 }\n * }).catch(err => {\n * console.log(err);\n * });\n *\n * //Using async/await\n * async () => {\n * try {\n * let results = await async.series([\n * function(callback) {\n * setTimeout(function() {\n * // do some async task\n * callback(null, 'one');\n * }, 200);\n * },\n * function(callback) {\n * setTimeout(function() {\n * // then do another async task\n * callback(null, 'two');\n * }, 100);\n * }\n * ]);\n * console.log(results);\n * // results is equal to ['one','two']\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n * // an example using an object instead of an array\n * async () => {\n * try {\n * let results = await async.parallel({\n * one: function(callback) {\n * setTimeout(function() {\n * // do some async task\n * callback(null, 1);\n * }, 200);\n * },\n * two: function(callback) {\n * setTimeout(function() {\n * // then do another async task\n * callback(null, 2);\n * }, 100);\n * }\n * });\n * console.log(results);\n * // results is equal to: { one: 1, two: 2 }\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n */\nfunction series(tasks, callback) {\n return _parallel(eachOfSeries$1, tasks, callback);\n}\n\n/**\n * Returns `true` if at least one element in the `coll` satisfies an async test.\n * If any iteratee call returns `true`, the main `callback` is immediately\n * called.\n *\n * @name some\n * @static\n * @memberOf module:Collections\n * @method\n * @alias any\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async truth test to apply to each item\n * in the collections in parallel.\n * The iteratee should complete with a boolean `result` value.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called as soon as any\n * iteratee returns `true`, or after all the iteratee functions have finished.\n * Result will be either `true` or `false` depending on the values of the async\n * tests. Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n * @example\n *\n * // dir1 is a directory that contains file1.txt, file2.txt\n * // dir2 is a directory that contains file3.txt, file4.txt\n * // dir3 is a directory that contains file5.txt\n * // dir4 does not exist\n *\n * // asynchronous function that checks if a file exists\n * function fileExists(file, callback) {\n * fs.access(file, fs.constants.F_OK, (err) => {\n * callback(null, !err);\n * });\n * }\n *\n * // Using callbacks\n * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists,\n * function(err, result) {\n * console.log(result);\n * // true\n * // result is true since some file in the list exists\n * }\n *);\n *\n * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists,\n * function(err, result) {\n * console.log(result);\n * // false\n * // result is false since none of the files exists\n * }\n *);\n *\n * // Using Promises\n * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists)\n * .then( result => {\n * console.log(result);\n * // true\n * // result is true since some file in the list exists\n * }).catch( err => {\n * console.log(err);\n * });\n *\n * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists)\n * .then( result => {\n * console.log(result);\n * // false\n * // result is false since none of the files exists\n * }).catch( err => {\n * console.log(err);\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists);\n * console.log(result);\n * // true\n * // result is true since some file in the list exists\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n * async () => {\n * try {\n * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists);\n * console.log(result);\n * // false\n * // result is false since none of the files exists\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n */\nfunction some(coll, iteratee, callback) {\n return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback)\n}\nvar some$1 = awaitify(some, 3);\n\n/**\n * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time.\n *\n * @name someLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.some]{@link module:Collections.some}\n * @alias anyLimit\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - An async truth test to apply to each item\n * in the collections in parallel.\n * The iteratee should complete with a boolean `result` value.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called as soon as any\n * iteratee returns `true`, or after all the iteratee functions have finished.\n * Result will be either `true` or `false` depending on the values of the async\n * tests. Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n */\nfunction someLimit(coll, limit, iteratee, callback) {\n return _createTester(Boolean, res => res)(eachOfLimit$2(limit), coll, iteratee, callback)\n}\nvar someLimit$1 = awaitify(someLimit, 4);\n\n/**\n * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time.\n *\n * @name someSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.some]{@link module:Collections.some}\n * @alias anySeries\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async truth test to apply to each item\n * in the collections in series.\n * The iteratee should complete with a boolean `result` value.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called as soon as any\n * iteratee returns `true`, or after all the iteratee functions have finished.\n * Result will be either `true` or `false` depending on the values of the async\n * tests. Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n */\nfunction someSeries(coll, iteratee, callback) {\n return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback)\n}\nvar someSeries$1 = awaitify(someSeries, 3);\n\n/**\n * Sorts a list by the results of running each `coll` value through an async\n * `iteratee`.\n *\n * @name sortBy\n * @static\n * @memberOf module:Collections\n * @method\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with a value to use as the sort criteria as\n * its `result`.\n * Invoked with (item, callback).\n * @param {Function} callback - A callback which is called after all the\n * `iteratee` functions have finished, or an error occurs. Results is the items\n * from the original `coll` sorted by the values returned by the `iteratee`\n * calls. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback passed\n * @example\n *\n * // bigfile.txt is a file that is 251100 bytes in size\n * // mediumfile.txt is a file that is 11000 bytes in size\n * // smallfile.txt is a file that is 121 bytes in size\n *\n * // asynchronous function that returns the file size in bytes\n * function getFileSizeInBytes(file, callback) {\n * fs.stat(file, function(err, stat) {\n * if (err) {\n * return callback(err);\n * }\n * callback(null, stat.size);\n * });\n * }\n *\n * // Using callbacks\n * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes,\n * function(err, results) {\n * if (err) {\n * console.log(err);\n * } else {\n * console.log(results);\n * // results is now the original array of files sorted by\n * // file size (ascending by default), e.g.\n * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']\n * }\n * }\n * );\n *\n * // By modifying the callback parameter the\n * // sorting order can be influenced:\n *\n * // ascending order\n * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) {\n * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) {\n * if (getFileSizeErr) return callback(getFileSizeErr);\n * callback(null, fileSize);\n * });\n * }, function(err, results) {\n * if (err) {\n * console.log(err);\n * } else {\n * console.log(results);\n * // results is now the original array of files sorted by\n * // file size (ascending by default), e.g.\n * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']\n * }\n * }\n * );\n *\n * // descending order\n * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) {\n * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) {\n * if (getFileSizeErr) {\n * return callback(getFileSizeErr);\n * }\n * callback(null, fileSize * -1);\n * });\n * }, function(err, results) {\n * if (err) {\n * console.log(err);\n * } else {\n * console.log(results);\n * // results is now the original array of files sorted by\n * // file size (ascending by default), e.g.\n * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt']\n * }\n * }\n * );\n *\n * // Error handling\n * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes,\n * function(err, results) {\n * if (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * } else {\n * console.log(results);\n * }\n * }\n * );\n *\n * // Using Promises\n * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes)\n * .then( results => {\n * console.log(results);\n * // results is now the original array of files sorted by\n * // file size (ascending by default), e.g.\n * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']\n * }).catch( err => {\n * console.log(err);\n * });\n *\n * // Error handling\n * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes)\n * .then( results => {\n * console.log(results);\n * }).catch( err => {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * });\n *\n * // Using async/await\n * (async () => {\n * try {\n * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes);\n * console.log(results);\n * // results is now the original array of files sorted by\n * // file size (ascending by default), e.g.\n * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt']\n * }\n * catch (err) {\n * console.log(err);\n * }\n * })();\n *\n * // Error handling\n * async () => {\n * try {\n * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes);\n * console.log(results);\n * }\n * catch (err) {\n * console.log(err);\n * // [ Error: ENOENT: no such file or directory ]\n * }\n * }\n *\n */\nfunction sortBy (coll, iteratee, callback) {\n var _iteratee = wrapAsync(iteratee);\n return map$1(coll, (x, iterCb) => {\n _iteratee(x, (err, criteria) => {\n if (err) return iterCb(err);\n iterCb(err, {value: x, criteria});\n });\n }, (err, results) => {\n if (err) return callback(err);\n callback(null, results.sort(comparator).map(v => v.value));\n });\n\n function comparator(left, right) {\n var a = left.criteria, b = right.criteria;\n return a < b ? -1 : a > b ? 1 : 0;\n }\n}\nvar sortBy$1 = awaitify(sortBy, 3);\n\n/**\n * Sets a time limit on an asynchronous function. If the function does not call\n * its callback within the specified milliseconds, it will be called with a\n * timeout error. The code property for the error object will be `'ETIMEDOUT'`.\n *\n * @name timeout\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {AsyncFunction} asyncFn - The async function to limit in time.\n * @param {number} milliseconds - The specified time limit.\n * @param {*} [info] - Any variable you want attached (`string`, `object`, etc)\n * to timeout Error for more information..\n * @returns {AsyncFunction} Returns a wrapped function that can be used with any\n * of the control flow functions.\n * Invoke this function with the same parameters as you would `asyncFunc`.\n * @example\n *\n * function myFunction(foo, callback) {\n * doAsyncTask(foo, function(err, data) {\n * // handle errors\n * if (err) return callback(err);\n *\n * // do some stuff ...\n *\n * // return processed data\n * return callback(null, data);\n * });\n * }\n *\n * var wrapped = async.timeout(myFunction, 1000);\n *\n * // call `wrapped` as you would `myFunction`\n * wrapped({ bar: 'bar' }, function(err, data) {\n * // if `myFunction` takes < 1000 ms to execute, `err`\n * // and `data` will have their expected values\n *\n * // else `err` will be an Error with the code 'ETIMEDOUT'\n * });\n */\nfunction timeout(asyncFn, milliseconds, info) {\n var fn = wrapAsync(asyncFn);\n\n return initialParams((args, callback) => {\n var timedOut = false;\n var timer;\n\n function timeoutCallback() {\n var name = asyncFn.name || 'anonymous';\n var error = new Error('Callback function \"' + name + '\" timed out.');\n error.code = 'ETIMEDOUT';\n if (info) {\n error.info = info;\n }\n timedOut = true;\n callback(error);\n }\n\n args.push((...cbArgs) => {\n if (!timedOut) {\n callback(...cbArgs);\n clearTimeout(timer);\n }\n });\n\n // setup timer and call original function\n timer = setTimeout(timeoutCallback, milliseconds);\n fn(...args);\n });\n}\n\nfunction range(size) {\n var result = Array(size);\n while (size--) {\n result[size] = size;\n }\n return result;\n}\n\n/**\n * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name timesLimit\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.times]{@link module:ControlFlow.times}\n * @category Control Flow\n * @param {number} count - The number of times to run the function.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - The async function to call `n` times.\n * Invoked with the iteration index and a callback: (n, next).\n * @param {Function} callback - see [async.map]{@link module:Collections.map}.\n * @returns {Promise} a promise, if no callback is provided\n */\nfunction timesLimit(count, limit, iteratee, callback) {\n var _iteratee = wrapAsync(iteratee);\n return mapLimit$1(range(count), limit, _iteratee, callback);\n}\n\n/**\n * Calls the `iteratee` function `n` times, and accumulates results in the same\n * manner you would use with [map]{@link module:Collections.map}.\n *\n * @name times\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.map]{@link module:Collections.map}\n * @category Control Flow\n * @param {number} n - The number of times to run the function.\n * @param {AsyncFunction} iteratee - The async function to call `n` times.\n * Invoked with the iteration index and a callback: (n, next).\n * @param {Function} callback - see {@link module:Collections.map}.\n * @returns {Promise} a promise, if no callback is provided\n * @example\n *\n * // Pretend this is some complicated async factory\n * var createUser = function(id, callback) {\n * callback(null, {\n * id: 'user' + id\n * });\n * };\n *\n * // generate 5 users\n * async.times(5, function(n, next) {\n * createUser(n, function(err, user) {\n * next(err, user);\n * });\n * }, function(err, users) {\n * // we should now have 5 users\n * });\n */\nfunction times (n, iteratee, callback) {\n return timesLimit(n, Infinity, iteratee, callback)\n}\n\n/**\n * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time.\n *\n * @name timesSeries\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.times]{@link module:ControlFlow.times}\n * @category Control Flow\n * @param {number} n - The number of times to run the function.\n * @param {AsyncFunction} iteratee - The async function to call `n` times.\n * Invoked with the iteration index and a callback: (n, next).\n * @param {Function} callback - see {@link module:Collections.map}.\n * @returns {Promise} a promise, if no callback is provided\n */\nfunction timesSeries (n, iteratee, callback) {\n return timesLimit(n, 1, iteratee, callback)\n}\n\n/**\n * A relative of `reduce`. Takes an Object or Array, and iterates over each\n * element in parallel, each step potentially mutating an `accumulator` value.\n * The type of the accumulator defaults to the type of collection passed in.\n *\n * @name transform\n * @static\n * @memberOf module:Collections\n * @method\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {*} [accumulator] - The initial state of the transform. If omitted,\n * it will default to an empty Object or Array, depending on the type of `coll`\n * @param {AsyncFunction} iteratee - A function applied to each item in the\n * collection that potentially modifies the accumulator.\n * Invoked with (accumulator, item, key, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Result is the transformed accumulator.\n * Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n * @example\n *\n * // file1.txt is a file that is 1000 bytes in size\n * // file2.txt is a file that is 2000 bytes in size\n * // file3.txt is a file that is 3000 bytes in size\n *\n * // helper function that returns human-readable size format from bytes\n * function formatBytes(bytes, decimals = 2) {\n * // implementation not included for brevity\n * return humanReadbleFilesize;\n * }\n *\n * const fileList = ['file1.txt','file2.txt','file3.txt'];\n *\n * // asynchronous function that returns the file size, transformed to human-readable format\n * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc.\n * function transformFileSize(acc, value, key, callback) {\n * fs.stat(value, function(err, stat) {\n * if (err) {\n * return callback(err);\n * }\n * acc[key] = formatBytes(stat.size);\n * callback(null);\n * });\n * }\n *\n * // Using callbacks\n * async.transform(fileList, transformFileSize, function(err, result) {\n * if(err) {\n * console.log(err);\n * } else {\n * console.log(result);\n * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ]\n * }\n * });\n *\n * // Using Promises\n * async.transform(fileList, transformFileSize)\n * .then(result => {\n * console.log(result);\n * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ]\n * }).catch(err => {\n * console.log(err);\n * });\n *\n * // Using async/await\n * (async () => {\n * try {\n * let result = await async.transform(fileList, transformFileSize);\n * console.log(result);\n * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ]\n * }\n * catch (err) {\n * console.log(err);\n * }\n * })();\n *\n * @example\n *\n * // file1.txt is a file that is 1000 bytes in size\n * // file2.txt is a file that is 2000 bytes in size\n * // file3.txt is a file that is 3000 bytes in size\n *\n * // helper function that returns human-readable size format from bytes\n * function formatBytes(bytes, decimals = 2) {\n * // implementation not included for brevity\n * return humanReadbleFilesize;\n * }\n *\n * const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' };\n *\n * // asynchronous function that returns the file size, transformed to human-readable format\n * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc.\n * function transformFileSize(acc, value, key, callback) {\n * fs.stat(value, function(err, stat) {\n * if (err) {\n * return callback(err);\n * }\n * acc[key] = formatBytes(stat.size);\n * callback(null);\n * });\n * }\n *\n * // Using callbacks\n * async.transform(fileMap, transformFileSize, function(err, result) {\n * if(err) {\n * console.log(err);\n * } else {\n * console.log(result);\n * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }\n * }\n * });\n *\n * // Using Promises\n * async.transform(fileMap, transformFileSize)\n * .then(result => {\n * console.log(result);\n * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }\n * }).catch(err => {\n * console.log(err);\n * });\n *\n * // Using async/await\n * async () => {\n * try {\n * let result = await async.transform(fileMap, transformFileSize);\n * console.log(result);\n * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' }\n * }\n * catch (err) {\n * console.log(err);\n * }\n * }\n *\n */\nfunction transform (coll, accumulator, iteratee, callback) {\n if (arguments.length <= 3 && typeof accumulator === 'function') {\n callback = iteratee;\n iteratee = accumulator;\n accumulator = Array.isArray(coll) ? [] : {};\n }\n callback = once(callback || promiseCallback());\n var _iteratee = wrapAsync(iteratee);\n\n eachOf$1(coll, (v, k, cb) => {\n _iteratee(accumulator, v, k, cb);\n }, err => callback(err, accumulator));\n return callback[PROMISE_SYMBOL]\n}\n\n/**\n * It runs each task in series but stops whenever any of the functions were\n * successful. If one of the tasks were successful, the `callback` will be\n * passed the result of the successful task. If all tasks fail, the callback\n * will be passed the error and result (if any) of the final attempt.\n *\n * @name tryEach\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to\n * run, each function is passed a `callback(err, result)` it must call on\n * completion with an error `err` (which can be `null`) and an optional `result`\n * value.\n * @param {Function} [callback] - An optional callback which is called when one\n * of the tasks has succeeded, or all have failed. It receives the `err` and\n * `result` arguments of the last attempt at completing the `task`. Invoked with\n * (err, results).\n * @returns {Promise} a promise, if no callback is passed\n * @example\n * async.tryEach([\n * function getDataFromFirstWebsite(callback) {\n * // Try getting the data from the first website\n * callback(err, data);\n * },\n * function getDataFromSecondWebsite(callback) {\n * // First website failed,\n * // Try getting the data from the backup website\n * callback(err, data);\n * }\n * ],\n * // optional callback\n * function(err, results) {\n * Now do something with the data.\n * });\n *\n */\nfunction tryEach(tasks, callback) {\n var error = null;\n var result;\n return eachSeries$1(tasks, (task, taskCb) => {\n wrapAsync(task)((err, ...args) => {\n if (err === false) return taskCb(err);\n\n if (args.length < 2) {\n [result] = args;\n } else {\n result = args;\n }\n error = err;\n taskCb(err ? null : {});\n });\n }, () => callback(error, result));\n}\n\nvar tryEach$1 = awaitify(tryEach);\n\n/**\n * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original,\n * unmemoized form. Handy for testing.\n *\n * @name unmemoize\n * @static\n * @memberOf module:Utils\n * @method\n * @see [async.memoize]{@link module:Utils.memoize}\n * @category Util\n * @param {AsyncFunction} fn - the memoized function\n * @returns {AsyncFunction} a function that calls the original unmemoized function\n */\nfunction unmemoize(fn) {\n return (...args) => {\n return (fn.unmemoized || fn)(...args);\n };\n}\n\n/**\n * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when\n * stopped, or an error occurs.\n *\n * @name whilst\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {AsyncFunction} test - asynchronous truth test to perform before each\n * execution of `iteratee`. Invoked with (callback).\n * @param {AsyncFunction} iteratee - An async function which is called each time\n * `test` passes. Invoked with (callback).\n * @param {Function} [callback] - A callback which is called after the test\n * function has failed and repeated execution of `iteratee` has stopped. `callback`\n * will be passed an error and any arguments passed to the final `iteratee`'s\n * callback. Invoked with (err, [results]);\n * @returns {Promise} a promise, if no callback is passed\n * @example\n *\n * var count = 0;\n * async.whilst(\n * function test(cb) { cb(null, count < 5); },\n * function iter(callback) {\n * count++;\n * setTimeout(function() {\n * callback(null, count);\n * }, 1000);\n * },\n * function (err, n) {\n * // 5 seconds have passed, n = 5\n * }\n * );\n */\nfunction whilst(test, iteratee, callback) {\n callback = onlyOnce(callback);\n var _fn = wrapAsync(iteratee);\n var _test = wrapAsync(test);\n var results = [];\n\n function next(err, ...rest) {\n if (err) return callback(err);\n results = rest;\n if (err === false) return;\n _test(check);\n }\n\n function check(err, truth) {\n if (err) return callback(err);\n if (err === false) return;\n if (!truth) return callback(null, ...results);\n _fn(next);\n }\n\n return _test(check);\n}\nvar whilst$1 = awaitify(whilst, 3);\n\n/**\n * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when\n * stopped, or an error occurs. `callback` will be passed an error and any\n * arguments passed to the final `iteratee`'s callback.\n *\n * The inverse of [whilst]{@link module:ControlFlow.whilst}.\n *\n * @name until\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.whilst]{@link module:ControlFlow.whilst}\n * @category Control Flow\n * @param {AsyncFunction} test - asynchronous truth test to perform before each\n * execution of `iteratee`. Invoked with (callback).\n * @param {AsyncFunction} iteratee - An async function which is called each time\n * `test` fails. Invoked with (callback).\n * @param {Function} [callback] - A callback which is called after the test\n * function has passed and repeated execution of `iteratee` has stopped. `callback`\n * will be passed an error and any arguments passed to the final `iteratee`'s\n * callback. Invoked with (err, [results]);\n * @returns {Promise} a promise, if a callback is not passed\n *\n * @example\n * const results = []\n * let finished = false\n * async.until(function test(cb) {\n * cb(null, finished)\n * }, function iter(next) {\n * fetchPage(url, (err, body) => {\n * if (err) return next(err)\n * results = results.concat(body.objects)\n * finished = !!body.next\n * next(err)\n * })\n * }, function done (err) {\n * // all pages have been fetched\n * })\n */\nfunction until(test, iteratee, callback) {\n const _test = wrapAsync(test);\n return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback);\n}\n\n/**\n * Runs the `tasks` array of functions in series, each passing their results to\n * the next in the array. However, if any of the `tasks` pass an error to their\n * own callback, the next function is not executed, and the main `callback` is\n * immediately called with the error.\n *\n * @name waterfall\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Array} tasks - An array of [async functions]{@link AsyncFunction}\n * to run.\n * Each function should complete with any number of `result` values.\n * The `result` values will be passed as arguments, in order, to the next task.\n * @param {Function} [callback] - An optional callback to run once all the\n * functions have completed. This will be passed the results of the last task's\n * callback. Invoked with (err, [results]).\n * @returns {Promise} a promise, if a callback is omitted\n * @example\n *\n * async.waterfall([\n * function(callback) {\n * callback(null, 'one', 'two');\n * },\n * function(arg1, arg2, callback) {\n * // arg1 now equals 'one' and arg2 now equals 'two'\n * callback(null, 'three');\n * },\n * function(arg1, callback) {\n * // arg1 now equals 'three'\n * callback(null, 'done');\n * }\n * ], function (err, result) {\n * // result now equals 'done'\n * });\n *\n * // Or, with named functions:\n * async.waterfall([\n * myFirstFunction,\n * mySecondFunction,\n * myLastFunction,\n * ], function (err, result) {\n * // result now equals 'done'\n * });\n * function myFirstFunction(callback) {\n * callback(null, 'one', 'two');\n * }\n * function mySecondFunction(arg1, arg2, callback) {\n * // arg1 now equals 'one' and arg2 now equals 'two'\n * callback(null, 'three');\n * }\n * function myLastFunction(arg1, callback) {\n * // arg1 now equals 'three'\n * callback(null, 'done');\n * }\n */\nfunction waterfall (tasks, callback) {\n callback = once(callback);\n if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions'));\n if (!tasks.length) return callback();\n var taskIndex = 0;\n\n function nextTask(args) {\n var task = wrapAsync(tasks[taskIndex++]);\n task(...args, onlyOnce(next));\n }\n\n function next(err, ...args) {\n if (err === false) return\n if (err || taskIndex === tasks.length) {\n return callback(err, ...args);\n }\n nextTask(args);\n }\n\n nextTask([]);\n}\n\nvar waterfall$1 = awaitify(waterfall);\n\n/**\n * An \"async function\" in the context of Async is an asynchronous function with\n * a variable number of parameters, with the final parameter being a callback.\n * (`function (arg1, arg2, ..., callback) {}`)\n * The final callback is of the form `callback(err, results...)`, which must be\n * called once the function is completed. The callback should be called with a\n * Error as its first argument to signal that an error occurred.\n * Otherwise, if no error occurred, it should be called with `null` as the first\n * argument, and any additional `result` arguments that may apply, to signal\n * successful completion.\n * The callback must be called exactly once, ideally on a later tick of the\n * JavaScript event loop.\n *\n * This type of function is also referred to as a \"Node-style async function\",\n * or a \"continuation passing-style function\" (CPS). Most of the methods of this\n * library are themselves CPS/Node-style async functions, or functions that\n * return CPS/Node-style async functions.\n *\n * Wherever we accept a Node-style async function, we also directly accept an\n * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}.\n * In this case, the `async` function will not be passed a final callback\n * argument, and any thrown error will be used as the `err` argument of the\n * implicit callback, and the return value will be used as the `result` value.\n * (i.e. a `rejected` of the returned Promise becomes the `err` callback\n * argument, and a `resolved` value becomes the `result`.)\n *\n * Note, due to JavaScript limitations, we can only detect native `async`\n * functions and not transpilied implementations.\n * Your environment must have `async`/`await` support for this to work.\n * (e.g. Node > v7.6, or a recent version of a modern browser).\n * If you are using `async` functions through a transpiler (e.g. Babel), you\n * must still wrap the function with [asyncify]{@link module:Utils.asyncify},\n * because the `async function` will be compiled to an ordinary function that\n * returns a promise.\n *\n * @typedef {Function} AsyncFunction\n * @static\n */\n\n\nvar index = {\n apply,\n applyEach,\n applyEachSeries,\n asyncify,\n auto,\n autoInject,\n cargo: cargo$1,\n cargoQueue: cargo,\n compose,\n concat: concat$1,\n concatLimit: concatLimit$1,\n concatSeries: concatSeries$1,\n constant: constant$1,\n detect: detect$1,\n detectLimit: detectLimit$1,\n detectSeries: detectSeries$1,\n dir,\n doUntil,\n doWhilst: doWhilst$1,\n each,\n eachLimit: eachLimit$1,\n eachOf: eachOf$1,\n eachOfLimit: eachOfLimit$1,\n eachOfSeries: eachOfSeries$1,\n eachSeries: eachSeries$1,\n ensureAsync,\n every: every$1,\n everyLimit: everyLimit$1,\n everySeries: everySeries$1,\n filter: filter$1,\n filterLimit: filterLimit$1,\n filterSeries: filterSeries$1,\n forever: forever$1,\n groupBy,\n groupByLimit: groupByLimit$1,\n groupBySeries,\n log,\n map: map$1,\n mapLimit: mapLimit$1,\n mapSeries: mapSeries$1,\n mapValues,\n mapValuesLimit: mapValuesLimit$1,\n mapValuesSeries,\n memoize,\n nextTick,\n parallel,\n parallelLimit,\n priorityQueue,\n queue,\n race: race$1,\n reduce: reduce$1,\n reduceRight,\n reflect,\n reflectAll,\n reject: reject$1,\n rejectLimit: rejectLimit$1,\n rejectSeries: rejectSeries$1,\n retry,\n retryable,\n seq,\n series,\n setImmediate: setImmediate$1,\n some: some$1,\n someLimit: someLimit$1,\n someSeries: someSeries$1,\n sortBy: sortBy$1,\n timeout,\n times,\n timesLimit,\n timesSeries,\n transform,\n tryEach: tryEach$1,\n unmemoize,\n until,\n waterfall: waterfall$1,\n whilst: whilst$1,\n\n // aliases\n all: every$1,\n allLimit: everyLimit$1,\n allSeries: everySeries$1,\n any: some$1,\n anyLimit: someLimit$1,\n anySeries: someSeries$1,\n find: detect$1,\n findLimit: detectLimit$1,\n findSeries: detectSeries$1,\n flatMap: concat$1,\n flatMapLimit: concatLimit$1,\n flatMapSeries: concatSeries$1,\n forEach: each,\n forEachSeries: eachSeries$1,\n forEachLimit: eachLimit$1,\n forEachOf: eachOf$1,\n forEachOfSeries: eachOfSeries$1,\n forEachOfLimit: eachOfLimit$1,\n inject: reduce$1,\n foldl: reduce$1,\n foldr: reduceRight,\n select: filter$1,\n selectLimit: filterLimit$1,\n selectSeries: filterSeries$1,\n wrapSync: asyncify,\n during: whilst$1,\n doDuring: doWhilst$1\n};\n\nexport { every$1 as all, everyLimit$1 as allLimit, everySeries$1 as allSeries, some$1 as any, someLimit$1 as anyLimit, someSeries$1 as anySeries, apply, applyEach, applyEachSeries, asyncify, auto, autoInject, cargo$1 as cargo, cargo as cargoQueue, compose, concat$1 as concat, concatLimit$1 as concatLimit, concatSeries$1 as concatSeries, constant$1 as constant, index as default, detect$1 as detect, detectLimit$1 as detectLimit, detectSeries$1 as detectSeries, dir, doWhilst$1 as doDuring, doUntil, doWhilst$1 as doWhilst, whilst$1 as during, each, eachLimit$1 as eachLimit, eachOf$1 as eachOf, eachOfLimit$1 as eachOfLimit, eachOfSeries$1 as eachOfSeries, eachSeries$1 as eachSeries, ensureAsync, every$1 as every, everyLimit$1 as everyLimit, everySeries$1 as everySeries, filter$1 as filter, filterLimit$1 as filterLimit, filterSeries$1 as filterSeries, detect$1 as find, detectLimit$1 as findLimit, detectSeries$1 as findSeries, concat$1 as flatMap, concatLimit$1 as flatMapLimit, concatSeries$1 as flatMapSeries, reduce$1 as foldl, reduceRight as foldr, each as forEach, eachLimit$1 as forEachLimit, eachOf$1 as forEachOf, eachOfLimit$1 as forEachOfLimit, eachOfSeries$1 as forEachOfSeries, eachSeries$1 as forEachSeries, forever$1 as forever, groupBy, groupByLimit$1 as groupByLimit, groupBySeries, reduce$1 as inject, log, map$1 as map, mapLimit$1 as mapLimit, mapSeries$1 as mapSeries, mapValues, mapValuesLimit$1 as mapValuesLimit, mapValuesSeries, memoize, nextTick, parallel, parallelLimit, priorityQueue, queue, race$1 as race, reduce$1 as reduce, reduceRight, reflect, reflectAll, reject$1 as reject, rejectLimit$1 as rejectLimit, rejectSeries$1 as rejectSeries, retry, retryable, filter$1 as select, filterLimit$1 as selectLimit, filterSeries$1 as selectSeries, seq, series, setImmediate$1 as setImmediate, some$1 as some, someLimit$1 as someLimit, someSeries$1 as someSeries, sortBy$1 as sortBy, timeout, times, timesLimit, timesSeries, transform, tryEach$1 as tryEach, unmemoize, until, waterfall$1 as waterfall, whilst$1 as whilst, asyncify as wrapSync };\n","var constants = require('constants')\n\nvar origCwd = process.cwd\nvar cwd = null\n\nvar platform = process.env.GRACEFUL_FS_PLATFORM || process.platform\n\nprocess.cwd = function() {\n if (!cwd)\n cwd = origCwd.call(process)\n return cwd\n}\ntry {\n process.cwd()\n} catch (er) {}\n\n// This check is needed until node.js 12 is required\nif (typeof process.chdir === 'function') {\n var chdir = process.chdir\n process.chdir = function (d) {\n cwd = null\n chdir.call(process, d)\n }\n if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir)\n}\n\nmodule.exports = patch\n\nfunction patch (fs) {\n // (re-)implement some things that are known busted or missing.\n\n // lchmod, broken prior to 0.6.2\n // back-port the fix here.\n if (constants.hasOwnProperty('O_SYMLINK') &&\n process.version.match(/^v0\\.6\\.[0-2]|^v0\\.5\\./)) {\n patchLchmod(fs)\n }\n\n // lutimes implementation, or no-op\n if (!fs.lutimes) {\n patchLutimes(fs)\n }\n\n // https://github.com/isaacs/node-graceful-fs/issues/4\n // Chown should not fail on einval or eperm if non-root.\n // It should not fail on enosys ever, as this just indicates\n // that a fs doesn't support the intended operation.\n\n fs.chown = chownFix(fs.chown)\n fs.fchown = chownFix(fs.fchown)\n fs.lchown = chownFix(fs.lchown)\n\n fs.chmod = chmodFix(fs.chmod)\n fs.fchmod = chmodFix(fs.fchmod)\n fs.lchmod = chmodFix(fs.lchmod)\n\n fs.chownSync = chownFixSync(fs.chownSync)\n fs.fchownSync = chownFixSync(fs.fchownSync)\n fs.lchownSync = chownFixSync(fs.lchownSync)\n\n fs.chmodSync = chmodFixSync(fs.chmodSync)\n fs.fchmodSync = chmodFixSync(fs.fchmodSync)\n fs.lchmodSync = chmodFixSync(fs.lchmodSync)\n\n fs.stat = statFix(fs.stat)\n fs.fstat = statFix(fs.fstat)\n fs.lstat = statFix(fs.lstat)\n\n fs.statSync = statFixSync(fs.statSync)\n fs.fstatSync = statFixSync(fs.fstatSync)\n fs.lstatSync = statFixSync(fs.lstatSync)\n\n // if lchmod/lchown do not exist, then make them no-ops\n if (fs.chmod && !fs.lchmod) {\n fs.lchmod = function (path, mode, cb) {\n if (cb) process.nextTick(cb)\n }\n fs.lchmodSync = function () {}\n }\n if (fs.chown && !fs.lchown) {\n fs.lchown = function (path, uid, gid, cb) {\n if (cb) process.nextTick(cb)\n }\n fs.lchownSync = function () {}\n }\n\n // on Windows, A/V software can lock the directory, causing this\n // to fail with an EACCES or EPERM if the directory contains newly\n // created files. Try again on failure, for up to 60 seconds.\n\n // Set the timeout this long because some Windows Anti-Virus, such as Parity\n // bit9, may lock files for up to a minute, causing npm package install\n // failures. Also, take care to yield the scheduler. Windows scheduling gives\n // CPU to a busy looping process, which can cause the program causing the lock\n // contention to be starved of CPU by node, so the contention doesn't resolve.\n if (platform === \"win32\") {\n fs.rename = typeof fs.rename !== 'function' ? fs.rename\n : (function (fs$rename) {\n function rename (from, to, cb) {\n var start = Date.now()\n var backoff = 0;\n fs$rename(from, to, function CB (er) {\n if (er\n && (er.code === \"EACCES\" || er.code === \"EPERM\" || er.code === \"EBUSY\")\n && Date.now() - start < 60000) {\n setTimeout(function() {\n fs.stat(to, function (stater, st) {\n if (stater && stater.code === \"ENOENT\")\n fs$rename(from, to, CB);\n else\n cb(er)\n })\n }, backoff)\n if (backoff < 100)\n backoff += 10;\n return;\n }\n if (cb) cb(er)\n })\n }\n if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename)\n return rename\n })(fs.rename)\n }\n\n // if read() returns EAGAIN, then just try it again.\n fs.read = typeof fs.read !== 'function' ? fs.read\n : (function (fs$read) {\n function read (fd, buffer, offset, length, position, callback_) {\n var callback\n if (callback_ && typeof callback_ === 'function') {\n var eagCounter = 0\n callback = function (er, _, __) {\n if (er && er.code === 'EAGAIN' && eagCounter < 10) {\n eagCounter ++\n return fs$read.call(fs, fd, buffer, offset, length, position, callback)\n }\n callback_.apply(this, arguments)\n }\n }\n return fs$read.call(fs, fd, buffer, offset, length, position, callback)\n }\n\n // This ensures `util.promisify` works as it does for native `fs.read`.\n if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read)\n return read\n })(fs.read)\n\n fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync\n : (function (fs$readSync) { return function (fd, buffer, offset, length, position) {\n var eagCounter = 0\n while (true) {\n try {\n return fs$readSync.call(fs, fd, buffer, offset, length, position)\n } catch (er) {\n if (er.code === 'EAGAIN' && eagCounter < 10) {\n eagCounter ++\n continue\n }\n throw er\n }\n }\n }})(fs.readSync)\n\n function patchLchmod (fs) {\n fs.lchmod = function (path, mode, callback) {\n fs.open( path\n , constants.O_WRONLY | constants.O_SYMLINK\n , mode\n , function (err, fd) {\n if (err) {\n if (callback) callback(err)\n return\n }\n // prefer to return the chmod error, if one occurs,\n // but still try to close, and report closing errors if they occur.\n fs.fchmod(fd, mode, function (err) {\n fs.close(fd, function(err2) {\n if (callback) callback(err || err2)\n })\n })\n })\n }\n\n fs.lchmodSync = function (path, mode) {\n var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode)\n\n // prefer to return the chmod error, if one occurs,\n // but still try to close, and report closing errors if they occur.\n var threw = true\n var ret\n try {\n ret = fs.fchmodSync(fd, mode)\n threw = false\n } finally {\n if (threw) {\n try {\n fs.closeSync(fd)\n } catch (er) {}\n } else {\n fs.closeSync(fd)\n }\n }\n return ret\n }\n }\n\n function patchLutimes (fs) {\n if (constants.hasOwnProperty(\"O_SYMLINK\") && fs.futimes) {\n fs.lutimes = function (path, at, mt, cb) {\n fs.open(path, constants.O_SYMLINK, function (er, fd) {\n if (er) {\n if (cb) cb(er)\n return\n }\n fs.futimes(fd, at, mt, function (er) {\n fs.close(fd, function (er2) {\n if (cb) cb(er || er2)\n })\n })\n })\n }\n\n fs.lutimesSync = function (path, at, mt) {\n var fd = fs.openSync(path, constants.O_SYMLINK)\n var ret\n var threw = true\n try {\n ret = fs.futimesSync(fd, at, mt)\n threw = false\n } finally {\n if (threw) {\n try {\n fs.closeSync(fd)\n } catch (er) {}\n } else {\n fs.closeSync(fd)\n }\n }\n return ret\n }\n\n } else if (fs.futimes) {\n fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) }\n fs.lutimesSync = function () {}\n }\n }\n\n function chmodFix (orig) {\n if (!orig) return orig\n return function (target, mode, cb) {\n return orig.call(fs, target, mode, function (er) {\n if (chownErOk(er)) er = null\n if (cb) cb.apply(this, arguments)\n })\n }\n }\n\n function chmodFixSync (orig) {\n if (!orig) return orig\n return function (target, mode) {\n try {\n return orig.call(fs, target, mode)\n } catch (er) {\n if (!chownErOk(er)) throw er\n }\n }\n }\n\n\n function chownFix (orig) {\n if (!orig) return orig\n return function (target, uid, gid, cb) {\n return orig.call(fs, target, uid, gid, function (er) {\n if (chownErOk(er)) er = null\n if (cb) cb.apply(this, arguments)\n })\n }\n }\n\n function chownFixSync (orig) {\n if (!orig) return orig\n return function (target, uid, gid) {\n try {\n return orig.call(fs, target, uid, gid)\n } catch (er) {\n if (!chownErOk(er)) throw er\n }\n }\n }\n\n function statFix (orig) {\n if (!orig) return orig\n // Older versions of Node erroneously returned signed integers for\n // uid + gid.\n return function (target, options, cb) {\n if (typeof options === 'function') {\n cb = options\n options = null\n }\n function callback (er, stats) {\n if (stats) {\n if (stats.uid < 0) stats.uid += 0x100000000\n if (stats.gid < 0) stats.gid += 0x100000000\n }\n if (cb) cb.apply(this, arguments)\n }\n return options ? orig.call(fs, target, options, callback)\n : orig.call(fs, target, callback)\n }\n }\n\n function statFixSync (orig) {\n if (!orig) return orig\n // Older versions of Node erroneously returned signed integers for\n // uid + gid.\n return function (target, options) {\n var stats = options ? orig.call(fs, target, options)\n : orig.call(fs, target)\n if (stats) {\n if (stats.uid < 0) stats.uid += 0x100000000\n if (stats.gid < 0) stats.gid += 0x100000000\n }\n return stats;\n }\n }\n\n // ENOSYS means that the fs doesn't support the op. Just ignore\n // that, because it doesn't matter.\n //\n // if there's no getuid, or if getuid() is something other\n // than 0, and the error is EINVAL or EPERM, then just ignore\n // it.\n //\n // This specific case is a silent failure in cp, install, tar,\n // and most other unix tools that manage permissions.\n //\n // When running as root, or if other types of errors are\n // encountered, then it's strict.\n function chownErOk (er) {\n if (!er)\n return true\n\n if (er.code === \"ENOSYS\")\n return true\n\n var nonroot = !process.getuid || process.getuid() !== 0\n if (nonroot) {\n if (er.code === \"EINVAL\" || er.code === \"EPERM\")\n return true\n }\n\n return false\n }\n}\n","var Stream = require('stream').Stream\n\nmodule.exports = legacy\n\nfunction legacy (fs) {\n return {\n ReadStream: ReadStream,\n WriteStream: WriteStream\n }\n\n function ReadStream (path, options) {\n if (!(this instanceof ReadStream)) return new ReadStream(path, options);\n\n Stream.call(this);\n\n var self = this;\n\n this.path = path;\n this.fd = null;\n this.readable = true;\n this.paused = false;\n\n this.flags = 'r';\n this.mode = 438; /*=0666*/\n this.bufferSize = 64 * 1024;\n\n options = options || {};\n\n // Mixin options into this\n var keys = Object.keys(options);\n for (var index = 0, length = keys.length; index < length; index++) {\n var key = keys[index];\n this[key] = options[key];\n }\n\n if (this.encoding) this.setEncoding(this.encoding);\n\n if (this.start !== undefined) {\n if ('number' !== typeof this.start) {\n throw TypeError('start must be a Number');\n }\n if (this.end === undefined) {\n this.end = Infinity;\n } else if ('number' !== typeof this.end) {\n throw TypeError('end must be a Number');\n }\n\n if (this.start > this.end) {\n throw new Error('start must be <= end');\n }\n\n this.pos = this.start;\n }\n\n if (this.fd !== null) {\n process.nextTick(function() {\n self._read();\n });\n return;\n }\n\n fs.open(this.path, this.flags, this.mode, function (err, fd) {\n if (err) {\n self.emit('error', err);\n self.readable = false;\n return;\n }\n\n self.fd = fd;\n self.emit('open', fd);\n self._read();\n })\n }\n\n function WriteStream (path, options) {\n if (!(this instanceof WriteStream)) return new WriteStream(path, options);\n\n Stream.call(this);\n\n this.path = path;\n this.fd = null;\n this.writable = true;\n\n this.flags = 'w';\n this.encoding = 'binary';\n this.mode = 438; /*=0666*/\n this.bytesWritten = 0;\n\n options = options || {};\n\n // Mixin options into this\n var keys = Object.keys(options);\n for (var index = 0, length = keys.length; index < length; index++) {\n var key = keys[index];\n this[key] = options[key];\n }\n\n if (this.start !== undefined) {\n if ('number' !== typeof this.start) {\n throw TypeError('start must be a Number');\n }\n if (this.start < 0) {\n throw new Error('start must be >= zero');\n }\n\n this.pos = this.start;\n }\n\n this.busy = false;\n this._queue = [];\n\n if (this.fd === null) {\n this._open = fs.open;\n this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);\n this.flush();\n }\n }\n}\n","'use strict'\n\nmodule.exports = clone\n\nvar getPrototypeOf = Object.getPrototypeOf || function (obj) {\n return obj.__proto__\n}\n\nfunction clone (obj) {\n if (obj === null || typeof obj !== 'object')\n return obj\n\n if (obj instanceof Object)\n var copy = { __proto__: getPrototypeOf(obj) }\n else\n var copy = Object.create(null)\n\n Object.getOwnPropertyNames(obj).forEach(function (key) {\n Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key))\n })\n\n return copy\n}\n","var fs = require('fs')\nvar polyfills = require('./polyfills.js')\nvar legacy = require('./legacy-streams.js')\nvar clone = require('./clone.js')\n\nvar util = require('util')\n\n/* istanbul ignore next - node 0.x polyfill */\nvar gracefulQueue\nvar previousSymbol\n\n/* istanbul ignore else - node 0.x polyfill */\nif (typeof Symbol === 'function' && typeof Symbol.for === 'function') {\n gracefulQueue = Symbol.for('graceful-fs.queue')\n // This is used in testing by future versions\n previousSymbol = Symbol.for('graceful-fs.previous')\n} else {\n gracefulQueue = '___graceful-fs.queue'\n previousSymbol = '___graceful-fs.previous'\n}\n\nfunction noop () {}\n\nfunction publishQueue(context, queue) {\n Object.defineProperty(context, gracefulQueue, {\n get: function() {\n return queue\n }\n })\n}\n\nvar debug = noop\nif (util.debuglog)\n debug = util.debuglog('gfs4')\nelse if (/\\bgfs4\\b/i.test(process.env.NODE_DEBUG || ''))\n debug = function() {\n var m = util.format.apply(util, arguments)\n m = 'GFS4: ' + m.split(/\\n/).join('\\nGFS4: ')\n console.error(m)\n }\n\n// Once time initialization\nif (!fs[gracefulQueue]) {\n // This queue can be shared by multiple loaded instances\n var queue = global[gracefulQueue] || []\n publishQueue(fs, queue)\n\n // Patch fs.close/closeSync to shared queue version, because we need\n // to retry() whenever a close happens *anywhere* in the program.\n // This is essential when multiple graceful-fs instances are\n // in play at the same time.\n fs.close = (function (fs$close) {\n function close (fd, cb) {\n return fs$close.call(fs, fd, function (err) {\n // This function uses the graceful-fs shared queue\n if (!err) {\n resetQueue()\n }\n\n if (typeof cb === 'function')\n cb.apply(this, arguments)\n })\n }\n\n Object.defineProperty(close, previousSymbol, {\n value: fs$close\n })\n return close\n })(fs.close)\n\n fs.closeSync = (function (fs$closeSync) {\n function closeSync (fd) {\n // This function uses the graceful-fs shared queue\n fs$closeSync.apply(fs, arguments)\n resetQueue()\n }\n\n Object.defineProperty(closeSync, previousSymbol, {\n value: fs$closeSync\n })\n return closeSync\n })(fs.closeSync)\n\n if (/\\bgfs4\\b/i.test(process.env.NODE_DEBUG || '')) {\n process.on('exit', function() {\n debug(fs[gracefulQueue])\n require('assert').equal(fs[gracefulQueue].length, 0)\n })\n }\n}\n\nif (!global[gracefulQueue]) {\n publishQueue(global, fs[gracefulQueue]);\n}\n\nmodule.exports = patch(clone(fs))\nif (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {\n module.exports = patch(fs)\n fs.__patched = true;\n}\n\nfunction patch (fs) {\n // Everything that references the open() function needs to be in here\n polyfills(fs)\n fs.gracefulify = patch\n\n fs.createReadStream = createReadStream\n fs.createWriteStream = createWriteStream\n var fs$readFile = fs.readFile\n fs.readFile = readFile\n function readFile (path, options, cb) {\n if (typeof options === 'function')\n cb = options, options = null\n\n return go$readFile(path, options, cb)\n\n function go$readFile (path, options, cb, startTime) {\n return fs$readFile(path, options, function (err) {\n if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))\n enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()])\n else {\n if (typeof cb === 'function')\n cb.apply(this, arguments)\n }\n })\n }\n }\n\n var fs$writeFile = fs.writeFile\n fs.writeFile = writeFile\n function writeFile (path, data, options, cb) {\n if (typeof options === 'function')\n cb = options, options = null\n\n return go$writeFile(path, data, options, cb)\n\n function go$writeFile (path, data, options, cb, startTime) {\n return fs$writeFile(path, data, options, function (err) {\n if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))\n enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()])\n else {\n if (typeof cb === 'function')\n cb.apply(this, arguments)\n }\n })\n }\n }\n\n var fs$appendFile = fs.appendFile\n if (fs$appendFile)\n fs.appendFile = appendFile\n function appendFile (path, data, options, cb) {\n if (typeof options === 'function')\n cb = options, options = null\n\n return go$appendFile(path, data, options, cb)\n\n function go$appendFile (path, data, options, cb, startTime) {\n return fs$appendFile(path, data, options, function (err) {\n if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))\n enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()])\n else {\n if (typeof cb === 'function')\n cb.apply(this, arguments)\n }\n })\n }\n }\n\n var fs$copyFile = fs.copyFile\n if (fs$copyFile)\n fs.copyFile = copyFile\n function copyFile (src, dest, flags, cb) {\n if (typeof flags === 'function') {\n cb = flags\n flags = 0\n }\n return go$copyFile(src, dest, flags, cb)\n\n function go$copyFile (src, dest, flags, cb, startTime) {\n return fs$copyFile(src, dest, flags, function (err) {\n if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))\n enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()])\n else {\n if (typeof cb === 'function')\n cb.apply(this, arguments)\n }\n })\n }\n }\n\n var fs$readdir = fs.readdir\n fs.readdir = readdir\n var noReaddirOptionVersions = /^v[0-5]\\./\n function readdir (path, options, cb) {\n if (typeof options === 'function')\n cb = options, options = null\n\n var go$readdir = noReaddirOptionVersions.test(process.version)\n ? function go$readdir (path, options, cb, startTime) {\n return fs$readdir(path, fs$readdirCallback(\n path, options, cb, startTime\n ))\n }\n : function go$readdir (path, options, cb, startTime) {\n return fs$readdir(path, options, fs$readdirCallback(\n path, options, cb, startTime\n ))\n }\n\n return go$readdir(path, options, cb)\n\n function fs$readdirCallback (path, options, cb, startTime) {\n return function (err, files) {\n if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))\n enqueue([\n go$readdir,\n [path, options, cb],\n err,\n startTime || Date.now(),\n Date.now()\n ])\n else {\n if (files && files.sort)\n files.sort()\n\n if (typeof cb === 'function')\n cb.call(this, err, files)\n }\n }\n }\n }\n\n if (process.version.substr(0, 4) === 'v0.8') {\n var legStreams = legacy(fs)\n ReadStream = legStreams.ReadStream\n WriteStream = legStreams.WriteStream\n }\n\n var fs$ReadStream = fs.ReadStream\n if (fs$ReadStream) {\n ReadStream.prototype = Object.create(fs$ReadStream.prototype)\n ReadStream.prototype.open = ReadStream$open\n }\n\n var fs$WriteStream = fs.WriteStream\n if (fs$WriteStream) {\n WriteStream.prototype = Object.create(fs$WriteStream.prototype)\n WriteStream.prototype.open = WriteStream$open\n }\n\n Object.defineProperty(fs, 'ReadStream', {\n get: function () {\n return ReadStream\n },\n set: function (val) {\n ReadStream = val\n },\n enumerable: true,\n configurable: true\n })\n Object.defineProperty(fs, 'WriteStream', {\n get: function () {\n return WriteStream\n },\n set: function (val) {\n WriteStream = val\n },\n enumerable: true,\n configurable: true\n })\n\n // legacy names\n var FileReadStream = ReadStream\n Object.defineProperty(fs, 'FileReadStream', {\n get: function () {\n return FileReadStream\n },\n set: function (val) {\n FileReadStream = val\n },\n enumerable: true,\n configurable: true\n })\n var FileWriteStream = WriteStream\n Object.defineProperty(fs, 'FileWriteStream', {\n get: function () {\n return FileWriteStream\n },\n set: function (val) {\n FileWriteStream = val\n },\n enumerable: true,\n configurable: true\n })\n\n function ReadStream (path, options) {\n if (this instanceof ReadStream)\n return fs$ReadStream.apply(this, arguments), this\n else\n return ReadStream.apply(Object.create(ReadStream.prototype), arguments)\n }\n\n function ReadStream$open () {\n var that = this\n open(that.path, that.flags, that.mode, function (err, fd) {\n if (err) {\n if (that.autoClose)\n that.destroy()\n\n that.emit('error', err)\n } else {\n that.fd = fd\n that.emit('open', fd)\n that.read()\n }\n })\n }\n\n function WriteStream (path, options) {\n if (this instanceof WriteStream)\n return fs$WriteStream.apply(this, arguments), this\n else\n return WriteStream.apply(Object.create(WriteStream.prototype), arguments)\n }\n\n function WriteStream$open () {\n var that = this\n open(that.path, that.flags, that.mode, function (err, fd) {\n if (err) {\n that.destroy()\n that.emit('error', err)\n } else {\n that.fd = fd\n that.emit('open', fd)\n }\n })\n }\n\n function createReadStream (path, options) {\n return new fs.ReadStream(path, options)\n }\n\n function createWriteStream (path, options) {\n return new fs.WriteStream(path, options)\n }\n\n var fs$open = fs.open\n fs.open = open\n function open (path, flags, mode, cb) {\n if (typeof mode === 'function')\n cb = mode, mode = null\n\n return go$open(path, flags, mode, cb)\n\n function go$open (path, flags, mode, cb, startTime) {\n return fs$open(path, flags, mode, function (err, fd) {\n if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))\n enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()])\n else {\n if (typeof cb === 'function')\n cb.apply(this, arguments)\n }\n })\n }\n }\n\n return fs\n}\n\nfunction enqueue (elem) {\n debug('ENQUEUE', elem[0].name, elem[1])\n fs[gracefulQueue].push(elem)\n retry()\n}\n\n// keep track of the timeout between retry() calls\nvar retryTimer\n\n// reset the startTime and lastTime to now\n// this resets the start of the 60 second overall timeout as well as the\n// delay between attempts so that we'll retry these jobs sooner\nfunction resetQueue () {\n var now = Date.now()\n for (var i = 0; i < fs[gracefulQueue].length; ++i) {\n // entries that are only a length of 2 are from an older version, don't\n // bother modifying those since they'll be retried anyway.\n if (fs[gracefulQueue][i].length > 2) {\n fs[gracefulQueue][i][3] = now // startTime\n fs[gracefulQueue][i][4] = now // lastTime\n }\n }\n // call retry to make sure we're actively processing the queue\n retry()\n}\n\nfunction retry () {\n // clear the timer and remove it to help prevent unintended concurrency\n clearTimeout(retryTimer)\n retryTimer = undefined\n\n if (fs[gracefulQueue].length === 0)\n return\n\n var elem = fs[gracefulQueue].shift()\n var fn = elem[0]\n var args = elem[1]\n // these items may be unset if they were added by an older graceful-fs\n var err = elem[2]\n var startTime = elem[3]\n var lastTime = elem[4]\n\n // if we don't have a startTime we have no way of knowing if we've waited\n // long enough, so go ahead and retry this item now\n if (startTime === undefined) {\n debug('RETRY', fn.name, args)\n fn.apply(null, args)\n } else if (Date.now() - startTime >= 60000) {\n // it's been more than 60 seconds total, bail now\n debug('TIMEOUT', fn.name, args)\n var cb = args.pop()\n if (typeof cb === 'function')\n cb.call(null, err)\n } else {\n // the amount of time between the last attempt and right now\n var sinceAttempt = Date.now() - lastTime\n // the amount of time between when we first tried, and when we last tried\n // rounded up to at least 1\n var sinceStart = Math.max(lastTime - startTime, 1)\n // backoff. wait longer than the total time we've been retrying, but only\n // up to a maximum of 100ms\n var desiredDelay = Math.min(sinceStart * 1.2, 100)\n // it's been long enough since the last retry, do it again\n if (sinceAttempt >= desiredDelay) {\n debug('RETRY', fn.name, args)\n fn.apply(null, args.concat([startTime]))\n } else {\n // if we can't do this job yet, push it to the end of the queue\n // and let the next iteration check again\n fs[gracefulQueue].push(elem)\n }\n }\n\n // schedule our next run if one isn't already scheduled\n if (retryTimer === undefined) {\n retryTimer = setTimeout(retry, 0)\n }\n}\n","'use strict';\n\nconst isStream = stream =>\n\tstream !== null &&\n\ttypeof stream === 'object' &&\n\ttypeof stream.pipe === 'function';\n\nisStream.writable = stream =>\n\tisStream(stream) &&\n\tstream.writable !== false &&\n\ttypeof stream._write === 'function' &&\n\ttypeof stream._writableState === 'object';\n\nisStream.readable = stream =>\n\tisStream(stream) &&\n\tstream.readable !== false &&\n\ttypeof stream._read === 'function' &&\n\ttypeof stream._readableState === 'object';\n\nisStream.duplex = stream =>\n\tisStream.writable(stream) &&\n\tisStream.readable(stream);\n\nisStream.transform = stream =>\n\tisStream.duplex(stream) &&\n\ttypeof stream._transform === 'function';\n\nmodule.exports = isStream;\n","'use strict';\n\nif (typeof process === 'undefined' ||\n !process.version ||\n process.version.indexOf('v0.') === 0 ||\n process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {\n module.exports = { nextTick: nextTick };\n} else {\n module.exports = process\n}\n\nfunction nextTick(fn, arg1, arg2, arg3) {\n if (typeof fn !== 'function') {\n throw new TypeError('\"callback\" argument must be a function');\n }\n var len = arguments.length;\n var args, i;\n switch (len) {\n case 0:\n case 1:\n return process.nextTick(fn);\n case 2:\n return process.nextTick(function afterTickOne() {\n fn.call(null, arg1);\n });\n case 3:\n return process.nextTick(function afterTickTwo() {\n fn.call(null, arg1, arg2);\n });\n case 4:\n return process.nextTick(function afterTickThree() {\n fn.call(null, arg1, arg2, arg3);\n });\n default:\n args = new Array(len - 1);\n i = 0;\n while (i < args.length) {\n args[i++] = arguments[i];\n }\n return process.nextTick(function afterTick() {\n fn.apply(null, args);\n });\n }\n}\n\n","var toString = {}.toString;\n\nmodule.exports = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n","module.exports = require('stream');\n","/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\n\nfunction isArray(arg) {\n if (Array.isArray) {\n return Array.isArray(arg);\n }\n return objectToString(arg) === '[object Array]';\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\n\nfunction isError(e) {\n return (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = require('buffer').Buffer.isBuffer;\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n","try {\n var util = require('util');\n /* istanbul ignore next */\n if (typeof util.inherits !== 'function') throw '';\n module.exports = util.inherits;\n} catch (e) {\n /* istanbul ignore next */\n module.exports = require('./inherits_browser.js');\n}\n","'use strict';\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar Buffer = require('safe-buffer').Buffer;\nvar util = require('util');\n\nfunction copyBuffer(src, target, offset) {\n src.copy(target, offset);\n}\n\nmodule.exports = function () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n BufferList.prototype.push = function push(v) {\n var entry = { data: v, next: null };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n };\n\n BufferList.prototype.unshift = function unshift(v) {\n var entry = { data: v, next: this.head };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n };\n\n BufferList.prototype.shift = function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n };\n\n BufferList.prototype.clear = function clear() {\n this.head = this.tail = null;\n this.length = 0;\n };\n\n BufferList.prototype.join = function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n while (p = p.next) {\n ret += s + p.data;\n }return ret;\n };\n\n BufferList.prototype.concat = function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n return ret;\n };\n\n return BufferList;\n}();\n\nif (util && util.inspect && util.inspect.custom) {\n module.exports.prototype[util.inspect.custom] = function () {\n var obj = util.inspect({ length: this.length });\n return this.constructor.name + ' ' + obj;\n };\n}","'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\n// undocumented cb() API, needed for core, not for public API\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err) {\n if (!this._writableState) {\n pna.nextTick(emitErrorNT, this, err);\n } else if (!this._writableState.errorEmitted) {\n this._writableState.errorEmitted = true;\n pna.nextTick(emitErrorNT, this, err);\n }\n }\n\n return this;\n }\n\n // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n }\n\n // if this is a duplex stream mark the writable part as destroyed as well\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n if (!_this._writableState) {\n pna.nextTick(emitErrorNT, _this, err);\n } else if (!_this._writableState.errorEmitted) {\n _this._writableState.errorEmitted = true;\n pna.nextTick(emitErrorNT, _this, err);\n }\n } else if (cb) {\n cb(err);\n }\n });\n\n return this;\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finalCalled = false;\n this._writableState.prefinished = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy\n};","\n/**\n * For Node.js, simply re-export the core `util.deprecate` function.\n */\n\nmodule.exports = require('util').deprecate;\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\nmodule.exports = Writable;\n\n/* */\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n}\n\n// It seems a linked list but it is not\n// there will be only 2 of these for each stream\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* */\n\n/**/\nvar asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;\n/**/\n\n/**/\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n\n/**/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/**/\n\n/**/\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/**/\n\n/**/\nvar Stream = require('./internal/streams/stream');\n/**/\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\nvar OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/**/\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nutil.inherits(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;\n\n // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n var hwm = options.highWaterMark;\n var writableHwm = options.writableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // if _final has been called\n this.finalCalled = false;\n\n // drain event flag.\n this.needDrain = false;\n // at the start of calling end()\n this.ending = false;\n // when end() has been called, and returned\n this.ended = false;\n // when 'finish' is emitted\n this.finished = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0;\n\n // a flag to see when we're in the middle of a write.\n this.writing = false;\n\n // when true all writes will be buffered until .uncork() call\n this.corked = 0;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false;\n\n // the callback that's passed to _write(chunk,cb)\n this.onwrite = function (er) {\n onwrite(stream, er);\n };\n\n // the callback that the user supplies to write(chunk,encoding,cb)\n this.writecb = null;\n\n // the amount that is being written when _write is called.\n this.writelen = 0;\n\n this.bufferedRequest = null;\n this.lastBufferedRequest = null;\n\n // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n this.pendingcb = 0;\n\n // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n this.prefinished = false;\n\n // True if the error was already emitted and should not be thrown again\n this.errorEmitted = false;\n\n // count buffered requests\n this.bufferedRequestCount = 0;\n\n // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n while (current) {\n out.push(current);\n current = current.next;\n }\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function () {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})();\n\n// Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\nvar realHasInstance;\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function (object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function (object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {\n return new Writable(options);\n }\n\n this._writableState = new WritableState(options, this);\n\n // legacy.\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n\n if (typeof options.writev === 'function') this._writev = options.writev;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n}\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n this.emit('error', new Error('Cannot pipe, not readable'));\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new Error('write after end');\n // TODO: defer error events consistently everywhere, not just the cb\n stream.emit('error', er);\n pna.nextTick(cb, er);\n}\n\n// Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\nfunction validChunk(stream, state, chunk, cb) {\n var valid = true;\n var er = false;\n\n if (chunk === null) {\n er = new TypeError('May not write null values to stream');\n } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n if (er) {\n stream.emit('error', er);\n pna.nextTick(cb, er);\n valid = false;\n }\n return valid;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n\n if (typeof cb !== 'function') cb = nop;\n\n if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n\n return ret;\n};\n\nWritable.prototype.cork = function () {\n var state = this._writableState;\n\n state.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n\n if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n var len = state.objectMode ? 1 : chunk.length;\n\n state.length += len;\n\n var ret = state.length < state.highWaterMark;\n // we must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n pna.nextTick(cb, er);\n // this can emit finish, and it will always happen\n // after error\n pna.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n // this can emit finish, but finish must\n // always follow error\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n\n onwriteStateUpdate(state);\n\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state);\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n /**/\n asyncWrite(afterWrite, stream, state, finished, cb);\n /**/\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n}\n\n// Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n}\n\n// if there's something in the buffer waiting, then process it\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n\n var count = 0;\n var allBuffers = true;\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n buffer.allBuffers = allBuffers;\n\n doWrite(stream, state, true, state.length, buffer, '', holder.finish);\n\n // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n state.pendingcb++;\n state.lastBufferedRequest = null;\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--;\n // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new Error('_write() is not implemented'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);\n\n // .end() fully uncorks\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n }\n\n // ignore unnecessary end() calls.\n if (!state.ending) endWritable(this, state, cb);\n};\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n if (err) {\n stream.emit('error', err);\n }\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function') {\n state.pendingcb++;\n state.finalCalled = true;\n pna.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n if (need) {\n prefinish(stream, state);\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n }\n }\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n if (cb) {\n if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);\n }\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n }\n\n // reuse the free corkReq.\n state.corkedRequestsFree.next = corkReq;\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n get: function () {\n if (this._writableState === undefined) {\n return false;\n }\n return this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._writableState.destroyed = value;\n }\n});\n\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\nWritable.prototype._destroy = function (err, cb) {\n this.end();\n cb(err);\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n\n'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\n/**/\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n for (var key in obj) {\n keys.push(key);\n }return keys;\n};\n/**/\n\nmodule.exports = Duplex;\n\n/**/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/**/\n\nvar Readable = require('./_stream_readable');\nvar Writable = require('./_stream_writable');\n\nutil.inherits(Duplex, Readable);\n\n{\n // avoid scope creep, the keys array can then be collected\n var keys = objectKeys(Writable.prototype);\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n\n Readable.call(this, options);\n Writable.call(this, options);\n\n if (options && options.readable === false) this.readable = false;\n\n if (options && options.writable === false) this.writable = false;\n\n this.allowHalfOpen = true;\n if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;\n\n this.once('end', onend);\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// the no-half-open enforcer\nfunction onend() {\n // if we allow half-open state, or if the writable side ended,\n // then we're ok.\n if (this.allowHalfOpen || this._writableState.ended) return;\n\n // no more data can be written.\n // But allow more writes to happen in this tick.\n pna.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});\n\nDuplex.prototype._destroy = function (err, cb) {\n this.push(null);\n this.end();\n\n pna.nextTick(cb, err);\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\nmodule.exports = Readable;\n\n/**/\nvar isArray = require('isarray');\n/**/\n\n/**/\nvar Duplex;\n/**/\n\nReadable.ReadableState = ReadableState;\n\n/**/\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function (emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\n/**/\nvar Stream = require('./internal/streams/stream');\n/**/\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\nvar OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/**/\n\n/**/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/**/\n\n/**/\nvar debugUtil = require('util');\nvar debug = void 0;\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function () {};\n}\n/**/\n\nvar BufferList = require('./internal/streams/BufferList');\nvar destroyImpl = require('./internal/streams/destroy');\nvar StringDecoder;\n\nutil.inherits(Readable, Stream);\n\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);\n\n // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];\n}\n\nfunction ReadableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;\n\n // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n var hwm = options.highWaterMark;\n var readableHwm = options.readableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false;\n\n // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n this.sync = true;\n\n // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // the number of writers that are awaiting a drain event in .pipe()s\n this.awaitDrain = 0;\n\n // if true, a maybeReadMore has been scheduled\n this.readingMore = false;\n\n this.decoder = null;\n this.encoding = null;\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n if (!(this instanceof Readable)) return new Readable(options);\n\n this._readableState = new ReadableState(options, this);\n\n // legacy\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined) {\n return false;\n }\n return this._readableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n }\n});\n\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\nReadable.prototype._destroy = function (err, cb) {\n this.push(null);\n cb(err);\n};\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n};\n\n// Unshift should *always* be something directly out of read()\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n var state = stream._readableState;\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n if (er) {\n stream.emit('error', er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n stream.emit('error', new Error('stream.push() after EOF'));\n } else {\n state.reading = false;\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n }\n }\n\n return needMoreData(state);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n stream.emit('data', chunk);\n stream.read(0);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n\n if (state.needReadable) emitReadable(stream);\n }\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n return er;\n}\n\n// if it's past the high water mark, we can push in some more.\n// Also, if we have no data yet, we can stand some\n// more bytes. This is to work around cases where hwm=0,\n// such as the repl. Also, if the push() triggered a\n// readable event, and the user called read(largeNumber) such that\n// needReadable was set, then we ought to push more, so that another\n// 'readable' event will be triggered.\nfunction needMoreData(state) {\n return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n};\n\n// backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this._readableState.decoder = new StringDecoder(enc);\n this._readableState.encoding = enc;\n return this;\n};\n\n// Don't raise the hwm > 8MB\nvar MAX_HWM = 0x800000;\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n return n;\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n }\n // If we're asking for more than the current hwm, then raise the hwm.\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n;\n // Don't have enough\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n return state.length;\n}\n\n// you can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n\n if (n !== 0) state.emittedReadable = false;\n\n // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state);\n\n // if we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n var doRead = state.needReadable;\n debug('need readable', doRead);\n\n // if we currently have less than the highWaterMark, then also read some\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n }\n\n // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true;\n // if the length is currently zero, then we *need* a readable event.\n if (state.length === 0) state.needReadable = true;\n // call internal read method\n this._read(state.highWaterMark);\n state.sync = false;\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = true;\n n = 0;\n } else {\n state.length -= n;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true;\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n if (state.ended) return;\n if (state.decoder) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n state.ended = true;\n\n // emit 'readable' now to make sure it gets picked up.\n emitReadable(stream);\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n var state = stream._readableState;\n state.needReadable = false;\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);\n }\n}\n\nfunction emitReadable_(stream) {\n debug('emit readable');\n stream.emit('readable');\n flow(stream);\n}\n\n// at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n pna.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n var len = state.length;\n while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length)\n // didn't get any data, stop spinning.\n break;else len = state.length;\n }\n state.readingMore = false;\n}\n\n// abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n this.emit('error', new Error('_read() is not implemented'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n default:\n state.pipes.push(dest);\n break;\n }\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);\n\n dest.on('unpipe', onunpipe);\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n }\n\n // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n\n var cleanedUp = false;\n function cleanup() {\n debug('cleanup');\n // cleanup event handlers once the pipe is broken\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n\n cleanedUp = true;\n\n // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n // If the user pushes more data while we're writing to dest then we'll end up\n // in ondata again. However, we only want to increase awaitDrain once because\n // dest will only emit one 'drain' event for the multiple writes.\n // => Introduce a guard on increasing awaitDrain.\n var increasedAwaitDrain = false;\n src.on('data', ondata);\n function ondata(chunk) {\n debug('ondata');\n increasedAwaitDrain = false;\n var ret = dest.write(chunk);\n if (false === ret && !increasedAwaitDrain) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', state.awaitDrain);\n state.awaitDrain++;\n increasedAwaitDrain = true;\n }\n src.pause();\n }\n }\n\n // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);\n }\n\n // Make sure our error handler is attached before userland ones.\n prependListener(dest, 'error', onerror);\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n dest.once('close', onclose);\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n }\n\n // tell the dest that it's being piped to\n dest.emit('pipe', src);\n\n // start the flow if it hasn't been started already.\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function () {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = { hasUnpiped: false };\n\n // if we're not piping anywhere, then do nothing.\n if (state.pipesCount === 0) return this;\n\n // just one destination. most common case.\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n\n if (!dest) dest = state.pipes;\n\n // got a match.\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n }\n\n // slow case. multiple pipe destinations.\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, { hasUnpiped: false });\n }return this;\n }\n\n // try to find the right one.\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n\n dest.emit('unpipe', this, unpipeInfo);\n\n return this;\n};\n\n// set up data events if they are asked for\n// Ensure readable listeners eventually get something\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n\n if (ev === 'data') {\n // Start flowing on next tick if stream isn't explicitly paused\n if (this._readableState.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n var state = this._readableState;\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.emittedReadable = false;\n if (!state.reading) {\n pna.nextTick(nReadingNextTick, this);\n } else if (state.length) {\n emitReadable(this);\n }\n }\n }\n\n return res;\n};\nReadable.prototype.addListener = Readable.prototype.on;\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n var state = this._readableState;\n if (!state.flowing) {\n debug('resume');\n state.flowing = true;\n resume(this, state);\n }\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n pna.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n if (!state.reading) {\n debug('resume read 0');\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n state.awaitDrain = 0;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n if (false !== this._readableState.flowing) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n while (state.flowing && stream.read() !== null) {}\n}\n\n// wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n\n stream.on('end', function () {\n debug('wrapped end');\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk);\n\n // don't skip over falsy values in objectMode\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n if (!ret) {\n paused = true;\n stream.pause();\n }\n });\n\n // proxy all the other methods.\n // important when wrapping filters and duplexes.\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function (method) {\n return function () {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n }\n\n // proxy certain important events.\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n }\n\n // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n this._read = function (n) {\n debug('wrapped _read', n);\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._readableState.highWaterMark;\n }\n});\n\n// exposed for testing purposes only.\nReadable._fromList = fromList;\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = fromListPartial(n, state.buffer, state.decoder);\n }\n\n return ret;\n}\n\n// Extracts only enough buffered data to satisfy the amount requested.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromListPartial(n, list, hasStrings) {\n var ret;\n if (n < list.head.data.length) {\n // slice is the same for buffers and strings\n ret = list.head.data.slice(0, n);\n list.head.data = list.head.data.slice(n);\n } else if (n === list.head.data.length) {\n // first chunk is a perfect match\n ret = list.shift();\n } else {\n // result spans more than one buffer\n ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);\n }\n return ret;\n}\n\n// Copies a specified amount of characters from the list of buffered data\n// chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBufferString(n, list) {\n var p = list.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = str.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\n// Copies a specified amount of bytes from the list of buffered data chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n\n // If we get here before consuming all the bytes, then that is a\n // bug in node. Should never happen.\n if (state.length > 0) throw new Error('\"endReadable()\" called on non-empty stream');\n\n if (!state.endEmitted) {\n state.ended = true;\n pna.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n // Check that we didn't get one last unshift.\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n }\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n return -1;\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n'use strict';\n\nmodule.exports = Transform;\n\nvar Duplex = require('./_stream_duplex');\n\n/**/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/**/\n\nutil.inherits(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n\n var cb = ts.writecb;\n\n if (!cb) {\n return this.emit('error', new Error('write callback called multiple times'));\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n\n cb(er);\n\n var rs = this._readableState;\n rs.reading = false;\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n\n Duplex.call(this, options);\n\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n };\n\n // start out asking for a readable event once data is transformed.\n this._readableState.needReadable = true;\n\n // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n\n if (typeof options.flush === 'function') this._flush = options.flush;\n }\n\n // When the writable side finishes, then flush out anything remaining.\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function') {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n};\n\n// This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\nTransform.prototype._transform = function (chunk, encoding, cb) {\n throw new Error('_transform() is not implemented');\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n};\n\n// Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && ts.writecb && !ts.transforming) {\n ts.transforming = true;\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n var _this2 = this;\n\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n _this2.emit('close');\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data);\n\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');\n\n if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');\n\n return stream.push(null);\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n'use strict';\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\n/**/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/**/\n\nutil.inherits(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};","var Stream = require('stream');\nif (process.env.READABLE_STREAM === 'disable' && Stream) {\n module.exports = Stream;\n exports = module.exports = Stream.Readable;\n exports.Readable = Stream.Readable;\n exports.Writable = Stream.Writable;\n exports.Duplex = Stream.Duplex;\n exports.Transform = Stream.Transform;\n exports.PassThrough = Stream.PassThrough;\n exports.Stream = Stream;\n} else {\n exports = module.exports = require('./lib/_stream_readable.js');\n exports.Stream = Stream || exports;\n exports.Readable = exports;\n exports.Writable = require('./lib/_stream_writable.js');\n exports.Duplex = require('./lib/_stream_duplex.js');\n exports.Transform = require('./lib/_stream_transform.js');\n exports.PassThrough = require('./lib/_stream_passthrough.js');\n}\n","module.exports = require('./readable').PassThrough\n","var util = require('util');\nvar PassThrough = require('readable-stream/passthrough');\n\nmodule.exports = {\n Readable: Readable,\n Writable: Writable\n};\n\nutil.inherits(Readable, PassThrough);\nutil.inherits(Writable, PassThrough);\n\n// Patch the given method of instance so that the callback\n// is executed once, before the actual method is called the\n// first time.\nfunction beforeFirstCall(instance, method, callback) {\n instance[method] = function() {\n delete instance[method];\n callback.apply(this, arguments);\n return this[method].apply(this, arguments);\n };\n}\n\nfunction Readable(fn, options) {\n if (!(this instanceof Readable))\n return new Readable(fn, options);\n\n PassThrough.call(this, options);\n\n beforeFirstCall(this, '_read', function() {\n var source = fn.call(this, options);\n var emit = this.emit.bind(this, 'error');\n source.on('error', emit);\n source.pipe(this);\n });\n\n this.emit('readable');\n}\n\nfunction Writable(fn, options) {\n if (!(this instanceof Writable))\n return new Writable(fn, options);\n\n PassThrough.call(this, options);\n\n beforeFirstCall(this, '_write', function() {\n var destination = fn.call(this, options);\n var emit = this.emit.bind(this, 'error');\n destination.on('error', emit);\n this.pipe(destination);\n });\n\n this.emit('writable');\n}\n\n","/*!\n * normalize-path \n *\n * Copyright (c) 2014-2018, Jon Schlinkert.\n * Released under the MIT License.\n */\n\nmodule.exports = function(path, stripTrailing) {\n if (typeof path !== 'string') {\n throw new TypeError('expected path to be a string');\n }\n\n if (path === '\\\\' || path === '/') return '/';\n\n var len = path.length;\n if (len <= 1) return path;\n\n // ensure that win32 namespaces has two leading slashes, so that the path is\n // handled properly by the win32 version of path.parse() after being normalized\n // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces\n var prefix = '';\n if (len > 4 && path[3] === '\\\\') {\n var ch = path[2];\n if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\\\\\') {\n path = path.slice(2);\n prefix = '//';\n }\n }\n\n var segs = path.split(/[/\\\\]+/);\n if (stripTrailing !== false && segs[segs.length - 1] === '') {\n segs.pop();\n }\n return prefix + segs.join('/');\n};\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nmodule.exports = identity;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nmodule.exports = apply;\n","var apply = require('./_apply');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\nfunction overRest(func, start, transform) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = transform(array);\n return apply(func, this, otherArgs);\n };\n}\n\nmodule.exports = overRest;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nmodule.exports = constant;\n","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nmodule.exports = freeGlobal;\n","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nmodule.exports = root;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nmodule.exports = Symbol;\n","var Symbol = require('./_Symbol');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nmodule.exports = getRawTag;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nmodule.exports = objectToString;\n","var Symbol = require('./_Symbol'),\n getRawTag = require('./_getRawTag'),\n objectToString = require('./_objectToString');\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nmodule.exports = baseGetTag;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nmodule.exports = isObject;\n","var baseGetTag = require('./_baseGetTag'),\n isObject = require('./isObject');\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nmodule.exports = isFunction;\n","var root = require('./_root');\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nmodule.exports = coreJsData;\n","var coreJsData = require('./_coreJsData');\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nmodule.exports = isMasked;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nmodule.exports = toSource;\n","var isFunction = require('./isFunction'),\n isMasked = require('./_isMasked'),\n isObject = require('./isObject'),\n toSource = require('./_toSource');\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nmodule.exports = baseIsNative;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nmodule.exports = getValue;\n","var baseIsNative = require('./_baseIsNative'),\n getValue = require('./_getValue');\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nmodule.exports = getNative;\n","var getNative = require('./_getNative');\n\nvar defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n}());\n\nmodule.exports = defineProperty;\n","var constant = require('./constant'),\n defineProperty = require('./_defineProperty'),\n identity = require('./identity');\n\n/**\n * The base implementation of `setToString` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar baseSetToString = !defineProperty ? identity : function(func, string) {\n return defineProperty(func, 'toString', {\n 'configurable': true,\n 'enumerable': false,\n 'value': constant(string),\n 'writable': true\n });\n};\n\nmodule.exports = baseSetToString;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nmodule.exports = shortOut;\n","var baseSetToString = require('./_baseSetToString'),\n shortOut = require('./_shortOut');\n\n/**\n * Sets the `toString` method of `func` to return `string`.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar setToString = shortOut(baseSetToString);\n\nmodule.exports = setToString;\n","var identity = require('./identity'),\n overRest = require('./_overRest'),\n setToString = require('./_setToString');\n\n/**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\nfunction baseRest(func, start) {\n return setToString(overRest(func, start, identity), func + '');\n}\n\nmodule.exports = baseRest;\n","/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nmodule.exports = eq;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nmodule.exports = isLength;\n","var isFunction = require('./isFunction'),\n isLength = require('./isLength');\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nmodule.exports = isArrayLike;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nmodule.exports = isIndex;\n","var eq = require('./eq'),\n isArrayLike = require('./isArrayLike'),\n isIndex = require('./_isIndex'),\n isObject = require('./isObject');\n\n/**\n * Checks if the given arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n * else `false`.\n */\nfunction isIterateeCall(value, index, object) {\n if (!isObject(object)) {\n return false;\n }\n var type = typeof index;\n if (type == 'number'\n ? (isArrayLike(object) && isIndex(index, object.length))\n : (type == 'string' && index in object)\n ) {\n return eq(object[index], value);\n }\n return false;\n}\n\nmodule.exports = isIterateeCall;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nmodule.exports = baseTimes;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nmodule.exports = isObjectLike;\n","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nmodule.exports = baseIsArguments;\n","var baseIsArguments = require('./_baseIsArguments'),\n isObjectLike = require('./isObjectLike');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nmodule.exports = isArguments;\n","/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nmodule.exports = isArray;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nmodule.exports = stubFalse;\n","var root = require('./_root'),\n stubFalse = require('./stubFalse');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nmodule.exports = isBuffer;\n","var baseGetTag = require('./_baseGetTag'),\n isLength = require('./isLength'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nmodule.exports = baseIsTypedArray;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nmodule.exports = baseUnary;\n","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nmodule.exports = nodeUtil;\n","var baseIsTypedArray = require('./_baseIsTypedArray'),\n baseUnary = require('./_baseUnary'),\n nodeUtil = require('./_nodeUtil');\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nmodule.exports = isTypedArray;\n","var baseTimes = require('./_baseTimes'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isBuffer = require('./isBuffer'),\n isIndex = require('./_isIndex'),\n isTypedArray = require('./isTypedArray');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = arrayLikeKeys;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nmodule.exports = isPrototype;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = nativeKeysIn;\n","var isObject = require('./isObject'),\n isPrototype = require('./_isPrototype'),\n nativeKeysIn = require('./_nativeKeysIn');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = baseKeysIn;\n","var arrayLikeKeys = require('./_arrayLikeKeys'),\n baseKeysIn = require('./_baseKeysIn'),\n isArrayLike = require('./isArrayLike');\n\n/**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\nfunction keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n}\n\nmodule.exports = keysIn;\n","var baseRest = require('./_baseRest'),\n eq = require('./eq'),\n isIterateeCall = require('./_isIterateeCall'),\n keysIn = require('./keysIn');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns own and inherited enumerable string keyed properties of source\n * objects to the destination object for all destination properties that\n * resolve to `undefined`. Source objects are applied from left to right.\n * Once a property is set, additional values of the same property are ignored.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.defaultsDeep\n * @example\n *\n * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\nvar defaults = baseRest(function(object, sources) {\n object = Object(object);\n\n var index = -1;\n var length = sources.length;\n var guard = length > 2 ? sources[2] : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n length = 1;\n }\n\n while (++index < length) {\n var source = sources[index];\n var props = keysIn(source);\n var propsIndex = -1;\n var propsLength = props.length;\n\n while (++propsIndex < propsLength) {\n var key = props[propsIndex];\n var value = object[key];\n\n if (value === undefined ||\n (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {\n object[key] = source[key];\n }\n }\n }\n\n return object;\n});\n\nmodule.exports = defaults;\n","'use strict'\n\n/*\n This file is a reduced and adapted version of the main lib/internal/per_context/primordials.js file defined at\n\n https://github.com/nodejs/node/blob/main/lib/internal/per_context/primordials.js\n\n Don't try to replace with the original file and keep it up to date with the upstream file.\n*/\n\n// This is a simplified version of AggregateError\nclass AggregateError extends Error {\n constructor(errors) {\n if (!Array.isArray(errors)) {\n throw new TypeError(`Expected input to be an Array, got ${typeof errors}`)\n }\n let message = ''\n for (let i = 0; i < errors.length; i++) {\n message += ` ${errors[i].stack}\\n`\n }\n super(message)\n this.name = 'AggregateError'\n this.errors = errors\n }\n}\nmodule.exports = {\n AggregateError,\n ArrayIsArray(self) {\n return Array.isArray(self)\n },\n ArrayPrototypeIncludes(self, el) {\n return self.includes(el)\n },\n ArrayPrototypeIndexOf(self, el) {\n return self.indexOf(el)\n },\n ArrayPrototypeJoin(self, sep) {\n return self.join(sep)\n },\n ArrayPrototypeMap(self, fn) {\n return self.map(fn)\n },\n ArrayPrototypePop(self, el) {\n return self.pop(el)\n },\n ArrayPrototypePush(self, el) {\n return self.push(el)\n },\n ArrayPrototypeSlice(self, start, end) {\n return self.slice(start, end)\n },\n Error,\n FunctionPrototypeCall(fn, thisArgs, ...args) {\n return fn.call(thisArgs, ...args)\n },\n FunctionPrototypeSymbolHasInstance(self, instance) {\n return Function.prototype[Symbol.hasInstance].call(self, instance)\n },\n MathFloor: Math.floor,\n Number,\n NumberIsInteger: Number.isInteger,\n NumberIsNaN: Number.isNaN,\n NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER,\n NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER,\n NumberParseInt: Number.parseInt,\n ObjectDefineProperties(self, props) {\n return Object.defineProperties(self, props)\n },\n ObjectDefineProperty(self, name, prop) {\n return Object.defineProperty(self, name, prop)\n },\n ObjectGetOwnPropertyDescriptor(self, name) {\n return Object.getOwnPropertyDescriptor(self, name)\n },\n ObjectKeys(obj) {\n return Object.keys(obj)\n },\n ObjectSetPrototypeOf(target, proto) {\n return Object.setPrototypeOf(target, proto)\n },\n Promise,\n PromisePrototypeCatch(self, fn) {\n return self.catch(fn)\n },\n PromisePrototypeThen(self, thenFn, catchFn) {\n return self.then(thenFn, catchFn)\n },\n PromiseReject(err) {\n return Promise.reject(err)\n },\n PromiseResolve(val) {\n return Promise.resolve(val)\n },\n ReflectApply: Reflect.apply,\n RegExpPrototypeTest(self, value) {\n return self.test(value)\n },\n SafeSet: Set,\n String,\n StringPrototypeSlice(self, start, end) {\n return self.slice(start, end)\n },\n StringPrototypeToLowerCase(self) {\n return self.toLowerCase()\n },\n StringPrototypeToUpperCase(self) {\n return self.toUpperCase()\n },\n StringPrototypeTrim(self) {\n return self.trim()\n },\n Symbol,\n SymbolFor: Symbol.for,\n SymbolAsyncIterator: Symbol.asyncIterator,\n SymbolHasInstance: Symbol.hasInstance,\n SymbolIterator: Symbol.iterator,\n SymbolDispose: Symbol.dispose || Symbol('Symbol.dispose'),\n SymbolAsyncDispose: Symbol.asyncDispose || Symbol('Symbol.asyncDispose'),\n TypedArrayPrototypeSet(self, buf, len) {\n return self.set(buf, len)\n },\n Boolean,\n Uint8Array\n}\n","'use strict'\n\n/*\n This file is a reduced and adapted version of the main lib/internal/util/inspect.js file defined at\n\n https://github.com/nodejs/node/blob/main/lib/internal/util/inspect.js\n\n Don't try to replace with the original file and keep it up to date with the upstream file.\n*/\nmodule.exports = {\n format(format, ...args) {\n // Simplified version of https://nodejs.org/api/util.html#utilformatformat-args\n return format.replace(/%([sdifj])/g, function (...[_unused, type]) {\n const replacement = args.shift()\n if (type === 'f') {\n return replacement.toFixed(6)\n } else if (type === 'j') {\n return JSON.stringify(replacement)\n } else if (type === 's' && typeof replacement === 'object') {\n const ctor = replacement.constructor !== Object ? replacement.constructor.name : ''\n return `${ctor} {}`.trim()\n } else {\n return replacement.toString()\n }\n })\n },\n inspect(value) {\n // Vastly simplified version of https://nodejs.org/api/util.html#utilinspectobject-options\n switch (typeof value) {\n case 'string':\n if (value.includes(\"'\")) {\n if (!value.includes('\"')) {\n return `\"${value}\"`\n } else if (!value.includes('`') && !value.includes('${')) {\n return `\\`${value}\\``\n }\n }\n return `'${value}'`\n case 'number':\n if (isNaN(value)) {\n return 'NaN'\n } else if (Object.is(value, -0)) {\n return String(value)\n }\n return value\n case 'bigint':\n return `${String(value)}n`\n case 'boolean':\n case 'undefined':\n return String(value)\n case 'object':\n return '{}'\n }\n }\n}\n","'use strict'\n\nconst { format, inspect } = require('./util/inspect')\nconst { AggregateError: CustomAggregateError } = require('./primordials')\n\n/*\n This file is a reduced and adapted version of the main lib/internal/errors.js file defined at\n\n https://github.com/nodejs/node/blob/main/lib/internal/errors.js\n\n Don't try to replace with the original file and keep it up to date (starting from E(...) definitions)\n with the upstream file.\n*/\n\nconst AggregateError = globalThis.AggregateError || CustomAggregateError\nconst kIsNodeError = Symbol('kIsNodeError')\nconst kTypes = [\n 'string',\n 'function',\n 'number',\n 'object',\n // Accept 'Function' and 'Object' as alternative to the lower cased version.\n 'Function',\n 'Object',\n 'boolean',\n 'bigint',\n 'symbol'\n]\nconst classRegExp = /^([A-Z][a-z0-9]*)+$/\nconst nodeInternalPrefix = '__node_internal_'\nconst codes = {}\nfunction assert(value, message) {\n if (!value) {\n throw new codes.ERR_INTERNAL_ASSERTION(message)\n }\n}\n\n// Only use this for integers! Decimal numbers do not work with this function.\nfunction addNumericalSeparator(val) {\n let res = ''\n let i = val.length\n const start = val[0] === '-' ? 1 : 0\n for (; i >= start + 4; i -= 3) {\n res = `_${val.slice(i - 3, i)}${res}`\n }\n return `${val.slice(0, i)}${res}`\n}\nfunction getMessage(key, msg, args) {\n if (typeof msg === 'function') {\n assert(\n msg.length <= args.length,\n // Default options do not count.\n `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).`\n )\n return msg(...args)\n }\n const expectedLength = (msg.match(/%[dfijoOs]/g) || []).length\n assert(\n expectedLength === args.length,\n `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).`\n )\n if (args.length === 0) {\n return msg\n }\n return format(msg, ...args)\n}\nfunction E(code, message, Base) {\n if (!Base) {\n Base = Error\n }\n class NodeError extends Base {\n constructor(...args) {\n super(getMessage(code, message, args))\n }\n toString() {\n return `${this.name} [${code}]: ${this.message}`\n }\n }\n Object.defineProperties(NodeError.prototype, {\n name: {\n value: Base.name,\n writable: true,\n enumerable: false,\n configurable: true\n },\n toString: {\n value() {\n return `${this.name} [${code}]: ${this.message}`\n },\n writable: true,\n enumerable: false,\n configurable: true\n }\n })\n NodeError.prototype.code = code\n NodeError.prototype[kIsNodeError] = true\n codes[code] = NodeError\n}\nfunction hideStackFrames(fn) {\n // We rename the functions that will be hidden to cut off the stacktrace\n // at the outermost one\n const hidden = nodeInternalPrefix + fn.name\n Object.defineProperty(fn, 'name', {\n value: hidden\n })\n return fn\n}\nfunction aggregateTwoErrors(innerError, outerError) {\n if (innerError && outerError && innerError !== outerError) {\n if (Array.isArray(outerError.errors)) {\n // If `outerError` is already an `AggregateError`.\n outerError.errors.push(innerError)\n return outerError\n }\n const err = new AggregateError([outerError, innerError], outerError.message)\n err.code = outerError.code\n return err\n }\n return innerError || outerError\n}\nclass AbortError extends Error {\n constructor(message = 'The operation was aborted', options = undefined) {\n if (options !== undefined && typeof options !== 'object') {\n throw new codes.ERR_INVALID_ARG_TYPE('options', 'Object', options)\n }\n super(message, options)\n this.code = 'ABORT_ERR'\n this.name = 'AbortError'\n }\n}\nE('ERR_ASSERTION', '%s', Error)\nE(\n 'ERR_INVALID_ARG_TYPE',\n (name, expected, actual) => {\n assert(typeof name === 'string', \"'name' must be a string\")\n if (!Array.isArray(expected)) {\n expected = [expected]\n }\n let msg = 'The '\n if (name.endsWith(' argument')) {\n // For cases like 'first argument'\n msg += `${name} `\n } else {\n msg += `\"${name}\" ${name.includes('.') ? 'property' : 'argument'} `\n }\n msg += 'must be '\n const types = []\n const instances = []\n const other = []\n for (const value of expected) {\n assert(typeof value === 'string', 'All expected entries have to be of type string')\n if (kTypes.includes(value)) {\n types.push(value.toLowerCase())\n } else if (classRegExp.test(value)) {\n instances.push(value)\n } else {\n assert(value !== 'object', 'The value \"object\" should be written as \"Object\"')\n other.push(value)\n }\n }\n\n // Special handle `object` in case other instances are allowed to outline\n // the differences between each other.\n if (instances.length > 0) {\n const pos = types.indexOf('object')\n if (pos !== -1) {\n types.splice(types, pos, 1)\n instances.push('Object')\n }\n }\n if (types.length > 0) {\n switch (types.length) {\n case 1:\n msg += `of type ${types[0]}`\n break\n case 2:\n msg += `one of type ${types[0]} or ${types[1]}`\n break\n default: {\n const last = types.pop()\n msg += `one of type ${types.join(', ')}, or ${last}`\n }\n }\n if (instances.length > 0 || other.length > 0) {\n msg += ' or '\n }\n }\n if (instances.length > 0) {\n switch (instances.length) {\n case 1:\n msg += `an instance of ${instances[0]}`\n break\n case 2:\n msg += `an instance of ${instances[0]} or ${instances[1]}`\n break\n default: {\n const last = instances.pop()\n msg += `an instance of ${instances.join(', ')}, or ${last}`\n }\n }\n if (other.length > 0) {\n msg += ' or '\n }\n }\n switch (other.length) {\n case 0:\n break\n case 1:\n if (other[0].toLowerCase() !== other[0]) {\n msg += 'an '\n }\n msg += `${other[0]}`\n break\n case 2:\n msg += `one of ${other[0]} or ${other[1]}`\n break\n default: {\n const last = other.pop()\n msg += `one of ${other.join(', ')}, or ${last}`\n }\n }\n if (actual == null) {\n msg += `. Received ${actual}`\n } else if (typeof actual === 'function' && actual.name) {\n msg += `. Received function ${actual.name}`\n } else if (typeof actual === 'object') {\n var _actual$constructor\n if (\n (_actual$constructor = actual.constructor) !== null &&\n _actual$constructor !== undefined &&\n _actual$constructor.name\n ) {\n msg += `. Received an instance of ${actual.constructor.name}`\n } else {\n const inspected = inspect(actual, {\n depth: -1\n })\n msg += `. Received ${inspected}`\n }\n } else {\n let inspected = inspect(actual, {\n colors: false\n })\n if (inspected.length > 25) {\n inspected = `${inspected.slice(0, 25)}...`\n }\n msg += `. Received type ${typeof actual} (${inspected})`\n }\n return msg\n },\n TypeError\n)\nE(\n 'ERR_INVALID_ARG_VALUE',\n (name, value, reason = 'is invalid') => {\n let inspected = inspect(value)\n if (inspected.length > 128) {\n inspected = inspected.slice(0, 128) + '...'\n }\n const type = name.includes('.') ? 'property' : 'argument'\n return `The ${type} '${name}' ${reason}. Received ${inspected}`\n },\n TypeError\n)\nE(\n 'ERR_INVALID_RETURN_VALUE',\n (input, name, value) => {\n var _value$constructor\n const type =\n value !== null &&\n value !== undefined &&\n (_value$constructor = value.constructor) !== null &&\n _value$constructor !== undefined &&\n _value$constructor.name\n ? `instance of ${value.constructor.name}`\n : `type ${typeof value}`\n return `Expected ${input} to be returned from the \"${name}\"` + ` function but got ${type}.`\n },\n TypeError\n)\nE(\n 'ERR_MISSING_ARGS',\n (...args) => {\n assert(args.length > 0, 'At least one arg needs to be specified')\n let msg\n const len = args.length\n args = (Array.isArray(args) ? args : [args]).map((a) => `\"${a}\"`).join(' or ')\n switch (len) {\n case 1:\n msg += `The ${args[0]} argument`\n break\n case 2:\n msg += `The ${args[0]} and ${args[1]} arguments`\n break\n default:\n {\n const last = args.pop()\n msg += `The ${args.join(', ')}, and ${last} arguments`\n }\n break\n }\n return `${msg} must be specified`\n },\n TypeError\n)\nE(\n 'ERR_OUT_OF_RANGE',\n (str, range, input) => {\n assert(range, 'Missing \"range\" argument')\n let received\n if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n received = addNumericalSeparator(String(input))\n } else if (typeof input === 'bigint') {\n received = String(input)\n const limit = BigInt(2) ** BigInt(32)\n if (input > limit || input < -limit) {\n received = addNumericalSeparator(received)\n }\n received += 'n'\n } else {\n received = inspect(input)\n }\n return `The value of \"${str}\" is out of range. It must be ${range}. Received ${received}`\n },\n RangeError\n)\nE('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times', Error)\nE('ERR_METHOD_NOT_IMPLEMENTED', 'The %s method is not implemented', Error)\nE('ERR_STREAM_ALREADY_FINISHED', 'Cannot call %s after a stream was finished', Error)\nE('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable', Error)\nE('ERR_STREAM_DESTROYED', 'Cannot call %s after a stream was destroyed', Error)\nE('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError)\nE('ERR_STREAM_PREMATURE_CLOSE', 'Premature close', Error)\nE('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF', Error)\nE('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event', Error)\nE('ERR_STREAM_WRITE_AFTER_END', 'write after end', Error)\nE('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s', TypeError)\nmodule.exports = {\n AbortError,\n aggregateTwoErrors: hideStackFrames(aggregateTwoErrors),\n hideStackFrames,\n codes\n}\n","/**\n * @typedef {object} PrivateData\n * @property {EventTarget} eventTarget The event target.\n * @property {{type:string}} event The original event object.\n * @property {number} eventPhase The current event phase.\n * @property {EventTarget|null} currentTarget The current event target.\n * @property {boolean} canceled The flag to prevent default.\n * @property {boolean} stopped The flag to stop propagation.\n * @property {boolean} immediateStopped The flag to stop propagation immediately.\n * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null.\n * @property {number} timeStamp The unix time.\n * @private\n */\n\n/**\n * Private data for event wrappers.\n * @type {WeakMap}\n * @private\n */\nconst privateData = new WeakMap()\n\n/**\n * Cache for wrapper classes.\n * @type {WeakMap}\n * @private\n */\nconst wrappers = new WeakMap()\n\n/**\n * Get private data.\n * @param {Event} event The event object to get private data.\n * @returns {PrivateData} The private data of the event.\n * @private\n */\nfunction pd(event) {\n const retv = privateData.get(event)\n console.assert(\n retv != null,\n \"'this' is expected an Event object, but got\",\n event\n )\n return retv\n}\n\n/**\n * https://dom.spec.whatwg.org/#set-the-canceled-flag\n * @param data {PrivateData} private data.\n */\nfunction setCancelFlag(data) {\n if (data.passiveListener != null) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(\n \"Unable to preventDefault inside passive event listener invocation.\",\n data.passiveListener\n )\n }\n return\n }\n if (!data.event.cancelable) {\n return\n }\n\n data.canceled = true\n if (typeof data.event.preventDefault === \"function\") {\n data.event.preventDefault()\n }\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#interface-event\n * @private\n */\n/**\n * The event wrapper.\n * @constructor\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Event|{type:string}} event The original event to wrap.\n */\nfunction Event(eventTarget, event) {\n privateData.set(this, {\n eventTarget,\n event,\n eventPhase: 2,\n currentTarget: eventTarget,\n canceled: false,\n stopped: false,\n immediateStopped: false,\n passiveListener: null,\n timeStamp: event.timeStamp || Date.now(),\n })\n\n // https://heycam.github.io/webidl/#Unforgeable\n Object.defineProperty(this, \"isTrusted\", { value: false, enumerable: true })\n\n // Define accessors\n const keys = Object.keys(event)\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in this)) {\n Object.defineProperty(this, key, defineRedirectDescriptor(key))\n }\n }\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEvent.prototype = {\n /**\n * The type of this event.\n * @type {string}\n */\n get type() {\n return pd(this).event.type\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get target() {\n return pd(this).eventTarget\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get currentTarget() {\n return pd(this).currentTarget\n },\n\n /**\n * @returns {EventTarget[]} The composed path of this event.\n */\n composedPath() {\n const currentTarget = pd(this).currentTarget\n if (currentTarget == null) {\n return []\n }\n return [currentTarget]\n },\n\n /**\n * Constant of NONE.\n * @type {number}\n */\n get NONE() {\n return 0\n },\n\n /**\n * Constant of CAPTURING_PHASE.\n * @type {number}\n */\n get CAPTURING_PHASE() {\n return 1\n },\n\n /**\n * Constant of AT_TARGET.\n * @type {number}\n */\n get AT_TARGET() {\n return 2\n },\n\n /**\n * Constant of BUBBLING_PHASE.\n * @type {number}\n */\n get BUBBLING_PHASE() {\n return 3\n },\n\n /**\n * The target of this event.\n * @type {number}\n */\n get eventPhase() {\n return pd(this).eventPhase\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopPropagation() {\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.stopPropagation === \"function\") {\n data.event.stopPropagation()\n }\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopImmediatePropagation() {\n const data = pd(this)\n\n data.stopped = true\n data.immediateStopped = true\n if (typeof data.event.stopImmediatePropagation === \"function\") {\n data.event.stopImmediatePropagation()\n }\n },\n\n /**\n * The flag to be bubbling.\n * @type {boolean}\n */\n get bubbles() {\n return Boolean(pd(this).event.bubbles)\n },\n\n /**\n * The flag to be cancelable.\n * @type {boolean}\n */\n get cancelable() {\n return Boolean(pd(this).event.cancelable)\n },\n\n /**\n * Cancel this event.\n * @returns {void}\n */\n preventDefault() {\n setCancelFlag(pd(this))\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n */\n get defaultPrevented() {\n return pd(this).canceled\n },\n\n /**\n * The flag to be composed.\n * @type {boolean}\n */\n get composed() {\n return Boolean(pd(this).event.composed)\n },\n\n /**\n * The unix time of this event.\n * @type {number}\n */\n get timeStamp() {\n return pd(this).timeStamp\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n * @deprecated\n */\n get srcElement() {\n return pd(this).eventTarget\n },\n\n /**\n * The flag to stop event bubbling.\n * @type {boolean}\n * @deprecated\n */\n get cancelBubble() {\n return pd(this).stopped\n },\n set cancelBubble(value) {\n if (!value) {\n return\n }\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.cancelBubble === \"boolean\") {\n data.event.cancelBubble = true\n }\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n * @deprecated\n */\n get returnValue() {\n return !pd(this).canceled\n },\n set returnValue(value) {\n if (!value) {\n setCancelFlag(pd(this))\n }\n },\n\n /**\n * Initialize this event object. But do nothing under event dispatching.\n * @param {string} type The event type.\n * @param {boolean} [bubbles=false] The flag to be possible to bubble up.\n * @param {boolean} [cancelable=false] The flag to be possible to cancel.\n * @deprecated\n */\n initEvent() {\n // Do nothing.\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(Event.prototype, \"constructor\", {\n value: Event,\n configurable: true,\n writable: true,\n})\n\n// Ensure `event instanceof window.Event` is `true`.\nif (typeof window !== \"undefined\" && typeof window.Event !== \"undefined\") {\n Object.setPrototypeOf(Event.prototype, window.Event.prototype)\n\n // Make association for wrappers.\n wrappers.set(window.Event.prototype, Event)\n}\n\n/**\n * Get the property descriptor to redirect a given property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to redirect the property.\n * @private\n */\nfunction defineRedirectDescriptor(key) {\n return {\n get() {\n return pd(this).event[key]\n },\n set(value) {\n pd(this).event[key] = value\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Get the property descriptor to call a given method property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to call the method property.\n * @private\n */\nfunction defineCallDescriptor(key) {\n return {\n value() {\n const event = pd(this).event\n return event[key].apply(event, arguments)\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define new wrapper class.\n * @param {Function} BaseEvent The base wrapper class.\n * @param {Object} proto The prototype of the original event.\n * @returns {Function} The defined wrapper class.\n * @private\n */\nfunction defineWrapper(BaseEvent, proto) {\n const keys = Object.keys(proto)\n if (keys.length === 0) {\n return BaseEvent\n }\n\n /** CustomEvent */\n function CustomEvent(eventTarget, event) {\n BaseEvent.call(this, eventTarget, event)\n }\n\n CustomEvent.prototype = Object.create(BaseEvent.prototype, {\n constructor: { value: CustomEvent, configurable: true, writable: true },\n })\n\n // Define accessors.\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in BaseEvent.prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, key)\n const isFunc = typeof descriptor.value === \"function\"\n Object.defineProperty(\n CustomEvent.prototype,\n key,\n isFunc\n ? defineCallDescriptor(key)\n : defineRedirectDescriptor(key)\n )\n }\n }\n\n return CustomEvent\n}\n\n/**\n * Get the wrapper class of a given prototype.\n * @param {Object} proto The prototype of the original event to get its wrapper.\n * @returns {Function} The wrapper class.\n * @private\n */\nfunction getWrapper(proto) {\n if (proto == null || proto === Object.prototype) {\n return Event\n }\n\n let wrapper = wrappers.get(proto)\n if (wrapper == null) {\n wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto)\n wrappers.set(proto, wrapper)\n }\n return wrapper\n}\n\n/**\n * Wrap a given event to management a dispatching.\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Object} event The event to wrap.\n * @returns {Event} The wrapper instance.\n * @private\n */\nexport function wrapEvent(eventTarget, event) {\n const Wrapper = getWrapper(Object.getPrototypeOf(event))\n return new Wrapper(eventTarget, event)\n}\n\n/**\n * Get the immediateStopped flag of a given event.\n * @param {Event} event The event to get.\n * @returns {boolean} The flag to stop propagation immediately.\n * @private\n */\nexport function isStopped(event) {\n return pd(event).immediateStopped\n}\n\n/**\n * Set the current event phase of a given event.\n * @param {Event} event The event to set current target.\n * @param {number} eventPhase New event phase.\n * @returns {void}\n * @private\n */\nexport function setEventPhase(event, eventPhase) {\n pd(event).eventPhase = eventPhase\n}\n\n/**\n * Set the current target of a given event.\n * @param {Event} event The event to set current target.\n * @param {EventTarget|null} currentTarget New current target.\n * @returns {void}\n * @private\n */\nexport function setCurrentTarget(event, currentTarget) {\n pd(event).currentTarget = currentTarget\n}\n\n/**\n * Set a passive listener of a given event.\n * @param {Event} event The event to set current target.\n * @param {Function|null} passiveListener New passive listener.\n * @returns {void}\n * @private\n */\nexport function setPassiveListener(event, passiveListener) {\n pd(event).passiveListener = passiveListener\n}\n","import {\n isStopped,\n setCurrentTarget,\n setEventPhase,\n setPassiveListener,\n wrapEvent,\n} from \"./event.mjs\"\n\n/**\n * @typedef {object} ListenerNode\n * @property {Function} listener\n * @property {1|2|3} listenerType\n * @property {boolean} passive\n * @property {boolean} once\n * @property {ListenerNode|null} next\n * @private\n */\n\n/**\n * @type {WeakMap>}\n * @private\n */\nconst listenersMap = new WeakMap()\n\n// Listener types\nconst CAPTURE = 1\nconst BUBBLE = 2\nconst ATTRIBUTE = 3\n\n/**\n * Check whether a given value is an object or not.\n * @param {any} x The value to check.\n * @returns {boolean} `true` if the value is an object.\n */\nfunction isObject(x) {\n return x !== null && typeof x === \"object\" //eslint-disable-line no-restricted-syntax\n}\n\n/**\n * Get listeners.\n * @param {EventTarget} eventTarget The event target to get.\n * @returns {Map} The listeners.\n * @private\n */\nfunction getListeners(eventTarget) {\n const listeners = listenersMap.get(eventTarget)\n if (listeners == null) {\n throw new TypeError(\n \"'this' is expected an EventTarget object, but got another value.\"\n )\n }\n return listeners\n}\n\n/**\n * Get the property descriptor for the event attribute of a given event.\n * @param {string} eventName The event name to get property descriptor.\n * @returns {PropertyDescriptor} The property descriptor.\n * @private\n */\nfunction defineEventAttributeDescriptor(eventName) {\n return {\n get() {\n const listeners = getListeners(this)\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n return node.listener\n }\n node = node.next\n }\n return null\n },\n\n set(listener) {\n if (typeof listener !== \"function\" && !isObject(listener)) {\n listener = null // eslint-disable-line no-param-reassign\n }\n const listeners = getListeners(this)\n\n // Traverse to the tail while removing old value.\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n // Remove old value.\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n node = node.next\n }\n\n // Add new value.\n if (listener !== null) {\n const newNode = {\n listener,\n listenerType: ATTRIBUTE,\n passive: false,\n once: false,\n next: null,\n }\n if (prev === null) {\n listeners.set(eventName, newNode)\n } else {\n prev.next = newNode\n }\n }\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define an event attribute (e.g. `eventTarget.onclick`).\n * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.\n * @param {string} eventName The event name to define.\n * @returns {void}\n */\nfunction defineEventAttribute(eventTargetPrototype, eventName) {\n Object.defineProperty(\n eventTargetPrototype,\n `on${eventName}`,\n defineEventAttributeDescriptor(eventName)\n )\n}\n\n/**\n * Define a custom EventTarget with event attributes.\n * @param {string[]} eventNames Event names for event attributes.\n * @returns {EventTarget} The custom EventTarget.\n * @private\n */\nfunction defineCustomEventTarget(eventNames) {\n /** CustomEventTarget */\n function CustomEventTarget() {\n EventTarget.call(this)\n }\n\n CustomEventTarget.prototype = Object.create(EventTarget.prototype, {\n constructor: {\n value: CustomEventTarget,\n configurable: true,\n writable: true,\n },\n })\n\n for (let i = 0; i < eventNames.length; ++i) {\n defineEventAttribute(CustomEventTarget.prototype, eventNames[i])\n }\n\n return CustomEventTarget\n}\n\n/**\n * EventTarget.\n *\n * - This is constructor if no arguments.\n * - This is a function which returns a CustomEventTarget constructor if there are arguments.\n *\n * For example:\n *\n * class A extends EventTarget {}\n * class B extends EventTarget(\"message\") {}\n * class C extends EventTarget(\"message\", \"error\") {}\n * class D extends EventTarget([\"message\", \"error\"]) {}\n */\nfunction EventTarget() {\n /*eslint-disable consistent-return */\n if (this instanceof EventTarget) {\n listenersMap.set(this, new Map())\n return\n }\n if (arguments.length === 1 && Array.isArray(arguments[0])) {\n return defineCustomEventTarget(arguments[0])\n }\n if (arguments.length > 0) {\n const types = new Array(arguments.length)\n for (let i = 0; i < arguments.length; ++i) {\n types[i] = arguments[i]\n }\n return defineCustomEventTarget(types)\n }\n throw new TypeError(\"Cannot call a class as a function\")\n /*eslint-enable consistent-return */\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEventTarget.prototype = {\n /**\n * Add a given listener to this event target.\n * @param {string} eventName The event name to add.\n * @param {Function} listener The listener to add.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n addEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n if (typeof listener !== \"function\" && !isObject(listener)) {\n throw new TypeError(\"'listener' should be a function or an object.\")\n }\n\n const listeners = getListeners(this)\n const optionsIsObj = isObject(options)\n const capture = optionsIsObj\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n const newNode = {\n listener,\n listenerType,\n passive: optionsIsObj && Boolean(options.passive),\n once: optionsIsObj && Boolean(options.once),\n next: null,\n }\n\n // Set it as the first node if the first node is null.\n let node = listeners.get(eventName)\n if (node === undefined) {\n listeners.set(eventName, newNode)\n return\n }\n\n // Traverse to the tail while checking duplication..\n let prev = null\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n // Should ignore duplication.\n return\n }\n prev = node\n node = node.next\n }\n\n // Add it.\n prev.next = newNode\n },\n\n /**\n * Remove a given listener from this event target.\n * @param {string} eventName The event name to remove.\n * @param {Function} listener The listener to remove.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n removeEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n\n const listeners = getListeners(this)\n const capture = isObject(options)\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n return\n }\n\n prev = node\n node = node.next\n }\n },\n\n /**\n * Dispatch a given event.\n * @param {Event|{type:string}} event The event to dispatch.\n * @returns {boolean} `false` if canceled.\n */\n dispatchEvent(event) {\n if (event == null || typeof event.type !== \"string\") {\n throw new TypeError('\"event.type\" should be a string.')\n }\n\n // If listeners aren't registered, terminate.\n const listeners = getListeners(this)\n const eventName = event.type\n let node = listeners.get(eventName)\n if (node == null) {\n return true\n }\n\n // Since we cannot rewrite several properties, so wrap object.\n const wrappedEvent = wrapEvent(this, event)\n\n // This doesn't process capturing phase and bubbling phase.\n // This isn't participating in a tree.\n let prev = null\n while (node != null) {\n // Remove this listener if it's once\n if (node.once) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n // Call this listener\n setPassiveListener(\n wrappedEvent,\n node.passive ? node.listener : null\n )\n if (typeof node.listener === \"function\") {\n try {\n node.listener.call(this, wrappedEvent)\n } catch (err) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(err)\n }\n }\n } else if (\n node.listenerType !== ATTRIBUTE &&\n typeof node.listener.handleEvent === \"function\"\n ) {\n node.listener.handleEvent(wrappedEvent)\n }\n\n // Break if `event.stopImmediatePropagation` was called.\n if (isStopped(wrappedEvent)) {\n break\n }\n\n node = node.next\n }\n setPassiveListener(wrappedEvent, null)\n setEventPhase(wrappedEvent, 0)\n setCurrentTarget(wrappedEvent, null)\n\n return !wrappedEvent.defaultPrevented\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(EventTarget.prototype, \"constructor\", {\n value: EventTarget,\n configurable: true,\n writable: true,\n})\n\n// Ensure `eventTarget instanceof window.EventTarget` is `true`.\nif (\n typeof window !== \"undefined\" &&\n typeof window.EventTarget !== \"undefined\"\n) {\n Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype)\n}\n\nexport { defineEventAttribute, EventTarget }\nexport default EventTarget\n","import {\n // Event,\n EventTarget,\n // Type,\n defineEventAttribute,\n} from \"event-target-shim\"\n\n// Known Limitation\n// Use `any` because the type of `AbortSignal` in `lib.dom.d.ts` is wrong and\n// to make assignable our `AbortSignal` into that.\n// https://github.com/Microsoft/TSJS-lib-generator/pull/623\ntype Events = {\n abort: any // Event & Type<\"abort\">\n}\ntype EventAttributes = {\n onabort: any // Event & Type<\"abort\">\n}\n\n/**\n * The signal class.\n * @see https://dom.spec.whatwg.org/#abortsignal\n */\nexport default class AbortSignal extends EventTarget {\n /**\n * AbortSignal cannot be constructed directly.\n */\n public constructor() {\n super()\n throw new TypeError(\"AbortSignal cannot be constructed directly\")\n }\n\n /**\n * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise.\n */\n public get aborted(): boolean {\n const aborted = abortedFlags.get(this)\n if (typeof aborted !== \"boolean\") {\n throw new TypeError(\n `Expected 'this' to be an 'AbortSignal' object, but got ${\n this === null ? \"null\" : typeof this\n }`,\n )\n }\n return aborted\n }\n}\ndefineEventAttribute(AbortSignal.prototype, \"abort\")\n\n/**\n * Create an AbortSignal object.\n */\nexport function createAbortSignal(): AbortSignal {\n const signal = Object.create(AbortSignal.prototype)\n EventTarget.call(signal)\n abortedFlags.set(signal, false)\n return signal\n}\n\n/**\n * Abort a given signal.\n */\nexport function abortSignal(signal: AbortSignal): void {\n if (abortedFlags.get(signal) !== false) {\n return\n }\n\n abortedFlags.set(signal, true)\n signal.dispatchEvent<\"abort\">({ type: \"abort\" })\n}\n\n/**\n * Aborted flag for each instances.\n */\nconst abortedFlags = new WeakMap()\n\n// Properties should be enumerable.\nObject.defineProperties(AbortSignal.prototype, {\n aborted: { enumerable: true },\n})\n\n// `toString()` should return `\"[object AbortSignal]\"`\nif (typeof Symbol === \"function\" && typeof Symbol.toStringTag === \"symbol\") {\n Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, {\n configurable: true,\n value: \"AbortSignal\",\n })\n}\n","import AbortSignal, { abortSignal, createAbortSignal } from \"./abort-signal\"\n\n/**\n * The AbortController.\n * @see https://dom.spec.whatwg.org/#abortcontroller\n */\nexport default class AbortController {\n /**\n * Initialize this controller.\n */\n public constructor() {\n signals.set(this, createAbortSignal())\n }\n\n /**\n * Returns the `AbortSignal` object associated with this object.\n */\n public get signal(): AbortSignal {\n return getSignal(this)\n }\n\n /**\n * Abort and signal to any observers that the associated activity is to be aborted.\n */\n public abort(): void {\n abortSignal(getSignal(this))\n }\n}\n\n/**\n * Associated signals.\n */\nconst signals = new WeakMap()\n\n/**\n * Get the associated signal of a given controller.\n */\nfunction getSignal(controller: AbortController): AbortSignal {\n const signal = signals.get(controller)\n if (signal == null) {\n throw new TypeError(\n `Expected 'this' to be an 'AbortController' object, but got ${\n controller === null ? \"null\" : typeof controller\n }`,\n )\n }\n return signal\n}\n\n// Properties should be enumerable.\nObject.defineProperties(AbortController.prototype, {\n signal: { enumerable: true },\n abort: { enumerable: true },\n})\n\nif (typeof Symbol === \"function\" && typeof Symbol.toStringTag === \"symbol\") {\n Object.defineProperty(AbortController.prototype, Symbol.toStringTag, {\n configurable: true,\n value: \"AbortController\",\n })\n}\n\nexport { AbortController, AbortSignal }\n","'use strict'\n\nconst bufferModule = require('buffer')\nconst { format, inspect } = require('./util/inspect')\nconst {\n codes: { ERR_INVALID_ARG_TYPE }\n} = require('./errors')\nconst { kResistStopPropagation, AggregateError, SymbolDispose } = require('./primordials')\nconst AbortSignal = globalThis.AbortSignal || require('abort-controller').AbortSignal\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nconst AsyncFunction = Object.getPrototypeOf(async function () {}).constructor\nconst Blob = globalThis.Blob || bufferModule.Blob\n/* eslint-disable indent */\nconst isBlob =\n typeof Blob !== 'undefined'\n ? function isBlob(b) {\n // eslint-disable-next-line indent\n return b instanceof Blob\n }\n : function isBlob(b) {\n return false\n }\n/* eslint-enable indent */\n\nconst validateAbortSignal = (signal, name) => {\n if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) {\n throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal)\n }\n}\nconst validateFunction = (value, name) => {\n if (typeof value !== 'function') {\n throw new ERR_INVALID_ARG_TYPE(name, 'Function', value)\n }\n}\nmodule.exports = {\n AggregateError,\n kEmptyObject: Object.freeze({}),\n once(callback) {\n let called = false\n return function (...args) {\n if (called) {\n return\n }\n called = true\n callback.apply(this, args)\n }\n },\n createDeferredPromise: function () {\n let resolve\n let reject\n\n // eslint-disable-next-line promise/param-names\n const promise = new Promise((res, rej) => {\n resolve = res\n reject = rej\n })\n return {\n promise,\n resolve,\n reject\n }\n },\n promisify(fn) {\n return new Promise((resolve, reject) => {\n fn((err, ...args) => {\n if (err) {\n return reject(err)\n }\n return resolve(...args)\n })\n })\n },\n debuglog() {\n return function () {}\n },\n format,\n inspect,\n types: {\n isAsyncFunction(fn) {\n return fn instanceof AsyncFunction\n },\n isArrayBufferView(arr) {\n return ArrayBuffer.isView(arr)\n }\n },\n isBlob,\n deprecate(fn, message) {\n return fn\n },\n addAbortListener:\n require('events').addAbortListener ||\n function addAbortListener(signal, listener) {\n if (signal === undefined) {\n throw new ERR_INVALID_ARG_TYPE('signal', 'AbortSignal', signal)\n }\n validateAbortSignal(signal, 'signal')\n validateFunction(listener, 'listener')\n let removeEventListener\n if (signal.aborted) {\n queueMicrotask(() => listener())\n } else {\n signal.addEventListener('abort', listener, {\n __proto__: null,\n once: true,\n [kResistStopPropagation]: true\n })\n removeEventListener = () => {\n signal.removeEventListener('abort', listener)\n }\n }\n return {\n __proto__: null,\n [SymbolDispose]() {\n var _removeEventListener\n ;(_removeEventListener = removeEventListener) === null || _removeEventListener === undefined\n ? undefined\n : _removeEventListener()\n }\n }\n },\n AbortSignalAny:\n AbortSignal.any ||\n function AbortSignalAny(signals) {\n // Fast path if there is only one signal.\n if (signals.length === 1) {\n return signals[0]\n }\n const ac = new AbortController()\n const abort = () => ac.abort()\n signals.forEach((signal) => {\n validateAbortSignal(signal, 'signals')\n signal.addEventListener('abort', abort, {\n once: true\n })\n })\n ac.signal.addEventListener(\n 'abort',\n () => {\n signals.forEach((signal) => signal.removeEventListener('abort', abort))\n },\n {\n once: true\n }\n )\n return ac.signal\n }\n}\nmodule.exports.promisify.custom = Symbol.for('nodejs.util.promisify.custom')\n","/* eslint jsdoc/require-jsdoc: \"error\" */\n\n'use strict'\n\nconst {\n ArrayIsArray,\n ArrayPrototypeIncludes,\n ArrayPrototypeJoin,\n ArrayPrototypeMap,\n NumberIsInteger,\n NumberIsNaN,\n NumberMAX_SAFE_INTEGER,\n NumberMIN_SAFE_INTEGER,\n NumberParseInt,\n ObjectPrototypeHasOwnProperty,\n RegExpPrototypeExec,\n String,\n StringPrototypeToUpperCase,\n StringPrototypeTrim\n} = require('../ours/primordials')\nconst {\n hideStackFrames,\n codes: { ERR_SOCKET_BAD_PORT, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_OUT_OF_RANGE, ERR_UNKNOWN_SIGNAL }\n} = require('../ours/errors')\nconst { normalizeEncoding } = require('../ours/util')\nconst { isAsyncFunction, isArrayBufferView } = require('../ours/util').types\nconst signals = {}\n\n/**\n * @param {*} value\n * @returns {boolean}\n */\nfunction isInt32(value) {\n return value === (value | 0)\n}\n\n/**\n * @param {*} value\n * @returns {boolean}\n */\nfunction isUint32(value) {\n return value === value >>> 0\n}\nconst octalReg = /^[0-7]+$/\nconst modeDesc = 'must be a 32-bit unsigned integer or an octal string'\n\n/**\n * Parse and validate values that will be converted into mode_t (the S_*\n * constants). Only valid numbers and octal strings are allowed. They could be\n * converted to 32-bit unsigned integers or non-negative signed integers in the\n * C++ land, but any value higher than 0o777 will result in platform-specific\n * behaviors.\n * @param {*} value Values to be validated\n * @param {string} name Name of the argument\n * @param {number} [def] If specified, will be returned for invalid values\n * @returns {number}\n */\nfunction parseFileMode(value, name, def) {\n if (typeof value === 'undefined') {\n value = def\n }\n if (typeof value === 'string') {\n if (RegExpPrototypeExec(octalReg, value) === null) {\n throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc)\n }\n value = NumberParseInt(value, 8)\n }\n validateUint32(value, name)\n return value\n}\n\n/**\n * @callback validateInteger\n * @param {*} value\n * @param {string} name\n * @param {number} [min]\n * @param {number} [max]\n * @returns {asserts value is number}\n */\n\n/** @type {validateInteger} */\nconst validateInteger = hideStackFrames((value, name, min = NumberMIN_SAFE_INTEGER, max = NumberMAX_SAFE_INTEGER) => {\n if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n if (!NumberIsInteger(value)) throw new ERR_OUT_OF_RANGE(name, 'an integer', value)\n if (value < min || value > max) throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value)\n})\n\n/**\n * @callback validateInt32\n * @param {*} value\n * @param {string} name\n * @param {number} [min]\n * @param {number} [max]\n * @returns {asserts value is number}\n */\n\n/** @type {validateInt32} */\nconst validateInt32 = hideStackFrames((value, name, min = -2147483648, max = 2147483647) => {\n // The defaults for min and max correspond to the limits of 32-bit integers.\n if (typeof value !== 'number') {\n throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n }\n if (!NumberIsInteger(value)) {\n throw new ERR_OUT_OF_RANGE(name, 'an integer', value)\n }\n if (value < min || value > max) {\n throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value)\n }\n})\n\n/**\n * @callback validateUint32\n * @param {*} value\n * @param {string} name\n * @param {number|boolean} [positive=false]\n * @returns {asserts value is number}\n */\n\n/** @type {validateUint32} */\nconst validateUint32 = hideStackFrames((value, name, positive = false) => {\n if (typeof value !== 'number') {\n throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n }\n if (!NumberIsInteger(value)) {\n throw new ERR_OUT_OF_RANGE(name, 'an integer', value)\n }\n const min = positive ? 1 : 0\n // 2 ** 32 === 4294967296\n const max = 4294967295\n if (value < min || value > max) {\n throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value)\n }\n})\n\n/**\n * @callback validateString\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is string}\n */\n\n/** @type {validateString} */\nfunction validateString(value, name) {\n if (typeof value !== 'string') throw new ERR_INVALID_ARG_TYPE(name, 'string', value)\n}\n\n/**\n * @callback validateNumber\n * @param {*} value\n * @param {string} name\n * @param {number} [min]\n * @param {number} [max]\n * @returns {asserts value is number}\n */\n\n/** @type {validateNumber} */\nfunction validateNumber(value, name, min = undefined, max) {\n if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n if (\n (min != null && value < min) ||\n (max != null && value > max) ||\n ((min != null || max != null) && NumberIsNaN(value))\n ) {\n throw new ERR_OUT_OF_RANGE(\n name,\n `${min != null ? `>= ${min}` : ''}${min != null && max != null ? ' && ' : ''}${max != null ? `<= ${max}` : ''}`,\n value\n )\n }\n}\n\n/**\n * @callback validateOneOf\n * @template T\n * @param {T} value\n * @param {string} name\n * @param {T[]} oneOf\n */\n\n/** @type {validateOneOf} */\nconst validateOneOf = hideStackFrames((value, name, oneOf) => {\n if (!ArrayPrototypeIncludes(oneOf, value)) {\n const allowed = ArrayPrototypeJoin(\n ArrayPrototypeMap(oneOf, (v) => (typeof v === 'string' ? `'${v}'` : String(v))),\n ', '\n )\n const reason = 'must be one of: ' + allowed\n throw new ERR_INVALID_ARG_VALUE(name, value, reason)\n }\n})\n\n/**\n * @callback validateBoolean\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is boolean}\n */\n\n/** @type {validateBoolean} */\nfunction validateBoolean(value, name) {\n if (typeof value !== 'boolean') throw new ERR_INVALID_ARG_TYPE(name, 'boolean', value)\n}\n\n/**\n * @param {any} options\n * @param {string} key\n * @param {boolean} defaultValue\n * @returns {boolean}\n */\nfunction getOwnPropertyValueOrDefault(options, key, defaultValue) {\n return options == null || !ObjectPrototypeHasOwnProperty(options, key) ? defaultValue : options[key]\n}\n\n/**\n * @callback validateObject\n * @param {*} value\n * @param {string} name\n * @param {{\n * allowArray?: boolean,\n * allowFunction?: boolean,\n * nullable?: boolean\n * }} [options]\n */\n\n/** @type {validateObject} */\nconst validateObject = hideStackFrames((value, name, options = null) => {\n const allowArray = getOwnPropertyValueOrDefault(options, 'allowArray', false)\n const allowFunction = getOwnPropertyValueOrDefault(options, 'allowFunction', false)\n const nullable = getOwnPropertyValueOrDefault(options, 'nullable', false)\n if (\n (!nullable && value === null) ||\n (!allowArray && ArrayIsArray(value)) ||\n (typeof value !== 'object' && (!allowFunction || typeof value !== 'function'))\n ) {\n throw new ERR_INVALID_ARG_TYPE(name, 'Object', value)\n }\n})\n\n/**\n * @callback validateDictionary - We are using the Web IDL Standard definition\n * of \"dictionary\" here, which means any value\n * whose Type is either Undefined, Null, or\n * Object (which includes functions).\n * @param {*} value\n * @param {string} name\n * @see https://webidl.spec.whatwg.org/#es-dictionary\n * @see https://tc39.es/ecma262/#table-typeof-operator-results\n */\n\n/** @type {validateDictionary} */\nconst validateDictionary = hideStackFrames((value, name) => {\n if (value != null && typeof value !== 'object' && typeof value !== 'function') {\n throw new ERR_INVALID_ARG_TYPE(name, 'a dictionary', value)\n }\n})\n\n/**\n * @callback validateArray\n * @param {*} value\n * @param {string} name\n * @param {number} [minLength]\n * @returns {asserts value is any[]}\n */\n\n/** @type {validateArray} */\nconst validateArray = hideStackFrames((value, name, minLength = 0) => {\n if (!ArrayIsArray(value)) {\n throw new ERR_INVALID_ARG_TYPE(name, 'Array', value)\n }\n if (value.length < minLength) {\n const reason = `must be longer than ${minLength}`\n throw new ERR_INVALID_ARG_VALUE(name, value, reason)\n }\n})\n\n/**\n * @callback validateStringArray\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is string[]}\n */\n\n/** @type {validateStringArray} */\nfunction validateStringArray(value, name) {\n validateArray(value, name)\n for (let i = 0; i < value.length; i++) {\n validateString(value[i], `${name}[${i}]`)\n }\n}\n\n/**\n * @callback validateBooleanArray\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is boolean[]}\n */\n\n/** @type {validateBooleanArray} */\nfunction validateBooleanArray(value, name) {\n validateArray(value, name)\n for (let i = 0; i < value.length; i++) {\n validateBoolean(value[i], `${name}[${i}]`)\n }\n}\n\n/**\n * @callback validateAbortSignalArray\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is AbortSignal[]}\n */\n\n/** @type {validateAbortSignalArray} */\nfunction validateAbortSignalArray(value, name) {\n validateArray(value, name)\n for (let i = 0; i < value.length; i++) {\n const signal = value[i]\n const indexedName = `${name}[${i}]`\n if (signal == null) {\n throw new ERR_INVALID_ARG_TYPE(indexedName, 'AbortSignal', signal)\n }\n validateAbortSignal(signal, indexedName)\n }\n}\n\n/**\n * @param {*} signal\n * @param {string} [name='signal']\n * @returns {asserts signal is keyof signals}\n */\nfunction validateSignalName(signal, name = 'signal') {\n validateString(signal, name)\n if (signals[signal] === undefined) {\n if (signals[StringPrototypeToUpperCase(signal)] !== undefined) {\n throw new ERR_UNKNOWN_SIGNAL(signal + ' (signals must use all capital letters)')\n }\n throw new ERR_UNKNOWN_SIGNAL(signal)\n }\n}\n\n/**\n * @callback validateBuffer\n * @param {*} buffer\n * @param {string} [name='buffer']\n * @returns {asserts buffer is ArrayBufferView}\n */\n\n/** @type {validateBuffer} */\nconst validateBuffer = hideStackFrames((buffer, name = 'buffer') => {\n if (!isArrayBufferView(buffer)) {\n throw new ERR_INVALID_ARG_TYPE(name, ['Buffer', 'TypedArray', 'DataView'], buffer)\n }\n})\n\n/**\n * @param {string} data\n * @param {string} encoding\n */\nfunction validateEncoding(data, encoding) {\n const normalizedEncoding = normalizeEncoding(encoding)\n const length = data.length\n if (normalizedEncoding === 'hex' && length % 2 !== 0) {\n throw new ERR_INVALID_ARG_VALUE('encoding', encoding, `is invalid for data of length ${length}`)\n }\n}\n\n/**\n * Check that the port number is not NaN when coerced to a number,\n * is an integer and that it falls within the legal range of port numbers.\n * @param {*} port\n * @param {string} [name='Port']\n * @param {boolean} [allowZero=true]\n * @returns {number}\n */\nfunction validatePort(port, name = 'Port', allowZero = true) {\n if (\n (typeof port !== 'number' && typeof port !== 'string') ||\n (typeof port === 'string' && StringPrototypeTrim(port).length === 0) ||\n +port !== +port >>> 0 ||\n port > 0xffff ||\n (port === 0 && !allowZero)\n ) {\n throw new ERR_SOCKET_BAD_PORT(name, port, allowZero)\n }\n return port | 0\n}\n\n/**\n * @callback validateAbortSignal\n * @param {*} signal\n * @param {string} name\n */\n\n/** @type {validateAbortSignal} */\nconst validateAbortSignal = hideStackFrames((signal, name) => {\n if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) {\n throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal)\n }\n})\n\n/**\n * @callback validateFunction\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is Function}\n */\n\n/** @type {validateFunction} */\nconst validateFunction = hideStackFrames((value, name) => {\n if (typeof value !== 'function') throw new ERR_INVALID_ARG_TYPE(name, 'Function', value)\n})\n\n/**\n * @callback validatePlainFunction\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is Function}\n */\n\n/** @type {validatePlainFunction} */\nconst validatePlainFunction = hideStackFrames((value, name) => {\n if (typeof value !== 'function' || isAsyncFunction(value)) throw new ERR_INVALID_ARG_TYPE(name, 'Function', value)\n})\n\n/**\n * @callback validateUndefined\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is undefined}\n */\n\n/** @type {validateUndefined} */\nconst validateUndefined = hideStackFrames((value, name) => {\n if (value !== undefined) throw new ERR_INVALID_ARG_TYPE(name, 'undefined', value)\n})\n\n/**\n * @template T\n * @param {T} value\n * @param {string} name\n * @param {T[]} union\n */\nfunction validateUnion(value, name, union) {\n if (!ArrayPrototypeIncludes(union, value)) {\n throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value)\n }\n}\n\n/*\n The rules for the Link header field are described here:\n https://www.rfc-editor.org/rfc/rfc8288.html#section-3\n\n This regex validates any string surrounded by angle brackets\n (not necessarily a valid URI reference) followed by zero or more\n link-params separated by semicolons.\n*/\nconst linkValueRegExp = /^(?:<[^>]*>)(?:\\s*;\\s*[^;\"\\s]+(?:=(\")?[^;\"\\s]*\\1)?)*$/\n\n/**\n * @param {any} value\n * @param {string} name\n */\nfunction validateLinkHeaderFormat(value, name) {\n if (typeof value === 'undefined' || !RegExpPrototypeExec(linkValueRegExp, value)) {\n throw new ERR_INVALID_ARG_VALUE(\n name,\n value,\n 'must be an array or string of format \"; rel=preload; as=style\"'\n )\n }\n}\n\n/**\n * @param {any} hints\n * @return {string}\n */\nfunction validateLinkHeaderValue(hints) {\n if (typeof hints === 'string') {\n validateLinkHeaderFormat(hints, 'hints')\n return hints\n } else if (ArrayIsArray(hints)) {\n const hintsLength = hints.length\n let result = ''\n if (hintsLength === 0) {\n return result\n }\n for (let i = 0; i < hintsLength; i++) {\n const link = hints[i]\n validateLinkHeaderFormat(link, 'hints')\n result += link\n if (i !== hintsLength - 1) {\n result += ', '\n }\n }\n return result\n }\n throw new ERR_INVALID_ARG_VALUE(\n 'hints',\n hints,\n 'must be an array or string of format \"; rel=preload; as=style\"'\n )\n}\nmodule.exports = {\n isInt32,\n isUint32,\n parseFileMode,\n validateArray,\n validateStringArray,\n validateBooleanArray,\n validateAbortSignalArray,\n validateBoolean,\n validateBuffer,\n validateDictionary,\n validateEncoding,\n validateFunction,\n validateInt32,\n validateInteger,\n validateNumber,\n validateObject,\n validateOneOf,\n validatePlainFunction,\n validatePort,\n validateSignalName,\n validateString,\n validateUint32,\n validateUndefined,\n validateUnion,\n validateAbortSignal,\n validateLinkHeaderValue\n}\n","// for now just expose the builtin process global from node.js\nmodule.exports = global.process;\n","'use strict'\n\nconst { SymbolAsyncIterator, SymbolIterator, SymbolFor } = require('../../ours/primordials')\n\n// We need to use SymbolFor to make these globally available\n// for interopt with readable-stream, i.e. readable-stream\n// and node core needs to be able to read/write private state\n// from each other for proper interoperability.\nconst kIsDestroyed = SymbolFor('nodejs.stream.destroyed')\nconst kIsErrored = SymbolFor('nodejs.stream.errored')\nconst kIsReadable = SymbolFor('nodejs.stream.readable')\nconst kIsWritable = SymbolFor('nodejs.stream.writable')\nconst kIsDisturbed = SymbolFor('nodejs.stream.disturbed')\nconst kIsClosedPromise = SymbolFor('nodejs.webstream.isClosedPromise')\nconst kControllerErrorFunction = SymbolFor('nodejs.webstream.controllerErrorFunction')\nfunction isReadableNodeStream(obj, strict = false) {\n var _obj$_readableState\n return !!(\n (\n obj &&\n typeof obj.pipe === 'function' &&\n typeof obj.on === 'function' &&\n (!strict || (typeof obj.pause === 'function' && typeof obj.resume === 'function')) &&\n (!obj._writableState ||\n ((_obj$_readableState = obj._readableState) === null || _obj$_readableState === undefined\n ? undefined\n : _obj$_readableState.readable) !== false) &&\n // Duplex\n (!obj._writableState || obj._readableState)\n ) // Writable has .pipe.\n )\n}\nfunction isWritableNodeStream(obj) {\n var _obj$_writableState\n return !!(\n (\n obj &&\n typeof obj.write === 'function' &&\n typeof obj.on === 'function' &&\n (!obj._readableState ||\n ((_obj$_writableState = obj._writableState) === null || _obj$_writableState === undefined\n ? undefined\n : _obj$_writableState.writable) !== false)\n ) // Duplex\n )\n}\nfunction isDuplexNodeStream(obj) {\n return !!(\n obj &&\n typeof obj.pipe === 'function' &&\n obj._readableState &&\n typeof obj.on === 'function' &&\n typeof obj.write === 'function'\n )\n}\nfunction isNodeStream(obj) {\n return (\n obj &&\n (obj._readableState ||\n obj._writableState ||\n (typeof obj.write === 'function' && typeof obj.on === 'function') ||\n (typeof obj.pipe === 'function' && typeof obj.on === 'function'))\n )\n}\nfunction isReadableStream(obj) {\n return !!(\n obj &&\n !isNodeStream(obj) &&\n typeof obj.pipeThrough === 'function' &&\n typeof obj.getReader === 'function' &&\n typeof obj.cancel === 'function'\n )\n}\nfunction isWritableStream(obj) {\n return !!(obj && !isNodeStream(obj) && typeof obj.getWriter === 'function' && typeof obj.abort === 'function')\n}\nfunction isTransformStream(obj) {\n return !!(obj && !isNodeStream(obj) && typeof obj.readable === 'object' && typeof obj.writable === 'object')\n}\nfunction isWebStream(obj) {\n return isReadableStream(obj) || isWritableStream(obj) || isTransformStream(obj)\n}\nfunction isIterable(obj, isAsync) {\n if (obj == null) return false\n if (isAsync === true) return typeof obj[SymbolAsyncIterator] === 'function'\n if (isAsync === false) return typeof obj[SymbolIterator] === 'function'\n return typeof obj[SymbolAsyncIterator] === 'function' || typeof obj[SymbolIterator] === 'function'\n}\nfunction isDestroyed(stream) {\n if (!isNodeStream(stream)) return null\n const wState = stream._writableState\n const rState = stream._readableState\n const state = wState || rState\n return !!(stream.destroyed || stream[kIsDestroyed] || (state !== null && state !== undefined && state.destroyed))\n}\n\n// Have been end():d.\nfunction isWritableEnded(stream) {\n if (!isWritableNodeStream(stream)) return null\n if (stream.writableEnded === true) return true\n const wState = stream._writableState\n if (wState !== null && wState !== undefined && wState.errored) return false\n if (typeof (wState === null || wState === undefined ? undefined : wState.ended) !== 'boolean') return null\n return wState.ended\n}\n\n// Have emitted 'finish'.\nfunction isWritableFinished(stream, strict) {\n if (!isWritableNodeStream(stream)) return null\n if (stream.writableFinished === true) return true\n const wState = stream._writableState\n if (wState !== null && wState !== undefined && wState.errored) return false\n if (typeof (wState === null || wState === undefined ? undefined : wState.finished) !== 'boolean') return null\n return !!(wState.finished || (strict === false && wState.ended === true && wState.length === 0))\n}\n\n// Have been push(null):d.\nfunction isReadableEnded(stream) {\n if (!isReadableNodeStream(stream)) return null\n if (stream.readableEnded === true) return true\n const rState = stream._readableState\n if (!rState || rState.errored) return false\n if (typeof (rState === null || rState === undefined ? undefined : rState.ended) !== 'boolean') return null\n return rState.ended\n}\n\n// Have emitted 'end'.\nfunction isReadableFinished(stream, strict) {\n if (!isReadableNodeStream(stream)) return null\n const rState = stream._readableState\n if (rState !== null && rState !== undefined && rState.errored) return false\n if (typeof (rState === null || rState === undefined ? undefined : rState.endEmitted) !== 'boolean') return null\n return !!(rState.endEmitted || (strict === false && rState.ended === true && rState.length === 0))\n}\nfunction isReadable(stream) {\n if (stream && stream[kIsReadable] != null) return stream[kIsReadable]\n if (typeof (stream === null || stream === undefined ? undefined : stream.readable) !== 'boolean') return null\n if (isDestroyed(stream)) return false\n return isReadableNodeStream(stream) && stream.readable && !isReadableFinished(stream)\n}\nfunction isWritable(stream) {\n if (stream && stream[kIsWritable] != null) return stream[kIsWritable]\n if (typeof (stream === null || stream === undefined ? undefined : stream.writable) !== 'boolean') return null\n if (isDestroyed(stream)) return false\n return isWritableNodeStream(stream) && stream.writable && !isWritableEnded(stream)\n}\nfunction isFinished(stream, opts) {\n if (!isNodeStream(stream)) {\n return null\n }\n if (isDestroyed(stream)) {\n return true\n }\n if ((opts === null || opts === undefined ? undefined : opts.readable) !== false && isReadable(stream)) {\n return false\n }\n if ((opts === null || opts === undefined ? undefined : opts.writable) !== false && isWritable(stream)) {\n return false\n }\n return true\n}\nfunction isWritableErrored(stream) {\n var _stream$_writableStat, _stream$_writableStat2\n if (!isNodeStream(stream)) {\n return null\n }\n if (stream.writableErrored) {\n return stream.writableErrored\n }\n return (_stream$_writableStat =\n (_stream$_writableStat2 = stream._writableState) === null || _stream$_writableStat2 === undefined\n ? undefined\n : _stream$_writableStat2.errored) !== null && _stream$_writableStat !== undefined\n ? _stream$_writableStat\n : null\n}\nfunction isReadableErrored(stream) {\n var _stream$_readableStat, _stream$_readableStat2\n if (!isNodeStream(stream)) {\n return null\n }\n if (stream.readableErrored) {\n return stream.readableErrored\n }\n return (_stream$_readableStat =\n (_stream$_readableStat2 = stream._readableState) === null || _stream$_readableStat2 === undefined\n ? undefined\n : _stream$_readableStat2.errored) !== null && _stream$_readableStat !== undefined\n ? _stream$_readableStat\n : null\n}\nfunction isClosed(stream) {\n if (!isNodeStream(stream)) {\n return null\n }\n if (typeof stream.closed === 'boolean') {\n return stream.closed\n }\n const wState = stream._writableState\n const rState = stream._readableState\n if (\n typeof (wState === null || wState === undefined ? undefined : wState.closed) === 'boolean' ||\n typeof (rState === null || rState === undefined ? undefined : rState.closed) === 'boolean'\n ) {\n return (\n (wState === null || wState === undefined ? undefined : wState.closed) ||\n (rState === null || rState === undefined ? undefined : rState.closed)\n )\n }\n if (typeof stream._closed === 'boolean' && isOutgoingMessage(stream)) {\n return stream._closed\n }\n return null\n}\nfunction isOutgoingMessage(stream) {\n return (\n typeof stream._closed === 'boolean' &&\n typeof stream._defaultKeepAlive === 'boolean' &&\n typeof stream._removedConnection === 'boolean' &&\n typeof stream._removedContLen === 'boolean'\n )\n}\nfunction isServerResponse(stream) {\n return typeof stream._sent100 === 'boolean' && isOutgoingMessage(stream)\n}\nfunction isServerRequest(stream) {\n var _stream$req\n return (\n typeof stream._consuming === 'boolean' &&\n typeof stream._dumped === 'boolean' &&\n ((_stream$req = stream.req) === null || _stream$req === undefined ? undefined : _stream$req.upgradeOrConnect) ===\n undefined\n )\n}\nfunction willEmitClose(stream) {\n if (!isNodeStream(stream)) return null\n const wState = stream._writableState\n const rState = stream._readableState\n const state = wState || rState\n return (\n (!state && isServerResponse(stream)) || !!(state && state.autoDestroy && state.emitClose && state.closed === false)\n )\n}\nfunction isDisturbed(stream) {\n var _stream$kIsDisturbed\n return !!(\n stream &&\n ((_stream$kIsDisturbed = stream[kIsDisturbed]) !== null && _stream$kIsDisturbed !== undefined\n ? _stream$kIsDisturbed\n : stream.readableDidRead || stream.readableAborted)\n )\n}\nfunction isErrored(stream) {\n var _ref,\n _ref2,\n _ref3,\n _ref4,\n _ref5,\n _stream$kIsErrored,\n _stream$_readableStat3,\n _stream$_writableStat3,\n _stream$_readableStat4,\n _stream$_writableStat4\n return !!(\n stream &&\n ((_ref =\n (_ref2 =\n (_ref3 =\n (_ref4 =\n (_ref5 =\n (_stream$kIsErrored = stream[kIsErrored]) !== null && _stream$kIsErrored !== undefined\n ? _stream$kIsErrored\n : stream.readableErrored) !== null && _ref5 !== undefined\n ? _ref5\n : stream.writableErrored) !== null && _ref4 !== undefined\n ? _ref4\n : (_stream$_readableStat3 = stream._readableState) === null || _stream$_readableStat3 === undefined\n ? undefined\n : _stream$_readableStat3.errorEmitted) !== null && _ref3 !== undefined\n ? _ref3\n : (_stream$_writableStat3 = stream._writableState) === null || _stream$_writableStat3 === undefined\n ? undefined\n : _stream$_writableStat3.errorEmitted) !== null && _ref2 !== undefined\n ? _ref2\n : (_stream$_readableStat4 = stream._readableState) === null || _stream$_readableStat4 === undefined\n ? undefined\n : _stream$_readableStat4.errored) !== null && _ref !== undefined\n ? _ref\n : (_stream$_writableStat4 = stream._writableState) === null || _stream$_writableStat4 === undefined\n ? undefined\n : _stream$_writableStat4.errored)\n )\n}\nmodule.exports = {\n isDestroyed,\n kIsDestroyed,\n isDisturbed,\n kIsDisturbed,\n isErrored,\n kIsErrored,\n isReadable,\n kIsReadable,\n kIsClosedPromise,\n kControllerErrorFunction,\n kIsWritable,\n isClosed,\n isDuplexNodeStream,\n isFinished,\n isIterable,\n isReadableNodeStream,\n isReadableStream,\n isReadableEnded,\n isReadableFinished,\n isReadableErrored,\n isNodeStream,\n isWebStream,\n isWritable,\n isWritableNodeStream,\n isWritableStream,\n isWritableEnded,\n isWritableFinished,\n isWritableErrored,\n isServerRequest,\n isServerResponse,\n willEmitClose,\n isTransformStream\n}\n","// Ported from https://github.com/mafintosh/end-of-stream with\n// permission from the author, Mathias Buus (@mafintosh).\n\n'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst { AbortError, codes } = require('../../ours/errors')\nconst { ERR_INVALID_ARG_TYPE, ERR_STREAM_PREMATURE_CLOSE } = codes\nconst { kEmptyObject, once } = require('../../ours/util')\nconst { validateAbortSignal, validateFunction, validateObject, validateBoolean } = require('../validators')\nconst { Promise, PromisePrototypeThen, SymbolDispose } = require('../../ours/primordials')\nconst {\n isClosed,\n isReadable,\n isReadableNodeStream,\n isReadableStream,\n isReadableFinished,\n isReadableErrored,\n isWritable,\n isWritableNodeStream,\n isWritableStream,\n isWritableFinished,\n isWritableErrored,\n isNodeStream,\n willEmitClose: _willEmitClose,\n kIsClosedPromise\n} = require('./utils')\nlet addAbortListener\nfunction isRequest(stream) {\n return stream.setHeader && typeof stream.abort === 'function'\n}\nconst nop = () => {}\nfunction eos(stream, options, callback) {\n var _options$readable, _options$writable\n if (arguments.length === 2) {\n callback = options\n options = kEmptyObject\n } else if (options == null) {\n options = kEmptyObject\n } else {\n validateObject(options, 'options')\n }\n validateFunction(callback, 'callback')\n validateAbortSignal(options.signal, 'options.signal')\n callback = once(callback)\n if (isReadableStream(stream) || isWritableStream(stream)) {\n return eosWeb(stream, options, callback)\n }\n if (!isNodeStream(stream)) {\n throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream)\n }\n const readable =\n (_options$readable = options.readable) !== null && _options$readable !== undefined\n ? _options$readable\n : isReadableNodeStream(stream)\n const writable =\n (_options$writable = options.writable) !== null && _options$writable !== undefined\n ? _options$writable\n : isWritableNodeStream(stream)\n const wState = stream._writableState\n const rState = stream._readableState\n const onlegacyfinish = () => {\n if (!stream.writable) {\n onfinish()\n }\n }\n\n // TODO (ronag): Improve soft detection to include core modules and\n // common ecosystem modules that do properly emit 'close' but fail\n // this generic check.\n let willEmitClose =\n _willEmitClose(stream) && isReadableNodeStream(stream) === readable && isWritableNodeStream(stream) === writable\n let writableFinished = isWritableFinished(stream, false)\n const onfinish = () => {\n writableFinished = true\n // Stream should not be destroyed here. If it is that\n // means that user space is doing something differently and\n // we cannot trust willEmitClose.\n if (stream.destroyed) {\n willEmitClose = false\n }\n if (willEmitClose && (!stream.readable || readable)) {\n return\n }\n if (!readable || readableFinished) {\n callback.call(stream)\n }\n }\n let readableFinished = isReadableFinished(stream, false)\n const onend = () => {\n readableFinished = true\n // Stream should not be destroyed here. If it is that\n // means that user space is doing something differently and\n // we cannot trust willEmitClose.\n if (stream.destroyed) {\n willEmitClose = false\n }\n if (willEmitClose && (!stream.writable || writable)) {\n return\n }\n if (!writable || writableFinished) {\n callback.call(stream)\n }\n }\n const onerror = (err) => {\n callback.call(stream, err)\n }\n let closed = isClosed(stream)\n const onclose = () => {\n closed = true\n const errored = isWritableErrored(stream) || isReadableErrored(stream)\n if (errored && typeof errored !== 'boolean') {\n return callback.call(stream, errored)\n }\n if (readable && !readableFinished && isReadableNodeStream(stream, true)) {\n if (!isReadableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE())\n }\n if (writable && !writableFinished) {\n if (!isWritableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE())\n }\n callback.call(stream)\n }\n const onclosed = () => {\n closed = true\n const errored = isWritableErrored(stream) || isReadableErrored(stream)\n if (errored && typeof errored !== 'boolean') {\n return callback.call(stream, errored)\n }\n callback.call(stream)\n }\n const onrequest = () => {\n stream.req.on('finish', onfinish)\n }\n if (isRequest(stream)) {\n stream.on('complete', onfinish)\n if (!willEmitClose) {\n stream.on('abort', onclose)\n }\n if (stream.req) {\n onrequest()\n } else {\n stream.on('request', onrequest)\n }\n } else if (writable && !wState) {\n // legacy streams\n stream.on('end', onlegacyfinish)\n stream.on('close', onlegacyfinish)\n }\n\n // Not all streams will emit 'close' after 'aborted'.\n if (!willEmitClose && typeof stream.aborted === 'boolean') {\n stream.on('aborted', onclose)\n }\n stream.on('end', onend)\n stream.on('finish', onfinish)\n if (options.error !== false) {\n stream.on('error', onerror)\n }\n stream.on('close', onclose)\n if (closed) {\n process.nextTick(onclose)\n } else if (\n (wState !== null && wState !== undefined && wState.errorEmitted) ||\n (rState !== null && rState !== undefined && rState.errorEmitted)\n ) {\n if (!willEmitClose) {\n process.nextTick(onclosed)\n }\n } else if (\n !readable &&\n (!willEmitClose || isReadable(stream)) &&\n (writableFinished || isWritable(stream) === false)\n ) {\n process.nextTick(onclosed)\n } else if (\n !writable &&\n (!willEmitClose || isWritable(stream)) &&\n (readableFinished || isReadable(stream) === false)\n ) {\n process.nextTick(onclosed)\n } else if (rState && stream.req && stream.aborted) {\n process.nextTick(onclosed)\n }\n const cleanup = () => {\n callback = nop\n stream.removeListener('aborted', onclose)\n stream.removeListener('complete', onfinish)\n stream.removeListener('abort', onclose)\n stream.removeListener('request', onrequest)\n if (stream.req) stream.req.removeListener('finish', onfinish)\n stream.removeListener('end', onlegacyfinish)\n stream.removeListener('close', onlegacyfinish)\n stream.removeListener('finish', onfinish)\n stream.removeListener('end', onend)\n stream.removeListener('error', onerror)\n stream.removeListener('close', onclose)\n }\n if (options.signal && !closed) {\n const abort = () => {\n // Keep it because cleanup removes it.\n const endCallback = callback\n cleanup()\n endCallback.call(\n stream,\n new AbortError(undefined, {\n cause: options.signal.reason\n })\n )\n }\n if (options.signal.aborted) {\n process.nextTick(abort)\n } else {\n addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n const disposable = addAbortListener(options.signal, abort)\n const originalCallback = callback\n callback = once((...args) => {\n disposable[SymbolDispose]()\n originalCallback.apply(stream, args)\n })\n }\n }\n return cleanup\n}\nfunction eosWeb(stream, options, callback) {\n let isAborted = false\n let abort = nop\n if (options.signal) {\n abort = () => {\n isAborted = true\n callback.call(\n stream,\n new AbortError(undefined, {\n cause: options.signal.reason\n })\n )\n }\n if (options.signal.aborted) {\n process.nextTick(abort)\n } else {\n addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n const disposable = addAbortListener(options.signal, abort)\n const originalCallback = callback\n callback = once((...args) => {\n disposable[SymbolDispose]()\n originalCallback.apply(stream, args)\n })\n }\n }\n const resolverFn = (...args) => {\n if (!isAborted) {\n process.nextTick(() => callback.apply(stream, args))\n }\n }\n PromisePrototypeThen(stream[kIsClosedPromise].promise, resolverFn, resolverFn)\n return nop\n}\nfunction finished(stream, opts) {\n var _opts\n let autoCleanup = false\n if (opts === null) {\n opts = kEmptyObject\n }\n if ((_opts = opts) !== null && _opts !== undefined && _opts.cleanup) {\n validateBoolean(opts.cleanup, 'cleanup')\n autoCleanup = opts.cleanup\n }\n return new Promise((resolve, reject) => {\n const cleanup = eos(stream, opts, (err) => {\n if (autoCleanup) {\n cleanup()\n }\n if (err) {\n reject(err)\n } else {\n resolve()\n }\n })\n })\n}\nmodule.exports = eos\nmodule.exports.finished = finished\n","'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst {\n aggregateTwoErrors,\n codes: { ERR_MULTIPLE_CALLBACK },\n AbortError\n} = require('../../ours/errors')\nconst { Symbol } = require('../../ours/primordials')\nconst { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = require('./utils')\nconst kDestroy = Symbol('kDestroy')\nconst kConstruct = Symbol('kConstruct')\nfunction checkError(err, w, r) {\n if (err) {\n // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364\n err.stack // eslint-disable-line no-unused-expressions\n\n if (w && !w.errored) {\n w.errored = err\n }\n if (r && !r.errored) {\n r.errored = err\n }\n }\n}\n\n// Backwards compat. cb() is undocumented and unused in core but\n// unfortunately might be used by modules.\nfunction destroy(err, cb) {\n const r = this._readableState\n const w = this._writableState\n // With duplex streams we use the writable side for state.\n const s = w || r\n if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) {\n if (typeof cb === 'function') {\n cb()\n }\n return this\n }\n\n // We set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n checkError(err, w, r)\n if (w) {\n w.destroyed = true\n }\n if (r) {\n r.destroyed = true\n }\n\n // If still constructing then defer calling _destroy.\n if (!s.constructed) {\n this.once(kDestroy, function (er) {\n _destroy(this, aggregateTwoErrors(er, err), cb)\n })\n } else {\n _destroy(this, err, cb)\n }\n return this\n}\nfunction _destroy(self, err, cb) {\n let called = false\n function onDestroy(err) {\n if (called) {\n return\n }\n called = true\n const r = self._readableState\n const w = self._writableState\n checkError(err, w, r)\n if (w) {\n w.closed = true\n }\n if (r) {\n r.closed = true\n }\n if (typeof cb === 'function') {\n cb(err)\n }\n if (err) {\n process.nextTick(emitErrorCloseNT, self, err)\n } else {\n process.nextTick(emitCloseNT, self)\n }\n }\n try {\n self._destroy(err || null, onDestroy)\n } catch (err) {\n onDestroy(err)\n }\n}\nfunction emitErrorCloseNT(self, err) {\n emitErrorNT(self, err)\n emitCloseNT(self)\n}\nfunction emitCloseNT(self) {\n const r = self._readableState\n const w = self._writableState\n if (w) {\n w.closeEmitted = true\n }\n if (r) {\n r.closeEmitted = true\n }\n if ((w !== null && w !== undefined && w.emitClose) || (r !== null && r !== undefined && r.emitClose)) {\n self.emit('close')\n }\n}\nfunction emitErrorNT(self, err) {\n const r = self._readableState\n const w = self._writableState\n if ((w !== null && w !== undefined && w.errorEmitted) || (r !== null && r !== undefined && r.errorEmitted)) {\n return\n }\n if (w) {\n w.errorEmitted = true\n }\n if (r) {\n r.errorEmitted = true\n }\n self.emit('error', err)\n}\nfunction undestroy() {\n const r = this._readableState\n const w = this._writableState\n if (r) {\n r.constructed = true\n r.closed = false\n r.closeEmitted = false\n r.destroyed = false\n r.errored = null\n r.errorEmitted = false\n r.reading = false\n r.ended = r.readable === false\n r.endEmitted = r.readable === false\n }\n if (w) {\n w.constructed = true\n w.destroyed = false\n w.closed = false\n w.closeEmitted = false\n w.errored = null\n w.errorEmitted = false\n w.finalCalled = false\n w.prefinished = false\n w.ended = w.writable === false\n w.ending = w.writable === false\n w.finished = w.writable === false\n }\n}\nfunction errorOrDestroy(stream, err, sync) {\n // We have tests that rely on errors being emitted\n // in the same tick, so changing this is semver major.\n // For now when you opt-in to autoDestroy we allow\n // the error to be emitted nextTick. In a future\n // semver major update we should change the default to this.\n\n const r = stream._readableState\n const w = stream._writableState\n if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) {\n return this\n }\n if ((r !== null && r !== undefined && r.autoDestroy) || (w !== null && w !== undefined && w.autoDestroy))\n stream.destroy(err)\n else if (err) {\n // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364\n err.stack // eslint-disable-line no-unused-expressions\n\n if (w && !w.errored) {\n w.errored = err\n }\n if (r && !r.errored) {\n r.errored = err\n }\n if (sync) {\n process.nextTick(emitErrorNT, stream, err)\n } else {\n emitErrorNT(stream, err)\n }\n }\n}\nfunction construct(stream, cb) {\n if (typeof stream._construct !== 'function') {\n return\n }\n const r = stream._readableState\n const w = stream._writableState\n if (r) {\n r.constructed = false\n }\n if (w) {\n w.constructed = false\n }\n stream.once(kConstruct, cb)\n if (stream.listenerCount(kConstruct) > 1) {\n // Duplex\n return\n }\n process.nextTick(constructNT, stream)\n}\nfunction constructNT(stream) {\n let called = false\n function onConstruct(err) {\n if (called) {\n errorOrDestroy(stream, err !== null && err !== undefined ? err : new ERR_MULTIPLE_CALLBACK())\n return\n }\n called = true\n const r = stream._readableState\n const w = stream._writableState\n const s = w || r\n if (r) {\n r.constructed = true\n }\n if (w) {\n w.constructed = true\n }\n if (s.destroyed) {\n stream.emit(kDestroy, err)\n } else if (err) {\n errorOrDestroy(stream, err, true)\n } else {\n process.nextTick(emitConstructNT, stream)\n }\n }\n try {\n stream._construct((err) => {\n process.nextTick(onConstruct, err)\n })\n } catch (err) {\n process.nextTick(onConstruct, err)\n }\n}\nfunction emitConstructNT(stream) {\n stream.emit(kConstruct)\n}\nfunction isRequest(stream) {\n return (stream === null || stream === undefined ? undefined : stream.setHeader) && typeof stream.abort === 'function'\n}\nfunction emitCloseLegacy(stream) {\n stream.emit('close')\n}\nfunction emitErrorCloseLegacy(stream, err) {\n stream.emit('error', err)\n process.nextTick(emitCloseLegacy, stream)\n}\n\n// Normalize destroy for legacy.\nfunction destroyer(stream, err) {\n if (!stream || isDestroyed(stream)) {\n return\n }\n if (!err && !isFinished(stream)) {\n err = new AbortError()\n }\n\n // TODO: Remove isRequest branches.\n if (isServerRequest(stream)) {\n stream.socket = null\n stream.destroy(err)\n } else if (isRequest(stream)) {\n stream.abort()\n } else if (isRequest(stream.req)) {\n stream.req.abort()\n } else if (typeof stream.destroy === 'function') {\n stream.destroy(err)\n } else if (typeof stream.close === 'function') {\n // TODO: Don't lose err?\n stream.close()\n } else if (err) {\n process.nextTick(emitErrorCloseLegacy, stream, err)\n } else {\n process.nextTick(emitCloseLegacy, stream)\n }\n if (!stream.destroyed) {\n stream[kIsDestroyed] = true\n }\n}\nmodule.exports = {\n construct,\n destroyer,\n destroy,\n undestroy,\n errorOrDestroy\n}\n","'use strict'\n\nconst { ArrayIsArray, ObjectSetPrototypeOf } = require('../../ours/primordials')\nconst { EventEmitter: EE } = require('events')\nfunction Stream(opts) {\n EE.call(this, opts)\n}\nObjectSetPrototypeOf(Stream.prototype, EE.prototype)\nObjectSetPrototypeOf(Stream, EE)\nStream.prototype.pipe = function (dest, options) {\n const source = this\n function ondata(chunk) {\n if (dest.writable && dest.write(chunk) === false && source.pause) {\n source.pause()\n }\n }\n source.on('data', ondata)\n function ondrain() {\n if (source.readable && source.resume) {\n source.resume()\n }\n }\n dest.on('drain', ondrain)\n\n // If the 'end' option is not supplied, dest.end() will be called when\n // source gets the 'end' or 'close' events. Only dest.end() once.\n if (!dest._isStdio && (!options || options.end !== false)) {\n source.on('end', onend)\n source.on('close', onclose)\n }\n let didOnEnd = false\n function onend() {\n if (didOnEnd) return\n didOnEnd = true\n dest.end()\n }\n function onclose() {\n if (didOnEnd) return\n didOnEnd = true\n if (typeof dest.destroy === 'function') dest.destroy()\n }\n\n // Don't leave dangling pipes when there are errors.\n function onerror(er) {\n cleanup()\n if (EE.listenerCount(this, 'error') === 0) {\n this.emit('error', er)\n }\n }\n prependListener(source, 'error', onerror)\n prependListener(dest, 'error', onerror)\n\n // Remove all the event listeners that were added.\n function cleanup() {\n source.removeListener('data', ondata)\n dest.removeListener('drain', ondrain)\n source.removeListener('end', onend)\n source.removeListener('close', onclose)\n source.removeListener('error', onerror)\n dest.removeListener('error', onerror)\n source.removeListener('end', cleanup)\n source.removeListener('close', cleanup)\n dest.removeListener('close', cleanup)\n }\n source.on('end', cleanup)\n source.on('close', cleanup)\n dest.on('close', cleanup)\n dest.emit('pipe', source)\n\n // Allow for unix-like usage: A.pipe(B).pipe(C)\n return dest\n}\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn)\n\n // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n if (!emitter._events || !emitter._events[event]) emitter.on(event, fn)\n else if (ArrayIsArray(emitter._events[event])) emitter._events[event].unshift(fn)\n else emitter._events[event] = [fn, emitter._events[event]]\n}\nmodule.exports = {\n Stream,\n prependListener\n}\n","'use strict'\n\nconst { SymbolDispose } = require('../../ours/primordials')\nconst { AbortError, codes } = require('../../ours/errors')\nconst { isNodeStream, isWebStream, kControllerErrorFunction } = require('./utils')\nconst eos = require('./end-of-stream')\nconst { ERR_INVALID_ARG_TYPE } = codes\nlet addAbortListener\n\n// This method is inlined here for readable-stream\n// It also does not allow for signal to not exist on the stream\n// https://github.com/nodejs/node/pull/36061#discussion_r533718029\nconst validateAbortSignal = (signal, name) => {\n if (typeof signal !== 'object' || !('aborted' in signal)) {\n throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal)\n }\n}\nmodule.exports.addAbortSignal = function addAbortSignal(signal, stream) {\n validateAbortSignal(signal, 'signal')\n if (!isNodeStream(stream) && !isWebStream(stream)) {\n throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream)\n }\n return module.exports.addAbortSignalNoValidate(signal, stream)\n}\nmodule.exports.addAbortSignalNoValidate = function (signal, stream) {\n if (typeof signal !== 'object' || !('aborted' in signal)) {\n return stream\n }\n const onAbort = isNodeStream(stream)\n ? () => {\n stream.destroy(\n new AbortError(undefined, {\n cause: signal.reason\n })\n )\n }\n : () => {\n stream[kControllerErrorFunction](\n new AbortError(undefined, {\n cause: signal.reason\n })\n )\n }\n if (signal.aborted) {\n onAbort()\n } else {\n addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n const disposable = addAbortListener(signal, onAbort)\n eos(stream, disposable[SymbolDispose])\n }\n return stream\n}\n","'use strict'\n\nconst { StringPrototypeSlice, SymbolIterator, TypedArrayPrototypeSet, Uint8Array } = require('../../ours/primordials')\nconst { Buffer } = require('buffer')\nconst { inspect } = require('../../ours/util')\nmodule.exports = class BufferList {\n constructor() {\n this.head = null\n this.tail = null\n this.length = 0\n }\n push(v) {\n const entry = {\n data: v,\n next: null\n }\n if (this.length > 0) this.tail.next = entry\n else this.head = entry\n this.tail = entry\n ++this.length\n }\n unshift(v) {\n const entry = {\n data: v,\n next: this.head\n }\n if (this.length === 0) this.tail = entry\n this.head = entry\n ++this.length\n }\n shift() {\n if (this.length === 0) return\n const ret = this.head.data\n if (this.length === 1) this.head = this.tail = null\n else this.head = this.head.next\n --this.length\n return ret\n }\n clear() {\n this.head = this.tail = null\n this.length = 0\n }\n join(s) {\n if (this.length === 0) return ''\n let p = this.head\n let ret = '' + p.data\n while ((p = p.next) !== null) ret += s + p.data\n return ret\n }\n concat(n) {\n if (this.length === 0) return Buffer.alloc(0)\n const ret = Buffer.allocUnsafe(n >>> 0)\n let p = this.head\n let i = 0\n while (p) {\n TypedArrayPrototypeSet(ret, p.data, i)\n i += p.data.length\n p = p.next\n }\n return ret\n }\n\n // Consumes a specified amount of bytes or characters from the buffered data.\n consume(n, hasStrings) {\n const data = this.head.data\n if (n < data.length) {\n // `slice` is the same for buffers and strings.\n const slice = data.slice(0, n)\n this.head.data = data.slice(n)\n return slice\n }\n if (n === data.length) {\n // First chunk is a perfect match.\n return this.shift()\n }\n // Result spans more than one buffer.\n return hasStrings ? this._getString(n) : this._getBuffer(n)\n }\n first() {\n return this.head.data\n }\n *[SymbolIterator]() {\n for (let p = this.head; p; p = p.next) {\n yield p.data\n }\n }\n\n // Consumes a specified amount of characters from the buffered data.\n _getString(n) {\n let ret = ''\n let p = this.head\n let c = 0\n do {\n const str = p.data\n if (n > str.length) {\n ret += str\n n -= str.length\n } else {\n if (n === str.length) {\n ret += str\n ++c\n if (p.next) this.head = p.next\n else this.head = this.tail = null\n } else {\n ret += StringPrototypeSlice(str, 0, n)\n this.head = p\n p.data = StringPrototypeSlice(str, n)\n }\n break\n }\n ++c\n } while ((p = p.next) !== null)\n this.length -= c\n return ret\n }\n\n // Consumes a specified amount of bytes from the buffered data.\n _getBuffer(n) {\n const ret = Buffer.allocUnsafe(n)\n const retLen = n\n let p = this.head\n let c = 0\n do {\n const buf = p.data\n if (n > buf.length) {\n TypedArrayPrototypeSet(ret, buf, retLen - n)\n n -= buf.length\n } else {\n if (n === buf.length) {\n TypedArrayPrototypeSet(ret, buf, retLen - n)\n ++c\n if (p.next) this.head = p.next\n else this.head = this.tail = null\n } else {\n TypedArrayPrototypeSet(ret, new Uint8Array(buf.buffer, buf.byteOffset, n), retLen - n)\n this.head = p\n p.data = buf.slice(n)\n }\n break\n }\n ++c\n } while ((p = p.next) !== null)\n this.length -= c\n return ret\n }\n\n // Make sure the linked list only shows the minimal necessary information.\n [Symbol.for('nodejs.util.inspect.custom')](_, options) {\n return inspect(this, {\n ...options,\n // Only inspect one level.\n depth: 0,\n // It should not recurse.\n customInspect: false\n })\n }\n}\n","'use strict'\n\nconst { MathFloor, NumberIsInteger } = require('../../ours/primordials')\nconst { validateInteger } = require('../validators')\nconst { ERR_INVALID_ARG_VALUE } = require('../../ours/errors').codes\nlet defaultHighWaterMarkBytes = 16 * 1024\nlet defaultHighWaterMarkObjectMode = 16\nfunction highWaterMarkFrom(options, isDuplex, duplexKey) {\n return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null\n}\nfunction getDefaultHighWaterMark(objectMode) {\n return objectMode ? defaultHighWaterMarkObjectMode : defaultHighWaterMarkBytes\n}\nfunction setDefaultHighWaterMark(objectMode, value) {\n validateInteger(value, 'value', 0)\n if (objectMode) {\n defaultHighWaterMarkObjectMode = value\n } else {\n defaultHighWaterMarkBytes = value\n }\n}\nfunction getHighWaterMark(state, options, duplexKey, isDuplex) {\n const hwm = highWaterMarkFrom(options, isDuplex, duplexKey)\n if (hwm != null) {\n if (!NumberIsInteger(hwm) || hwm < 0) {\n const name = isDuplex ? `options.${duplexKey}` : 'options.highWaterMark'\n throw new ERR_INVALID_ARG_VALUE(name, hwm)\n }\n return MathFloor(hwm)\n }\n\n // Default value\n return getDefaultHighWaterMark(state.objectMode)\n}\nmodule.exports = {\n getHighWaterMark,\n getDefaultHighWaterMark,\n setDefaultHighWaterMark\n}\n","/*! safe-buffer. MIT License. Feross Aboukhadijeh */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}","'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } = require('../../ours/primordials')\nconst { Buffer } = require('buffer')\nconst { ERR_INVALID_ARG_TYPE, ERR_STREAM_NULL_VALUES } = require('../../ours/errors').codes\nfunction from(Readable, iterable, opts) {\n let iterator\n if (typeof iterable === 'string' || iterable instanceof Buffer) {\n return new Readable({\n objectMode: true,\n ...opts,\n read() {\n this.push(iterable)\n this.push(null)\n }\n })\n }\n let isAsync\n if (iterable && iterable[SymbolAsyncIterator]) {\n isAsync = true\n iterator = iterable[SymbolAsyncIterator]()\n } else if (iterable && iterable[SymbolIterator]) {\n isAsync = false\n iterator = iterable[SymbolIterator]()\n } else {\n throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable)\n }\n const readable = new Readable({\n objectMode: true,\n highWaterMark: 1,\n // TODO(ronag): What options should be allowed?\n ...opts\n })\n\n // Flag to protect against _read\n // being called before last iteration completion.\n let reading = false\n readable._read = function () {\n if (!reading) {\n reading = true\n next()\n }\n }\n readable._destroy = function (error, cb) {\n PromisePrototypeThen(\n close(error),\n () => process.nextTick(cb, error),\n // nextTick is here in case cb throws\n (e) => process.nextTick(cb, e || error)\n )\n }\n async function close(error) {\n const hadError = error !== undefined && error !== null\n const hasThrow = typeof iterator.throw === 'function'\n if (hadError && hasThrow) {\n const { value, done } = await iterator.throw(error)\n await value\n if (done) {\n return\n }\n }\n if (typeof iterator.return === 'function') {\n const { value } = await iterator.return()\n await value\n }\n }\n async function next() {\n for (;;) {\n try {\n const { value, done } = isAsync ? await iterator.next() : iterator.next()\n if (done) {\n readable.push(null)\n } else {\n const res = value && typeof value.then === 'function' ? await value : value\n if (res === null) {\n reading = false\n throw new ERR_STREAM_NULL_VALUES()\n } else if (readable.push(res)) {\n continue\n } else {\n reading = false\n }\n }\n } catch (err) {\n readable.destroy(err)\n }\n break\n }\n }\n return readable\n}\nmodule.exports = from\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst {\n ArrayPrototypeIndexOf,\n NumberIsInteger,\n NumberIsNaN,\n NumberParseInt,\n ObjectDefineProperties,\n ObjectKeys,\n ObjectSetPrototypeOf,\n Promise,\n SafeSet,\n SymbolAsyncDispose,\n SymbolAsyncIterator,\n Symbol\n} = require('../../ours/primordials')\nmodule.exports = Readable\nReadable.ReadableState = ReadableState\nconst { EventEmitter: EE } = require('events')\nconst { Stream, prependListener } = require('./legacy')\nconst { Buffer } = require('buffer')\nconst { addAbortSignal } = require('./add-abort-signal')\nconst eos = require('./end-of-stream')\nlet debug = require('../../ours/util').debuglog('stream', (fn) => {\n debug = fn\n})\nconst BufferList = require('./buffer_list')\nconst destroyImpl = require('./destroy')\nconst { getHighWaterMark, getDefaultHighWaterMark } = require('./state')\nconst {\n aggregateTwoErrors,\n codes: {\n ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED,\n ERR_OUT_OF_RANGE,\n ERR_STREAM_PUSH_AFTER_EOF,\n ERR_STREAM_UNSHIFT_AFTER_END_EVENT\n },\n AbortError\n} = require('../../ours/errors')\nconst { validateObject } = require('../validators')\nconst kPaused = Symbol('kPaused')\nconst { StringDecoder } = require('string_decoder/')\nconst from = require('./from')\nObjectSetPrototypeOf(Readable.prototype, Stream.prototype)\nObjectSetPrototypeOf(Readable, Stream)\nconst nop = () => {}\nconst { errorOrDestroy } = destroyImpl\nconst kObjectMode = 1 << 0\nconst kEnded = 1 << 1\nconst kEndEmitted = 1 << 2\nconst kReading = 1 << 3\nconst kConstructed = 1 << 4\nconst kSync = 1 << 5\nconst kNeedReadable = 1 << 6\nconst kEmittedReadable = 1 << 7\nconst kReadableListening = 1 << 8\nconst kResumeScheduled = 1 << 9\nconst kErrorEmitted = 1 << 10\nconst kEmitClose = 1 << 11\nconst kAutoDestroy = 1 << 12\nconst kDestroyed = 1 << 13\nconst kClosed = 1 << 14\nconst kCloseEmitted = 1 << 15\nconst kMultiAwaitDrain = 1 << 16\nconst kReadingMore = 1 << 17\nconst kDataEmitted = 1 << 18\n\n// TODO(benjamingr) it is likely slower to do it this way than with free functions\nfunction makeBitMapDescriptor(bit) {\n return {\n enumerable: false,\n get() {\n return (this.state & bit) !== 0\n },\n set(value) {\n if (value) this.state |= bit\n else this.state &= ~bit\n }\n }\n}\nObjectDefineProperties(ReadableState.prototype, {\n objectMode: makeBitMapDescriptor(kObjectMode),\n ended: makeBitMapDescriptor(kEnded),\n endEmitted: makeBitMapDescriptor(kEndEmitted),\n reading: makeBitMapDescriptor(kReading),\n // Stream is still being constructed and cannot be\n // destroyed until construction finished or failed.\n // Async construction is opt in, therefore we start as\n // constructed.\n constructed: makeBitMapDescriptor(kConstructed),\n // A flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n sync: makeBitMapDescriptor(kSync),\n // Whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n needReadable: makeBitMapDescriptor(kNeedReadable),\n emittedReadable: makeBitMapDescriptor(kEmittedReadable),\n readableListening: makeBitMapDescriptor(kReadableListening),\n resumeScheduled: makeBitMapDescriptor(kResumeScheduled),\n // True if the error was already emitted and should not be thrown again.\n errorEmitted: makeBitMapDescriptor(kErrorEmitted),\n emitClose: makeBitMapDescriptor(kEmitClose),\n autoDestroy: makeBitMapDescriptor(kAutoDestroy),\n // Has it been destroyed.\n destroyed: makeBitMapDescriptor(kDestroyed),\n // Indicates whether the stream has finished destroying.\n closed: makeBitMapDescriptor(kClosed),\n // True if close has been emitted or would have been emitted\n // depending on emitClose.\n closeEmitted: makeBitMapDescriptor(kCloseEmitted),\n multiAwaitDrain: makeBitMapDescriptor(kMultiAwaitDrain),\n // If true, a maybeReadMore has been scheduled.\n readingMore: makeBitMapDescriptor(kReadingMore),\n dataEmitted: makeBitMapDescriptor(kDataEmitted)\n})\nfunction ReadableState(options, stream, isDuplex) {\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof require('./duplex')\n\n // Bit map field to store ReadableState more effciently with 1 bit per field\n // instead of a V8 slot per field.\n this.state = kEmitClose | kAutoDestroy | kConstructed | kSync\n // Object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away.\n if (options && options.objectMode) this.state |= kObjectMode\n if (isDuplex && options && options.readableObjectMode) this.state |= kObjectMode\n\n // The point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n this.highWaterMark = options\n ? getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex)\n : getDefaultHighWaterMark(false)\n\n // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift().\n this.buffer = new BufferList()\n this.length = 0\n this.pipes = []\n this.flowing = null\n this[kPaused] = null\n\n // Should close be emitted on destroy. Defaults to true.\n if (options && options.emitClose === false) this.state &= ~kEmitClose\n\n // Should .destroy() be called after 'end' (and potentially 'finish').\n if (options && options.autoDestroy === false) this.state &= ~kAutoDestroy\n\n // Indicates whether the stream has errored. When true no further\n // _read calls, 'data' or 'readable' events should occur. This is needed\n // since when autoDestroy is disabled we need a way to tell whether the\n // stream has failed.\n this.errored = null\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = (options && options.defaultEncoding) || 'utf8'\n\n // Ref the piped dest which we need a drain event on it\n // type: null | Writable | Set.\n this.awaitDrainWriters = null\n this.decoder = null\n this.encoding = null\n if (options && options.encoding) {\n this.decoder = new StringDecoder(options.encoding)\n this.encoding = options.encoding\n }\n}\nfunction Readable(options) {\n if (!(this instanceof Readable)) return new Readable(options)\n\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the ReadableState constructor, at least with V8 6.5.\n const isDuplex = this instanceof require('./duplex')\n this._readableState = new ReadableState(options, this, isDuplex)\n if (options) {\n if (typeof options.read === 'function') this._read = options.read\n if (typeof options.destroy === 'function') this._destroy = options.destroy\n if (typeof options.construct === 'function') this._construct = options.construct\n if (options.signal && !isDuplex) addAbortSignal(options.signal, this)\n }\n Stream.call(this, options)\n destroyImpl.construct(this, () => {\n if (this._readableState.needReadable) {\n maybeReadMore(this, this._readableState)\n }\n })\n}\nReadable.prototype.destroy = destroyImpl.destroy\nReadable.prototype._undestroy = destroyImpl.undestroy\nReadable.prototype._destroy = function (err, cb) {\n cb(err)\n}\nReadable.prototype[EE.captureRejectionSymbol] = function (err) {\n this.destroy(err)\n}\nReadable.prototype[SymbolAsyncDispose] = function () {\n let error\n if (!this.destroyed) {\n error = this.readableEnded ? null : new AbortError()\n this.destroy(error)\n }\n return new Promise((resolve, reject) => eos(this, (err) => (err && err !== error ? reject(err) : resolve(null))))\n}\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n return readableAddChunk(this, chunk, encoding, false)\n}\n\n// Unshift should *always* be something directly out of read().\nReadable.prototype.unshift = function (chunk, encoding) {\n return readableAddChunk(this, chunk, encoding, true)\n}\nfunction readableAddChunk(stream, chunk, encoding, addToFront) {\n debug('readableAddChunk', chunk)\n const state = stream._readableState\n let err\n if ((state.state & kObjectMode) === 0) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding\n if (state.encoding !== encoding) {\n if (addToFront && state.encoding) {\n // When unshifting, if state.encoding is set, we have to save\n // the string in the BufferList with the state encoding.\n chunk = Buffer.from(chunk, encoding).toString(state.encoding)\n } else {\n chunk = Buffer.from(chunk, encoding)\n encoding = ''\n }\n }\n } else if (chunk instanceof Buffer) {\n encoding = ''\n } else if (Stream._isUint8Array(chunk)) {\n chunk = Stream._uint8ArrayToBuffer(chunk)\n encoding = ''\n } else if (chunk != null) {\n err = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk)\n }\n }\n if (err) {\n errorOrDestroy(stream, err)\n } else if (chunk === null) {\n state.state &= ~kReading\n onEofChunk(stream, state)\n } else if ((state.state & kObjectMode) !== 0 || (chunk && chunk.length > 0)) {\n if (addToFront) {\n if ((state.state & kEndEmitted) !== 0) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT())\n else if (state.destroyed || state.errored) return false\n else addChunk(stream, state, chunk, true)\n } else if (state.ended) {\n errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF())\n } else if (state.destroyed || state.errored) {\n return false\n } else {\n state.state &= ~kReading\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk)\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false)\n else maybeReadMore(stream, state)\n } else {\n addChunk(stream, state, chunk, false)\n }\n }\n } else if (!addToFront) {\n state.state &= ~kReading\n maybeReadMore(stream, state)\n }\n\n // We can push more data if we are below the highWaterMark.\n // Also, if we have no data yet, we can stand some more bytes.\n // This is to work around cases where hwm=0, such as the repl.\n return !state.ended && (state.length < state.highWaterMark || state.length === 0)\n}\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync && stream.listenerCount('data') > 0) {\n // Use the guard to avoid creating `Set()` repeatedly\n // when we have multiple pipes.\n if ((state.state & kMultiAwaitDrain) !== 0) {\n state.awaitDrainWriters.clear()\n } else {\n state.awaitDrainWriters = null\n }\n state.dataEmitted = true\n stream.emit('data', chunk)\n } else {\n // Update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length\n if (addToFront) state.buffer.unshift(chunk)\n else state.buffer.push(chunk)\n if ((state.state & kNeedReadable) !== 0) emitReadable(stream)\n }\n maybeReadMore(stream, state)\n}\nReadable.prototype.isPaused = function () {\n const state = this._readableState\n return state[kPaused] === true || state.flowing === false\n}\n\n// Backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n const decoder = new StringDecoder(enc)\n this._readableState.decoder = decoder\n // If setEncoding(null), decoder.encoding equals utf8.\n this._readableState.encoding = this._readableState.decoder.encoding\n const buffer = this._readableState.buffer\n // Iterate over current buffer to convert already stored Buffers:\n let content = ''\n for (const data of buffer) {\n content += decoder.write(data)\n }\n buffer.clear()\n if (content !== '') buffer.push(content)\n this._readableState.length = content.length\n return this\n}\n\n// Don't raise the hwm > 1GB.\nconst MAX_HWM = 0x40000000\nfunction computeNewHighWaterMark(n) {\n if (n > MAX_HWM) {\n throw new ERR_OUT_OF_RANGE('size', '<= 1GiB', n)\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts.\n n--\n n |= n >>> 1\n n |= n >>> 2\n n |= n >>> 4\n n |= n >>> 8\n n |= n >>> 16\n n++\n }\n return n\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n if (n <= 0 || (state.length === 0 && state.ended)) return 0\n if ((state.state & kObjectMode) !== 0) return 1\n if (NumberIsNaN(n)) {\n // Only flow one buffer at a time.\n if (state.flowing && state.length) return state.buffer.first().length\n return state.length\n }\n if (n <= state.length) return n\n return state.ended ? state.length : 0\n}\n\n// You can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n debug('read', n)\n // Same as parseInt(undefined, 10), however V8 7.3 performance regressed\n // in this scenario, so we are doing it manually.\n if (n === undefined) {\n n = NaN\n } else if (!NumberIsInteger(n)) {\n n = NumberParseInt(n, 10)\n }\n const state = this._readableState\n const nOrig = n\n\n // If we're asking for more than the current hwm, then raise the hwm.\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n)\n if (n !== 0) state.state &= ~kEmittedReadable\n\n // If we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (\n n === 0 &&\n state.needReadable &&\n ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)\n ) {\n debug('read: emitReadable', state.length, state.ended)\n if (state.length === 0 && state.ended) endReadable(this)\n else emitReadable(this)\n return null\n }\n n = howMuchToRead(n, state)\n\n // If we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this)\n return null\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n let doRead = (state.state & kNeedReadable) !== 0\n debug('need readable', doRead)\n\n // If we currently have less than the highWaterMark, then also read some.\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true\n debug('length less than watermark', doRead)\n }\n\n // However, if we've ended, then there's no point, if we're already\n // reading, then it's unnecessary, if we're constructing we have to wait,\n // and if we're destroyed or errored, then it's not allowed,\n if (state.ended || state.reading || state.destroyed || state.errored || !state.constructed) {\n doRead = false\n debug('reading, ended or constructing', doRead)\n } else if (doRead) {\n debug('do read')\n state.state |= kReading | kSync\n // If the length is currently zero, then we *need* a readable event.\n if (state.length === 0) state.state |= kNeedReadable\n\n // Call internal read method\n try {\n this._read(state.highWaterMark)\n } catch (err) {\n errorOrDestroy(this, err)\n }\n state.state &= ~kSync\n\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (!state.reading) n = howMuchToRead(nOrig, state)\n }\n let ret\n if (n > 0) ret = fromList(n, state)\n else ret = null\n if (ret === null) {\n state.needReadable = state.length <= state.highWaterMark\n n = 0\n } else {\n state.length -= n\n if (state.multiAwaitDrain) {\n state.awaitDrainWriters.clear()\n } else {\n state.awaitDrainWriters = null\n }\n }\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended) endReadable(this)\n }\n if (ret !== null && !state.errorEmitted && !state.closeEmitted) {\n state.dataEmitted = true\n this.emit('data', ret)\n }\n return ret\n}\nfunction onEofChunk(stream, state) {\n debug('onEofChunk')\n if (state.ended) return\n if (state.decoder) {\n const chunk = state.decoder.end()\n if (chunk && chunk.length) {\n state.buffer.push(chunk)\n state.length += state.objectMode ? 1 : chunk.length\n }\n }\n state.ended = true\n if (state.sync) {\n // If we are sync, wait until next tick to emit the data.\n // Otherwise we risk emitting data in the flow()\n // the readable code triggers during a read() call.\n emitReadable(stream)\n } else {\n // Emit 'readable' now to make sure it gets picked up.\n state.needReadable = false\n state.emittedReadable = true\n // We have to emit readable now that we are EOF. Modules\n // in the ecosystem (e.g. dicer) rely on this event being sync.\n emitReadable_(stream)\n }\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n const state = stream._readableState\n debug('emitReadable', state.needReadable, state.emittedReadable)\n state.needReadable = false\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing)\n state.emittedReadable = true\n process.nextTick(emitReadable_, stream)\n }\n}\nfunction emitReadable_(stream) {\n const state = stream._readableState\n debug('emitReadable_', state.destroyed, state.length, state.ended)\n if (!state.destroyed && !state.errored && (state.length || state.ended)) {\n stream.emit('readable')\n state.emittedReadable = false\n }\n\n // The stream needs another readable event if:\n // 1. It is not flowing, as the flow mechanism will take\n // care of it.\n // 2. It is not ended.\n // 3. It is below the highWaterMark, so we can schedule\n // another readable later.\n state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark\n flow(stream)\n}\n\n// At this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore && state.constructed) {\n state.readingMore = true\n process.nextTick(maybeReadMore_, stream, state)\n }\n}\nfunction maybeReadMore_(stream, state) {\n // Attempt to read more data if we should.\n //\n // The conditions for reading more data are (one of):\n // - Not enough data buffered (state.length < state.highWaterMark). The loop\n // is responsible for filling the buffer with enough data if such data\n // is available. If highWaterMark is 0 and we are not in the flowing mode\n // we should _not_ attempt to buffer any extra data. We'll get more data\n // when the stream consumer calls read() instead.\n // - No data in the buffer, and the stream is in flowing mode. In this mode\n // the loop below is responsible for ensuring read() is called. Failing to\n // call read here would abort the flow and there's no other mechanism for\n // continuing the flow if the stream consumer has just subscribed to the\n // 'data' event.\n //\n // In addition to the above conditions to keep reading data, the following\n // conditions prevent the data from being read:\n // - The stream has ended (state.ended).\n // - There is already a pending 'read' operation (state.reading). This is a\n // case where the stream has called the implementation defined _read()\n // method, but they are processing the call asynchronously and have _not_\n // called push() with new data. In this case we skip performing more\n // read()s. The execution ends in this method again after the _read() ends\n // up calling push() with more data.\n while (\n !state.reading &&\n !state.ended &&\n (state.length < state.highWaterMark || (state.flowing && state.length === 0))\n ) {\n const len = state.length\n debug('maybeReadMore read 0')\n stream.read(0)\n if (len === state.length)\n // Didn't get any data, stop spinning.\n break\n }\n state.readingMore = false\n}\n\n// Abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n throw new ERR_METHOD_NOT_IMPLEMENTED('_read()')\n}\nReadable.prototype.pipe = function (dest, pipeOpts) {\n const src = this\n const state = this._readableState\n if (state.pipes.length === 1) {\n if (!state.multiAwaitDrain) {\n state.multiAwaitDrain = true\n state.awaitDrainWriters = new SafeSet(state.awaitDrainWriters ? [state.awaitDrainWriters] : [])\n }\n }\n state.pipes.push(dest)\n debug('pipe count=%d opts=%j', state.pipes.length, pipeOpts)\n const doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr\n const endFn = doEnd ? onend : unpipe\n if (state.endEmitted) process.nextTick(endFn)\n else src.once('end', endFn)\n dest.on('unpipe', onunpipe)\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe')\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true\n cleanup()\n }\n }\n }\n function onend() {\n debug('onend')\n dest.end()\n }\n let ondrain\n let cleanedUp = false\n function cleanup() {\n debug('cleanup')\n // Cleanup event handlers once the pipe is broken.\n dest.removeListener('close', onclose)\n dest.removeListener('finish', onfinish)\n if (ondrain) {\n dest.removeListener('drain', ondrain)\n }\n dest.removeListener('error', onerror)\n dest.removeListener('unpipe', onunpipe)\n src.removeListener('end', onend)\n src.removeListener('end', unpipe)\n src.removeListener('data', ondata)\n cleanedUp = true\n\n // If the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (ondrain && state.awaitDrainWriters && (!dest._writableState || dest._writableState.needDrain)) ondrain()\n }\n function pause() {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if (!cleanedUp) {\n if (state.pipes.length === 1 && state.pipes[0] === dest) {\n debug('false write response, pause', 0)\n state.awaitDrainWriters = dest\n state.multiAwaitDrain = false\n } else if (state.pipes.length > 1 && state.pipes.includes(dest)) {\n debug('false write response, pause', state.awaitDrainWriters.size)\n state.awaitDrainWriters.add(dest)\n }\n src.pause()\n }\n if (!ondrain) {\n // When the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n ondrain = pipeOnDrain(src, dest)\n dest.on('drain', ondrain)\n }\n }\n src.on('data', ondata)\n function ondata(chunk) {\n debug('ondata')\n const ret = dest.write(chunk)\n debug('dest.write', ret)\n if (ret === false) {\n pause()\n }\n }\n\n // If the dest has an error, then stop piping into it.\n // However, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er)\n unpipe()\n dest.removeListener('error', onerror)\n if (dest.listenerCount('error') === 0) {\n const s = dest._writableState || dest._readableState\n if (s && !s.errorEmitted) {\n // User incorrectly emitted 'error' directly on the stream.\n errorOrDestroy(dest, er)\n } else {\n dest.emit('error', er)\n }\n }\n }\n\n // Make sure our error handler is attached before userland ones.\n prependListener(dest, 'error', onerror)\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish)\n unpipe()\n }\n dest.once('close', onclose)\n function onfinish() {\n debug('onfinish')\n dest.removeListener('close', onclose)\n unpipe()\n }\n dest.once('finish', onfinish)\n function unpipe() {\n debug('unpipe')\n src.unpipe(dest)\n }\n\n // Tell the dest that it's being piped to.\n dest.emit('pipe', src)\n\n // Start the flow if it hasn't been started already.\n\n if (dest.writableNeedDrain === true) {\n pause()\n } else if (!state.flowing) {\n debug('pipe resume')\n src.resume()\n }\n return dest\n}\nfunction pipeOnDrain(src, dest) {\n return function pipeOnDrainFunctionResult() {\n const state = src._readableState\n\n // `ondrain` will call directly,\n // `this` maybe not a reference to dest,\n // so we use the real dest here.\n if (state.awaitDrainWriters === dest) {\n debug('pipeOnDrain', 1)\n state.awaitDrainWriters = null\n } else if (state.multiAwaitDrain) {\n debug('pipeOnDrain', state.awaitDrainWriters.size)\n state.awaitDrainWriters.delete(dest)\n }\n if ((!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) && src.listenerCount('data')) {\n src.resume()\n }\n }\n}\nReadable.prototype.unpipe = function (dest) {\n const state = this._readableState\n const unpipeInfo = {\n hasUnpiped: false\n }\n\n // If we're not piping anywhere, then do nothing.\n if (state.pipes.length === 0) return this\n if (!dest) {\n // remove all.\n const dests = state.pipes\n state.pipes = []\n this.pause()\n for (let i = 0; i < dests.length; i++)\n dests[i].emit('unpipe', this, {\n hasUnpiped: false\n })\n return this\n }\n\n // Try to find the right one.\n const index = ArrayPrototypeIndexOf(state.pipes, dest)\n if (index === -1) return this\n state.pipes.splice(index, 1)\n if (state.pipes.length === 0) this.pause()\n dest.emit('unpipe', this, unpipeInfo)\n return this\n}\n\n// Set up data events if they are asked for\n// Ensure readable listeners eventually get something.\nReadable.prototype.on = function (ev, fn) {\n const res = Stream.prototype.on.call(this, ev, fn)\n const state = this._readableState\n if (ev === 'data') {\n // Update readableListening so that resume() may be a no-op\n // a few lines down. This is needed to support once('readable').\n state.readableListening = this.listenerCount('readable') > 0\n\n // Try start flowing on next tick if stream isn't explicitly paused.\n if (state.flowing !== false) this.resume()\n } else if (ev === 'readable') {\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true\n state.flowing = false\n state.emittedReadable = false\n debug('on readable', state.length, state.reading)\n if (state.length) {\n emitReadable(this)\n } else if (!state.reading) {\n process.nextTick(nReadingNextTick, this)\n }\n }\n }\n return res\n}\nReadable.prototype.addListener = Readable.prototype.on\nReadable.prototype.removeListener = function (ev, fn) {\n const res = Stream.prototype.removeListener.call(this, ev, fn)\n if (ev === 'readable') {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this)\n }\n return res\n}\nReadable.prototype.off = Readable.prototype.removeListener\nReadable.prototype.removeAllListeners = function (ev) {\n const res = Stream.prototype.removeAllListeners.apply(this, arguments)\n if (ev === 'readable' || ev === undefined) {\n // We need to check if there is someone still listening to\n // readable and reset the state. However this needs to happen\n // after readable has been emitted but before I/O (nextTick) to\n // support once('readable', fn) cycles. This means that calling\n // resume within the same tick will have no\n // effect.\n process.nextTick(updateReadableListening, this)\n }\n return res\n}\nfunction updateReadableListening(self) {\n const state = self._readableState\n state.readableListening = self.listenerCount('readable') > 0\n if (state.resumeScheduled && state[kPaused] === false) {\n // Flowing needs to be set to true now, otherwise\n // the upcoming resume will not flow.\n state.flowing = true\n\n // Crude way to check if we should resume.\n } else if (self.listenerCount('data') > 0) {\n self.resume()\n } else if (!state.readableListening) {\n state.flowing = null\n }\n}\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0')\n self.read(0)\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n const state = this._readableState\n if (!state.flowing) {\n debug('resume')\n // We flow only if there is no one listening\n // for readable, but we still have to call\n // resume().\n state.flowing = !state.readableListening\n resume(this, state)\n }\n state[kPaused] = false\n return this\n}\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true\n process.nextTick(resume_, stream, state)\n }\n}\nfunction resume_(stream, state) {\n debug('resume', state.reading)\n if (!state.reading) {\n stream.read(0)\n }\n state.resumeScheduled = false\n stream.emit('resume')\n flow(stream)\n if (state.flowing && !state.reading) stream.read(0)\n}\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing)\n if (this._readableState.flowing !== false) {\n debug('pause')\n this._readableState.flowing = false\n this.emit('pause')\n }\n this._readableState[kPaused] = true\n return this\n}\nfunction flow(stream) {\n const state = stream._readableState\n debug('flow', state.flowing)\n while (state.flowing && stream.read() !== null);\n}\n\n// Wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n let paused = false\n\n // TODO (ronag): Should this.destroy(err) emit\n // 'error' on the wrapped stream? Would require\n // a static factory method, e.g. Readable.wrap(stream).\n\n stream.on('data', (chunk) => {\n if (!this.push(chunk) && stream.pause) {\n paused = true\n stream.pause()\n }\n })\n stream.on('end', () => {\n this.push(null)\n })\n stream.on('error', (err) => {\n errorOrDestroy(this, err)\n })\n stream.on('close', () => {\n this.destroy()\n })\n stream.on('destroy', () => {\n this.destroy()\n })\n this._read = () => {\n if (paused && stream.resume) {\n paused = false\n stream.resume()\n }\n }\n\n // Proxy all the other methods. Important when wrapping filters and duplexes.\n const streamKeys = ObjectKeys(stream)\n for (let j = 1; j < streamKeys.length; j++) {\n const i = streamKeys[j]\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = stream[i].bind(stream)\n }\n }\n return this\n}\nReadable.prototype[SymbolAsyncIterator] = function () {\n return streamToAsyncIterator(this)\n}\nReadable.prototype.iterator = function (options) {\n if (options !== undefined) {\n validateObject(options, 'options')\n }\n return streamToAsyncIterator(this, options)\n}\nfunction streamToAsyncIterator(stream, options) {\n if (typeof stream.read !== 'function') {\n stream = Readable.wrap(stream, {\n objectMode: true\n })\n }\n const iter = createAsyncIterator(stream, options)\n iter.stream = stream\n return iter\n}\nasync function* createAsyncIterator(stream, options) {\n let callback = nop\n function next(resolve) {\n if (this === stream) {\n callback()\n callback = nop\n } else {\n callback = resolve\n }\n }\n stream.on('readable', next)\n let error\n const cleanup = eos(\n stream,\n {\n writable: false\n },\n (err) => {\n error = err ? aggregateTwoErrors(error, err) : null\n callback()\n callback = nop\n }\n )\n try {\n while (true) {\n const chunk = stream.destroyed ? null : stream.read()\n if (chunk !== null) {\n yield chunk\n } else if (error) {\n throw error\n } else if (error === null) {\n return\n } else {\n await new Promise(next)\n }\n }\n } catch (err) {\n error = aggregateTwoErrors(error, err)\n throw error\n } finally {\n if (\n (error || (options === null || options === undefined ? undefined : options.destroyOnReturn) !== false) &&\n (error === undefined || stream._readableState.autoDestroy)\n ) {\n destroyImpl.destroyer(stream, null)\n } else {\n stream.off('readable', next)\n cleanup()\n }\n }\n}\n\n// Making it explicit these properties are not enumerable\n// because otherwise some prototype manipulation in\n// userland will fail.\nObjectDefineProperties(Readable.prototype, {\n readable: {\n __proto__: null,\n get() {\n const r = this._readableState\n // r.readable === false means that this is part of a Duplex stream\n // where the readable side was disabled upon construction.\n // Compat. The user might manually disable readable side through\n // deprecated setter.\n return !!r && r.readable !== false && !r.destroyed && !r.errorEmitted && !r.endEmitted\n },\n set(val) {\n // Backwards compat.\n if (this._readableState) {\n this._readableState.readable = !!val\n }\n }\n },\n readableDidRead: {\n __proto__: null,\n enumerable: false,\n get: function () {\n return this._readableState.dataEmitted\n }\n },\n readableAborted: {\n __proto__: null,\n enumerable: false,\n get: function () {\n return !!(\n this._readableState.readable !== false &&\n (this._readableState.destroyed || this._readableState.errored) &&\n !this._readableState.endEmitted\n )\n }\n },\n readableHighWaterMark: {\n __proto__: null,\n enumerable: false,\n get: function () {\n return this._readableState.highWaterMark\n }\n },\n readableBuffer: {\n __proto__: null,\n enumerable: false,\n get: function () {\n return this._readableState && this._readableState.buffer\n }\n },\n readableFlowing: {\n __proto__: null,\n enumerable: false,\n get: function () {\n return this._readableState.flowing\n },\n set: function (state) {\n if (this._readableState) {\n this._readableState.flowing = state\n }\n }\n },\n readableLength: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._readableState.length\n }\n },\n readableObjectMode: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._readableState ? this._readableState.objectMode : false\n }\n },\n readableEncoding: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._readableState ? this._readableState.encoding : null\n }\n },\n errored: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._readableState ? this._readableState.errored : null\n }\n },\n closed: {\n __proto__: null,\n get() {\n return this._readableState ? this._readableState.closed : false\n }\n },\n destroyed: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._readableState ? this._readableState.destroyed : false\n },\n set(value) {\n // We ignore the value if the stream\n // has not been initialized yet.\n if (!this._readableState) {\n return\n }\n\n // Backward compatibility, the user is explicitly\n // managing destroyed.\n this._readableState.destroyed = value\n }\n },\n readableEnded: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._readableState ? this._readableState.endEmitted : false\n }\n }\n})\nObjectDefineProperties(ReadableState.prototype, {\n // Legacy getter for `pipesCount`.\n pipesCount: {\n __proto__: null,\n get() {\n return this.pipes.length\n }\n },\n // Legacy property for `paused`.\n paused: {\n __proto__: null,\n get() {\n return this[kPaused] !== false\n },\n set(value) {\n this[kPaused] = !!value\n }\n }\n})\n\n// Exposed for testing purposes only.\nReadable._fromList = fromList\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n // nothing buffered.\n if (state.length === 0) return null\n let ret\n if (state.objectMode) ret = state.buffer.shift()\n else if (!n || n >= state.length) {\n // Read it all, truncate the list.\n if (state.decoder) ret = state.buffer.join('')\n else if (state.buffer.length === 1) ret = state.buffer.first()\n else ret = state.buffer.concat(state.length)\n state.buffer.clear()\n } else {\n // read part of list.\n ret = state.buffer.consume(n, state.decoder)\n }\n return ret\n}\nfunction endReadable(stream) {\n const state = stream._readableState\n debug('endReadable', state.endEmitted)\n if (!state.endEmitted) {\n state.ended = true\n process.nextTick(endReadableNT, state, stream)\n }\n}\nfunction endReadableNT(state, stream) {\n debug('endReadableNT', state.endEmitted, state.length)\n\n // Check that we didn't get one last unshift.\n if (!state.errored && !state.closeEmitted && !state.endEmitted && state.length === 0) {\n state.endEmitted = true\n stream.emit('end')\n if (stream.writable && stream.allowHalfOpen === false) {\n process.nextTick(endWritableNT, stream)\n } else if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the writable side is ready for autoDestroy as well.\n const wState = stream._writableState\n const autoDestroy =\n !wState ||\n (wState.autoDestroy &&\n // We don't expect the writable to ever 'finish'\n // if writable is explicitly set to false.\n (wState.finished || wState.writable === false))\n if (autoDestroy) {\n stream.destroy()\n }\n }\n }\n}\nfunction endWritableNT(stream) {\n const writable = stream.writable && !stream.writableEnded && !stream.destroyed\n if (writable) {\n stream.end()\n }\n}\nReadable.from = function (iterable, opts) {\n return from(Readable, iterable, opts)\n}\nlet webStreamsAdapters\n\n// Lazy to avoid circular references\nfunction lazyWebStreams() {\n if (webStreamsAdapters === undefined) webStreamsAdapters = {}\n return webStreamsAdapters\n}\nReadable.fromWeb = function (readableStream, options) {\n return lazyWebStreams().newStreamReadableFromReadableStream(readableStream, options)\n}\nReadable.toWeb = function (streamReadable, options) {\n return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable, options)\n}\nReadable.wrap = function (src, options) {\n var _ref, _src$readableObjectMo\n return new Readable({\n objectMode:\n (_ref =\n (_src$readableObjectMo = src.readableObjectMode) !== null && _src$readableObjectMo !== undefined\n ? _src$readableObjectMo\n : src.objectMode) !== null && _ref !== undefined\n ? _ref\n : true,\n ...options,\n destroy(err, callback) {\n destroyImpl.destroyer(src, err)\n callback(err)\n }\n }).wrap(src)\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst {\n ArrayPrototypeSlice,\n Error,\n FunctionPrototypeSymbolHasInstance,\n ObjectDefineProperty,\n ObjectDefineProperties,\n ObjectSetPrototypeOf,\n StringPrototypeToLowerCase,\n Symbol,\n SymbolHasInstance\n} = require('../../ours/primordials')\nmodule.exports = Writable\nWritable.WritableState = WritableState\nconst { EventEmitter: EE } = require('events')\nconst Stream = require('./legacy').Stream\nconst { Buffer } = require('buffer')\nconst destroyImpl = require('./destroy')\nconst { addAbortSignal } = require('./add-abort-signal')\nconst { getHighWaterMark, getDefaultHighWaterMark } = require('./state')\nconst {\n ERR_INVALID_ARG_TYPE,\n ERR_METHOD_NOT_IMPLEMENTED,\n ERR_MULTIPLE_CALLBACK,\n ERR_STREAM_CANNOT_PIPE,\n ERR_STREAM_DESTROYED,\n ERR_STREAM_ALREADY_FINISHED,\n ERR_STREAM_NULL_VALUES,\n ERR_STREAM_WRITE_AFTER_END,\n ERR_UNKNOWN_ENCODING\n} = require('../../ours/errors').codes\nconst { errorOrDestroy } = destroyImpl\nObjectSetPrototypeOf(Writable.prototype, Stream.prototype)\nObjectSetPrototypeOf(Writable, Stream)\nfunction nop() {}\nconst kOnFinished = Symbol('kOnFinished')\nfunction WritableState(options, stream, isDuplex) {\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream,\n // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof require('./duplex')\n\n // Object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!(options && options.objectMode)\n if (isDuplex) this.objectMode = this.objectMode || !!(options && options.writableObjectMode)\n\n // The point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write().\n this.highWaterMark = options\n ? getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex)\n : getDefaultHighWaterMark(false)\n\n // if _final has been called.\n this.finalCalled = false\n\n // drain event flag.\n this.needDrain = false\n // At the start of calling end()\n this.ending = false\n // When end() has been called, and returned.\n this.ended = false\n // When 'finish' is emitted.\n this.finished = false\n\n // Has it been destroyed\n this.destroyed = false\n\n // Should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n const noDecode = !!(options && options.decodeStrings === false)\n this.decodeStrings = !noDecode\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = (options && options.defaultEncoding) || 'utf8'\n\n // Not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0\n\n // A flag to see when we're in the middle of a write.\n this.writing = false\n\n // When true all writes will be buffered until .uncork() call.\n this.corked = 0\n\n // A flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true\n\n // A flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false\n\n // The callback that's passed to _write(chunk, cb).\n this.onwrite = onwrite.bind(undefined, stream)\n\n // The callback that the user supplies to write(chunk, encoding, cb).\n this.writecb = null\n\n // The amount that is being written when _write is called.\n this.writelen = 0\n\n // Storage for data passed to the afterWrite() callback in case of\n // synchronous _write() completion.\n this.afterWriteTickInfo = null\n resetBuffer(this)\n\n // Number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted.\n this.pendingcb = 0\n\n // Stream is still being constructed and cannot be\n // destroyed until construction finished or failed.\n // Async construction is opt in, therefore we start as\n // constructed.\n this.constructed = true\n\n // Emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams.\n this.prefinished = false\n\n // True if the error was already emitted and should not be thrown again.\n this.errorEmitted = false\n\n // Should close be emitted on destroy. Defaults to true.\n this.emitClose = !options || options.emitClose !== false\n\n // Should .destroy() be called after 'finish' (and potentially 'end').\n this.autoDestroy = !options || options.autoDestroy !== false\n\n // Indicates whether the stream has errored. When true all write() calls\n // should return false. This is needed since when autoDestroy\n // is disabled we need a way to tell whether the stream has failed.\n this.errored = null\n\n // Indicates whether the stream has finished destroying.\n this.closed = false\n\n // True if close has been emitted or would have been emitted\n // depending on emitClose.\n this.closeEmitted = false\n this[kOnFinished] = []\n}\nfunction resetBuffer(state) {\n state.buffered = []\n state.bufferedIndex = 0\n state.allBuffers = true\n state.allNoop = true\n}\nWritableState.prototype.getBuffer = function getBuffer() {\n return ArrayPrototypeSlice(this.buffered, this.bufferedIndex)\n}\nObjectDefineProperty(WritableState.prototype, 'bufferedRequestCount', {\n __proto__: null,\n get() {\n return this.buffered.length - this.bufferedIndex\n }\n})\nfunction Writable(options) {\n // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n\n // Checking for a Stream.Duplex instance is faster here instead of inside\n // the WritableState constructor, at least with V8 6.5.\n const isDuplex = this instanceof require('./duplex')\n if (!isDuplex && !FunctionPrototypeSymbolHasInstance(Writable, this)) return new Writable(options)\n this._writableState = new WritableState(options, this, isDuplex)\n if (options) {\n if (typeof options.write === 'function') this._write = options.write\n if (typeof options.writev === 'function') this._writev = options.writev\n if (typeof options.destroy === 'function') this._destroy = options.destroy\n if (typeof options.final === 'function') this._final = options.final\n if (typeof options.construct === 'function') this._construct = options.construct\n if (options.signal) addAbortSignal(options.signal, this)\n }\n Stream.call(this, options)\n destroyImpl.construct(this, () => {\n const state = this._writableState\n if (!state.writing) {\n clearBuffer(this, state)\n }\n finishMaybe(this, state)\n })\n}\nObjectDefineProperty(Writable, SymbolHasInstance, {\n __proto__: null,\n value: function (object) {\n if (FunctionPrototypeSymbolHasInstance(this, object)) return true\n if (this !== Writable) return false\n return object && object._writableState instanceof WritableState\n }\n})\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE())\n}\nfunction _write(stream, chunk, encoding, cb) {\n const state = stream._writableState\n if (typeof encoding === 'function') {\n cb = encoding\n encoding = state.defaultEncoding\n } else {\n if (!encoding) encoding = state.defaultEncoding\n else if (encoding !== 'buffer' && !Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding)\n if (typeof cb !== 'function') cb = nop\n }\n if (chunk === null) {\n throw new ERR_STREAM_NULL_VALUES()\n } else if (!state.objectMode) {\n if (typeof chunk === 'string') {\n if (state.decodeStrings !== false) {\n chunk = Buffer.from(chunk, encoding)\n encoding = 'buffer'\n }\n } else if (chunk instanceof Buffer) {\n encoding = 'buffer'\n } else if (Stream._isUint8Array(chunk)) {\n chunk = Stream._uint8ArrayToBuffer(chunk)\n encoding = 'buffer'\n } else {\n throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk)\n }\n }\n let err\n if (state.ending) {\n err = new ERR_STREAM_WRITE_AFTER_END()\n } else if (state.destroyed) {\n err = new ERR_STREAM_DESTROYED('write')\n }\n if (err) {\n process.nextTick(cb, err)\n errorOrDestroy(stream, err, true)\n return err\n }\n state.pendingcb++\n return writeOrBuffer(stream, state, chunk, encoding, cb)\n}\nWritable.prototype.write = function (chunk, encoding, cb) {\n return _write(this, chunk, encoding, cb) === true\n}\nWritable.prototype.cork = function () {\n this._writableState.corked++\n}\nWritable.prototype.uncork = function () {\n const state = this._writableState\n if (state.corked) {\n state.corked--\n if (!state.writing) clearBuffer(this, state)\n }\n}\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = StringPrototypeToLowerCase(encoding)\n if (!Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding)\n this._writableState.defaultEncoding = encoding\n return this\n}\n\n// If we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, chunk, encoding, callback) {\n const len = state.objectMode ? 1 : chunk.length\n state.length += len\n\n // stream._write resets state.length\n const ret = state.length < state.highWaterMark\n // We must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true\n if (state.writing || state.corked || state.errored || !state.constructed) {\n state.buffered.push({\n chunk,\n encoding,\n callback\n })\n if (state.allBuffers && encoding !== 'buffer') {\n state.allBuffers = false\n }\n if (state.allNoop && callback !== nop) {\n state.allNoop = false\n }\n } else {\n state.writelen = len\n state.writecb = callback\n state.writing = true\n state.sync = true\n stream._write(chunk, encoding, state.onwrite)\n state.sync = false\n }\n\n // Return false if errored or destroyed in order to break\n // any synchronous while(stream.write(data)) loops.\n return ret && !state.errored && !state.destroyed\n}\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len\n state.writecb = cb\n state.writing = true\n state.sync = true\n if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'))\n else if (writev) stream._writev(chunk, state.onwrite)\n else stream._write(chunk, encoding, state.onwrite)\n state.sync = false\n}\nfunction onwriteError(stream, state, er, cb) {\n --state.pendingcb\n cb(er)\n // Ensure callbacks are invoked even when autoDestroy is\n // not enabled. Passing `er` here doesn't make sense since\n // it's related to one specific write, not to the buffered\n // writes.\n errorBuffer(state)\n // This can emit error, but error must always follow cb.\n errorOrDestroy(stream, er)\n}\nfunction onwrite(stream, er) {\n const state = stream._writableState\n const sync = state.sync\n const cb = state.writecb\n if (typeof cb !== 'function') {\n errorOrDestroy(stream, new ERR_MULTIPLE_CALLBACK())\n return\n }\n state.writing = false\n state.writecb = null\n state.length -= state.writelen\n state.writelen = 0\n if (er) {\n // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364\n er.stack // eslint-disable-line no-unused-expressions\n\n if (!state.errored) {\n state.errored = er\n }\n\n // In case of duplex streams we need to notify the readable side of the\n // error.\n if (stream._readableState && !stream._readableState.errored) {\n stream._readableState.errored = er\n }\n if (sync) {\n process.nextTick(onwriteError, stream, state, er, cb)\n } else {\n onwriteError(stream, state, er, cb)\n }\n } else {\n if (state.buffered.length > state.bufferedIndex) {\n clearBuffer(stream, state)\n }\n if (sync) {\n // It is a common case that the callback passed to .write() is always\n // the same. In that case, we do not schedule a new nextTick(), but\n // rather just increase a counter, to improve performance and avoid\n // memory allocations.\n if (state.afterWriteTickInfo !== null && state.afterWriteTickInfo.cb === cb) {\n state.afterWriteTickInfo.count++\n } else {\n state.afterWriteTickInfo = {\n count: 1,\n cb,\n stream,\n state\n }\n process.nextTick(afterWriteTick, state.afterWriteTickInfo)\n }\n } else {\n afterWrite(stream, state, 1, cb)\n }\n }\n}\nfunction afterWriteTick({ stream, state, count, cb }) {\n state.afterWriteTickInfo = null\n return afterWrite(stream, state, count, cb)\n}\nfunction afterWrite(stream, state, count, cb) {\n const needDrain = !state.ending && !stream.destroyed && state.length === 0 && state.needDrain\n if (needDrain) {\n state.needDrain = false\n stream.emit('drain')\n }\n while (count-- > 0) {\n state.pendingcb--\n cb()\n }\n if (state.destroyed) {\n errorBuffer(state)\n }\n finishMaybe(stream, state)\n}\n\n// If there's something in the buffer waiting, then invoke callbacks.\nfunction errorBuffer(state) {\n if (state.writing) {\n return\n }\n for (let n = state.bufferedIndex; n < state.buffered.length; ++n) {\n var _state$errored\n const { chunk, callback } = state.buffered[n]\n const len = state.objectMode ? 1 : chunk.length\n state.length -= len\n callback(\n (_state$errored = state.errored) !== null && _state$errored !== undefined\n ? _state$errored\n : new ERR_STREAM_DESTROYED('write')\n )\n }\n const onfinishCallbacks = state[kOnFinished].splice(0)\n for (let i = 0; i < onfinishCallbacks.length; i++) {\n var _state$errored2\n onfinishCallbacks[i](\n (_state$errored2 = state.errored) !== null && _state$errored2 !== undefined\n ? _state$errored2\n : new ERR_STREAM_DESTROYED('end')\n )\n }\n resetBuffer(state)\n}\n\n// If there's something in the buffer waiting, then process it.\nfunction clearBuffer(stream, state) {\n if (state.corked || state.bufferProcessing || state.destroyed || !state.constructed) {\n return\n }\n const { buffered, bufferedIndex, objectMode } = state\n const bufferedLength = buffered.length - bufferedIndex\n if (!bufferedLength) {\n return\n }\n let i = bufferedIndex\n state.bufferProcessing = true\n if (bufferedLength > 1 && stream._writev) {\n state.pendingcb -= bufferedLength - 1\n const callback = state.allNoop\n ? nop\n : (err) => {\n for (let n = i; n < buffered.length; ++n) {\n buffered[n].callback(err)\n }\n }\n // Make a copy of `buffered` if it's going to be used by `callback` above,\n // since `doWrite` will mutate the array.\n const chunks = state.allNoop && i === 0 ? buffered : ArrayPrototypeSlice(buffered, i)\n chunks.allBuffers = state.allBuffers\n doWrite(stream, state, true, state.length, chunks, '', callback)\n resetBuffer(state)\n } else {\n do {\n const { chunk, encoding, callback } = buffered[i]\n buffered[i++] = null\n const len = objectMode ? 1 : chunk.length\n doWrite(stream, state, false, len, chunk, encoding, callback)\n } while (i < buffered.length && !state.writing)\n if (i === buffered.length) {\n resetBuffer(state)\n } else if (i > 256) {\n buffered.splice(0, i)\n state.bufferedIndex = 0\n } else {\n state.bufferedIndex = i\n }\n }\n state.bufferProcessing = false\n}\nWritable.prototype._write = function (chunk, encoding, cb) {\n if (this._writev) {\n this._writev(\n [\n {\n chunk,\n encoding\n }\n ],\n cb\n )\n } else {\n throw new ERR_METHOD_NOT_IMPLEMENTED('_write()')\n }\n}\nWritable.prototype._writev = null\nWritable.prototype.end = function (chunk, encoding, cb) {\n const state = this._writableState\n if (typeof chunk === 'function') {\n cb = chunk\n chunk = null\n encoding = null\n } else if (typeof encoding === 'function') {\n cb = encoding\n encoding = null\n }\n let err\n if (chunk !== null && chunk !== undefined) {\n const ret = _write(this, chunk, encoding)\n if (ret instanceof Error) {\n err = ret\n }\n }\n\n // .end() fully uncorks.\n if (state.corked) {\n state.corked = 1\n this.uncork()\n }\n if (err) {\n // Do nothing...\n } else if (!state.errored && !state.ending) {\n // This is forgiving in terms of unnecessary calls to end() and can hide\n // logic errors. However, usually such errors are harmless and causing a\n // hard error can be disproportionately destructive. It is not always\n // trivial for the user to determine whether end() needs to be called\n // or not.\n\n state.ending = true\n finishMaybe(this, state, true)\n state.ended = true\n } else if (state.finished) {\n err = new ERR_STREAM_ALREADY_FINISHED('end')\n } else if (state.destroyed) {\n err = new ERR_STREAM_DESTROYED('end')\n }\n if (typeof cb === 'function') {\n if (err || state.finished) {\n process.nextTick(cb, err)\n } else {\n state[kOnFinished].push(cb)\n }\n }\n return this\n}\nfunction needFinish(state) {\n return (\n state.ending &&\n !state.destroyed &&\n state.constructed &&\n state.length === 0 &&\n !state.errored &&\n state.buffered.length === 0 &&\n !state.finished &&\n !state.writing &&\n !state.errorEmitted &&\n !state.closeEmitted\n )\n}\nfunction callFinal(stream, state) {\n let called = false\n function onFinish(err) {\n if (called) {\n errorOrDestroy(stream, err !== null && err !== undefined ? err : ERR_MULTIPLE_CALLBACK())\n return\n }\n called = true\n state.pendingcb--\n if (err) {\n const onfinishCallbacks = state[kOnFinished].splice(0)\n for (let i = 0; i < onfinishCallbacks.length; i++) {\n onfinishCallbacks[i](err)\n }\n errorOrDestroy(stream, err, state.sync)\n } else if (needFinish(state)) {\n state.prefinished = true\n stream.emit('prefinish')\n // Backwards compat. Don't check state.sync here.\n // Some streams assume 'finish' will be emitted\n // asynchronously relative to _final callback.\n state.pendingcb++\n process.nextTick(finish, stream, state)\n }\n }\n state.sync = true\n state.pendingcb++\n try {\n stream._final(onFinish)\n } catch (err) {\n onFinish(err)\n }\n state.sync = false\n}\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function' && !state.destroyed) {\n state.finalCalled = true\n callFinal(stream, state)\n } else {\n state.prefinished = true\n stream.emit('prefinish')\n }\n }\n}\nfunction finishMaybe(stream, state, sync) {\n if (needFinish(state)) {\n prefinish(stream, state)\n if (state.pendingcb === 0) {\n if (sync) {\n state.pendingcb++\n process.nextTick(\n (stream, state) => {\n if (needFinish(state)) {\n finish(stream, state)\n } else {\n state.pendingcb--\n }\n },\n stream,\n state\n )\n } else if (needFinish(state)) {\n state.pendingcb++\n finish(stream, state)\n }\n }\n }\n}\nfunction finish(stream, state) {\n state.pendingcb--\n state.finished = true\n const onfinishCallbacks = state[kOnFinished].splice(0)\n for (let i = 0; i < onfinishCallbacks.length; i++) {\n onfinishCallbacks[i]()\n }\n stream.emit('finish')\n if (state.autoDestroy) {\n // In case of duplex streams we need a way to detect\n // if the readable side is ready for autoDestroy as well.\n const rState = stream._readableState\n const autoDestroy =\n !rState ||\n (rState.autoDestroy &&\n // We don't expect the readable to ever 'end'\n // if readable is explicitly set to false.\n (rState.endEmitted || rState.readable === false))\n if (autoDestroy) {\n stream.destroy()\n }\n }\n}\nObjectDefineProperties(Writable.prototype, {\n closed: {\n __proto__: null,\n get() {\n return this._writableState ? this._writableState.closed : false\n }\n },\n destroyed: {\n __proto__: null,\n get() {\n return this._writableState ? this._writableState.destroyed : false\n },\n set(value) {\n // Backward compatibility, the user is explicitly managing destroyed.\n if (this._writableState) {\n this._writableState.destroyed = value\n }\n }\n },\n writable: {\n __proto__: null,\n get() {\n const w = this._writableState\n // w.writable === false means that this is part of a Duplex stream\n // where the writable side was disabled upon construction.\n // Compat. The user might manually disable writable side through\n // deprecated setter.\n return !!w && w.writable !== false && !w.destroyed && !w.errored && !w.ending && !w.ended\n },\n set(val) {\n // Backwards compatible.\n if (this._writableState) {\n this._writableState.writable = !!val\n }\n }\n },\n writableFinished: {\n __proto__: null,\n get() {\n return this._writableState ? this._writableState.finished : false\n }\n },\n writableObjectMode: {\n __proto__: null,\n get() {\n return this._writableState ? this._writableState.objectMode : false\n }\n },\n writableBuffer: {\n __proto__: null,\n get() {\n return this._writableState && this._writableState.getBuffer()\n }\n },\n writableEnded: {\n __proto__: null,\n get() {\n return this._writableState ? this._writableState.ending : false\n }\n },\n writableNeedDrain: {\n __proto__: null,\n get() {\n const wState = this._writableState\n if (!wState) return false\n return !wState.destroyed && !wState.ending && wState.needDrain\n }\n },\n writableHighWaterMark: {\n __proto__: null,\n get() {\n return this._writableState && this._writableState.highWaterMark\n }\n },\n writableCorked: {\n __proto__: null,\n get() {\n return this._writableState ? this._writableState.corked : 0\n }\n },\n writableLength: {\n __proto__: null,\n get() {\n return this._writableState && this._writableState.length\n }\n },\n errored: {\n __proto__: null,\n enumerable: false,\n get() {\n return this._writableState ? this._writableState.errored : null\n }\n },\n writableAborted: {\n __proto__: null,\n enumerable: false,\n get: function () {\n return !!(\n this._writableState.writable !== false &&\n (this._writableState.destroyed || this._writableState.errored) &&\n !this._writableState.finished\n )\n }\n }\n})\nconst destroy = destroyImpl.destroy\nWritable.prototype.destroy = function (err, cb) {\n const state = this._writableState\n\n // Invoke pending callbacks.\n if (!state.destroyed && (state.bufferedIndex < state.buffered.length || state[kOnFinished].length)) {\n process.nextTick(errorBuffer, state)\n }\n destroy.call(this, err, cb)\n return this\n}\nWritable.prototype._undestroy = destroyImpl.undestroy\nWritable.prototype._destroy = function (err, cb) {\n cb(err)\n}\nWritable.prototype[EE.captureRejectionSymbol] = function (err) {\n this.destroy(err)\n}\nlet webStreamsAdapters\n\n// Lazy to avoid circular references\nfunction lazyWebStreams() {\n if (webStreamsAdapters === undefined) webStreamsAdapters = {}\n return webStreamsAdapters\n}\nWritable.fromWeb = function (writableStream, options) {\n return lazyWebStreams().newStreamWritableFromWritableStream(writableStream, options)\n}\nWritable.toWeb = function (streamWritable) {\n return lazyWebStreams().newWritableStreamFromStreamWritable(streamWritable)\n}\n","/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\n;('use strict')\nconst bufferModule = require('buffer')\nconst {\n isReadable,\n isWritable,\n isIterable,\n isNodeStream,\n isReadableNodeStream,\n isWritableNodeStream,\n isDuplexNodeStream,\n isReadableStream,\n isWritableStream\n} = require('./utils')\nconst eos = require('./end-of-stream')\nconst {\n AbortError,\n codes: { ERR_INVALID_ARG_TYPE, ERR_INVALID_RETURN_VALUE }\n} = require('../../ours/errors')\nconst { destroyer } = require('./destroy')\nconst Duplex = require('./duplex')\nconst Readable = require('./readable')\nconst Writable = require('./writable')\nconst { createDeferredPromise } = require('../../ours/util')\nconst from = require('./from')\nconst Blob = globalThis.Blob || bufferModule.Blob\nconst isBlob =\n typeof Blob !== 'undefined'\n ? function isBlob(b) {\n return b instanceof Blob\n }\n : function isBlob(b) {\n return false\n }\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nconst { FunctionPrototypeCall } = require('../../ours/primordials')\n\n// This is needed for pre node 17.\nclass Duplexify extends Duplex {\n constructor(options) {\n super(options)\n\n // https://github.com/nodejs/node/pull/34385\n\n if ((options === null || options === undefined ? undefined : options.readable) === false) {\n this._readableState.readable = false\n this._readableState.ended = true\n this._readableState.endEmitted = true\n }\n if ((options === null || options === undefined ? undefined : options.writable) === false) {\n this._writableState.writable = false\n this._writableState.ending = true\n this._writableState.ended = true\n this._writableState.finished = true\n }\n }\n}\nmodule.exports = function duplexify(body, name) {\n if (isDuplexNodeStream(body)) {\n return body\n }\n if (isReadableNodeStream(body)) {\n return _duplexify({\n readable: body\n })\n }\n if (isWritableNodeStream(body)) {\n return _duplexify({\n writable: body\n })\n }\n if (isNodeStream(body)) {\n return _duplexify({\n writable: false,\n readable: false\n })\n }\n if (isReadableStream(body)) {\n return _duplexify({\n readable: Readable.fromWeb(body)\n })\n }\n if (isWritableStream(body)) {\n return _duplexify({\n writable: Writable.fromWeb(body)\n })\n }\n if (typeof body === 'function') {\n const { value, write, final, destroy } = fromAsyncGen(body)\n if (isIterable(value)) {\n return from(Duplexify, value, {\n // TODO (ronag): highWaterMark?\n objectMode: true,\n write,\n final,\n destroy\n })\n }\n const then = value === null || value === undefined ? undefined : value.then\n if (typeof then === 'function') {\n let d\n const promise = FunctionPrototypeCall(\n then,\n value,\n (val) => {\n if (val != null) {\n throw new ERR_INVALID_RETURN_VALUE('nully', 'body', val)\n }\n },\n (err) => {\n destroyer(d, err)\n }\n )\n return (d = new Duplexify({\n // TODO (ronag): highWaterMark?\n objectMode: true,\n readable: false,\n write,\n final(cb) {\n final(async () => {\n try {\n await promise\n process.nextTick(cb, null)\n } catch (err) {\n process.nextTick(cb, err)\n }\n })\n },\n destroy\n }))\n }\n throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or AsyncFunction', name, value)\n }\n if (isBlob(body)) {\n return duplexify(body.arrayBuffer())\n }\n if (isIterable(body)) {\n return from(Duplexify, body, {\n // TODO (ronag): highWaterMark?\n objectMode: true,\n writable: false\n })\n }\n if (\n isReadableStream(body === null || body === undefined ? undefined : body.readable) &&\n isWritableStream(body === null || body === undefined ? undefined : body.writable)\n ) {\n return Duplexify.fromWeb(body)\n }\n if (\n typeof (body === null || body === undefined ? undefined : body.writable) === 'object' ||\n typeof (body === null || body === undefined ? undefined : body.readable) === 'object'\n ) {\n const readable =\n body !== null && body !== undefined && body.readable\n ? isReadableNodeStream(body === null || body === undefined ? undefined : body.readable)\n ? body === null || body === undefined\n ? undefined\n : body.readable\n : duplexify(body.readable)\n : undefined\n const writable =\n body !== null && body !== undefined && body.writable\n ? isWritableNodeStream(body === null || body === undefined ? undefined : body.writable)\n ? body === null || body === undefined\n ? undefined\n : body.writable\n : duplexify(body.writable)\n : undefined\n return _duplexify({\n readable,\n writable\n })\n }\n const then = body === null || body === undefined ? undefined : body.then\n if (typeof then === 'function') {\n let d\n FunctionPrototypeCall(\n then,\n body,\n (val) => {\n if (val != null) {\n d.push(val)\n }\n d.push(null)\n },\n (err) => {\n destroyer(d, err)\n }\n )\n return (d = new Duplexify({\n objectMode: true,\n writable: false,\n read() {}\n }))\n }\n throw new ERR_INVALID_ARG_TYPE(\n name,\n [\n 'Blob',\n 'ReadableStream',\n 'WritableStream',\n 'Stream',\n 'Iterable',\n 'AsyncIterable',\n 'Function',\n '{ readable, writable } pair',\n 'Promise'\n ],\n body\n )\n}\nfunction fromAsyncGen(fn) {\n let { promise, resolve } = createDeferredPromise()\n const ac = new AbortController()\n const signal = ac.signal\n const value = fn(\n (async function* () {\n while (true) {\n const _promise = promise\n promise = null\n const { chunk, done, cb } = await _promise\n process.nextTick(cb)\n if (done) return\n if (signal.aborted)\n throw new AbortError(undefined, {\n cause: signal.reason\n })\n ;({ promise, resolve } = createDeferredPromise())\n yield chunk\n }\n })(),\n {\n signal\n }\n )\n return {\n value,\n write(chunk, encoding, cb) {\n const _resolve = resolve\n resolve = null\n _resolve({\n chunk,\n done: false,\n cb\n })\n },\n final(cb) {\n const _resolve = resolve\n resolve = null\n _resolve({\n done: true,\n cb\n })\n },\n destroy(err, cb) {\n ac.abort()\n cb(err)\n }\n }\n}\nfunction _duplexify(pair) {\n const r = pair.readable && typeof pair.readable.read !== 'function' ? Readable.wrap(pair.readable) : pair.readable\n const w = pair.writable\n let readable = !!isReadable(r)\n let writable = !!isWritable(w)\n let ondrain\n let onfinish\n let onreadable\n let onclose\n let d\n function onfinished(err) {\n const cb = onclose\n onclose = null\n if (cb) {\n cb(err)\n } else if (err) {\n d.destroy(err)\n }\n }\n\n // TODO(ronag): Avoid double buffering.\n // Implement Writable/Readable/Duplex traits.\n // See, https://github.com/nodejs/node/pull/33515.\n d = new Duplexify({\n // TODO (ronag): highWaterMark?\n readableObjectMode: !!(r !== null && r !== undefined && r.readableObjectMode),\n writableObjectMode: !!(w !== null && w !== undefined && w.writableObjectMode),\n readable,\n writable\n })\n if (writable) {\n eos(w, (err) => {\n writable = false\n if (err) {\n destroyer(r, err)\n }\n onfinished(err)\n })\n d._write = function (chunk, encoding, callback) {\n if (w.write(chunk, encoding)) {\n callback()\n } else {\n ondrain = callback\n }\n }\n d._final = function (callback) {\n w.end()\n onfinish = callback\n }\n w.on('drain', function () {\n if (ondrain) {\n const cb = ondrain\n ondrain = null\n cb()\n }\n })\n w.on('finish', function () {\n if (onfinish) {\n const cb = onfinish\n onfinish = null\n cb()\n }\n })\n }\n if (readable) {\n eos(r, (err) => {\n readable = false\n if (err) {\n destroyer(r, err)\n }\n onfinished(err)\n })\n r.on('readable', function () {\n if (onreadable) {\n const cb = onreadable\n onreadable = null\n cb()\n }\n })\n r.on('end', function () {\n d.push(null)\n })\n d._read = function () {\n while (true) {\n const buf = r.read()\n if (buf === null) {\n onreadable = d._read\n return\n }\n if (!d.push(buf)) {\n return\n }\n }\n }\n }\n d._destroy = function (err, callback) {\n if (!err && onclose !== null) {\n err = new AbortError()\n }\n onreadable = null\n ondrain = null\n onfinish = null\n if (onclose === null) {\n callback(err)\n } else {\n onclose = callback\n destroyer(w, err)\n destroyer(r, err)\n }\n }\n return d\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototype inheritance, this class\n// prototypically inherits from Readable, and then parasitically from\n// Writable.\n\n'use strict'\n\nconst {\n ObjectDefineProperties,\n ObjectGetOwnPropertyDescriptor,\n ObjectKeys,\n ObjectSetPrototypeOf\n} = require('../../ours/primordials')\nmodule.exports = Duplex\nconst Readable = require('./readable')\nconst Writable = require('./writable')\nObjectSetPrototypeOf(Duplex.prototype, Readable.prototype)\nObjectSetPrototypeOf(Duplex, Readable)\n{\n const keys = ObjectKeys(Writable.prototype)\n // Allow the keys array to be GC'ed.\n for (let i = 0; i < keys.length; i++) {\n const method = keys[i]\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]\n }\n}\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options)\n Readable.call(this, options)\n Writable.call(this, options)\n if (options) {\n this.allowHalfOpen = options.allowHalfOpen !== false\n if (options.readable === false) {\n this._readableState.readable = false\n this._readableState.ended = true\n this._readableState.endEmitted = true\n }\n if (options.writable === false) {\n this._writableState.writable = false\n this._writableState.ending = true\n this._writableState.ended = true\n this._writableState.finished = true\n }\n } else {\n this.allowHalfOpen = true\n }\n}\nObjectDefineProperties(Duplex.prototype, {\n writable: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writable')\n },\n writableHighWaterMark: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableHighWaterMark')\n },\n writableObjectMode: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableObjectMode')\n },\n writableBuffer: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableBuffer')\n },\n writableLength: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableLength')\n },\n writableFinished: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableFinished')\n },\n writableCorked: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableCorked')\n },\n writableEnded: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableEnded')\n },\n writableNeedDrain: {\n __proto__: null,\n ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableNeedDrain')\n },\n destroyed: {\n __proto__: null,\n get() {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false\n }\n return this._readableState.destroyed && this._writableState.destroyed\n },\n set(value) {\n // Backward compatibility, the user is explicitly\n // managing destroyed.\n if (this._readableState && this._writableState) {\n this._readableState.destroyed = value\n this._writableState.destroyed = value\n }\n }\n }\n})\nlet webStreamsAdapters\n\n// Lazy to avoid circular references\nfunction lazyWebStreams() {\n if (webStreamsAdapters === undefined) webStreamsAdapters = {}\n return webStreamsAdapters\n}\nDuplex.fromWeb = function (pair, options) {\n return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair, options)\n}\nDuplex.toWeb = function (duplex) {\n return lazyWebStreams().newReadableWritablePairFromDuplex(duplex)\n}\nlet duplexify\nDuplex.from = function (body) {\n if (!duplexify) {\n duplexify = require('./duplexify')\n }\n return duplexify(body, 'body')\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n'use strict'\n\nconst { ObjectSetPrototypeOf, Symbol } = require('../../ours/primordials')\nmodule.exports = Transform\nconst { ERR_METHOD_NOT_IMPLEMENTED } = require('../../ours/errors').codes\nconst Duplex = require('./duplex')\nconst { getHighWaterMark } = require('./state')\nObjectSetPrototypeOf(Transform.prototype, Duplex.prototype)\nObjectSetPrototypeOf(Transform, Duplex)\nconst kCallback = Symbol('kCallback')\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options)\n\n // TODO (ronag): This should preferably always be\n // applied but would be semver-major. Or even better;\n // make Transform a Readable with the Writable interface.\n const readableHighWaterMark = options ? getHighWaterMark(this, options, 'readableHighWaterMark', true) : null\n if (readableHighWaterMark === 0) {\n // A Duplex will buffer both on the writable and readable side while\n // a Transform just wants to buffer hwm number of elements. To avoid\n // buffering twice we disable buffering on the writable side.\n options = {\n ...options,\n highWaterMark: null,\n readableHighWaterMark,\n // TODO (ronag): 0 is not optimal since we have\n // a \"bug\" where we check needDrain before calling _write and not after.\n // Refs: https://github.com/nodejs/node/pull/32887\n // Refs: https://github.com/nodejs/node/pull/35941\n writableHighWaterMark: options.writableHighWaterMark || 0\n }\n }\n Duplex.call(this, options)\n\n // We have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false\n this[kCallback] = null\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform\n if (typeof options.flush === 'function') this._flush = options.flush\n }\n\n // When the writable side finishes, then flush out anything remaining.\n // Backwards compat. Some Transform streams incorrectly implement _final\n // instead of or in addition to _flush. By using 'prefinish' instead of\n // implementing _final we continue supporting this unfortunate use case.\n this.on('prefinish', prefinish)\n}\nfunction final(cb) {\n if (typeof this._flush === 'function' && !this.destroyed) {\n this._flush((er, data) => {\n if (er) {\n if (cb) {\n cb(er)\n } else {\n this.destroy(er)\n }\n return\n }\n if (data != null) {\n this.push(data)\n }\n this.push(null)\n if (cb) {\n cb()\n }\n })\n } else {\n this.push(null)\n if (cb) {\n cb()\n }\n }\n}\nfunction prefinish() {\n if (this._final !== final) {\n final.call(this)\n }\n}\nTransform.prototype._final = final\nTransform.prototype._transform = function (chunk, encoding, callback) {\n throw new ERR_METHOD_NOT_IMPLEMENTED('_transform()')\n}\nTransform.prototype._write = function (chunk, encoding, callback) {\n const rState = this._readableState\n const wState = this._writableState\n const length = rState.length\n this._transform(chunk, encoding, (err, val) => {\n if (err) {\n callback(err)\n return\n }\n if (val != null) {\n this.push(val)\n }\n if (\n wState.ended ||\n // Backwards compat.\n length === rState.length ||\n // Backwards compat.\n rState.length < rState.highWaterMark\n ) {\n callback()\n } else {\n this[kCallback] = callback\n }\n })\n}\nTransform.prototype._read = function () {\n if (this[kCallback]) {\n const callback = this[kCallback]\n this[kCallback] = null\n callback()\n }\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n'use strict'\n\nconst { ObjectSetPrototypeOf } = require('../../ours/primordials')\nmodule.exports = PassThrough\nconst Transform = require('./transform')\nObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype)\nObjectSetPrototypeOf(PassThrough, Transform)\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options)\n Transform.call(this, options)\n}\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk)\n}\n","/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n// Ported from https://github.com/mafintosh/pump with\n// permission from the author, Mathias Buus (@mafintosh).\n\n;('use strict')\nconst { ArrayIsArray, Promise, SymbolAsyncIterator, SymbolDispose } = require('../../ours/primordials')\nconst eos = require('./end-of-stream')\nconst { once } = require('../../ours/util')\nconst destroyImpl = require('./destroy')\nconst Duplex = require('./duplex')\nconst {\n aggregateTwoErrors,\n codes: {\n ERR_INVALID_ARG_TYPE,\n ERR_INVALID_RETURN_VALUE,\n ERR_MISSING_ARGS,\n ERR_STREAM_DESTROYED,\n ERR_STREAM_PREMATURE_CLOSE\n },\n AbortError\n} = require('../../ours/errors')\nconst { validateFunction, validateAbortSignal } = require('../validators')\nconst {\n isIterable,\n isReadable,\n isReadableNodeStream,\n isNodeStream,\n isTransformStream,\n isWebStream,\n isReadableStream,\n isReadableFinished\n} = require('./utils')\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nlet PassThrough\nlet Readable\nlet addAbortListener\nfunction destroyer(stream, reading, writing) {\n let finished = false\n stream.on('close', () => {\n finished = true\n })\n const cleanup = eos(\n stream,\n {\n readable: reading,\n writable: writing\n },\n (err) => {\n finished = !err\n }\n )\n return {\n destroy: (err) => {\n if (finished) return\n finished = true\n destroyImpl.destroyer(stream, err || new ERR_STREAM_DESTROYED('pipe'))\n },\n cleanup\n }\n}\nfunction popCallback(streams) {\n // Streams should never be an empty array. It should always contain at least\n // a single stream. Therefore optimize for the average case instead of\n // checking for length === 0 as well.\n validateFunction(streams[streams.length - 1], 'streams[stream.length - 1]')\n return streams.pop()\n}\nfunction makeAsyncIterable(val) {\n if (isIterable(val)) {\n return val\n } else if (isReadableNodeStream(val)) {\n // Legacy streams are not Iterable.\n return fromReadable(val)\n }\n throw new ERR_INVALID_ARG_TYPE('val', ['Readable', 'Iterable', 'AsyncIterable'], val)\n}\nasync function* fromReadable(val) {\n if (!Readable) {\n Readable = require('./readable')\n }\n yield* Readable.prototype[SymbolAsyncIterator].call(val)\n}\nasync function pumpToNode(iterable, writable, finish, { end }) {\n let error\n let onresolve = null\n const resume = (err) => {\n if (err) {\n error = err\n }\n if (onresolve) {\n const callback = onresolve\n onresolve = null\n callback()\n }\n }\n const wait = () =>\n new Promise((resolve, reject) => {\n if (error) {\n reject(error)\n } else {\n onresolve = () => {\n if (error) {\n reject(error)\n } else {\n resolve()\n }\n }\n }\n })\n writable.on('drain', resume)\n const cleanup = eos(\n writable,\n {\n readable: false\n },\n resume\n )\n try {\n if (writable.writableNeedDrain) {\n await wait()\n }\n for await (const chunk of iterable) {\n if (!writable.write(chunk)) {\n await wait()\n }\n }\n if (end) {\n writable.end()\n await wait()\n }\n finish()\n } catch (err) {\n finish(error !== err ? aggregateTwoErrors(error, err) : err)\n } finally {\n cleanup()\n writable.off('drain', resume)\n }\n}\nasync function pumpToWeb(readable, writable, finish, { end }) {\n if (isTransformStream(writable)) {\n writable = writable.writable\n }\n // https://streams.spec.whatwg.org/#example-manual-write-with-backpressure\n const writer = writable.getWriter()\n try {\n for await (const chunk of readable) {\n await writer.ready\n writer.write(chunk).catch(() => {})\n }\n await writer.ready\n if (end) {\n await writer.close()\n }\n finish()\n } catch (err) {\n try {\n await writer.abort(err)\n finish(err)\n } catch (err) {\n finish(err)\n }\n }\n}\nfunction pipeline(...streams) {\n return pipelineImpl(streams, once(popCallback(streams)))\n}\nfunction pipelineImpl(streams, callback, opts) {\n if (streams.length === 1 && ArrayIsArray(streams[0])) {\n streams = streams[0]\n }\n if (streams.length < 2) {\n throw new ERR_MISSING_ARGS('streams')\n }\n const ac = new AbortController()\n const signal = ac.signal\n const outerSignal = opts === null || opts === undefined ? undefined : opts.signal\n\n // Need to cleanup event listeners if last stream is readable\n // https://github.com/nodejs/node/issues/35452\n const lastStreamCleanup = []\n validateAbortSignal(outerSignal, 'options.signal')\n function abort() {\n finishImpl(new AbortError())\n }\n addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n let disposable\n if (outerSignal) {\n disposable = addAbortListener(outerSignal, abort)\n }\n let error\n let value\n const destroys = []\n let finishCount = 0\n function finish(err) {\n finishImpl(err, --finishCount === 0)\n }\n function finishImpl(err, final) {\n var _disposable\n if (err && (!error || error.code === 'ERR_STREAM_PREMATURE_CLOSE')) {\n error = err\n }\n if (!error && !final) {\n return\n }\n while (destroys.length) {\n destroys.shift()(error)\n }\n ;(_disposable = disposable) === null || _disposable === undefined ? undefined : _disposable[SymbolDispose]()\n ac.abort()\n if (final) {\n if (!error) {\n lastStreamCleanup.forEach((fn) => fn())\n }\n process.nextTick(callback, error, value)\n }\n }\n let ret\n for (let i = 0; i < streams.length; i++) {\n const stream = streams[i]\n const reading = i < streams.length - 1\n const writing = i > 0\n const end = reading || (opts === null || opts === undefined ? undefined : opts.end) !== false\n const isLastStream = i === streams.length - 1\n if (isNodeStream(stream)) {\n if (end) {\n const { destroy, cleanup } = destroyer(stream, reading, writing)\n destroys.push(destroy)\n if (isReadable(stream) && isLastStream) {\n lastStreamCleanup.push(cleanup)\n }\n }\n\n // Catch stream errors that occur after pipe/pump has completed.\n function onError(err) {\n if (err && err.name !== 'AbortError' && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n finish(err)\n }\n }\n stream.on('error', onError)\n if (isReadable(stream) && isLastStream) {\n lastStreamCleanup.push(() => {\n stream.removeListener('error', onError)\n })\n }\n }\n if (i === 0) {\n if (typeof stream === 'function') {\n ret = stream({\n signal\n })\n if (!isIterable(ret)) {\n throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or Stream', 'source', ret)\n }\n } else if (isIterable(stream) || isReadableNodeStream(stream) || isTransformStream(stream)) {\n ret = stream\n } else {\n ret = Duplex.from(stream)\n }\n } else if (typeof stream === 'function') {\n if (isTransformStream(ret)) {\n var _ret\n ret = makeAsyncIterable((_ret = ret) === null || _ret === undefined ? undefined : _ret.readable)\n } else {\n ret = makeAsyncIterable(ret)\n }\n ret = stream(ret, {\n signal\n })\n if (reading) {\n if (!isIterable(ret, true)) {\n throw new ERR_INVALID_RETURN_VALUE('AsyncIterable', `transform[${i - 1}]`, ret)\n }\n } else {\n var _ret2\n if (!PassThrough) {\n PassThrough = require('./passthrough')\n }\n\n // If the last argument to pipeline is not a stream\n // we must create a proxy stream so that pipeline(...)\n // always returns a stream which can be further\n // composed through `.pipe(stream)`.\n\n const pt = new PassThrough({\n objectMode: true\n })\n\n // Handle Promises/A+ spec, `then` could be a getter that throws on\n // second use.\n const then = (_ret2 = ret) === null || _ret2 === undefined ? undefined : _ret2.then\n if (typeof then === 'function') {\n finishCount++\n then.call(\n ret,\n (val) => {\n value = val\n if (val != null) {\n pt.write(val)\n }\n if (end) {\n pt.end()\n }\n process.nextTick(finish)\n },\n (err) => {\n pt.destroy(err)\n process.nextTick(finish, err)\n }\n )\n } else if (isIterable(ret, true)) {\n finishCount++\n pumpToNode(ret, pt, finish, {\n end\n })\n } else if (isReadableStream(ret) || isTransformStream(ret)) {\n const toRead = ret.readable || ret\n finishCount++\n pumpToNode(toRead, pt, finish, {\n end\n })\n } else {\n throw new ERR_INVALID_RETURN_VALUE('AsyncIterable or Promise', 'destination', ret)\n }\n ret = pt\n const { destroy, cleanup } = destroyer(ret, false, true)\n destroys.push(destroy)\n if (isLastStream) {\n lastStreamCleanup.push(cleanup)\n }\n }\n } else if (isNodeStream(stream)) {\n if (isReadableNodeStream(ret)) {\n finishCount += 2\n const cleanup = pipe(ret, stream, finish, {\n end\n })\n if (isReadable(stream) && isLastStream) {\n lastStreamCleanup.push(cleanup)\n }\n } else if (isTransformStream(ret) || isReadableStream(ret)) {\n const toRead = ret.readable || ret\n finishCount++\n pumpToNode(toRead, stream, finish, {\n end\n })\n } else if (isIterable(ret)) {\n finishCount++\n pumpToNode(ret, stream, finish, {\n end\n })\n } else {\n throw new ERR_INVALID_ARG_TYPE(\n 'val',\n ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'],\n ret\n )\n }\n ret = stream\n } else if (isWebStream(stream)) {\n if (isReadableNodeStream(ret)) {\n finishCount++\n pumpToWeb(makeAsyncIterable(ret), stream, finish, {\n end\n })\n } else if (isReadableStream(ret) || isIterable(ret)) {\n finishCount++\n pumpToWeb(ret, stream, finish, {\n end\n })\n } else if (isTransformStream(ret)) {\n finishCount++\n pumpToWeb(ret.readable, stream, finish, {\n end\n })\n } else {\n throw new ERR_INVALID_ARG_TYPE(\n 'val',\n ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'],\n ret\n )\n }\n ret = stream\n } else {\n ret = Duplex.from(stream)\n }\n }\n if (\n (signal !== null && signal !== undefined && signal.aborted) ||\n (outerSignal !== null && outerSignal !== undefined && outerSignal.aborted)\n ) {\n process.nextTick(abort)\n }\n return ret\n}\nfunction pipe(src, dst, finish, { end }) {\n let ended = false\n dst.on('close', () => {\n if (!ended) {\n // Finish if the destination closes before the source has completed.\n finish(new ERR_STREAM_PREMATURE_CLOSE())\n }\n })\n src.pipe(dst, {\n end: false\n }) // If end is true we already will have a listener to end dst.\n\n if (end) {\n // Compat. Before node v10.12.0 stdio used to throw an error so\n // pipe() did/does not end() stdio destinations.\n // Now they allow it but \"secretly\" don't close the underlying fd.\n\n function endFn() {\n ended = true\n dst.end()\n }\n if (isReadableFinished(src)) {\n // End the destination if the source has already ended.\n process.nextTick(endFn)\n } else {\n src.once('end', endFn)\n }\n } else {\n finish()\n }\n eos(\n src,\n {\n readable: true,\n writable: false\n },\n (err) => {\n const rState = src._readableState\n if (\n err &&\n err.code === 'ERR_STREAM_PREMATURE_CLOSE' &&\n rState &&\n rState.ended &&\n !rState.errored &&\n !rState.errorEmitted\n ) {\n // Some readable streams will emit 'close' before 'end'. However, since\n // this is on the readable side 'end' should still be emitted if the\n // stream has been ended and no error emitted. This should be allowed in\n // favor of backwards compatibility. Since the stream is piped to a\n // destination this should not result in any observable difference.\n // We don't need to check if this is a writable premature close since\n // eos will only fail with premature close on the reading side for\n // duplex streams.\n src.once('end', finish).once('error', finish)\n } else {\n finish(err)\n }\n }\n )\n return eos(\n dst,\n {\n readable: false,\n writable: true\n },\n finish\n )\n}\nmodule.exports = {\n pipelineImpl,\n pipeline\n}\n","'use strict'\n\nconst { pipeline } = require('./pipeline')\nconst Duplex = require('./duplex')\nconst { destroyer } = require('./destroy')\nconst {\n isNodeStream,\n isReadable,\n isWritable,\n isWebStream,\n isTransformStream,\n isWritableStream,\n isReadableStream\n} = require('./utils')\nconst {\n AbortError,\n codes: { ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS }\n} = require('../../ours/errors')\nconst eos = require('./end-of-stream')\nmodule.exports = function compose(...streams) {\n if (streams.length === 0) {\n throw new ERR_MISSING_ARGS('streams')\n }\n if (streams.length === 1) {\n return Duplex.from(streams[0])\n }\n const orgStreams = [...streams]\n if (typeof streams[0] === 'function') {\n streams[0] = Duplex.from(streams[0])\n }\n if (typeof streams[streams.length - 1] === 'function') {\n const idx = streams.length - 1\n streams[idx] = Duplex.from(streams[idx])\n }\n for (let n = 0; n < streams.length; ++n) {\n if (!isNodeStream(streams[n]) && !isWebStream(streams[n])) {\n // TODO(ronag): Add checks for non streams.\n continue\n }\n if (\n n < streams.length - 1 &&\n !(isReadable(streams[n]) || isReadableStream(streams[n]) || isTransformStream(streams[n]))\n ) {\n throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be readable')\n }\n if (n > 0 && !(isWritable(streams[n]) || isWritableStream(streams[n]) || isTransformStream(streams[n]))) {\n throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be writable')\n }\n }\n let ondrain\n let onfinish\n let onreadable\n let onclose\n let d\n function onfinished(err) {\n const cb = onclose\n onclose = null\n if (cb) {\n cb(err)\n } else if (err) {\n d.destroy(err)\n } else if (!readable && !writable) {\n d.destroy()\n }\n }\n const head = streams[0]\n const tail = pipeline(streams, onfinished)\n const writable = !!(isWritable(head) || isWritableStream(head) || isTransformStream(head))\n const readable = !!(isReadable(tail) || isReadableStream(tail) || isTransformStream(tail))\n\n // TODO(ronag): Avoid double buffering.\n // Implement Writable/Readable/Duplex traits.\n // See, https://github.com/nodejs/node/pull/33515.\n d = new Duplex({\n // TODO (ronag): highWaterMark?\n writableObjectMode: !!(head !== null && head !== undefined && head.writableObjectMode),\n readableObjectMode: !!(tail !== null && tail !== undefined && tail.readableObjectMode),\n writable,\n readable\n })\n if (writable) {\n if (isNodeStream(head)) {\n d._write = function (chunk, encoding, callback) {\n if (head.write(chunk, encoding)) {\n callback()\n } else {\n ondrain = callback\n }\n }\n d._final = function (callback) {\n head.end()\n onfinish = callback\n }\n head.on('drain', function () {\n if (ondrain) {\n const cb = ondrain\n ondrain = null\n cb()\n }\n })\n } else if (isWebStream(head)) {\n const writable = isTransformStream(head) ? head.writable : head\n const writer = writable.getWriter()\n d._write = async function (chunk, encoding, callback) {\n try {\n await writer.ready\n writer.write(chunk).catch(() => {})\n callback()\n } catch (err) {\n callback(err)\n }\n }\n d._final = async function (callback) {\n try {\n await writer.ready\n writer.close().catch(() => {})\n onfinish = callback\n } catch (err) {\n callback(err)\n }\n }\n }\n const toRead = isTransformStream(tail) ? tail.readable : tail\n eos(toRead, () => {\n if (onfinish) {\n const cb = onfinish\n onfinish = null\n cb()\n }\n })\n }\n if (readable) {\n if (isNodeStream(tail)) {\n tail.on('readable', function () {\n if (onreadable) {\n const cb = onreadable\n onreadable = null\n cb()\n }\n })\n tail.on('end', function () {\n d.push(null)\n })\n d._read = function () {\n while (true) {\n const buf = tail.read()\n if (buf === null) {\n onreadable = d._read\n return\n }\n if (!d.push(buf)) {\n return\n }\n }\n }\n } else if (isWebStream(tail)) {\n const readable = isTransformStream(tail) ? tail.readable : tail\n const reader = readable.getReader()\n d._read = async function () {\n while (true) {\n try {\n const { value, done } = await reader.read()\n if (!d.push(value)) {\n return\n }\n if (done) {\n d.push(null)\n return\n }\n } catch {\n return\n }\n }\n }\n }\n }\n d._destroy = function (err, callback) {\n if (!err && onclose !== null) {\n err = new AbortError()\n }\n onreadable = null\n ondrain = null\n onfinish = null\n if (onclose === null) {\n callback(err)\n } else {\n onclose = callback\n if (isNodeStream(tail)) {\n destroyer(tail, err)\n }\n }\n }\n return d\n}\n","'use strict'\n\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nconst {\n codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE },\n AbortError\n} = require('../../ours/errors')\nconst { validateAbortSignal, validateInteger, validateObject } = require('../validators')\nconst kWeakHandler = require('../../ours/primordials').Symbol('kWeak')\nconst kResistStopPropagation = require('../../ours/primordials').Symbol('kResistStopPropagation')\nconst { finished } = require('./end-of-stream')\nconst staticCompose = require('./compose')\nconst { addAbortSignalNoValidate } = require('./add-abort-signal')\nconst { isWritable, isNodeStream } = require('./utils')\nconst { deprecate } = require('../../ours/util')\nconst {\n ArrayPrototypePush,\n Boolean,\n MathFloor,\n Number,\n NumberIsNaN,\n Promise,\n PromiseReject,\n PromiseResolve,\n PromisePrototypeThen,\n Symbol\n} = require('../../ours/primordials')\nconst kEmpty = Symbol('kEmpty')\nconst kEof = Symbol('kEof')\nfunction compose(stream, options) {\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n if (isNodeStream(stream) && !isWritable(stream)) {\n throw new ERR_INVALID_ARG_VALUE('stream', stream, 'must be writable')\n }\n const composedStream = staticCompose(this, stream)\n if (options !== null && options !== undefined && options.signal) {\n // Not validating as we already validated before\n addAbortSignalNoValidate(options.signal, composedStream)\n }\n return composedStream\n}\nfunction map(fn, options) {\n if (typeof fn !== 'function') {\n throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n }\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n let concurrency = 1\n if ((options === null || options === undefined ? undefined : options.concurrency) != null) {\n concurrency = MathFloor(options.concurrency)\n }\n let highWaterMark = concurrency - 1\n if ((options === null || options === undefined ? undefined : options.highWaterMark) != null) {\n highWaterMark = MathFloor(options.highWaterMark)\n }\n validateInteger(concurrency, 'options.concurrency', 1)\n validateInteger(highWaterMark, 'options.highWaterMark', 0)\n highWaterMark += concurrency\n return async function* map() {\n const signal = require('../../ours/util').AbortSignalAny(\n [options === null || options === undefined ? undefined : options.signal].filter(Boolean)\n )\n const stream = this\n const queue = []\n const signalOpt = {\n signal\n }\n let next\n let resume\n let done = false\n let cnt = 0\n function onCatch() {\n done = true\n afterItemProcessed()\n }\n function afterItemProcessed() {\n cnt -= 1\n maybeResume()\n }\n function maybeResume() {\n if (resume && !done && cnt < concurrency && queue.length < highWaterMark) {\n resume()\n resume = null\n }\n }\n async function pump() {\n try {\n for await (let val of stream) {\n if (done) {\n return\n }\n if (signal.aborted) {\n throw new AbortError()\n }\n try {\n val = fn(val, signalOpt)\n if (val === kEmpty) {\n continue\n }\n val = PromiseResolve(val)\n } catch (err) {\n val = PromiseReject(err)\n }\n cnt += 1\n PromisePrototypeThen(val, afterItemProcessed, onCatch)\n queue.push(val)\n if (next) {\n next()\n next = null\n }\n if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) {\n await new Promise((resolve) => {\n resume = resolve\n })\n }\n }\n queue.push(kEof)\n } catch (err) {\n const val = PromiseReject(err)\n PromisePrototypeThen(val, afterItemProcessed, onCatch)\n queue.push(val)\n } finally {\n done = true\n if (next) {\n next()\n next = null\n }\n }\n }\n pump()\n try {\n while (true) {\n while (queue.length > 0) {\n const val = await queue[0]\n if (val === kEof) {\n return\n }\n if (signal.aborted) {\n throw new AbortError()\n }\n if (val !== kEmpty) {\n yield val\n }\n queue.shift()\n maybeResume()\n }\n await new Promise((resolve) => {\n next = resolve\n })\n }\n } finally {\n done = true\n if (resume) {\n resume()\n resume = null\n }\n }\n }.call(this)\n}\nfunction asIndexedPairs(options = undefined) {\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n return async function* asIndexedPairs() {\n let index = 0\n for await (const val of this) {\n var _options$signal\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal = options.signal) !== null &&\n _options$signal !== undefined &&\n _options$signal.aborted\n ) {\n throw new AbortError({\n cause: options.signal.reason\n })\n }\n yield [index++, val]\n }\n }.call(this)\n}\nasync function some(fn, options = undefined) {\n for await (const unused of filter.call(this, fn, options)) {\n return true\n }\n return false\n}\nasync function every(fn, options = undefined) {\n if (typeof fn !== 'function') {\n throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n }\n // https://en.wikipedia.org/wiki/De_Morgan%27s_laws\n return !(await some.call(\n this,\n async (...args) => {\n return !(await fn(...args))\n },\n options\n ))\n}\nasync function find(fn, options) {\n for await (const result of filter.call(this, fn, options)) {\n return result\n }\n return undefined\n}\nasync function forEach(fn, options) {\n if (typeof fn !== 'function') {\n throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n }\n async function forEachFn(value, options) {\n await fn(value, options)\n return kEmpty\n }\n // eslint-disable-next-line no-unused-vars\n for await (const unused of map.call(this, forEachFn, options));\n}\nfunction filter(fn, options) {\n if (typeof fn !== 'function') {\n throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n }\n async function filterFn(value, options) {\n if (await fn(value, options)) {\n return value\n }\n return kEmpty\n }\n return map.call(this, filterFn, options)\n}\n\n// Specific to provide better error to reduce since the argument is only\n// missing if the stream has no items in it - but the code is still appropriate\nclass ReduceAwareErrMissingArgs extends ERR_MISSING_ARGS {\n constructor() {\n super('reduce')\n this.message = 'Reduce of an empty stream requires an initial value'\n }\n}\nasync function reduce(reducer, initialValue, options) {\n var _options$signal2\n if (typeof reducer !== 'function') {\n throw new ERR_INVALID_ARG_TYPE('reducer', ['Function', 'AsyncFunction'], reducer)\n }\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n let hasInitialValue = arguments.length > 1\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal2 = options.signal) !== null &&\n _options$signal2 !== undefined &&\n _options$signal2.aborted\n ) {\n const err = new AbortError(undefined, {\n cause: options.signal.reason\n })\n this.once('error', () => {}) // The error is already propagated\n await finished(this.destroy(err))\n throw err\n }\n const ac = new AbortController()\n const signal = ac.signal\n if (options !== null && options !== undefined && options.signal) {\n const opts = {\n once: true,\n [kWeakHandler]: this,\n [kResistStopPropagation]: true\n }\n options.signal.addEventListener('abort', () => ac.abort(), opts)\n }\n let gotAnyItemFromStream = false\n try {\n for await (const value of this) {\n var _options$signal3\n gotAnyItemFromStream = true\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal3 = options.signal) !== null &&\n _options$signal3 !== undefined &&\n _options$signal3.aborted\n ) {\n throw new AbortError()\n }\n if (!hasInitialValue) {\n initialValue = value\n hasInitialValue = true\n } else {\n initialValue = await reducer(initialValue, value, {\n signal\n })\n }\n }\n if (!gotAnyItemFromStream && !hasInitialValue) {\n throw new ReduceAwareErrMissingArgs()\n }\n } finally {\n ac.abort()\n }\n return initialValue\n}\nasync function toArray(options) {\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n const result = []\n for await (const val of this) {\n var _options$signal4\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal4 = options.signal) !== null &&\n _options$signal4 !== undefined &&\n _options$signal4.aborted\n ) {\n throw new AbortError(undefined, {\n cause: options.signal.reason\n })\n }\n ArrayPrototypePush(result, val)\n }\n return result\n}\nfunction flatMap(fn, options) {\n const values = map.call(this, fn, options)\n return async function* flatMap() {\n for await (const val of values) {\n yield* val\n }\n }.call(this)\n}\nfunction toIntegerOrInfinity(number) {\n // We coerce here to align with the spec\n // https://github.com/tc39/proposal-iterator-helpers/issues/169\n number = Number(number)\n if (NumberIsNaN(number)) {\n return 0\n }\n if (number < 0) {\n throw new ERR_OUT_OF_RANGE('number', '>= 0', number)\n }\n return number\n}\nfunction drop(number, options = undefined) {\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n number = toIntegerOrInfinity(number)\n return async function* drop() {\n var _options$signal5\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal5 = options.signal) !== null &&\n _options$signal5 !== undefined &&\n _options$signal5.aborted\n ) {\n throw new AbortError()\n }\n for await (const val of this) {\n var _options$signal6\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal6 = options.signal) !== null &&\n _options$signal6 !== undefined &&\n _options$signal6.aborted\n ) {\n throw new AbortError()\n }\n if (number-- <= 0) {\n yield val\n }\n }\n }.call(this)\n}\nfunction take(number, options = undefined) {\n if (options != null) {\n validateObject(options, 'options')\n }\n if ((options === null || options === undefined ? undefined : options.signal) != null) {\n validateAbortSignal(options.signal, 'options.signal')\n }\n number = toIntegerOrInfinity(number)\n return async function* take() {\n var _options$signal7\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal7 = options.signal) !== null &&\n _options$signal7 !== undefined &&\n _options$signal7.aborted\n ) {\n throw new AbortError()\n }\n for await (const val of this) {\n var _options$signal8\n if (\n options !== null &&\n options !== undefined &&\n (_options$signal8 = options.signal) !== null &&\n _options$signal8 !== undefined &&\n _options$signal8.aborted\n ) {\n throw new AbortError()\n }\n if (number-- > 0) {\n yield val\n }\n\n // Don't get another item from iterator in case we reached the end\n if (number <= 0) {\n return\n }\n }\n }.call(this)\n}\nmodule.exports.streamReturningOperators = {\n asIndexedPairs: deprecate(asIndexedPairs, 'readable.asIndexedPairs will be removed in a future version.'),\n drop,\n filter,\n flatMap,\n map,\n take,\n compose\n}\nmodule.exports.promiseReturningOperators = {\n every,\n forEach,\n reduce,\n toArray,\n some,\n find\n}\n","'use strict'\n\nconst { ArrayPrototypePop, Promise } = require('../ours/primordials')\nconst { isIterable, isNodeStream, isWebStream } = require('../internal/streams/utils')\nconst { pipelineImpl: pl } = require('../internal/streams/pipeline')\nconst { finished } = require('../internal/streams/end-of-stream')\nrequire('../../lib/stream.js')\nfunction pipeline(...streams) {\n return new Promise((resolve, reject) => {\n let signal\n let end\n const lastArg = streams[streams.length - 1]\n if (\n lastArg &&\n typeof lastArg === 'object' &&\n !isNodeStream(lastArg) &&\n !isIterable(lastArg) &&\n !isWebStream(lastArg)\n ) {\n const options = ArrayPrototypePop(streams)\n signal = options.signal\n end = options.end\n }\n pl(\n streams,\n (err, value) => {\n if (err) {\n reject(err)\n } else {\n resolve(value)\n }\n },\n {\n signal,\n end\n }\n )\n })\n}\nmodule.exports = {\n finished,\n pipeline\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict'\n\n/* replacement start */\n\nconst { Buffer } = require('buffer')\n\n/* replacement end */\n\nconst { ObjectDefineProperty, ObjectKeys, ReflectApply } = require('./ours/primordials')\nconst {\n promisify: { custom: customPromisify }\n} = require('./ours/util')\nconst { streamReturningOperators, promiseReturningOperators } = require('./internal/streams/operators')\nconst {\n codes: { ERR_ILLEGAL_CONSTRUCTOR }\n} = require('./ours/errors')\nconst compose = require('./internal/streams/compose')\nconst { setDefaultHighWaterMark, getDefaultHighWaterMark } = require('./internal/streams/state')\nconst { pipeline } = require('./internal/streams/pipeline')\nconst { destroyer } = require('./internal/streams/destroy')\nconst eos = require('./internal/streams/end-of-stream')\nconst internalBuffer = {}\nconst promises = require('./stream/promises')\nconst utils = require('./internal/streams/utils')\nconst Stream = (module.exports = require('./internal/streams/legacy').Stream)\nStream.isDestroyed = utils.isDestroyed\nStream.isDisturbed = utils.isDisturbed\nStream.isErrored = utils.isErrored\nStream.isReadable = utils.isReadable\nStream.isWritable = utils.isWritable\nStream.Readable = require('./internal/streams/readable')\nfor (const key of ObjectKeys(streamReturningOperators)) {\n const op = streamReturningOperators[key]\n function fn(...args) {\n if (new.target) {\n throw ERR_ILLEGAL_CONSTRUCTOR()\n }\n return Stream.Readable.from(ReflectApply(op, this, args))\n }\n ObjectDefineProperty(fn, 'name', {\n __proto__: null,\n value: op.name\n })\n ObjectDefineProperty(fn, 'length', {\n __proto__: null,\n value: op.length\n })\n ObjectDefineProperty(Stream.Readable.prototype, key, {\n __proto__: null,\n value: fn,\n enumerable: false,\n configurable: true,\n writable: true\n })\n}\nfor (const key of ObjectKeys(promiseReturningOperators)) {\n const op = promiseReturningOperators[key]\n function fn(...args) {\n if (new.target) {\n throw ERR_ILLEGAL_CONSTRUCTOR()\n }\n return ReflectApply(op, this, args)\n }\n ObjectDefineProperty(fn, 'name', {\n __proto__: null,\n value: op.name\n })\n ObjectDefineProperty(fn, 'length', {\n __proto__: null,\n value: op.length\n })\n ObjectDefineProperty(Stream.Readable.prototype, key, {\n __proto__: null,\n value: fn,\n enumerable: false,\n configurable: true,\n writable: true\n })\n}\nStream.Writable = require('./internal/streams/writable')\nStream.Duplex = require('./internal/streams/duplex')\nStream.Transform = require('./internal/streams/transform')\nStream.PassThrough = require('./internal/streams/passthrough')\nStream.pipeline = pipeline\nconst { addAbortSignal } = require('./internal/streams/add-abort-signal')\nStream.addAbortSignal = addAbortSignal\nStream.finished = eos\nStream.destroy = destroyer\nStream.compose = compose\nStream.setDefaultHighWaterMark = setDefaultHighWaterMark\nStream.getDefaultHighWaterMark = getDefaultHighWaterMark\nObjectDefineProperty(Stream, 'promises', {\n __proto__: null,\n configurable: true,\n enumerable: true,\n get() {\n return promises\n }\n})\nObjectDefineProperty(pipeline, customPromisify, {\n __proto__: null,\n enumerable: true,\n get() {\n return promises.pipeline\n }\n})\nObjectDefineProperty(eos, customPromisify, {\n __proto__: null,\n enumerable: true,\n get() {\n return promises.finished\n }\n})\n\n// Backwards-compat with node 0.4.x\nStream.Stream = Stream\nStream._isUint8Array = function isUint8Array(value) {\n return value instanceof Uint8Array\n}\nStream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)\n}\n","'use strict'\n\nconst Stream = require('stream')\nif (Stream && process.env.READABLE_STREAM === 'disable') {\n const promises = Stream.promises\n\n // Explicit export naming is needed for ESM\n module.exports._uint8ArrayToBuffer = Stream._uint8ArrayToBuffer\n module.exports._isUint8Array = Stream._isUint8Array\n module.exports.isDisturbed = Stream.isDisturbed\n module.exports.isErrored = Stream.isErrored\n module.exports.isReadable = Stream.isReadable\n module.exports.Readable = Stream.Readable\n module.exports.Writable = Stream.Writable\n module.exports.Duplex = Stream.Duplex\n module.exports.Transform = Stream.Transform\n module.exports.PassThrough = Stream.PassThrough\n module.exports.addAbortSignal = Stream.addAbortSignal\n module.exports.finished = Stream.finished\n module.exports.destroy = Stream.destroy\n module.exports.pipeline = Stream.pipeline\n module.exports.compose = Stream.compose\n Object.defineProperty(Stream, 'promises', {\n configurable: true,\n enumerable: true,\n get() {\n return promises\n }\n })\n module.exports.Stream = Stream.Stream\n} else {\n const CustomStream = require('../stream')\n const promises = require('../stream/promises')\n const originalDestroy = CustomStream.Readable.destroy\n module.exports = CustomStream.Readable\n\n // Explicit export naming is needed for ESM\n module.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer\n module.exports._isUint8Array = CustomStream._isUint8Array\n module.exports.isDisturbed = CustomStream.isDisturbed\n module.exports.isErrored = CustomStream.isErrored\n module.exports.isReadable = CustomStream.isReadable\n module.exports.Readable = CustomStream.Readable\n module.exports.Writable = CustomStream.Writable\n module.exports.Duplex = CustomStream.Duplex\n module.exports.Transform = CustomStream.Transform\n module.exports.PassThrough = CustomStream.PassThrough\n module.exports.addAbortSignal = CustomStream.addAbortSignal\n module.exports.finished = CustomStream.finished\n module.exports.destroy = CustomStream.destroy\n module.exports.destroy = originalDestroy\n module.exports.pipeline = CustomStream.pipeline\n module.exports.compose = CustomStream.compose\n Object.defineProperty(CustomStream, 'promises', {\n configurable: true,\n enumerable: true,\n get() {\n return promises\n }\n })\n module.exports.Stream = CustomStream.Stream\n}\n\n// Allow default importing\nmodule.exports.default = module.exports\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nmodule.exports = arrayPush;\n","var Symbol = require('./_Symbol'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray');\n\n/** Built-in value references. */\nvar spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;\n\n/**\n * Checks if `value` is a flattenable `arguments` object or array.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.\n */\nfunction isFlattenable(value) {\n return isArray(value) || isArguments(value) ||\n !!(spreadableSymbol && value && value[spreadableSymbol]);\n}\n\nmodule.exports = isFlattenable;\n","var arrayPush = require('./_arrayPush'),\n isFlattenable = require('./_isFlattenable');\n\n/**\n * The base implementation of `_.flatten` with support for restricting flattening.\n *\n * @private\n * @param {Array} array The array to flatten.\n * @param {number} depth The maximum recursion depth.\n * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.\n * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.\n * @param {Array} [result=[]] The initial result value.\n * @returns {Array} Returns the new flattened array.\n */\nfunction baseFlatten(array, depth, predicate, isStrict, result) {\n var index = -1,\n length = array.length;\n\n predicate || (predicate = isFlattenable);\n result || (result = []);\n\n while (++index < length) {\n var value = array[index];\n if (depth > 0 && predicate(value)) {\n if (depth > 1) {\n // Recursively flatten arrays (susceptible to call stack limits).\n baseFlatten(value, depth - 1, predicate, isStrict, result);\n } else {\n arrayPush(result, value);\n }\n } else if (!isStrict) {\n result[result.length] = value;\n }\n }\n return result;\n}\n\nmodule.exports = baseFlatten;\n","var baseFlatten = require('./_baseFlatten');\n\n/**\n * Flattens `array` a single level deep.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flatten([1, [2, [3, [4]], 5]]);\n * // => [1, 2, [3, [4]], 5]\n */\nfunction flatten(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, 1) : [];\n}\n\nmodule.exports = flatten;\n","var getNative = require('./_getNative');\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nmodule.exports = nativeCreate;\n","var nativeCreate = require('./_nativeCreate');\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nmodule.exports = hashClear;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nmodule.exports = hashDelete;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nmodule.exports = hashGet;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nmodule.exports = hashHas;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nmodule.exports = hashSet;\n","var hashClear = require('./_hashClear'),\n hashDelete = require('./_hashDelete'),\n hashGet = require('./_hashGet'),\n hashHas = require('./_hashHas'),\n hashSet = require('./_hashSet');\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nmodule.exports = Hash;\n","/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nmodule.exports = listCacheClear;\n","var eq = require('./eq');\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nmodule.exports = assocIndexOf;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nmodule.exports = listCacheDelete;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nmodule.exports = listCacheGet;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nmodule.exports = listCacheHas;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nmodule.exports = listCacheSet;\n","var listCacheClear = require('./_listCacheClear'),\n listCacheDelete = require('./_listCacheDelete'),\n listCacheGet = require('./_listCacheGet'),\n listCacheHas = require('./_listCacheHas'),\n listCacheSet = require('./_listCacheSet');\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nmodule.exports = ListCache;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nmodule.exports = Map;\n","var Hash = require('./_Hash'),\n ListCache = require('./_ListCache'),\n Map = require('./_Map');\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nmodule.exports = mapCacheClear;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nmodule.exports = isKeyable;\n","var isKeyable = require('./_isKeyable');\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nmodule.exports = getMapData;\n","var getMapData = require('./_getMapData');\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nmodule.exports = mapCacheDelete;\n","var getMapData = require('./_getMapData');\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nmodule.exports = mapCacheGet;\n","var getMapData = require('./_getMapData');\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nmodule.exports = mapCacheHas;\n","var getMapData = require('./_getMapData');\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nmodule.exports = mapCacheSet;\n","var mapCacheClear = require('./_mapCacheClear'),\n mapCacheDelete = require('./_mapCacheDelete'),\n mapCacheGet = require('./_mapCacheGet'),\n mapCacheHas = require('./_mapCacheHas'),\n mapCacheSet = require('./_mapCacheSet');\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nmodule.exports = MapCache;\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nmodule.exports = setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {boolean} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nmodule.exports = setCacheHas;\n","var MapCache = require('./_MapCache'),\n setCacheAdd = require('./_setCacheAdd'),\n setCacheHas = require('./_setCacheHas');\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nmodule.exports = SetCache;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nmodule.exports = baseFindIndex;\n","/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nmodule.exports = baseIsNaN;\n","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nmodule.exports = strictIndexOf;\n","var baseFindIndex = require('./_baseFindIndex'),\n baseIsNaN = require('./_baseIsNaN'),\n strictIndexOf = require('./_strictIndexOf');\n\n/**\n * The base implementation of `_.indexOf` without `fromIndex` bounds checks.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseIndexOf(array, value, fromIndex) {\n return value === value\n ? strictIndexOf(array, value, fromIndex)\n : baseFindIndex(array, baseIsNaN, fromIndex);\n}\n\nmodule.exports = baseIndexOf;\n","var baseIndexOf = require('./_baseIndexOf');\n\n/**\n * A specialized version of `_.includes` for arrays without support for\n * specifying an index to search from.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludes(array, value) {\n var length = array == null ? 0 : array.length;\n return !!length && baseIndexOf(array, value, 0) > -1;\n}\n\nmodule.exports = arrayIncludes;\n","/**\n * This function is like `arrayIncludes` except that it accepts a comparator.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludesWith(array, value, comparator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (comparator(value, array[index])) {\n return true;\n }\n }\n return false;\n}\n\nmodule.exports = arrayIncludesWith;\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nmodule.exports = arrayMap;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nmodule.exports = cacheHas;\n","var SetCache = require('./_SetCache'),\n arrayIncludes = require('./_arrayIncludes'),\n arrayIncludesWith = require('./_arrayIncludesWith'),\n arrayMap = require('./_arrayMap'),\n baseUnary = require('./_baseUnary'),\n cacheHas = require('./_cacheHas');\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * The base implementation of methods like `_.difference` without support\n * for excluding multiple arrays or iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Array} values The values to exclude.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n */\nfunction baseDifference(array, values, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n isCommon = true,\n length = array.length,\n result = [],\n valuesLength = values.length;\n\n if (!length) {\n return result;\n }\n if (iteratee) {\n values = arrayMap(values, baseUnary(iteratee));\n }\n if (comparator) {\n includes = arrayIncludesWith;\n isCommon = false;\n }\n else if (values.length >= LARGE_ARRAY_SIZE) {\n includes = cacheHas;\n isCommon = false;\n values = new SetCache(values);\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee == null ? value : iteratee(value);\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var valuesIndex = valuesLength;\n while (valuesIndex--) {\n if (values[valuesIndex] === computed) {\n continue outer;\n }\n }\n result.push(value);\n }\n else if (!includes(values, computed, comparator)) {\n result.push(value);\n }\n }\n return result;\n}\n\nmodule.exports = baseDifference;\n","var isArrayLike = require('./isArrayLike'),\n isObjectLike = require('./isObjectLike');\n\n/**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\nfunction isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n}\n\nmodule.exports = isArrayLikeObject;\n","var baseDifference = require('./_baseDifference'),\n baseFlatten = require('./_baseFlatten'),\n baseRest = require('./_baseRest'),\n isArrayLikeObject = require('./isArrayLikeObject');\n\n/**\n * Creates an array of `array` values not included in the other given arrays\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. The order and references of result values are\n * determined by the first array.\n *\n * **Note:** Unlike `_.pullAll`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.without, _.xor\n * @example\n *\n * _.difference([2, 1], [2, 3]);\n * // => [1]\n */\nvar difference = baseRest(function(array, values) {\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))\n : [];\n});\n\nmodule.exports = difference;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nmodule.exports = Set;\n","/**\n * This method returns `undefined`.\n *\n * @static\n * @memberOf _\n * @since 2.3.0\n * @category Util\n * @example\n *\n * _.times(2, _.noop);\n * // => [undefined, undefined]\n */\nfunction noop() {\n // No operation performed.\n}\n\nmodule.exports = noop;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nmodule.exports = setToArray;\n","var Set = require('./_Set'),\n noop = require('./noop'),\n setToArray = require('./_setToArray');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Creates a set object of `values`.\n *\n * @private\n * @param {Array} values The values to add to the set.\n * @returns {Object} Returns the new set.\n */\nvar createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {\n return new Set(values);\n};\n\nmodule.exports = createSet;\n","var SetCache = require('./_SetCache'),\n arrayIncludes = require('./_arrayIncludes'),\n arrayIncludesWith = require('./_arrayIncludesWith'),\n cacheHas = require('./_cacheHas'),\n createSet = require('./_createSet'),\n setToArray = require('./_setToArray');\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * The base implementation of `_.uniqBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n */\nfunction baseUniq(array, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n length = array.length,\n isCommon = true,\n result = [],\n seen = result;\n\n if (comparator) {\n isCommon = false;\n includes = arrayIncludesWith;\n }\n else if (length >= LARGE_ARRAY_SIZE) {\n var set = iteratee ? null : createSet(array);\n if (set) {\n return setToArray(set);\n }\n isCommon = false;\n includes = cacheHas;\n seen = new SetCache;\n }\n else {\n seen = iteratee ? [] : result;\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var seenIndex = seen.length;\n while (seenIndex--) {\n if (seen[seenIndex] === computed) {\n continue outer;\n }\n }\n if (iteratee) {\n seen.push(computed);\n }\n result.push(value);\n }\n else if (!includes(seen, computed, comparator)) {\n if (seen !== result) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n}\n\nmodule.exports = baseUniq;\n","var baseFlatten = require('./_baseFlatten'),\n baseRest = require('./_baseRest'),\n baseUniq = require('./_baseUniq'),\n isArrayLikeObject = require('./isArrayLikeObject');\n\n/**\n * Creates an array of unique values, in order, from all given arrays using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * _.union([2], [1, 2]);\n * // => [2, 1]\n */\nvar union = baseRest(function(arrays) {\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));\n});\n\nmodule.exports = union;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nmodule.exports = overArg;\n","var overArg = require('./_overArg');\n\n/** Built-in value references. */\nvar getPrototype = overArg(Object.getPrototypeOf, Object);\n\nmodule.exports = getPrototype;\n","var baseGetTag = require('./_baseGetTag'),\n getPrototype = require('./_getPrototype'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to infer the `Object` constructor. */\nvar objectCtorString = funcToString.call(Object);\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nfunction isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n funcToString.call(Ctor) == objectCtorString;\n}\n\nmodule.exports = isPlainObject;\n","const MAX_PATTERN_LENGTH = 1024 * 64\nexport const assertValidPattern: (pattern: any) => void = (\n pattern: any\n): asserts pattern is string => {\n if (typeof pattern !== 'string') {\n throw new TypeError('invalid pattern')\n }\n\n if (pattern.length > MAX_PATTERN_LENGTH) {\n throw new TypeError('pattern is too long')\n }\n}\n","// translate the various posix character classes into unicode properties\n// this works across all unicode locales\n\n// { : [, /u flag required, negated]\nconst posixClasses: { [k: string]: [e: string, u: boolean, n?: boolean] } = {\n '[:alnum:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}', true],\n '[:alpha:]': ['\\\\p{L}\\\\p{Nl}', true],\n '[:ascii:]': ['\\\\x' + '00-\\\\x' + '7f', false],\n '[:blank:]': ['\\\\p{Zs}\\\\t', true],\n '[:cntrl:]': ['\\\\p{Cc}', true],\n '[:digit:]': ['\\\\p{Nd}', true],\n '[:graph:]': ['\\\\p{Z}\\\\p{C}', true, true],\n '[:lower:]': ['\\\\p{Ll}', true],\n '[:print:]': ['\\\\p{C}', true],\n '[:punct:]': ['\\\\p{P}', true],\n '[:space:]': ['\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f', true],\n '[:upper:]': ['\\\\p{Lu}', true],\n '[:word:]': ['\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}', true],\n '[:xdigit:]': ['A-Fa-f0-9', false],\n}\n\n// only need to escape a few things inside of brace expressions\n// escapes: [ \\ ] -\nconst braceEscape = (s: string) => s.replace(/[[\\]\\\\-]/g, '\\\\$&')\n// escape all regexp magic characters\nconst regexpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// everything has already been escaped, we just have to join\nconst rangesToString = (ranges: string[]): string => ranges.join('')\n\nexport type ParseClassResult = [\n src: string,\n uFlag: boolean,\n consumed: number,\n hasMagic: boolean\n]\n\n// takes a glob string at a posix brace expression, and returns\n// an equivalent regular expression source, and boolean indicating\n// whether the /u flag needs to be applied, and the number of chars\n// consumed to parse the character class.\n// This also removes out of order ranges, and returns ($.) if the\n// entire class just no good.\nexport const parseClass = (\n glob: string,\n position: number\n): ParseClassResult => {\n const pos = position\n /* c8 ignore start */\n if (glob.charAt(pos) !== '[') {\n throw new Error('not in a brace expression')\n }\n /* c8 ignore stop */\n const ranges: string[] = []\n const negs: string[] = []\n\n let i = pos + 1\n let sawStart = false\n let uflag = false\n let escaping = false\n let negate = false\n let endPos = pos\n let rangeStart = ''\n WHILE: while (i < glob.length) {\n const c = glob.charAt(i)\n if ((c === '!' || c === '^') && i === pos + 1) {\n negate = true\n i++\n continue\n }\n\n if (c === ']' && sawStart && !escaping) {\n endPos = i + 1\n break\n }\n\n sawStart = true\n if (c === '\\\\') {\n if (!escaping) {\n escaping = true\n i++\n continue\n }\n // escaped \\ char, fall through and treat like normal char\n }\n if (c === '[' && !escaping) {\n // either a posix class, a collation equivalent, or just a [\n for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {\n if (glob.startsWith(cls, i)) {\n // invalid, [a-[] is fine, but not [a-[:alpha]]\n if (rangeStart) {\n return ['$.', false, glob.length - pos, true]\n }\n i += cls.length\n if (neg) negs.push(unip)\n else ranges.push(unip)\n uflag = uflag || u\n continue WHILE\n }\n }\n }\n\n // now it's just a normal character, effectively\n escaping = false\n if (rangeStart) {\n // throw this range away if it's not valid, but others\n // can still match.\n if (c > rangeStart) {\n ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c))\n } else if (c === rangeStart) {\n ranges.push(braceEscape(c))\n }\n rangeStart = ''\n i++\n continue\n }\n\n // now might be the start of a range.\n // can be either c-d or c-] or c] or c] at this point\n if (glob.startsWith('-]', i + 1)) {\n ranges.push(braceEscape(c + '-'))\n i += 2\n continue\n }\n if (glob.startsWith('-', i + 1)) {\n rangeStart = c\n i += 2\n continue\n }\n\n // not the start of a range, just a single character\n ranges.push(braceEscape(c))\n i++\n }\n\n if (endPos < i) {\n // didn't see the end of the class, not a valid class,\n // but might still be valid as a literal match.\n return ['', false, 0, false]\n }\n\n // if we got no ranges and no negates, then we have a range that\n // cannot possibly match anything, and that poisons the whole glob\n if (!ranges.length && !negs.length) {\n return ['$.', false, glob.length - pos, true]\n }\n\n // if we got one positive range, and it's a single character, then that's\n // not actually a magic pattern, it's just that one literal character.\n // we should not treat that as \"magic\", we should just return the literal\n // character. [_] is a perfectly valid way to escape glob magic chars.\n if (\n negs.length === 0 &&\n ranges.length === 1 &&\n /^\\\\?.$/.test(ranges[0]) &&\n !negate\n ) {\n const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0]\n return [regexpEscape(r), false, endPos - pos, false]\n }\n\n const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']'\n const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']'\n const comb =\n ranges.length && negs.length\n ? '(' + sranges + '|' + snegs + ')'\n : ranges.length\n ? sranges\n : snegs\n\n return [comb, uflag, endPos - pos, true]\n}\n","import { MinimatchOptions } from './index.js'\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link windowsPathsNoEscape} option is used, then square-brace\n * escapes are removed, but not backslash escapes. For example, it will turn\n * the string `'[*]'` into `*`, but it will not turn `'\\\\*'` into `'*'`,\n * becuase `\\` is a path separator in `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both brace escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n */\nexport const unescape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n }: Pick = {}\n) => {\n return windowsPathsNoEscape\n ? s.replace(/\\[([^\\/\\\\])\\]/g, '$1')\n : s.replace(/((?!\\\\).|^)\\[([^\\/\\\\])\\]/g, '$1$2').replace(/\\\\([^\\/])/g, '$1')\n}\n","// parse a single path portion\n\nimport { parseClass } from './brace-expressions.js'\nimport { MinimatchOptions, MMRegExp } from './index.js'\nimport { unescape } from './unescape.js'\n\n// classes [] are handled by the parseClass method\n// for positive extglobs, we sub-parse the contents, and combine,\n// with the appropriate regexp close.\n// for negative extglobs, we sub-parse the contents, but then\n// have to include the rest of the pattern, then the parent, etc.,\n// as the thing that cannot be because RegExp negative lookaheads\n// are different from globs.\n//\n// So for example:\n// a@(i|w!(x|y)z|j)b => ^a(i|w((!?(x|y)zb).*)z|j)b$\n// 1 2 3 4 5 6 1 2 3 46 5 6\n//\n// Assembling the extglob requires not just the negated patterns themselves,\n// but also anything following the negative patterns up to the boundary\n// of the current pattern, plus anything following in the parent pattern.\n//\n//\n// So, first, we parse the string into an AST of extglobs, without turning\n// anything into regexps yet.\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y']}, 'z'], ['j']]}, 'b']\n//\n// Then, for all the negative extglobs, we append whatever comes after in\n// each parent as their tail\n//\n// ['a', {@ [['i'], ['w', {!['x', 'y'], 'z', 'b'}, 'z'], ['j']]}, 'b']\n//\n// Lastly, we turn each of these pieces into a regexp, and join\n//\n// v----- .* because there's more following,\n// v v otherwise, .+ because it must be\n// v v *something* there.\n// ['^a', {@ ['i', 'w(?:(!?(?:x|y).*zb$).*)z', 'j' ]}, 'b$']\n// copy what follows into here--^^^^^\n// ['^a', '(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)', 'b$']\n// ['^a(?:i|w(?:(?!(?:x|y).*zb$).*)z|j)b$']\n\nexport type ExtglobType = '!' | '?' | '+' | '*' | '@'\nconst types = new Set(['!', '?', '+', '*', '@'])\nconst isExtglobType = (c: string | null): c is ExtglobType =>\n types.has(c as ExtglobType)\nconst isExtglobAST = (c: AST): c is AST & { type: ExtglobType } =>\n isExtglobType(c.type)\n\nconst adoptionMap = new Map([\n ['!', ['@']],\n ['?', ['?', '@']],\n ['@', ['@']],\n ['*', ['*', '+', '?', '@']],\n ['+', ['+', '@']],\n])\n\nconst adoptionWithSpaceMap = new Map([\n ['!', ['?']],\n ['@', ['?']],\n ['+', ['?', '*']],\n])\n\nconst adoptionAnyMap = new Map([\n ['!', ['?', '@']],\n ['?', ['?', '@']],\n ['@', ['?', '@']],\n ['*', ['*', '+', '?', '@']],\n ['+', ['+', '@', '?', '*']],\n])\n\nconst usurpMap = new Map>([\n ['!', new Map([['!', '@']])],\n ['?', new Map([['*', '*'], ['+', '*']])],\n ['@', new Map([['!', '!'], ['?', '?'], ['@', '@'], ['*', '*'], ['+', '+']])],\n ['+', new Map([['?', '*'], ['*', '*']])],\n])\n\n// Patterns that get prepended to bind to the start of either the\n// entire string, or just a single path portion, to prevent dots\n// and/or traversal patterns, when needed.\n// Exts don't need the ^ or / bit, because the root binds that already.\nconst startNoTraversal = '(?!(?:^|/)\\\\.\\\\.?(?:$|/))'\nconst startNoDot = '(?!\\\\.)'\n\n// characters that indicate a start of pattern needs the \"no dots\" bit,\n// because a dot *might* be matched. ( is not in the list, because in\n// the case of a child extglob, it will handle the prevention itself.\nconst addPatternStart = new Set(['[', '.'])\n// cases where traversal is A-OK, no dot prevention needed\nconst justDots = new Set(['..', '.'])\nconst reSpecials = new Set('().*{}+?[]^$\\\\!')\nconst regExpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\n// any single thing other than /\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n// use + when we need to ensure that *something* matches, because the * is\n// the only thing in the path portion.\nconst starNoEmpty = qmark + '+?'\n\n// remove the \\ chars that we added if we end up doing a nonmagic compare\n// const deslash = (s: string) => s.replace(/\\\\(.)/g, '$1')\n\nexport class AST {\n type: ExtglobType | null\n readonly #root: AST\n\n #hasMagic?: boolean\n #uflag: boolean = false\n #parts: (string | AST)[] = []\n #parent?: AST\n #parentIndex: number\n #negs: AST[]\n #filledNegs: boolean = false\n #options: MinimatchOptions\n #toString?: string\n // set to true if it's an extglob with no children\n // (which really means one child of '')\n #emptyExt: boolean = false\n\n constructor(\n type: ExtglobType | null,\n parent?: AST,\n options: MinimatchOptions = {}\n ) {\n this.type = type\n // extglobs are inherently magical\n if (type) this.#hasMagic = true\n this.#parent = parent\n this.#root = this.#parent ? this.#parent.#root : this\n this.#options = this.#root === this ? options : this.#root.#options\n this.#negs = this.#root === this ? [] : this.#root.#negs\n if (type === '!' && !this.#root.#filledNegs) this.#negs.push(this)\n this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0\n }\n\n get hasMagic(): boolean | undefined {\n /* c8 ignore start */\n if (this.#hasMagic !== undefined) return this.#hasMagic\n /* c8 ignore stop */\n for (const p of this.#parts) {\n if (typeof p === 'string') continue\n if (p.type || p.hasMagic) return (this.#hasMagic = true)\n }\n // note: will be undefined until we generate the regexp src and find out\n return this.#hasMagic\n }\n\n // reconstructs the pattern\n toString(): string {\n if (this.#toString !== undefined) return this.#toString\n if (!this.type) {\n return (this.#toString = this.#parts.map(p => String(p)).join(''))\n } else {\n return (this.#toString =\n this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')')\n }\n }\n\n #fillNegs() {\n /* c8 ignore start */\n if (this !== this.#root) throw new Error('should only call on root')\n if (this.#filledNegs) return this\n /* c8 ignore stop */\n\n // call toString() once to fill this out\n this.toString()\n this.#filledNegs = true\n let n: AST | undefined\n while ((n = this.#negs.pop())) {\n if (n.type !== '!') continue\n // walk up the tree, appending everthing that comes AFTER parentIndex\n let p: AST | undefined = n\n let pp = p.#parent\n while (pp) {\n for (\n let i = p.#parentIndex + 1;\n !pp.type && i < pp.#parts.length;\n i++\n ) {\n for (const part of n.#parts) {\n /* c8 ignore start */\n if (typeof part === 'string') {\n throw new Error('string part in extglob AST??')\n }\n /* c8 ignore stop */\n part.copyIn(pp.#parts[i])\n }\n }\n p = pp\n pp = p.#parent\n }\n }\n return this\n }\n\n push(...parts: (string | AST)[]) {\n for (const p of parts) {\n if (p === '') continue\n /* c8 ignore start */\n if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {\n throw new Error('invalid part: ' + p)\n }\n /* c8 ignore stop */\n this.#parts.push(p)\n }\n }\n\n toJSON() {\n const ret: any[] =\n this.type === null\n ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))\n : [this.type, ...this.#parts.map(p => (p as AST).toJSON())]\n if (this.isStart() && !this.type) ret.unshift([])\n if (\n this.isEnd() &&\n (this === this.#root ||\n (this.#root.#filledNegs && this.#parent?.type === '!'))\n ) {\n ret.push({})\n }\n return ret\n }\n\n isStart(): boolean {\n if (this.#root === this) return true\n // if (this.type) return !!this.#parent?.isStart()\n if (!this.#parent?.isStart()) return false\n if (this.#parentIndex === 0) return true\n // if everything AHEAD of this is a negation, then it's still the \"start\"\n const p = this.#parent\n for (let i = 0; i < this.#parentIndex; i++) {\n const pp = p.#parts[i]\n if (!(pp instanceof AST && pp.type === '!')) {\n return false\n }\n }\n return true\n }\n\n isEnd(): boolean {\n if (this.#root === this) return true\n if (this.#parent?.type === '!') return true\n if (!this.#parent?.isEnd()) return false\n if (!this.type) return this.#parent?.isEnd()\n // if not root, it'll always have a parent\n /* c8 ignore start */\n const pl = this.#parent ? this.#parent.#parts.length : 0\n /* c8 ignore stop */\n return this.#parentIndex === pl - 1\n }\n\n copyIn(part: AST | string) {\n if (typeof part === 'string') this.push(part)\n else this.push(part.clone(this))\n }\n\n clone(parent: AST) {\n const c = new AST(this.type, parent)\n for (const p of this.#parts) {\n c.copyIn(p)\n }\n return c\n }\n\n static #parseAST(\n str: string,\n ast: AST,\n pos: number,\n opt: MinimatchOptions,\n extDepth: number\n ): number {\n const maxDepth = opt.maxExtglobRecursion ?? 2\n let escaping = false\n let inBrace = false\n let braceStart = -1\n let braceNeg = false\n if (ast.type === null) {\n // outside of a extglob, append until we find a start\n let i = pos\n let acc = ''\n while (i < str.length) {\n const c = str.charAt(i++)\n // still accumulate escapes at this point, but we do ignore\n // starts that are escaped\n if (escaping || c === '\\\\') {\n escaping = !escaping\n acc += c\n continue\n }\n\n if (inBrace) {\n if (i === braceStart + 1) {\n if (c === '^' || c === '!') {\n braceNeg = true\n }\n } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n inBrace = false\n }\n acc += c\n continue\n } else if (c === '[') {\n inBrace = true\n braceStart = i\n braceNeg = false\n acc += c\n continue\n }\n\n const doRecurse =\n !opt.noext &&\n isExtglobType(c) &&\n str.charAt(i) === '(' &&\n extDepth <= maxDepth\n if (doRecurse) {\n ast.push(acc)\n acc = ''\n const ext = new AST(c, ast)\n i = AST.#parseAST(str, ext, i, opt, extDepth + 1)\n ast.push(ext)\n continue\n }\n acc += c\n }\n ast.push(acc)\n return i\n }\n\n // some kind of extglob, pos is at the (\n // find the next | or )\n let i = pos + 1\n let part = new AST(null, ast)\n const parts: AST[] = []\n let acc = ''\n while (i < str.length) {\n const c = str.charAt(i++)\n // still accumulate escapes at this point, but we do ignore\n // starts that are escaped\n if (escaping || c === '\\\\') {\n escaping = !escaping\n acc += c\n continue\n }\n\n if (inBrace) {\n if (i === braceStart + 1) {\n if (c === '^' || c === '!') {\n braceNeg = true\n }\n } else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {\n inBrace = false\n }\n acc += c\n continue\n } else if (c === '[') {\n inBrace = true\n braceStart = i\n braceNeg = false\n acc += c\n continue\n }\n\n const doRecurse =\n isExtglobType(c) &&\n str.charAt(i) === '(' &&\n /* c8 ignore start - the maxDepth is sufficient here */\n (extDepth <= maxDepth || (ast && ast.#canAdoptType(c)))\n /* c8 ignore stop */\n if (doRecurse) {\n const depthAdd = ast && ast.#canAdoptType(c) ? 0 : 1\n part.push(acc)\n acc = ''\n const ext = new AST(c, part)\n part.push(ext)\n i = AST.#parseAST(str, ext, i, opt, extDepth + depthAdd)\n continue\n }\n if (c === '|') {\n part.push(acc)\n acc = ''\n parts.push(part)\n part = new AST(null, ast)\n continue\n }\n if (c === ')') {\n if (acc === '' && ast.#parts.length === 0) {\n ast.#emptyExt = true\n }\n part.push(acc)\n acc = ''\n ast.push(...parts, part)\n return i\n }\n acc += c\n }\n\n // unfinished extglob\n // if we got here, it was a malformed extglob! not an extglob, but\n // maybe something else in there.\n ast.type = null\n ast.#hasMagic = undefined\n ast.#parts = [str.substring(pos - 1)]\n return i\n }\n\n #canAdoptWithSpace(child?: AST | string): child is AST & {\n type: null\n parts: [AST & { type: ExtglobType }]\n } {\n return this.#canAdopt(child, adoptionWithSpaceMap)\n }\n\n #canAdopt(\n child?: AST | string,\n map: Map = adoptionMap\n ): child is AST & {\n type: null\n parts: [AST & { type: ExtglobType }]\n } {\n if (\n !child ||\n typeof child !== 'object' ||\n child.type !== null ||\n child.#parts.length !== 1 ||\n this.type === null\n ) {\n return false\n }\n const gc = child.#parts[0]\n if (!gc || typeof gc !== 'object' || gc.type === null) {\n return false\n }\n return (this as AST & { type: ExtglobType }).#canAdoptType(\n gc.type,\n map\n )\n }\n\n #canAdoptType(\n c: string,\n map: Map = adoptionAnyMap\n ): c is ExtglobType {\n return !!map.get(this.type as ExtglobType)?.includes(c as ExtglobType)\n }\n\n #adoptWithSpace(\n this: AST & { type: ExtglobType },\n child: AST & { type: null },\n index: number\n ) {\n const gc = child.#parts[0] as AST & { type: ExtglobType }\n const blank = new AST(null, gc, this.options)\n blank.#parts.push('')\n gc.push(blank)\n this.#adopt(child, index)\n }\n\n #adopt(child: AST & { type: null }, index: number) {\n const gc = child.#parts[0] as AST & { type: ExtglobType }\n this.#parts.splice(index, 1, ...gc.#parts)\n for (const p of gc.#parts) {\n if (typeof p === 'object') p.#parent = this\n }\n this.#toString = undefined\n }\n\n #canUsurpType(c: string): boolean {\n const m = usurpMap.get(this.type as ExtglobType)\n return !!(m?.has(c as ExtglobType))\n }\n\n #canUsurp(child?: AST | string): child is AST & {\n type: null\n parts: [AST & { type: ExtglobType }]\n } {\n if (\n !child ||\n typeof child !== 'object' ||\n child.type !== null ||\n child.#parts.length !== 1 ||\n this.type === null ||\n this.#parts.length !== 1\n ) {\n return false\n }\n const gc = child.#parts[0]\n if (!gc || typeof gc !== 'object' || gc.type === null) {\n return false\n }\n return (this as AST & { type: ExtglobType }).#canUsurpType(gc.type)\n }\n\n #usurp(this: AST & { type: ExtglobType }, child: AST & { type: null }) {\n const m = usurpMap.get(this.type as ExtglobType)\n const gc = child.#parts[0] as AST & { type: ExtglobType }\n const nt = m?.get(gc.type)\n /* c8 ignore start - impossible */\n if (!nt) return false\n /* c8 ignore stop */\n this.#parts = gc.#parts\n for (const p of this.#parts) {\n if (typeof p === 'object') p.#parent = this\n }\n this.type = nt\n this.#toString = undefined\n this.#emptyExt = false\n }\n\n #flatten() {\n if (!isExtglobAST(this)) {\n for (const p of this.#parts) {\n if (typeof p === 'object') p.#flatten()\n }\n } else {\n let iterations = 0\n let done = false\n do {\n done = true\n for (let i = 0; i < this.#parts.length; i++) {\n const c = this.#parts[i]\n if (typeof c === 'object') {\n c.#flatten()\n if (this.#canAdopt(c)) {\n done = false\n this.#adopt(c, i)\n } else if (this.#canAdoptWithSpace(c)) {\n done = false\n this.#adoptWithSpace(c, i)\n } else if (this.#canUsurp(c)) {\n done = false\n this.#usurp(c)\n }\n }\n }\n } while (!done && ++iterations < 10)\n }\n this.#toString = undefined\n }\n\n static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n const ast = new AST(null, undefined, options)\n AST.#parseAST(pattern, ast, 0, options, 0)\n return ast\n }\n\n // returns the regular expression if there's magic, or the unescaped\n // string if not.\n toMMPattern(): MMRegExp | string {\n // should only be called on root\n /* c8 ignore start */\n if (this !== this.#root) return this.#root.toMMPattern()\n /* c8 ignore stop */\n const glob = this.toString()\n const [re, body, hasMagic, uflag] = this.toRegExpSource()\n // if we're in nocase mode, and not nocaseMagicOnly, then we do\n // still need a regular expression if we have to case-insensitively\n // match capital/lowercase characters.\n const anyMagic =\n hasMagic ||\n this.#hasMagic ||\n (this.#options.nocase &&\n !this.#options.nocaseMagicOnly &&\n glob.toUpperCase() !== glob.toLowerCase())\n if (!anyMagic) {\n return body\n }\n\n const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '')\n return Object.assign(new RegExp(`^${re}$`, flags), {\n _src: re,\n _glob: glob,\n })\n }\n\n get options() {\n return this.#options\n }\n\n // returns the string match, the regexp source, whether there's magic\n // in the regexp (so a regular expression is required) and whether or\n // not the uflag is needed for the regular expression (for posix classes)\n // TODO: instead of injecting the start/end at this point, just return\n // the BODY of the regexp, along with the start/end portions suitable\n // for binding the start/end in either a joined full-path makeRe context\n // (where we bind to (^|/), or a standalone matchPart context (where\n // we bind to ^, and not /). Otherwise slashes get duped!\n //\n // In part-matching mode, the start is:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: ^(?!\\.\\.?$)\n // - if dots allowed or not possible: ^\n // - if dots possible and not allowed: ^(?!\\.)\n // end is:\n // - if not isEnd(): nothing\n // - else: $\n //\n // In full-path matching mode, we put the slash at the START of the\n // pattern, so start is:\n // - if first pattern: same as part-matching mode\n // - if not isStart(): nothing\n // - if traversal possible, but not allowed: /(?!\\.\\.?(?:$|/))\n // - if dots allowed or not possible: /\n // - if dots possible and not allowed: /(?!\\.)\n // end is:\n // - if last pattern, same as part-matching mode\n // - else nothing\n //\n // Always put the (?:$|/) on negated tails, though, because that has to be\n // there to bind the end of the negated pattern portion, and it's easier to\n // just stick it in now rather than try to inject it later in the middle of\n // the pattern.\n //\n // We can just always return the same end, and leave it up to the caller\n // to know whether it's going to be used joined or in parts.\n // And, if the start is adjusted slightly, can do the same there:\n // - if not isStart: nothing\n // - if traversal possible, but not allowed: (?:/|^)(?!\\.\\.?$)\n // - if dots allowed or not possible: (?:/|^)\n // - if dots possible and not allowed: (?:/|^)(?!\\.)\n //\n // But it's better to have a simpler binding without a conditional, for\n // performance, so probably better to return both start options.\n //\n // Then the caller just ignores the end if it's not the first pattern,\n // and the start always gets applied.\n //\n // But that's always going to be $ if it's the ending pattern, or nothing,\n // so the caller can just attach $ at the end of the pattern when building.\n //\n // So the todo is:\n // - better detect what kind of start is needed\n // - return both flavors of starting pattern\n // - attach $ at the end of the pattern when creating the actual RegExp\n //\n // Ah, but wait, no, that all only applies to the root when the first pattern\n // is not an extglob. If the first pattern IS an extglob, then we need all\n // that dot prevention biz to live in the extglob portions, because eg\n // +(*|.x*) can match .xy but not .yx.\n //\n // So, return the two flavors if it's #root and the first child is not an\n // AST, otherwise leave it to the child AST to handle it, and there,\n // use the (?:^|/) style of start binding.\n //\n // Even simplified further:\n // - Since the start for a join is eg /(?!\\.) and the start for a part\n // is ^(?!\\.), we can just prepend (?!\\.) to the pattern (either root\n // or start or whatever) and prepend ^ or / at the Regexp construction.\n toRegExpSource(\n allowDot?: boolean\n ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n const dot = allowDot ?? !!this.#options.dot\n if (this.#root === this) {\n this.#flatten()\n this.#fillNegs()\n }\n if (!isExtglobAST(this)) {\n const noEmpty = this.isStart() && this.isEnd()\n const src = this.#parts\n .map(p => {\n const [re, _, hasMagic, uflag] =\n typeof p === 'string'\n ? AST.#parseGlob(p, this.#hasMagic, noEmpty)\n : p.toRegExpSource(allowDot)\n this.#hasMagic = this.#hasMagic || hasMagic\n this.#uflag = this.#uflag || uflag\n return re\n })\n .join('')\n\n let start = ''\n if (this.isStart()) {\n if (typeof this.#parts[0] === 'string') {\n // this is the string that will match the start of the pattern,\n // so we need to protect against dots and such.\n\n // '.' and '..' cannot match unless the pattern is that exactly,\n // even if it starts with . or dot:true is set.\n const dotTravAllowed =\n this.#parts.length === 1 && justDots.has(this.#parts[0])\n if (!dotTravAllowed) {\n const aps = addPatternStart\n // check if we have a possibility of matching . or ..,\n // and prevent that.\n const needNoTrav =\n // dots are allowed, and the pattern starts with [ or .\n (dot && aps.has(src.charAt(0))) ||\n // the pattern starts with \\., and then [ or .\n (src.startsWith('\\\\.') && aps.has(src.charAt(2))) ||\n // the pattern starts with \\.\\., and then [ or .\n (src.startsWith('\\\\.\\\\.') && aps.has(src.charAt(4)))\n // no need to prevent dots if it can't match a dot, or if a\n // sub-pattern will be preventing it anyway.\n const needNoDot = !dot && !allowDot && aps.has(src.charAt(0))\n\n start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : ''\n }\n }\n }\n\n // append the \"end of path portion\" pattern to negation tails\n let end = ''\n if (\n this.isEnd() &&\n this.#root.#filledNegs &&\n this.#parent?.type === '!'\n ) {\n end = '(?:$|\\\\/)'\n }\n const final = start + src + end\n return [\n final,\n unescape(src),\n (this.#hasMagic = !!this.#hasMagic),\n this.#uflag,\n ]\n }\n\n // We need to calculate the body *twice* if it's a repeat pattern\n // at the start, once in nodot mode, then again in dot mode, so a\n // pattern like *(?) can match 'x.y'\n\n const repeated = this.type === '*' || this.type === '+'\n // some kind of extglob\n const start = this.type === '!' ? '(?:(?!(?:' : '(?:'\n let body = this.#partsToRegExp(dot)\n\n if (this.isStart() && this.isEnd() && !body && this.type !== '!') {\n // invalid extglob, has to at least be *something* present, if it's\n // the entire path portion.\n const s = this.toString()\n const me = this as AST\n me.#parts = [s]\n me.type = null\n me.#hasMagic = undefined\n return [s, unescape(this.toString()), false, false]\n }\n\n // XXX abstract out this map method\n let bodyDotAllowed =\n !repeated || allowDot || dot || !startNoDot\n ? ''\n : this.#partsToRegExp(true)\n if (bodyDotAllowed === body) {\n bodyDotAllowed = ''\n }\n if (bodyDotAllowed) {\n body = `(?:${body})(?:${bodyDotAllowed})*?`\n }\n\n // an empty !() is exactly equivalent to a starNoEmpty\n let final = ''\n if (this.type === '!' && this.#emptyExt) {\n final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty\n } else {\n const close =\n this.type === '!'\n ? // !() must match something,but !(x) can match ''\n '))' +\n (this.isStart() && !dot && !allowDot ? startNoDot : '') +\n star +\n ')'\n : this.type === '@'\n ? ')'\n : this.type === '?'\n ? ')?'\n : this.type === '+' && bodyDotAllowed\n ? ')'\n : this.type === '*' && bodyDotAllowed\n ? `)?`\n : `)${this.type}`\n final = start + body + close\n }\n return [\n final,\n unescape(body),\n (this.#hasMagic = !!this.#hasMagic),\n this.#uflag,\n ]\n }\n\n #partsToRegExp(dot: boolean) {\n return this.#parts\n .map(p => {\n // extglob ASTs should only contain parent ASTs\n /* c8 ignore start */\n if (typeof p === 'string') {\n throw new Error('string type in extglob ast??')\n }\n /* c8 ignore stop */\n // can ignore hasMagic, because extglobs are already always magic\n const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot)\n this.#uflag = this.#uflag || uflag\n return re\n })\n .filter(p => !(this.isStart() && this.isEnd()) || !!p)\n .join('|')\n }\n\n static #parseGlob(\n glob: string,\n hasMagic: boolean | undefined,\n noEmpty: boolean = false\n ): [re: string, body: string, hasMagic: boolean, uflag: boolean] {\n let escaping = false\n let re = ''\n let uflag = false\n // multiple stars that aren't globstars coalesce into one *\n let inStar = false\n for (let i = 0; i < glob.length; i++) {\n const c = glob.charAt(i)\n if (escaping) {\n escaping = false\n re += (reSpecials.has(c) ? '\\\\' : '') + c\n inStar = false\n continue\n }\n if (c === '\\\\') {\n if (i === glob.length - 1) {\n re += '\\\\\\\\'\n } else {\n escaping = true\n }\n continue\n }\n if (c === '[') {\n const [src, needUflag, consumed, magic] = parseClass(glob, i)\n if (consumed) {\n re += src\n uflag = uflag || needUflag\n i += consumed - 1\n hasMagic = hasMagic || magic\n inStar = false\n continue\n }\n }\n if (c === '*') {\n if (inStar) continue\n inStar = true\n re += noEmpty && /^[*]+$/.test(glob) ? starNoEmpty : star\n hasMagic = true\n continue\n } else {\n inStar = false\n }\n if (c === '?') {\n re += qmark\n hasMagic = true\n continue\n }\n re += regExpEscape(c)\n }\n return [re, unescape(glob), !!hasMagic, uflag]\n }\n}\n","import { MinimatchOptions } from './index.js'\n/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character. In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n */\nexport const escape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n }: Pick = {}\n) => {\n // don't need to escape +@! because we escape the parens\n // that make those magic, and escaping ! as [!] isn't valid,\n // because [!]] is a valid glob class meaning not ']'.\n return windowsPathsNoEscape\n ? s.replace(/[?*()[\\]]/g, '[$&]')\n : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&')\n}\n","import expand from 'brace-expansion'\nimport { assertValidPattern } from './assert-valid-pattern.js'\nimport { AST, ExtglobType } from './ast.js'\nimport { escape } from './escape.js'\nimport { unescape } from './unescape.js'\n\ntype Platform =\n | 'aix'\n | 'android'\n | 'darwin'\n | 'freebsd'\n | 'haiku'\n | 'linux'\n | 'openbsd'\n | 'sunos'\n | 'win32'\n | 'cygwin'\n | 'netbsd'\n\nexport interface MinimatchOptions {\n nobrace?: boolean\n nocomment?: boolean\n nonegate?: boolean\n debug?: boolean\n noglobstar?: boolean\n noext?: boolean\n nonull?: boolean\n windowsPathsNoEscape?: boolean\n allowWindowsEscape?: boolean\n partial?: boolean\n dot?: boolean\n nocase?: boolean\n nocaseMagicOnly?: boolean\n magicalBraces?: boolean\n matchBase?: boolean\n flipNegate?: boolean\n preserveMultipleSlashes?: boolean\n optimizationLevel?: number\n platform?: Platform\n windowsNoMagicRoot?: boolean\n maxGlobstarRecursion?: number\n maxExtglobRecursion?: number\n}\n\nexport const minimatch = (\n p: string,\n pattern: string,\n options: MinimatchOptions = {}\n) => {\n assertValidPattern(pattern)\n\n // shortcut: comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n return false\n }\n\n return new Minimatch(pattern, options).match(p)\n}\n\n// Optimized checking for the most common glob patterns.\nconst starDotExtRE = /^\\*+([^+@!?\\*\\[\\(]*)$/\nconst starDotExtTest = (ext: string) => (f: string) =>\n !f.startsWith('.') && f.endsWith(ext)\nconst starDotExtTestDot = (ext: string) => (f: string) => f.endsWith(ext)\nconst starDotExtTestNocase = (ext: string) => {\n ext = ext.toLowerCase()\n return (f: string) => !f.startsWith('.') && f.toLowerCase().endsWith(ext)\n}\nconst starDotExtTestNocaseDot = (ext: string) => {\n ext = ext.toLowerCase()\n return (f: string) => f.toLowerCase().endsWith(ext)\n}\nconst starDotStarRE = /^\\*+\\.\\*+$/\nconst starDotStarTest = (f: string) => !f.startsWith('.') && f.includes('.')\nconst starDotStarTestDot = (f: string) =>\n f !== '.' && f !== '..' && f.includes('.')\nconst dotStarRE = /^\\.\\*+$/\nconst dotStarTest = (f: string) => f !== '.' && f !== '..' && f.startsWith('.')\nconst starRE = /^\\*+$/\nconst starTest = (f: string) => f.length !== 0 && !f.startsWith('.')\nconst starTestDot = (f: string) => f.length !== 0 && f !== '.' && f !== '..'\nconst qmarksRE = /^\\?+([^+@!?\\*\\[\\(]*)?$/\nconst qmarksTestNocase = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExt([$0])\n if (!ext) return noext\n ext = ext.toLowerCase()\n return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestNocaseDot = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExtDot([$0])\n if (!ext) return noext\n ext = ext.toLowerCase()\n return (f: string) => noext(f) && f.toLowerCase().endsWith(ext)\n}\nconst qmarksTestDot = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExtDot([$0])\n return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTest = ([$0, ext = '']: RegExpMatchArray) => {\n const noext = qmarksTestNoExt([$0])\n return !ext ? noext : (f: string) => noext(f) && f.endsWith(ext)\n}\nconst qmarksTestNoExt = ([$0]: RegExpMatchArray) => {\n const len = $0.length\n return (f: string) => f.length === len && !f.startsWith('.')\n}\nconst qmarksTestNoExtDot = ([$0]: RegExpMatchArray) => {\n const len = $0.length\n return (f: string) => f.length === len && f !== '.' && f !== '..'\n}\n\n/* c8 ignore start */\nconst defaultPlatform: Platform = (\n typeof process === 'object' && process\n ? (typeof process.env === 'object' &&\n process.env &&\n process.env.__MINIMATCH_TESTING_PLATFORM__) ||\n process.platform\n : 'posix'\n) as Platform\ntype Sep = '\\\\' | '/'\nconst path: { [k: string]: { sep: Sep } } = {\n win32: { sep: '\\\\' },\n posix: { sep: '/' },\n}\n/* c8 ignore stop */\n\nexport const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep\nminimatch.sep = sep\n\nexport const GLOBSTAR = Symbol('globstar **')\nminimatch.GLOBSTAR = GLOBSTAR\n\n// any single thing other than /\n// don't need to escape / when using new RegExp()\nconst qmark = '[^/]'\n\n// * => any number of characters\nconst star = qmark + '*?'\n\n// ** when dots are allowed. Anything goes, except .. and .\n// not (^ or / followed by one or two dots followed by $ or /),\n// followed by anything, any number of times.\nconst twoStarDot = '(?:(?!(?:\\\\/|^)(?:\\\\.{1,2})($|\\\\/)).)*?'\n\n// not a ^ or / followed by a dot,\n// followed by anything, any number of times.\nconst twoStarNoDot = '(?:(?!(?:\\\\/|^)\\\\.).)*?'\n\nexport const filter =\n (pattern: string, options: MinimatchOptions = {}) =>\n (p: string) =>\n minimatch(p, pattern, options)\nminimatch.filter = filter\n\nconst ext = (a: MinimatchOptions, b: MinimatchOptions = {}) =>\n Object.assign({}, a, b)\n\nexport const defaults = (def: MinimatchOptions): typeof minimatch => {\n if (!def || typeof def !== 'object' || !Object.keys(def).length) {\n return minimatch\n }\n\n const orig = minimatch\n\n const m = (p: string, pattern: string, options: MinimatchOptions = {}) =>\n orig(p, pattern, ext(def, options))\n\n return Object.assign(m, {\n Minimatch: class Minimatch extends orig.Minimatch {\n constructor(pattern: string, options: MinimatchOptions = {}) {\n super(pattern, ext(def, options))\n }\n static defaults(options: MinimatchOptions) {\n return orig.defaults(ext(def, options)).Minimatch\n }\n },\n\n AST: class AST extends orig.AST {\n /* c8 ignore start */\n constructor(\n type: ExtglobType | null,\n parent?: AST,\n options: MinimatchOptions = {}\n ) {\n super(type, parent, ext(def, options))\n }\n /* c8 ignore stop */\n\n static fromGlob(pattern: string, options: MinimatchOptions = {}) {\n return orig.AST.fromGlob(pattern, ext(def, options))\n }\n },\n\n unescape: (\n s: string,\n options: Pick = {}\n ) => orig.unescape(s, ext(def, options)),\n\n escape: (\n s: string,\n options: Pick = {}\n ) => orig.escape(s, ext(def, options)),\n\n filter: (pattern: string, options: MinimatchOptions = {}) =>\n orig.filter(pattern, ext(def, options)),\n\n defaults: (options: MinimatchOptions) => orig.defaults(ext(def, options)),\n\n makeRe: (pattern: string, options: MinimatchOptions = {}) =>\n orig.makeRe(pattern, ext(def, options)),\n\n braceExpand: (pattern: string, options: MinimatchOptions = {}) =>\n orig.braceExpand(pattern, ext(def, options)),\n\n match: (list: string[], pattern: string, options: MinimatchOptions = {}) =>\n orig.match(list, pattern, ext(def, options)),\n\n sep: orig.sep,\n GLOBSTAR: GLOBSTAR as typeof GLOBSTAR,\n })\n}\nminimatch.defaults = defaults\n\n// Brace expansion:\n// a{b,c}d -> abd acd\n// a{b,}c -> abc ac\n// a{0..3}d -> a0d a1d a2d a3d\n// a{b,c{d,e}f}g -> abg acdfg acefg\n// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg\n//\n// Invalid sets are not expanded.\n// a{2..}b -> a{2..}b\n// a{b}c -> a{b}c\nexport const braceExpand = (\n pattern: string,\n options: MinimatchOptions = {}\n) => {\n assertValidPattern(pattern)\n\n // Thanks to Yeting Li for\n // improving this regexp to avoid a ReDOS vulnerability.\n if (options.nobrace || !/\\{(?:(?!\\{).)*\\}/.test(pattern)) {\n // shortcut. no need to expand.\n return [pattern]\n }\n\n return expand(pattern)\n}\nminimatch.braceExpand = braceExpand\n\n// parse a component of the expanded set.\n// At this point, no pattern may contain \"/\" in it\n// so we're going to return a 2d array, where each entry is the full\n// pattern, split on '/', and then turned into a regular expression.\n// A regexp is made at the end which joins each array with an\n// escaped /, and another full one which joins each regexp with |.\n//\n// Following the lead of Bash 4.1, note that \"**\" only has special meaning\n// when it is the *only* thing in a path portion. Otherwise, any series\n// of * is equivalent to a single *. Globstar behavior is enabled by\n// default, and can be disabled by setting options.noglobstar.\n\nexport const makeRe = (pattern: string, options: MinimatchOptions = {}) =>\n new Minimatch(pattern, options).makeRe()\nminimatch.makeRe = makeRe\n\nexport const match = (\n list: string[],\n pattern: string,\n options: MinimatchOptions = {}\n) => {\n const mm = new Minimatch(pattern, options)\n list = list.filter(f => mm.match(f))\n if (mm.options.nonull && !list.length) {\n list.push(pattern)\n }\n return list\n}\nminimatch.match = match\n\n// replace stuff like \\* with *\nconst globMagic = /[?*]|[+@!]\\(.*?\\)|\\[|\\]/\nconst regExpEscape = (s: string) =>\n s.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, '\\\\$&')\n\nexport type MMRegExp = RegExp & {\n _src?: string\n _glob?: string\n}\n\nexport type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR\nexport type ParseReturn = ParseReturnFiltered | false\n\nexport class Minimatch {\n options: MinimatchOptions\n set: ParseReturnFiltered[][]\n pattern: string\n\n windowsPathsNoEscape: boolean\n nonegate: boolean\n negate: boolean\n comment: boolean\n empty: boolean\n preserveMultipleSlashes: boolean\n partial: boolean\n globSet: string[]\n globParts: string[][]\n nocase: boolean\n\n isWindows: boolean\n platform: Platform\n windowsNoMagicRoot: boolean\n maxGlobstarRecursion: number\n\n regexp: false | null | MMRegExp\n constructor(pattern: string, options: MinimatchOptions = {}) {\n assertValidPattern(pattern)\n\n options = options || {}\n this.options = options\n this.maxGlobstarRecursion = options.maxGlobstarRecursion ?? 200\n this.pattern = pattern\n this.platform = options.platform || defaultPlatform\n this.isWindows = this.platform === 'win32'\n this.windowsPathsNoEscape =\n !!options.windowsPathsNoEscape || options.allowWindowsEscape === false\n if (this.windowsPathsNoEscape) {\n this.pattern = this.pattern.replace(/\\\\/g, '/')\n }\n this.preserveMultipleSlashes = !!options.preserveMultipleSlashes\n this.regexp = null\n this.negate = false\n this.nonegate = !!options.nonegate\n this.comment = false\n this.empty = false\n this.partial = !!options.partial\n this.nocase = !!this.options.nocase\n this.windowsNoMagicRoot =\n options.windowsNoMagicRoot !== undefined\n ? options.windowsNoMagicRoot\n : !!(this.isWindows && this.nocase)\n\n this.globSet = []\n this.globParts = []\n this.set = []\n\n // make the set of regexps etc.\n this.make()\n }\n\n hasMagic(): boolean {\n if (this.options.magicalBraces && this.set.length > 1) {\n return true\n }\n for (const pattern of this.set) {\n for (const part of pattern) {\n if (typeof part !== 'string') return true\n }\n }\n return false\n }\n\n debug(..._: any[]) {}\n\n make() {\n const pattern = this.pattern\n const options = this.options\n\n // empty patterns and comments match nothing.\n if (!options.nocomment && pattern.charAt(0) === '#') {\n this.comment = true\n return\n }\n\n if (!pattern) {\n this.empty = true\n return\n }\n\n // step 1: figure out negation, etc.\n this.parseNegate()\n\n // step 2: expand braces\n this.globSet = [...new Set(this.braceExpand())]\n\n if (options.debug) {\n this.debug = (...args: any[]) => console.error(...args)\n }\n\n this.debug(this.pattern, this.globSet)\n\n // step 3: now we have a set, so turn each one into a series of\n // path-portion matching patterns.\n // These will be regexps, except in the case of \"**\", which is\n // set to the GLOBSTAR object for globstar behavior,\n // and will not contain any / characters\n //\n // First, we preprocess to make the glob pattern sets a bit simpler\n // and deduped. There are some perf-killing patterns that can cause\n // problems with a glob walk, but we can simplify them down a bit.\n const rawGlobParts = this.globSet.map(s => this.slashSplit(s))\n this.globParts = this.preprocess(rawGlobParts)\n this.debug(this.pattern, this.globParts)\n\n // glob --> regexps\n let set = this.globParts.map((s, _, __) => {\n if (this.isWindows && this.windowsNoMagicRoot) {\n // check if it's a drive or unc path.\n const isUNC =\n s[0] === '' &&\n s[1] === '' &&\n (s[2] === '?' || !globMagic.test(s[2])) &&\n !globMagic.test(s[3])\n const isDrive = /^[a-z]:/i.test(s[0])\n if (isUNC) {\n return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))]\n } else if (isDrive) {\n return [s[0], ...s.slice(1).map(ss => this.parse(ss))]\n }\n }\n return s.map(ss => this.parse(ss))\n })\n\n this.debug(this.pattern, set)\n\n // filter out everything that didn't compile properly.\n this.set = set.filter(\n s => s.indexOf(false) === -1\n ) as ParseReturnFiltered[][]\n\n // do not treat the ? in UNC paths as magic\n if (this.isWindows) {\n for (let i = 0; i < this.set.length; i++) {\n const p = this.set[i]\n if (\n p[0] === '' &&\n p[1] === '' &&\n this.globParts[i][2] === '?' &&\n typeof p[3] === 'string' &&\n /^[a-z]:$/i.test(p[3])\n ) {\n p[2] = '?'\n }\n }\n }\n\n this.debug(this.pattern, this.set)\n }\n\n // various transforms to equivalent pattern sets that are\n // faster to process in a filesystem walk. The goal is to\n // eliminate what we can, and push all ** patterns as far\n // to the right as possible, even if it increases the number\n // of patterns that we have to process.\n preprocess(globParts: string[][]) {\n // if we're not in globstar mode, then turn all ** into *\n if (this.options.noglobstar) {\n for (let i = 0; i < globParts.length; i++) {\n for (let j = 0; j < globParts[i].length; j++) {\n if (globParts[i][j] === '**') {\n globParts[i][j] = '*'\n }\n }\n }\n }\n\n const { optimizationLevel = 1 } = this.options\n\n if (optimizationLevel >= 2) {\n // aggressive optimization for the purpose of fs walking\n globParts = this.firstPhasePreProcess(globParts)\n globParts = this.secondPhasePreProcess(globParts)\n } else if (optimizationLevel >= 1) {\n // just basic optimizations to remove some .. parts\n globParts = this.levelOneOptimize(globParts)\n } else {\n // just collapse multiple ** portions into one\n globParts = this.adjascentGlobstarOptimize(globParts)\n }\n\n return globParts\n }\n\n // just get rid of adjascent ** portions\n adjascentGlobstarOptimize(globParts: string[][]) {\n return globParts.map(parts => {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let i = gs\n while (parts[i + 1] === '**') {\n i++\n }\n if (i !== gs) {\n parts.splice(gs, i - gs)\n }\n }\n return parts\n })\n }\n\n // get rid of adjascent ** and resolve .. portions\n levelOneOptimize(globParts: string[][]) {\n return globParts.map(parts => {\n parts = parts.reduce((set: string[], part) => {\n const prev = set[set.length - 1]\n if (part === '**' && prev === '**') {\n return set\n }\n if (part === '..') {\n if (prev && prev !== '..' && prev !== '.' && prev !== '**') {\n set.pop()\n return set\n }\n }\n set.push(part)\n return set\n }, [])\n return parts.length === 0 ? [''] : parts\n })\n }\n\n levelTwoFileOptimize(parts: string | string[]) {\n if (!Array.isArray(parts)) {\n parts = this.slashSplit(parts)\n }\n let didSomething: boolean = false\n do {\n didSomething = false\n //
// -> 
/\n      if (!this.preserveMultipleSlashes) {\n        for (let i = 1; i < parts.length - 1; i++) {\n          const p = parts[i]\n          // don't squeeze out UNC patterns\n          if (i === 1 && p === '' && parts[0] === '') continue\n          if (p === '.' || p === '') {\n            didSomething = true\n            parts.splice(i, 1)\n            i--\n          }\n        }\n        if (\n          parts[0] === '.' &&\n          parts.length === 2 &&\n          (parts[1] === '.' || parts[1] === '')\n        ) {\n          didSomething = true\n          parts.pop()\n        }\n      }\n\n      // 
/

/../ ->

/\n      let dd: number = 0\n      while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n        const p = parts[dd - 1]\n        if (p && p !== '.' && p !== '..' && p !== '**') {\n          didSomething = true\n          parts.splice(dd - 1, 2)\n          dd -= 2\n        }\n      }\n    } while (didSomething)\n    return parts.length === 0 ? [''] : parts\n  }\n\n  // First phase: single-pattern processing\n  // 
 is 1 or more portions\n  //  is 1 or more portions\n  // 

is any portion other than ., .., '', or **\n // is . or ''\n //\n // **/.. is *brutal* for filesystem walking performance, because\n // it effectively resets the recursive walk each time it occurs,\n // and ** cannot be reduced out by a .. pattern part like a regexp\n // or most strings (other than .., ., and '') can be.\n //\n //

/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n //

// -> 
/\n  // 
/

/../ ->

/\n  // **/**/ -> **/\n  //\n  // **/*/ -> */**/ <== not valid because ** doesn't follow\n  // this WOULD be allowed if ** did follow symlinks, or * didn't\n  firstPhasePreProcess(globParts: string[][]) {\n    let didSomething = false\n    do {\n      didSomething = false\n      // 
/**/../

/

/ -> {

/../

/

/,

/**/

/

/}\n for (let parts of globParts) {\n let gs: number = -1\n while (-1 !== (gs = parts.indexOf('**', gs + 1))) {\n let gss: number = gs\n while (parts[gss + 1] === '**') {\n //

/**/**/ -> 
/**/\n            gss++\n          }\n          // eg, if gs is 2 and gss is 4, that means we have 3 **\n          // parts, and can remove 2 of them.\n          if (gss > gs) {\n            parts.splice(gs + 1, gss - gs)\n          }\n\n          let next = parts[gs + 1]\n          const p = parts[gs + 2]\n          const p2 = parts[gs + 3]\n          if (next !== '..') continue\n          if (\n            !p ||\n            p === '.' ||\n            p === '..' ||\n            !p2 ||\n            p2 === '.' ||\n            p2 === '..'\n          ) {\n            continue\n          }\n          didSomething = true\n          // edit parts in place, and push the new one\n          parts.splice(gs, 1)\n          const other = parts.slice(0)\n          other[gs] = '**'\n          globParts.push(other)\n          gs--\n        }\n\n        // 
// -> 
/\n        if (!this.preserveMultipleSlashes) {\n          for (let i = 1; i < parts.length - 1; i++) {\n            const p = parts[i]\n            // don't squeeze out UNC patterns\n            if (i === 1 && p === '' && parts[0] === '') continue\n            if (p === '.' || p === '') {\n              didSomething = true\n              parts.splice(i, 1)\n              i--\n            }\n          }\n          if (\n            parts[0] === '.' &&\n            parts.length === 2 &&\n            (parts[1] === '.' || parts[1] === '')\n          ) {\n            didSomething = true\n            parts.pop()\n          }\n        }\n\n        // 
/

/../ ->

/\n        let dd: number = 0\n        while (-1 !== (dd = parts.indexOf('..', dd + 1))) {\n          const p = parts[dd - 1]\n          if (p && p !== '.' && p !== '..' && p !== '**') {\n            didSomething = true\n            const needDot = dd === 1 && parts[dd + 1] === '**'\n            const splin = needDot ? ['.'] : []\n            parts.splice(dd - 1, 2, ...splin)\n            if (parts.length === 0) parts.push('')\n            dd -= 2\n          }\n        }\n      }\n    } while (didSomething)\n\n    return globParts\n  }\n\n  // second phase: multi-pattern dedupes\n  // {
/*/,
/

/} ->

/*/\n  // {
/,
/} -> 
/\n  // {
/**/,
/} -> 
/**/\n  //\n  // {
/**/,
/**/

/} ->

/**/\n  // ^-- not valid because ** doens't follow symlinks\n  secondPhasePreProcess(globParts: string[][]): string[][] {\n    for (let i = 0; i < globParts.length - 1; i++) {\n      for (let j = i + 1; j < globParts.length; j++) {\n        const matched = this.partsMatch(\n          globParts[i],\n          globParts[j],\n          !this.preserveMultipleSlashes\n        )\n        if (matched) {\n          globParts[i] = []\n          globParts[j] = matched\n          break\n        }\n      }\n    }\n    return globParts.filter(gs => gs.length)\n  }\n\n  partsMatch(\n    a: string[],\n    b: string[],\n    emptyGSMatch: boolean = false\n  ): false | string[] {\n    let ai = 0\n    let bi = 0\n    let result: string[] = []\n    let which: string = ''\n    while (ai < a.length && bi < b.length) {\n      if (a[ai] === b[bi]) {\n        result.push(which === 'b' ? b[bi] : a[ai])\n        ai++\n        bi++\n      } else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {\n        result.push(a[ai])\n        ai++\n      } else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {\n        result.push(b[bi])\n        bi++\n      } else if (\n        a[ai] === '*' &&\n        b[bi] &&\n        (this.options.dot || !b[bi].startsWith('.')) &&\n        b[bi] !== '**'\n      ) {\n        if (which === 'b') return false\n        which = 'a'\n        result.push(a[ai])\n        ai++\n        bi++\n      } else if (\n        b[bi] === '*' &&\n        a[ai] &&\n        (this.options.dot || !a[ai].startsWith('.')) &&\n        a[ai] !== '**'\n      ) {\n        if (which === 'a') return false\n        which = 'b'\n        result.push(b[bi])\n        ai++\n        bi++\n      } else {\n        return false\n      }\n    }\n    // if we fall out of the loop, it means they two are identical\n    // as long as their lengths match\n    return a.length === b.length && result\n  }\n\n  parseNegate() {\n    if (this.nonegate) return\n\n    const pattern = this.pattern\n    let negate = false\n    let negateOffset = 0\n\n    for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {\n      negate = !negate\n      negateOffset++\n    }\n\n    if (negateOffset) this.pattern = pattern.slice(negateOffset)\n    this.negate = negate\n  }\n\n  // set partial to true to test if, for example,\n  // \"/a/b\" matches the start of \"/*/b/*/d\"\n  // Partial means, if you run out of file before you run\n  // out of pattern, then that's fine, as long as all\n  // the parts match.\n  matchOne(\n    file: string[],\n    pattern: ParseReturn[],\n    partial: boolean = false\n  ) {\n    let fileStartIndex = 0\n    let patternStartIndex = 0\n\n    // UNC paths like //?/X:/... can match X:/... and vice versa\n    // Drive letters in absolute drive or unc paths are always compared\n    // case-insensitively.\n    if (this.isWindows) {\n      const fileDrive =\n        typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0])\n      const fileUNC =\n        !fileDrive &&\n        file[0] === '' &&\n        file[1] === '' &&\n        file[2] === '?' &&\n        /^[a-z]:$/i.test(file[3])\n\n      const patternDrive =\n        typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0])\n      const patternUNC =\n        !patternDrive &&\n        pattern[0] === '' &&\n        pattern[1] === '' &&\n        pattern[2] === '?' &&\n        typeof pattern[3] === 'string' &&\n        /^[a-z]:$/i.test(pattern[3])\n\n      const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined\n      const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined\n      if (typeof fdi === 'number' && typeof pdi === 'number') {\n        const [fd, pd]: [string, string] = [\n          file[fdi],\n          pattern[pdi] as string,\n        ]\n        if (fd.toLowerCase() === pd.toLowerCase()) {\n          pattern[pdi] = fd\n          patternStartIndex = pdi\n          fileStartIndex = fdi\n        }\n      }\n    }\n\n    // resolve and reduce . and .. portions in the file as well.\n    // dont' need to do the second phase, because it's only one string[]\n    const { optimizationLevel = 1 } = this.options\n    if (optimizationLevel >= 2) {\n      file = this.levelTwoFileOptimize(file)\n    }\n\n    if (pattern.includes(GLOBSTAR)) {\n      return this.#matchGlobstar(\n        file, pattern, partial, fileStartIndex, patternStartIndex\n      )\n    }\n\n    return this.#matchOne(\n      file, pattern, partial, fileStartIndex, patternStartIndex\n    )\n  }\n\n  #matchGlobstar(\n    file: string[],\n    pattern: ParseReturn[],\n    partial: boolean,\n    fileIndex: number,\n    patternIndex: number\n  ) {\n    const firstgs = pattern.indexOf(GLOBSTAR, patternIndex)\n    const lastgs = pattern.lastIndexOf(GLOBSTAR)\n\n    const [head, body, tail] = partial ? [\n      pattern.slice(patternIndex, firstgs),\n      pattern.slice(firstgs + 1),\n      [],\n    ] : [\n      pattern.slice(patternIndex, firstgs),\n      pattern.slice(firstgs + 1, lastgs),\n      pattern.slice(lastgs + 1),\n    ]\n\n    if (head.length) {\n      const fileHead = file.slice(fileIndex, fileIndex + head.length)\n      if (!this.#matchOne(fileHead, head, partial, 0, 0)) return false\n      fileIndex += head.length\n    }\n\n    let fileTailMatch: number = 0\n    if (tail.length) {\n      if (tail.length + fileIndex > file.length) return false\n      let tailStart = file.length - tail.length\n      if (this.#matchOne(file, tail, partial, tailStart, 0)) {\n        fileTailMatch = tail.length\n      } else {\n        if (\n          file[file.length - 1] !== '' ||\n          fileIndex + tail.length === file.length\n        ) {\n          return false\n        }\n        tailStart--\n        if (!this.#matchOne(file, tail, partial, tailStart, 0)) return false\n        fileTailMatch = tail.length + 1\n      }\n    }\n\n    if (!body.length) {\n      let sawSome = !!fileTailMatch\n      for (let i = fileIndex; i < file.length - fileTailMatch; i++) {\n        const f = String(file[i])\n        sawSome = true\n        if (\n          f === '.' || f === '..' ||\n          (!this.options.dot && f.startsWith('.'))\n        ) {\n          return false\n        }\n      }\n      return partial || sawSome\n    }\n\n    const bodySegments: [ParseReturn[], number][] = [[[], 0]]\n    let currentBody: [ParseReturn[], number] = bodySegments[0]\n    let nonGsParts = 0\n    const nonGsPartsSums: number[] = [0]\n    for (const b of body) {\n      if (b === GLOBSTAR) {\n        nonGsPartsSums.push(nonGsParts)\n        currentBody = [[], 0]\n        bodySegments.push(currentBody)\n      } else {\n        currentBody[0].push(b)\n        nonGsParts++\n      }\n    }\n    let i = bodySegments.length - 1\n    const fileLength = file.length - fileTailMatch\n    for (const b of bodySegments) {\n      b[1] = fileLength - ((nonGsPartsSums[i--] as number) + b[0].length)\n    }\n\n    return !!this.#matchGlobStarBodySections(\n      file, bodySegments, fileIndex, 0, partial, 0, !!fileTailMatch\n    )\n  }\n\n  #matchGlobStarBodySections(\n    file: string[],\n    bodySegments: [ParseReturn[], number][],\n    fileIndex: number,\n    bodyIndex: number,\n    partial: boolean,\n    globStarDepth: number,\n    sawTail: boolean\n  ): boolean | null {\n    const bs = bodySegments[bodyIndex]\n    if (!bs) {\n      for (let i = fileIndex; i < file.length; i++) {\n        sawTail = true\n        const f = file[i]\n        if (\n          f === '.' || f === '..' ||\n          (!this.options.dot && f.startsWith('.'))\n        ) {\n          return false\n        }\n      }\n      return sawTail\n    }\n\n    const [body, after] = bs\n    while (fileIndex <= after) {\n      const m = this.#matchOne(\n        file.slice(0, fileIndex + body.length),\n        body, partial, fileIndex, 0\n      )\n      if (m && globStarDepth < this.maxGlobstarRecursion) {\n        const sub = this.#matchGlobStarBodySections(\n          file, bodySegments, fileIndex + body.length,\n          bodyIndex + 1, partial, globStarDepth + 1, sawTail\n        )\n        if (sub !== false) return sub\n      }\n      const f = file[fileIndex]\n      if (\n        f === '.' || f === '..' ||\n        (!this.options.dot && f.startsWith('.'))\n      ) {\n        return false\n      }\n      fileIndex++\n    }\n    return partial || null\n  }\n\n  #matchOne(\n    file: string[],\n    pattern: ParseReturn[],\n    partial: boolean,\n    fileIndex: number,\n    patternIndex: number\n  ) {\n    let fi: number\n    let pi: number\n    let pl: number\n    let fl: number\n    for (\n      fi = fileIndex, pi = patternIndex,\n        fl = file.length, pl = pattern.length;\n      fi < fl && pi < pl;\n      fi++, pi++\n    ) {\n      this.debug('matchOne loop')\n      let p = pattern[pi]\n      let f = file[fi]\n\n      this.debug(pattern, p, f)\n\n      /* c8 ignore start */\n      if (p === false || p === GLOBSTAR) return false\n      /* c8 ignore stop */\n\n      let hit: boolean\n      if (typeof p === 'string') {\n        hit = f === p\n        this.debug('string match', p, f, hit)\n      } else {\n        hit = p.test(f)\n        this.debug('pattern match', p, f, hit)\n      }\n\n      if (!hit) return false\n    }\n\n    if (fi === fl && pi === pl) {\n      return true\n    } else if (fi === fl) {\n      return partial\n    } else if (pi === pl) {\n      return fi === fl - 1 && file[fi] === ''\n      /* c8 ignore start */\n    } else {\n      throw new Error('wtf?')\n    }\n    /* c8 ignore stop */\n  }\n\n  braceExpand(): string[] {\n    return braceExpand(this.pattern, this.options)\n  }\n\n  parse(pattern: string): ParseReturn {\n    assertValidPattern(pattern)\n\n    const options = this.options\n\n    // shortcuts\n    if (pattern === '**') return GLOBSTAR\n    if (pattern === '') return ''\n\n    // far and away, the most common glob pattern parts are\n    // *, *.*, and *.  Add a fast check method for those.\n    let m: RegExpMatchArray | null\n    let fastTest: null | ((f: string) => boolean) = null\n    if ((m = pattern.match(starRE))) {\n      fastTest = options.dot ? starTestDot : starTest\n    } else if ((m = pattern.match(starDotExtRE))) {\n      fastTest = (\n        options.nocase\n          ? options.dot\n            ? starDotExtTestNocaseDot\n            : starDotExtTestNocase\n          : options.dot\n          ? starDotExtTestDot\n          : starDotExtTest\n      )(m[1])\n    } else if ((m = pattern.match(qmarksRE))) {\n      fastTest = (\n        options.nocase\n          ? options.dot\n            ? qmarksTestNocaseDot\n            : qmarksTestNocase\n          : options.dot\n          ? qmarksTestDot\n          : qmarksTest\n      )(m)\n    } else if ((m = pattern.match(starDotStarRE))) {\n      fastTest = options.dot ? starDotStarTestDot : starDotStarTest\n    } else if ((m = pattern.match(dotStarRE))) {\n      fastTest = dotStarTest\n    }\n\n    const re = AST.fromGlob(pattern, this.options).toMMPattern()\n    if (fastTest && typeof re === 'object') {\n      // Avoids overriding in frozen environments\n      Reflect.defineProperty(re, 'test', { value: fastTest })\n    }\n    return re\n  }\n\n  makeRe() {\n    if (this.regexp || this.regexp === false) return this.regexp\n\n    // at this point, this.set is a 2d array of partial\n    // pattern strings, or \"**\".\n    //\n    // It's better to use .match().  This function shouldn't\n    // be used, really, but it's pretty convenient sometimes,\n    // when you just want to work with a regex.\n    const set = this.set\n\n    if (!set.length) {\n      this.regexp = false\n      return this.regexp\n    }\n    const options = this.options\n\n    const twoStar = options.noglobstar\n      ? star\n      : options.dot\n      ? twoStarDot\n      : twoStarNoDot\n    const flags = new Set(options.nocase ? ['i'] : [])\n\n    // regexpify non-globstar patterns\n    // if ** is only item, then we just do one twoStar\n    // if ** is first, and there are more, prepend (\\/|twoStar\\/)? to next\n    // if ** is last, append (\\/twoStar|) to previous\n    // if ** is in the middle, append (\\/|\\/twoStar\\/) to previous\n    // then filter out GLOBSTAR symbols\n    let re = set\n      .map(pattern => {\n        const pp: (string | typeof GLOBSTAR)[] = pattern.map(p => {\n          if (p instanceof RegExp) {\n            for (const f of p.flags.split('')) flags.add(f)\n          }\n          return typeof p === 'string'\n            ? regExpEscape(p)\n            : p === GLOBSTAR\n            ? GLOBSTAR\n            : p._src\n        }) as (string | typeof GLOBSTAR)[]\n        pp.forEach((p, i) => {\n          const next = pp[i + 1]\n          const prev = pp[i - 1]\n          if (p !== GLOBSTAR || prev === GLOBSTAR) {\n            return\n          }\n          if (prev === undefined) {\n            if (next !== undefined && next !== GLOBSTAR) {\n              pp[i + 1] = '(?:\\\\/|' + twoStar + '\\\\/)?' + next\n            } else {\n              pp[i] = twoStar\n            }\n          } else if (next === undefined) {\n            pp[i - 1] = prev + '(?:\\\\/|' + twoStar + ')?'\n          } else if (next !== GLOBSTAR) {\n            pp[i - 1] = prev + '(?:\\\\/|\\\\/' + twoStar + '\\\\/)' + next\n            pp[i + 1] = GLOBSTAR\n          }\n        })\n        return pp.filter(p => p !== GLOBSTAR).join('/')\n      })\n      .join('|')\n\n    // need to wrap in parens if we had more than one thing with |,\n    // otherwise only the first will be anchored to ^ and the last to $\n    const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', '']\n    // must match entire pattern\n    // ending in a * or ** will make it less strict.\n    re = '^' + open + re + close + '$'\n\n    // can match anything, as long as it's not this.\n    if (this.negate) re = '^(?!' + re + ').+$'\n\n    try {\n      this.regexp = new RegExp(re, [...flags].join(''))\n      /* c8 ignore start */\n    } catch (ex) {\n      // should be impossible\n      this.regexp = false\n    }\n    /* c8 ignore stop */\n    return this.regexp\n  }\n\n  slashSplit(p: string) {\n    // if p starts with // on windows, we preserve that\n    // so that UNC paths aren't broken.  Otherwise, any number of\n    // / characters are coalesced into one, unless\n    // preserveMultipleSlashes is set to true.\n    if (this.preserveMultipleSlashes) {\n      return p.split('/')\n    } else if (this.isWindows && /^\\/\\/[^\\/]+/.test(p)) {\n      // add an extra '' for the one we lose\n      return ['', ...p.split(/\\/+/)]\n    } else {\n      return p.split(/\\/+/)\n    }\n  }\n\n  match(f: string, partial = this.partial) {\n    this.debug('match', f, this.pattern)\n    // short-circuit in the case of busted things.\n    // comments, etc.\n    if (this.comment) {\n      return false\n    }\n    if (this.empty) {\n      return f === ''\n    }\n\n    if (f === '/' && partial) {\n      return true\n    }\n\n    const options = this.options\n\n    // windows: need to use /, not \\\n    if (this.isWindows) {\n      f = f.split('\\\\').join('/')\n    }\n\n    // treat the test path as a set of pathparts.\n    const ff = this.slashSplit(f)\n    this.debug(this.pattern, 'split', ff)\n\n    // just ONE of the pattern sets in this.set needs to match\n    // in order for it to be valid.  If negating, then just one\n    // match means that we have failed.\n    // Either way, return on the first hit.\n\n    const set = this.set\n    this.debug(this.pattern, 'set', set)\n\n    // Find the basename of the path by looking for the last non-empty segment\n    let filename: string = ff[ff.length - 1]\n    if (!filename) {\n      for (let i = ff.length - 2; !filename && i >= 0; i--) {\n        filename = ff[i]\n      }\n    }\n\n    for (let i = 0; i < set.length; i++) {\n      const pattern = set[i]\n      let file = ff\n      if (options.matchBase && pattern.length === 1) {\n        file = [filename]\n      }\n      const hit = this.matchOne(file, pattern, partial)\n      if (hit) {\n        if (options.flipNegate) {\n          return true\n        }\n        return !this.negate\n      }\n    }\n\n    // didn't get any hits.  this is success if it's a negative\n    // pattern, failure otherwise.\n    if (options.flipNegate) {\n      return false\n    }\n    return this.negate\n  }\n\n  static defaults(def: MinimatchOptions) {\n    return minimatch.defaults(def).Minimatch\n  }\n}\n/* c8 ignore start */\nexport { AST } from './ast.js'\nexport { escape } from './escape.js'\nexport { unescape } from './unescape.js'\n/* c8 ignore stop */\nminimatch.AST = AST\nminimatch.Minimatch = Minimatch\nminimatch.escape = escape\nminimatch.unescape = unescape\n","/**\n * @module LRUCache\n */\n\n// module-private names and types\ntype Perf = { now: () => number }\nconst perf: Perf =\n  typeof performance === 'object' &&\n  performance &&\n  typeof performance.now === 'function'\n    ? performance\n    : Date\n\nconst warned = new Set()\n\n// either a function or a class\ntype ForC = ((...a: any[]) => any) | { new (...a: any[]): any }\n\n/* c8 ignore start */\nconst PROCESS = (\n  typeof process === 'object' && !!process ? process : {}\n) as { [k: string]: any }\n/* c8 ignore start */\n\nconst emitWarning = (\n  msg: string,\n  type: string,\n  code: string,\n  fn: ForC\n) => {\n  typeof PROCESS.emitWarning === 'function'\n    ? PROCESS.emitWarning(msg, type, code, fn)\n    : console.error(`[${code}] ${type}: ${msg}`)\n}\n\nlet AC = globalThis.AbortController\nlet AS = globalThis.AbortSignal\n\n/* c8 ignore start */\nif (typeof AC === 'undefined') {\n  //@ts-ignore\n  AS = class AbortSignal {\n    onabort?: (...a: any[]) => any\n    _onabort: ((...a: any[]) => any)[] = []\n    reason?: any\n    aborted: boolean = false\n    addEventListener(_: string, fn: (...a: any[]) => any) {\n      this._onabort.push(fn)\n    }\n  }\n  //@ts-ignore\n  AC = class AbortController {\n    constructor() {\n      warnACPolyfill()\n    }\n    signal = new AS()\n    abort(reason: any) {\n      if (this.signal.aborted) return\n      //@ts-ignore\n      this.signal.reason = reason\n      //@ts-ignore\n      this.signal.aborted = true\n      //@ts-ignore\n      for (const fn of this.signal._onabort) {\n        fn(reason)\n      }\n      this.signal.onabort?.(reason)\n    }\n  }\n  let printACPolyfillWarning =\n    PROCESS.env?.LRU_CACHE_IGNORE_AC_WARNING !== '1'\n  const warnACPolyfill = () => {\n    if (!printACPolyfillWarning) return\n    printACPolyfillWarning = false\n    emitWarning(\n      'AbortController is not defined. If using lru-cache in ' +\n        'node 14, load an AbortController polyfill from the ' +\n        '`node-abort-controller` package. A minimal polyfill is ' +\n        'provided for use by LRUCache.fetch(), but it should not be ' +\n        'relied upon in other contexts (eg, passing it to other APIs that ' +\n        'use AbortController/AbortSignal might have undesirable effects). ' +\n        'You may disable this with LRU_CACHE_IGNORE_AC_WARNING=1 in the env.',\n      'NO_ABORT_CONTROLLER',\n      'ENOTSUP',\n      warnACPolyfill\n    )\n  }\n}\n/* c8 ignore stop */\n\nconst shouldWarn = (code: string) => !warned.has(code)\n\nconst TYPE = Symbol('type')\nexport type PosInt = number & { [TYPE]: 'Positive Integer' }\nexport type Index = number & { [TYPE]: 'LRUCache Index' }\n\nconst isPosInt = (n: any): n is PosInt =>\n  n && n === Math.floor(n) && n > 0 && isFinite(n)\n\nexport type UintArray = Uint8Array | Uint16Array | Uint32Array\nexport type NumberArray = UintArray | number[]\n\n/* c8 ignore start */\n// This is a little bit ridiculous, tbh.\n// The maximum array length is 2^32-1 or thereabouts on most JS impls.\n// And well before that point, you're caching the entire world, I mean,\n// that's ~32GB of just integers for the next/prev links, plus whatever\n// else to hold that many keys and values.  Just filling the memory with\n// zeroes at init time is brutal when you get that big.\n// But why not be complete?\n// Maybe in the future, these limits will have expanded.\nconst getUintArray = (max: number) =>\n  !isPosInt(max)\n    ? null\n    : max <= Math.pow(2, 8)\n    ? Uint8Array\n    : max <= Math.pow(2, 16)\n    ? Uint16Array\n    : max <= Math.pow(2, 32)\n    ? Uint32Array\n    : max <= Number.MAX_SAFE_INTEGER\n    ? ZeroArray\n    : null\n/* c8 ignore stop */\n\nclass ZeroArray extends Array {\n  constructor(size: number) {\n    super(size)\n    this.fill(0)\n  }\n}\nexport type { ZeroArray }\nexport type { Stack }\n\nexport type StackLike = Stack | Index[]\nclass Stack {\n  heap: NumberArray\n  length: number\n  // private constructor\n  static #constructing: boolean = false\n  static create(max: number): StackLike {\n    const HeapCls = getUintArray(max)\n    if (!HeapCls) return []\n    Stack.#constructing = true\n    const s = new Stack(max, HeapCls)\n    Stack.#constructing = false\n    return s\n  }\n  constructor(\n    max: number,\n    HeapCls: { new (n: number): NumberArray }\n  ) {\n    /* c8 ignore start */\n    if (!Stack.#constructing) {\n      throw new TypeError('instantiate Stack using Stack.create(n)')\n    }\n    /* c8 ignore stop */\n    this.heap = new HeapCls(max)\n    this.length = 0\n  }\n  push(n: Index) {\n    this.heap[this.length++] = n\n  }\n  pop(): Index {\n    return this.heap[--this.length] as Index\n  }\n}\n\n/**\n * Promise representing an in-progress {@link LRUCache#fetch} call\n */\nexport type BackgroundFetch = Promise & {\n  __returned: BackgroundFetch | undefined\n  __abortController: AbortController\n  __staleWhileFetching: V | undefined\n}\n\nexport type DisposeTask = [\n  value: V,\n  key: K,\n  reason: LRUCache.DisposeReason\n]\n\nexport namespace LRUCache {\n  /**\n   * An integer greater than 0, reflecting the calculated size of items\n   */\n  export type Size = number\n\n  /**\n   * Integer greater than 0, representing some number of milliseconds, or the\n   * time at which a TTL started counting from.\n   */\n  export type Milliseconds = number\n\n  /**\n   * An integer greater than 0, reflecting a number of items\n   */\n  export type Count = number\n\n  /**\n   * The reason why an item was removed from the cache, passed\n   * to the {@link Disposer} methods.\n   *\n   * - `evict`: The item was evicted because it is the least recently used,\n   *   and the cache is full.\n   * - `set`: A new value was set, overwriting the old value being disposed.\n   * - `delete`: The item was explicitly deleted, either by calling\n   *   {@link LRUCache#delete}, {@link LRUCache#clear}, or\n   *   {@link LRUCache#set} with an undefined value.\n   * - `expire`: The item was removed due to exceeding its TTL.\n   * - `fetch`: A {@link OptionsBase#fetchMethod} operation returned\n   *   `undefined` or was aborted, causing the item to be deleted.\n   */\n  export type DisposeReason =\n    | 'evict'\n    | 'set'\n    | 'delete'\n    | 'expire'\n    | 'fetch'\n  /**\n   * A method called upon item removal, passed as the\n   * {@link OptionsBase.dispose} and/or\n   * {@link OptionsBase.disposeAfter} options.\n   */\n  export type Disposer = (\n    value: V,\n    key: K,\n    reason: DisposeReason\n  ) => void\n\n  /**\n   * A function that returns the effective calculated size\n   * of an entry in the cache.\n   */\n  export type SizeCalculator = (value: V, key: K) => Size\n\n  /**\n   * Options provided to the\n   * {@link OptionsBase.fetchMethod} function.\n   */\n  export interface FetcherOptions {\n    signal: AbortSignal\n    options: FetcherFetchOptions\n    /**\n     * Object provided in the {@link FetchOptions.context} option to\n     * {@link LRUCache#fetch}\n     */\n    context: FC\n  }\n\n  /**\n   * Occasionally, it may be useful to track the internal behavior of the\n   * cache, particularly for logging, debugging, or for behavior within the\n   * `fetchMethod`. To do this, you can pass a `status` object to the\n   * {@link LRUCache#fetch}, {@link LRUCache#get}, {@link LRUCache#set},\n   * {@link LRUCache#memo}, and {@link LRUCache#has} methods.\n   *\n   * The `status` option should be a plain JavaScript object. The following\n   * fields will be set on it appropriately, depending on the situation.\n   */\n  export interface Status {\n    /**\n     * The status of a set() operation.\n     *\n     * - add: the item was not found in the cache, and was added\n     * - update: the item was in the cache, with the same value provided\n     * - replace: the item was in the cache, and replaced\n     * - miss: the item was not added to the cache for some reason\n     */\n    set?: 'add' | 'update' | 'replace' | 'miss'\n\n    /**\n     * the ttl stored for the item, or undefined if ttls are not used.\n     */\n    ttl?: Milliseconds\n\n    /**\n     * the start time for the item, or undefined if ttls are not used.\n     */\n    start?: Milliseconds\n\n    /**\n     * The timestamp used for TTL calculation\n     */\n    now?: Milliseconds\n\n    /**\n     * the remaining ttl for the item, or undefined if ttls are not used.\n     */\n    remainingTTL?: Milliseconds\n\n    /**\n     * The calculated size for the item, if sizes are used.\n     */\n    entrySize?: Size\n\n    /**\n     * The total calculated size of the cache, if sizes are used.\n     */\n    totalCalculatedSize?: Size\n\n    /**\n     * A flag indicating that the item was not stored, due to exceeding the\n     * {@link OptionsBase.maxEntrySize}\n     */\n    maxEntrySizeExceeded?: true\n\n    /**\n     * The old value, specified in the case of `set:'update'` or\n     * `set:'replace'`\n     */\n    oldValue?: V\n\n    /**\n     * The results of a {@link LRUCache#has} operation\n     *\n     * - hit: the item was found in the cache\n     * - stale: the item was found in the cache, but is stale\n     * - miss: the item was not found in the cache\n     */\n    has?: 'hit' | 'stale' | 'miss'\n\n    /**\n     * The status of a {@link LRUCache#fetch} operation.\n     * Note that this can change as the underlying fetch() moves through\n     * various states.\n     *\n     * - inflight: there is another fetch() for this key which is in process\n     * - get: there is no {@link OptionsBase.fetchMethod}, so\n     *   {@link LRUCache#get} was called.\n     * - miss: the item is not in cache, and will be fetched.\n     * - hit: the item is in the cache, and was resolved immediately.\n     * - stale: the item is in the cache, but stale.\n     * - refresh: the item is in the cache, and not stale, but\n     *   {@link FetchOptions.forceRefresh} was specified.\n     */\n    fetch?: 'get' | 'inflight' | 'miss' | 'hit' | 'stale' | 'refresh'\n\n    /**\n     * The {@link OptionsBase.fetchMethod} was called\n     */\n    fetchDispatched?: true\n\n    /**\n     * The cached value was updated after a successful call to\n     * {@link OptionsBase.fetchMethod}\n     */\n    fetchUpdated?: true\n\n    /**\n     * The reason for a fetch() rejection.  Either the error raised by the\n     * {@link OptionsBase.fetchMethod}, or the reason for an\n     * AbortSignal.\n     */\n    fetchError?: Error\n\n    /**\n     * The fetch received an abort signal\n     */\n    fetchAborted?: true\n\n    /**\n     * The abort signal received was ignored, and the fetch was allowed to\n     * continue.\n     */\n    fetchAbortIgnored?: true\n\n    /**\n     * The fetchMethod promise resolved successfully\n     */\n    fetchResolved?: true\n\n    /**\n     * The fetchMethod promise was rejected\n     */\n    fetchRejected?: true\n\n    /**\n     * The status of a {@link LRUCache#get} operation.\n     *\n     * - fetching: The item is currently being fetched.  If a previous value\n     *   is present and allowed, that will be returned.\n     * - stale: The item is in the cache, and is stale.\n     * - hit: the item is in the cache\n     * - miss: the item is not in the cache\n     */\n    get?: 'stale' | 'hit' | 'miss'\n\n    /**\n     * A fetch or get operation returned a stale value.\n     */\n    returnedStale?: true\n  }\n\n  /**\n   * options which override the options set in the LRUCache constructor\n   * when calling {@link LRUCache#fetch}.\n   *\n   * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n   * {@link OptionsBase.noDeleteOnFetchRejection},\n   * {@link OptionsBase.allowStaleOnFetchRejection},\n   * {@link FetchOptions.forceRefresh}, and\n   * {@link FetcherOptions.context}\n   *\n   * Any of these may be modified in the {@link OptionsBase.fetchMethod}\n   * function, but the {@link GetOptions} fields will of course have no\n   * effect, as the {@link LRUCache#get} call already happened by the time\n   * the fetchMethod is called.\n   */\n  export interface FetcherFetchOptions\n    extends Pick<\n      OptionsBase,\n      | 'allowStale'\n      | 'updateAgeOnGet'\n      | 'noDeleteOnStaleGet'\n      | 'sizeCalculation'\n      | 'ttl'\n      | 'noDisposeOnSet'\n      | 'noUpdateTTL'\n      | 'noDeleteOnFetchRejection'\n      | 'allowStaleOnFetchRejection'\n      | 'ignoreFetchAbort'\n      | 'allowStaleOnFetchAbort'\n    > {\n    status?: Status\n    size?: Size\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#fetch} method.\n   */\n  export interface FetchOptions\n    extends FetcherFetchOptions {\n    /**\n     * Set to true to force a re-load of the existing data, even if it\n     * is not yet stale.\n     */\n    forceRefresh?: boolean\n    /**\n     * Context provided to the {@link OptionsBase.fetchMethod} as\n     * the {@link FetcherOptions.context} param.\n     *\n     * If the FC type is specified as unknown (the default),\n     * undefined or void, then this is optional.  Otherwise, it will\n     * be required.\n     */\n    context?: FC\n    signal?: AbortSignal\n    status?: Status\n  }\n  /**\n   * Options provided to {@link LRUCache#fetch} when the FC type is something\n   * other than `unknown`, `undefined`, or `void`\n   */\n  export interface FetchOptionsWithContext\n    extends FetchOptions {\n    context: FC\n  }\n  /**\n   * Options provided to {@link LRUCache#fetch} when the FC type is\n   * `undefined` or `void`\n   */\n  export interface FetchOptionsNoContext\n    extends FetchOptions {\n    context?: undefined\n  }\n\n  export interface MemoOptions\n    extends Pick<\n      OptionsBase,\n      | 'allowStale'\n      | 'updateAgeOnGet'\n      | 'noDeleteOnStaleGet'\n      | 'sizeCalculation'\n      | 'ttl'\n      | 'noDisposeOnSet'\n      | 'noUpdateTTL'\n      | 'noDeleteOnFetchRejection'\n      | 'allowStaleOnFetchRejection'\n      | 'ignoreFetchAbort'\n      | 'allowStaleOnFetchAbort'\n    > {\n    /**\n     * Set to true to force a re-load of the existing data, even if it\n     * is not yet stale.\n     */\n    forceRefresh?: boolean\n    /**\n     * Context provided to the {@link OptionsBase.memoMethod} as\n     * the {@link MemoizerOptions.context} param.\n     *\n     * If the FC type is specified as unknown (the default),\n     * undefined or void, then this is optional.  Otherwise, it will\n     * be required.\n     */\n    context?: FC\n    status?: Status\n  }\n  /**\n   * Options provided to {@link LRUCache#memo} when the FC type is something\n   * other than `unknown`, `undefined`, or `void`\n   */\n  export interface MemoOptionsWithContext\n    extends MemoOptions {\n    context: FC\n  }\n  /**\n   * Options provided to {@link LRUCache#memo} when the FC type is\n   * `undefined` or `void`\n   */\n  export interface MemoOptionsNoContext\n    extends MemoOptions {\n    context?: undefined\n  }\n\n  /**\n   * Options provided to the\n   * {@link OptionsBase.memoMethod} function.\n   */\n  export interface MemoizerOptions {\n    options: MemoizerMemoOptions\n    /**\n     * Object provided in the {@link MemoOptions.context} option to\n     * {@link LRUCache#memo}\n     */\n    context: FC\n  }\n\n  /**\n   * options which override the options set in the LRUCache constructor\n   * when calling {@link LRUCache#memo}.\n   *\n   * This is the union of {@link GetOptions} and {@link SetOptions}, plus\n   * {@link MemoOptions.forceRefresh}, and\n   * {@link MemoerOptions.context}\n   *\n   * Any of these may be modified in the {@link OptionsBase.memoMethod}\n   * function, but the {@link GetOptions} fields will of course have no\n   * effect, as the {@link LRUCache#get} call already happened by the time\n   * the memoMethod is called.\n   */\n  export interface MemoizerMemoOptions\n    extends Pick<\n      OptionsBase,\n      | 'allowStale'\n      | 'updateAgeOnGet'\n      | 'noDeleteOnStaleGet'\n      | 'sizeCalculation'\n      | 'ttl'\n      | 'noDisposeOnSet'\n      | 'noUpdateTTL'\n    > {\n    status?: Status\n    size?: Size\n    start?: Milliseconds\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#has} method.\n   */\n  export interface HasOptions\n    extends Pick, 'updateAgeOnHas'> {\n    status?: Status\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#get} method.\n   */\n  export interface GetOptions\n    extends Pick<\n      OptionsBase,\n      'allowStale' | 'updateAgeOnGet' | 'noDeleteOnStaleGet'\n    > {\n    status?: Status\n  }\n\n  /**\n   * Options that may be passed to the {@link LRUCache#peek} method.\n   */\n  export interface PeekOptions\n    extends Pick, 'allowStale'> {}\n\n  /**\n   * Options that may be passed to the {@link LRUCache#set} method.\n   */\n  export interface SetOptions\n    extends Pick<\n      OptionsBase,\n      'sizeCalculation' | 'ttl' | 'noDisposeOnSet' | 'noUpdateTTL'\n    > {\n    /**\n     * If size tracking is enabled, then setting an explicit size\n     * in the {@link LRUCache#set} call will prevent calling the\n     * {@link OptionsBase.sizeCalculation} function.\n     */\n    size?: Size\n    /**\n     * If TTL tracking is enabled, then setting an explicit start\n     * time in the {@link LRUCache#set} call will override the\n     * default time from `performance.now()` or `Date.now()`.\n     *\n     * Note that it must be a valid value for whichever time-tracking\n     * method is in use.\n     */\n    start?: Milliseconds\n    status?: Status\n  }\n\n  /**\n   * The type signature for the {@link OptionsBase.fetchMethod} option.\n   */\n  export type Fetcher = (\n    key: K,\n    staleValue: V | undefined,\n    options: FetcherOptions\n  ) => Promise | V | undefined | void\n\n  /**\n   * the type signature for the {@link OptionsBase.memoMethod} option.\n   */\n  export type Memoizer = (\n    key: K,\n    staleValue: V | undefined,\n    options: MemoizerOptions\n  ) => V\n\n  /**\n   * Options which may be passed to the {@link LRUCache} constructor.\n   *\n   * Most of these may be overridden in the various options that use\n   * them.\n   *\n   * Despite all being technically optional, the constructor requires that\n   * a cache is at minimum limited by one or more of {@link OptionsBase.max},\n   * {@link OptionsBase.ttl}, or {@link OptionsBase.maxSize}.\n   *\n   * If {@link OptionsBase.ttl} is used alone, then it is strongly advised\n   * (and in fact required by the type definitions here) that the cache\n   * also set {@link OptionsBase.ttlAutopurge}, to prevent potentially\n   * unbounded storage.\n   *\n   * All options are also available on the {@link LRUCache} instance, making\n   * it safe to pass an LRUCache instance as the options argumemnt to\n   * make another empty cache of the same type.\n   *\n   * Some options are marked as read-only, because changing them after\n   * instantiation is not safe. Changing any of the other options will of\n   * course only have an effect on subsequent method calls.\n   */\n  export interface OptionsBase {\n    /**\n     * The maximum number of items to store in the cache before evicting\n     * old entries. This is read-only on the {@link LRUCache} instance,\n     * and may not be overridden.\n     *\n     * If set, then storage space will be pre-allocated at construction\n     * time, and the cache will perform significantly faster.\n     *\n     * Note that significantly fewer items may be stored, if\n     * {@link OptionsBase.maxSize} and/or {@link OptionsBase.ttl} are also\n     * set.\n     *\n     * **It is strongly recommended to set a `max` to prevent unbounded growth\n     * of the cache.**\n     */\n    max?: Count\n\n    /**\n     * Max time in milliseconds for items to live in cache before they are\n     * considered stale.  Note that stale items are NOT preemptively removed by\n     * default, and MAY live in the cache, contributing to its LRU max, long\n     * after they have expired, unless {@link OptionsBase.ttlAutopurge} is\n     * set.\n     *\n     * If set to `0` (the default value), then that means \"do not track\n     * TTL\", not \"expire immediately\".\n     *\n     * Also, as this cache is optimized for LRU/MRU operations, some of\n     * the staleness/TTL checks will reduce performance, as they will incur\n     * overhead by deleting items.\n     *\n     * This is not primarily a TTL cache, and does not make strong TTL\n     * guarantees. There is no pre-emptive pruning of expired items, but you\n     * _may_ set a TTL on the cache, and it will treat expired items as missing\n     * when they are fetched, and delete them.\n     *\n     * Optional, but must be a non-negative integer in ms if specified.\n     *\n     * This may be overridden by passing an options object to `cache.set()`.\n     *\n     * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n     * positive integer if set.\n     *\n     * Even if ttl tracking is enabled, **it is strongly recommended to set a\n     * `max` to prevent unbounded growth of the cache.**\n     *\n     * If ttl tracking is enabled, and `max` and `maxSize` are not set,\n     * and `ttlAutopurge` is not set, then a warning will be emitted\n     * cautioning about the potential for unbounded memory consumption.\n     * (The TypeScript definitions will also discourage this.)\n     */\n    ttl?: Milliseconds\n\n    /**\n     * Minimum amount of time in ms in which to check for staleness.\n     * Defaults to 1, which means that the current time is checked\n     * at most once per millisecond.\n     *\n     * Set to 0 to check the current time every time staleness is tested.\n     * (This reduces performance, and is theoretically unnecessary.)\n     *\n     * Setting this to a higher value will improve performance somewhat\n     * while using ttl tracking, albeit at the expense of keeping stale\n     * items around a bit longer than their TTLs would indicate.\n     *\n     * @default 1\n     */\n    ttlResolution?: Milliseconds\n\n    /**\n     * Preemptively remove stale items from the cache.\n     *\n     * Note that this may *significantly* degrade performance, especially if\n     * the cache is storing a large number of items. It is almost always best\n     * to just leave the stale items in the cache, and let them fall out as new\n     * items are added.\n     *\n     * Note that this means that {@link OptionsBase.allowStale} is a bit\n     * pointless, as stale items will be deleted almost as soon as they\n     * expire.\n     *\n     * Use with caution!\n     */\n    ttlAutopurge?: boolean\n\n    /**\n     * When using time-expiring entries with `ttl`, setting this to `true` will\n     * make each item's age reset to 0 whenever it is retrieved from cache with\n     * {@link LRUCache#get}, causing it to not expire. (It can still fall out\n     * of cache based on recency of use, of course.)\n     *\n     * Has no effect if {@link OptionsBase.ttl} is not set.\n     *\n     * This may be overridden by passing an options object to `cache.get()`.\n     */\n    updateAgeOnGet?: boolean\n\n    /**\n     * When using time-expiring entries with `ttl`, setting this to `true` will\n     * make each item's age reset to 0 whenever its presence in the cache is\n     * checked with {@link LRUCache#has}, causing it to not expire. (It can\n     * still fall out of cache based on recency of use, of course.)\n     *\n     * Has no effect if {@link OptionsBase.ttl} is not set.\n     */\n    updateAgeOnHas?: boolean\n\n    /**\n     * Allow {@link LRUCache#get} and {@link LRUCache#fetch} calls to return\n     * stale data, if available.\n     *\n     * By default, if you set `ttl`, stale items will only be deleted from the\n     * cache when you `get(key)`. That is, it's not preemptively pruning items,\n     * unless {@link OptionsBase.ttlAutopurge} is set.\n     *\n     * If you set `allowStale:true`, it'll return the stale value *as well as*\n     * deleting it. If you don't set this, then it'll return `undefined` when\n     * you try to get a stale entry.\n     *\n     * Note that when a stale entry is fetched, _even if it is returned due to\n     * `allowStale` being set_, it is removed from the cache immediately. You\n     * can suppress this behavior by setting\n     * {@link OptionsBase.noDeleteOnStaleGet}, either in the constructor, or in\n     * the options provided to {@link LRUCache#get}.\n     *\n     * This may be overridden by passing an options object to `cache.get()`.\n     * The `cache.has()` method will always return `false` for stale items.\n     *\n     * Only relevant if a ttl is set.\n     */\n    allowStale?: boolean\n\n    /**\n     * Function that is called on items when they are dropped from the\n     * cache, as `dispose(value, key, reason)`.\n     *\n     * This can be handy if you want to close file descriptors or do\n     * other cleanup tasks when items are no longer stored in the cache.\n     *\n     * **NOTE**: It is called _before_ the item has been fully removed\n     * from the cache, so if you want to put it right back in, you need\n     * to wait until the next tick. If you try to add it back in during\n     * the `dispose()` function call, it will break things in subtle and\n     * weird ways.\n     *\n     * Unlike several other options, this may _not_ be overridden by\n     * passing an option to `set()`, for performance reasons.\n     *\n     * The `reason` will be one of the following strings, corresponding\n     * to the reason for the item's deletion:\n     *\n     * - `evict` Item was evicted to make space for a new addition\n     * - `set` Item was overwritten by a new value\n     * - `expire` Item expired its TTL\n     * - `fetch` Item was deleted due to a failed or aborted fetch, or a\n     *   fetchMethod returning `undefined.\n     * - `delete` Item was removed by explicit `cache.delete(key)`,\n     *   `cache.clear()`, or `cache.set(key, undefined)`.\n     */\n    dispose?: Disposer\n\n    /**\n     * The same as {@link OptionsBase.dispose}, but called *after* the entry\n     * is completely removed and the cache is once again in a clean state.\n     *\n     * It is safe to add an item right back into the cache at this point.\n     * However, note that it is *very* easy to inadvertently create infinite\n     * recursion this way.\n     */\n    disposeAfter?: Disposer\n\n    /**\n     * Set to true to suppress calling the\n     * {@link OptionsBase.dispose} function if the entry key is\n     * still accessible within the cache.\n     *\n     * This may be overridden by passing an options object to\n     * {@link LRUCache#set}.\n     *\n     * Only relevant if `dispose` or `disposeAfter` are set.\n     */\n    noDisposeOnSet?: boolean\n\n    /**\n     * Boolean flag to tell the cache to not update the TTL when setting a new\n     * value for an existing key (ie, when updating a value rather than\n     * inserting a new value).  Note that the TTL value is _always_ set (if\n     * provided) when adding a new entry into the cache.\n     *\n     * Has no effect if a {@link OptionsBase.ttl} is not set.\n     *\n     * May be passed as an option to {@link LRUCache#set}.\n     */\n    noUpdateTTL?: boolean\n\n    /**\n     * Set to a positive integer to track the sizes of items added to the\n     * cache, and automatically evict items in order to stay below this size.\n     * Note that this may result in fewer than `max` items being stored.\n     *\n     * Attempting to add an item to the cache whose calculated size is greater\n     * that this amount will be a no-op. The item will not be cached, and no\n     * other items will be evicted.\n     *\n     * Optional, must be a positive integer if provided.\n     *\n     * Sets `maxEntrySize` to the same value, unless a different value is\n     * provided for `maxEntrySize`.\n     *\n     * At least one of `max`, `maxSize`, or `TTL` is required. This must be a\n     * positive integer if set.\n     *\n     * Even if size tracking is enabled, **it is strongly recommended to set a\n     * `max` to prevent unbounded growth of the cache.**\n     *\n     * Note also that size tracking can negatively impact performance,\n     * though for most cases, only minimally.\n     */\n    maxSize?: Size\n\n    /**\n     * The maximum allowed size for any single item in the cache.\n     *\n     * If a larger item is passed to {@link LRUCache#set} or returned by a\n     * {@link OptionsBase.fetchMethod} or {@link OptionsBase.memoMethod}, then\n     * it will not be stored in the cache.\n     *\n     * Attempting to add an item whose calculated size is greater than\n     * this amount will not cache the item or evict any old items, but\n     * WILL delete an existing value if one is already present.\n     *\n     * Optional, must be a positive integer if provided. Defaults to\n     * the value of `maxSize` if provided.\n     */\n    maxEntrySize?: Size\n\n    /**\n     * A function that returns a number indicating the item's size.\n     *\n     * Requires {@link OptionsBase.maxSize} to be set.\n     *\n     * If not provided, and {@link OptionsBase.maxSize} or\n     * {@link OptionsBase.maxEntrySize} are set, then all\n     * {@link LRUCache#set} calls **must** provide an explicit\n     * {@link SetOptions.size} or sizeCalculation param.\n     */\n    sizeCalculation?: SizeCalculator\n\n    /**\n     * Method that provides the implementation for {@link LRUCache#fetch}\n     *\n     * ```ts\n     * fetchMethod(key, staleValue, { signal, options, context })\n     * ```\n     *\n     * If `fetchMethod` is not provided, then `cache.fetch(key)` is equivalent\n     * to `Promise.resolve(cache.get(key))`.\n     *\n     * If at any time, `signal.aborted` is set to `true`, or if the\n     * `signal.onabort` method is called, or if it emits an `'abort'` event\n     * which you can listen to with `addEventListener`, then that means that\n     * the fetch should be abandoned. This may be passed along to async\n     * functions aware of AbortController/AbortSignal behavior.\n     *\n     * The `fetchMethod` should **only** return `undefined` or a Promise\n     * resolving to `undefined` if the AbortController signaled an `abort`\n     * event. In all other cases, it should return or resolve to a value\n     * suitable for adding to the cache.\n     *\n     * The `options` object is a union of the options that may be provided to\n     * `set()` and `get()`. If they are modified, then that will result in\n     * modifying the settings to `cache.set()` when the value is resolved, and\n     * in the case of\n     * {@link OptionsBase.noDeleteOnFetchRejection} and\n     * {@link OptionsBase.allowStaleOnFetchRejection}, the handling of\n     * `fetchMethod` failures.\n     *\n     * For example, a DNS cache may update the TTL based on the value returned\n     * from a remote DNS server by changing `options.ttl` in the `fetchMethod`.\n     */\n    fetchMethod?: Fetcher\n\n    /**\n     * Method that provides the implementation for {@link LRUCache#memo}\n     */\n    memoMethod?: Memoizer\n\n    /**\n     * Set to true to suppress the deletion of stale data when a\n     * {@link OptionsBase.fetchMethod} returns a rejected promise.\n     */\n    noDeleteOnFetchRejection?: boolean\n\n    /**\n     * Do not delete stale items when they are retrieved with\n     * {@link LRUCache#get}.\n     *\n     * Note that the `get` return value will still be `undefined`\n     * unless {@link OptionsBase.allowStale} is true.\n     *\n     * When using time-expiring entries with `ttl`, by default stale\n     * items will be removed from the cache when the key is accessed\n     * with `cache.get()`.\n     *\n     * Setting this option will cause stale items to remain in the cache, until\n     * they are explicitly deleted with `cache.delete(key)`, or retrieved with\n     * `noDeleteOnStaleGet` set to `false`.\n     *\n     * This may be overridden by passing an options object to `cache.get()`.\n     *\n     * Only relevant if a ttl is used.\n     */\n    noDeleteOnStaleGet?: boolean\n\n    /**\n     * Set to true to allow returning stale data when a\n     * {@link OptionsBase.fetchMethod} throws an error or returns a rejected\n     * promise.\n     *\n     * This differs from using {@link OptionsBase.allowStale} in that stale\n     * data will ONLY be returned in the case that the {@link LRUCache#fetch}\n     * fails, not any other times.\n     *\n     * If a `fetchMethod` fails, and there is no stale value available, the\n     * `fetch()` will resolve to `undefined`. Ie, all `fetchMethod` errors are\n     * suppressed.\n     *\n     * Implies `noDeleteOnFetchRejection`.\n     *\n     * This may be set in calls to `fetch()`, or defaulted on the constructor,\n     * or overridden by modifying the options object in the `fetchMethod`.\n     */\n    allowStaleOnFetchRejection?: boolean\n\n    /**\n     * Set to true to return a stale value from the cache when the\n     * `AbortSignal` passed to the {@link OptionsBase.fetchMethod} dispatches\n     * an `'abort'` event, whether user-triggered, or due to internal cache\n     * behavior.\n     *\n     * Unless {@link OptionsBase.ignoreFetchAbort} is also set, the underlying\n     * {@link OptionsBase.fetchMethod} will still be considered canceled, and\n     * any value it returns will be ignored and not cached.\n     *\n     * Caveat: since fetches are aborted when a new value is explicitly\n     * set in the cache, this can lead to fetch returning a stale value,\n     * since that was the fallback value _at the moment the `fetch()` was\n     * initiated_, even though the new updated value is now present in\n     * the cache.\n     *\n     * For example:\n     *\n     * ```ts\n     * const cache = new LRUCache({\n     *   ttl: 100,\n     *   fetchMethod: async (url, oldValue, { signal }) =>  {\n     *     const res = await fetch(url, { signal })\n     *     return await res.json()\n     *   }\n     * })\n     * cache.set('https://example.com/', { some: 'data' })\n     * // 100ms go by...\n     * const result = cache.fetch('https://example.com/')\n     * cache.set('https://example.com/', { other: 'thing' })\n     * console.log(await result) // { some: 'data' }\n     * console.log(cache.get('https://example.com/')) // { other: 'thing' }\n     * ```\n     */\n    allowStaleOnFetchAbort?: boolean\n\n    /**\n     * Set to true to ignore the `abort` event emitted by the `AbortSignal`\n     * object passed to {@link OptionsBase.fetchMethod}, and still cache the\n     * resulting resolution value, as long as it is not `undefined`.\n     *\n     * When used on its own, this means aborted {@link LRUCache#fetch} calls\n     * are not immediately resolved or rejected when they are aborted, and\n     * instead take the full time to await.\n     *\n     * When used with {@link OptionsBase.allowStaleOnFetchAbort}, aborted\n     * {@link LRUCache#fetch} calls will resolve immediately to their stale\n     * cached value or `undefined`, and will continue to process and eventually\n     * update the cache when they resolve, as long as the resulting value is\n     * not `undefined`, thus supporting a \"return stale on timeout while\n     * refreshing\" mechanism by passing `AbortSignal.timeout(n)` as the signal.\n     *\n     * For example:\n     *\n     * ```ts\n     * const c = new LRUCache({\n     *   ttl: 100,\n     *   ignoreFetchAbort: true,\n     *   allowStaleOnFetchAbort: true,\n     *   fetchMethod: async (key, oldValue, { signal }) => {\n     *     // note: do NOT pass the signal to fetch()!\n     *     // let's say this fetch can take a long time.\n     *     const res = await fetch(`https://slow-backend-server/${key}`)\n     *     return await res.json()\n     *   },\n     * })\n     *\n     * // this will return the stale value after 100ms, while still\n     * // updating in the background for next time.\n     * const val = await c.fetch('key', { signal: AbortSignal.timeout(100) })\n     * ```\n     *\n     * **Note**: regardless of this setting, an `abort` event _is still\n     * emitted on the `AbortSignal` object_, so may result in invalid results\n     * when passed to other underlying APIs that use AbortSignals.\n     *\n     * This may be overridden in the {@link OptionsBase.fetchMethod} or the\n     * call to {@link LRUCache#fetch}.\n     */\n    ignoreFetchAbort?: boolean\n  }\n\n  export interface OptionsMaxLimit\n    extends OptionsBase {\n    max: Count\n  }\n  export interface OptionsTTLLimit\n    extends OptionsBase {\n    ttl: Milliseconds\n    ttlAutopurge: boolean\n  }\n  export interface OptionsSizeLimit\n    extends OptionsBase {\n    maxSize: Size\n  }\n\n  /**\n   * The valid safe options for the {@link LRUCache} constructor\n   */\n  export type Options =\n    | OptionsMaxLimit\n    | OptionsSizeLimit\n    | OptionsTTLLimit\n\n  /**\n   * Entry objects used by {@link LRUCache#load} and {@link LRUCache#dump},\n   * and returned by {@link LRUCache#info}.\n   */\n  export interface Entry {\n    value: V\n    ttl?: Milliseconds\n    size?: Size\n    start?: Milliseconds\n  }\n}\n\n/**\n * Default export, the thing you're using this module to get.\n *\n * The `K` and `V` types define the key and value types, respectively. The\n * optional `FC` type defines the type of the `context` object passed to\n * `cache.fetch()` and `cache.memo()`.\n *\n * Keys and values **must not** be `null` or `undefined`.\n *\n * All properties from the options object (with the exception of `max`,\n * `maxSize`, `fetchMethod`, `memoMethod`, `dispose` and `disposeAfter`) are\n * added as normal public members. (The listed options are read-only getters.)\n *\n * Changing any of these will alter the defaults for subsequent method calls.\n */\nexport class LRUCache\n  implements Map\n{\n  // options that cannot be changed without disaster\n  readonly #max: LRUCache.Count\n  readonly #maxSize: LRUCache.Size\n  readonly #dispose?: LRUCache.Disposer\n  readonly #disposeAfter?: LRUCache.Disposer\n  readonly #fetchMethod?: LRUCache.Fetcher\n  readonly #memoMethod?: LRUCache.Memoizer\n\n  /**\n   * {@link LRUCache.OptionsBase.ttl}\n   */\n  ttl: LRUCache.Milliseconds\n\n  /**\n   * {@link LRUCache.OptionsBase.ttlResolution}\n   */\n  ttlResolution: LRUCache.Milliseconds\n  /**\n   * {@link LRUCache.OptionsBase.ttlAutopurge}\n   */\n  ttlAutopurge: boolean\n  /**\n   * {@link LRUCache.OptionsBase.updateAgeOnGet}\n   */\n  updateAgeOnGet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.updateAgeOnHas}\n   */\n  updateAgeOnHas: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStale}\n   */\n  allowStale: boolean\n\n  /**\n   * {@link LRUCache.OptionsBase.noDisposeOnSet}\n   */\n  noDisposeOnSet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.noUpdateTTL}\n   */\n  noUpdateTTL: boolean\n  /**\n   * {@link LRUCache.OptionsBase.maxEntrySize}\n   */\n  maxEntrySize: LRUCache.Size\n  /**\n   * {@link LRUCache.OptionsBase.sizeCalculation}\n   */\n  sizeCalculation?: LRUCache.SizeCalculator\n  /**\n   * {@link LRUCache.OptionsBase.noDeleteOnFetchRejection}\n   */\n  noDeleteOnFetchRejection: boolean\n  /**\n   * {@link LRUCache.OptionsBase.noDeleteOnStaleGet}\n   */\n  noDeleteOnStaleGet: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort}\n   */\n  allowStaleOnFetchAbort: boolean\n  /**\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchRejection}\n   */\n  allowStaleOnFetchRejection: boolean\n  /**\n   * {@link LRUCache.OptionsBase.ignoreFetchAbort}\n   */\n  ignoreFetchAbort: boolean\n\n  // computed properties\n  #size: LRUCache.Count\n  #calculatedSize: LRUCache.Size\n  #keyMap: Map\n  #keyList: (K | undefined)[]\n  #valList: (V | BackgroundFetch | undefined)[]\n  #next: NumberArray\n  #prev: NumberArray\n  #head: Index\n  #tail: Index\n  #free: StackLike\n  #disposed?: DisposeTask[]\n  #sizes?: ZeroArray\n  #starts?: ZeroArray\n  #ttls?: ZeroArray\n\n  #hasDispose: boolean\n  #hasFetchMethod: boolean\n  #hasDisposeAfter: boolean\n\n  /**\n   * Do not call this method unless you need to inspect the\n   * inner workings of the cache.  If anything returned by this\n   * object is modified in any way, strange breakage may occur.\n   *\n   * These fields are private for a reason!\n   *\n   * @internal\n   */\n  static unsafeExposeInternals<\n    K extends {},\n    V extends {},\n    FC extends unknown = unknown\n  >(c: LRUCache) {\n    return {\n      // properties\n      starts: c.#starts,\n      ttls: c.#ttls,\n      sizes: c.#sizes,\n      keyMap: c.#keyMap as Map,\n      keyList: c.#keyList,\n      valList: c.#valList,\n      next: c.#next,\n      prev: c.#prev,\n      get head() {\n        return c.#head\n      },\n      get tail() {\n        return c.#tail\n      },\n      free: c.#free,\n      // methods\n      isBackgroundFetch: (p: any) => c.#isBackgroundFetch(p),\n      backgroundFetch: (\n        k: K,\n        index: number | undefined,\n        options: LRUCache.FetchOptions,\n        context: any\n      ): BackgroundFetch =>\n        c.#backgroundFetch(\n          k,\n          index as Index | undefined,\n          options,\n          context\n        ),\n      moveToTail: (index: number): void =>\n        c.#moveToTail(index as Index),\n      indexes: (options?: { allowStale: boolean }) =>\n        c.#indexes(options),\n      rindexes: (options?: { allowStale: boolean }) =>\n        c.#rindexes(options),\n      isStale: (index: number | undefined) =>\n        c.#isStale(index as Index),\n    }\n  }\n\n  // Protected read-only members\n\n  /**\n   * {@link LRUCache.OptionsBase.max} (read-only)\n   */\n  get max(): LRUCache.Count {\n    return this.#max\n  }\n  /**\n   * {@link LRUCache.OptionsBase.maxSize} (read-only)\n   */\n  get maxSize(): LRUCache.Count {\n    return this.#maxSize\n  }\n  /**\n   * The total computed size of items in the cache (read-only)\n   */\n  get calculatedSize(): LRUCache.Size {\n    return this.#calculatedSize\n  }\n  /**\n   * The number of items stored in the cache (read-only)\n   */\n  get size(): LRUCache.Count {\n    return this.#size\n  }\n  /**\n   * {@link LRUCache.OptionsBase.fetchMethod} (read-only)\n   */\n  get fetchMethod(): LRUCache.Fetcher | undefined {\n    return this.#fetchMethod\n  }\n  get memoMethod(): LRUCache.Memoizer | undefined {\n    return this.#memoMethod\n  }\n  /**\n   * {@link LRUCache.OptionsBase.dispose} (read-only)\n   */\n  get dispose() {\n    return this.#dispose\n  }\n  /**\n   * {@link LRUCache.OptionsBase.disposeAfter} (read-only)\n   */\n  get disposeAfter() {\n    return this.#disposeAfter\n  }\n\n  constructor(\n    options: LRUCache.Options | LRUCache\n  ) {\n    const {\n      max = 0,\n      ttl,\n      ttlResolution = 1,\n      ttlAutopurge,\n      updateAgeOnGet,\n      updateAgeOnHas,\n      allowStale,\n      dispose,\n      disposeAfter,\n      noDisposeOnSet,\n      noUpdateTTL,\n      maxSize = 0,\n      maxEntrySize = 0,\n      sizeCalculation,\n      fetchMethod,\n      memoMethod,\n      noDeleteOnFetchRejection,\n      noDeleteOnStaleGet,\n      allowStaleOnFetchRejection,\n      allowStaleOnFetchAbort,\n      ignoreFetchAbort,\n    } = options\n\n    if (max !== 0 && !isPosInt(max)) {\n      throw new TypeError('max option must be a nonnegative integer')\n    }\n\n    const UintArray = max ? getUintArray(max) : Array\n    if (!UintArray) {\n      throw new Error('invalid max value: ' + max)\n    }\n\n    this.#max = max\n    this.#maxSize = maxSize\n    this.maxEntrySize = maxEntrySize || this.#maxSize\n    this.sizeCalculation = sizeCalculation\n    if (this.sizeCalculation) {\n      if (!this.#maxSize && !this.maxEntrySize) {\n        throw new TypeError(\n          'cannot set sizeCalculation without setting maxSize or maxEntrySize'\n        )\n      }\n      if (typeof this.sizeCalculation !== 'function') {\n        throw new TypeError('sizeCalculation set to non-function')\n      }\n    }\n\n    if (\n      memoMethod !== undefined &&\n      typeof memoMethod !== 'function'\n    ) {\n      throw new TypeError('memoMethod must be a function if defined')\n    }\n    this.#memoMethod = memoMethod\n\n    if (\n      fetchMethod !== undefined &&\n      typeof fetchMethod !== 'function'\n    ) {\n      throw new TypeError(\n        'fetchMethod must be a function if specified'\n      )\n    }\n    this.#fetchMethod = fetchMethod\n    this.#hasFetchMethod = !!fetchMethod\n\n    this.#keyMap = new Map()\n    this.#keyList = new Array(max).fill(undefined)\n    this.#valList = new Array(max).fill(undefined)\n    this.#next = new UintArray(max)\n    this.#prev = new UintArray(max)\n    this.#head = 0 as Index\n    this.#tail = 0 as Index\n    this.#free = Stack.create(max)\n    this.#size = 0\n    this.#calculatedSize = 0\n\n    if (typeof dispose === 'function') {\n      this.#dispose = dispose\n    }\n    if (typeof disposeAfter === 'function') {\n      this.#disposeAfter = disposeAfter\n      this.#disposed = []\n    } else {\n      this.#disposeAfter = undefined\n      this.#disposed = undefined\n    }\n    this.#hasDispose = !!this.#dispose\n    this.#hasDisposeAfter = !!this.#disposeAfter\n\n    this.noDisposeOnSet = !!noDisposeOnSet\n    this.noUpdateTTL = !!noUpdateTTL\n    this.noDeleteOnFetchRejection = !!noDeleteOnFetchRejection\n    this.allowStaleOnFetchRejection = !!allowStaleOnFetchRejection\n    this.allowStaleOnFetchAbort = !!allowStaleOnFetchAbort\n    this.ignoreFetchAbort = !!ignoreFetchAbort\n\n    // NB: maxEntrySize is set to maxSize if it's set\n    if (this.maxEntrySize !== 0) {\n      if (this.#maxSize !== 0) {\n        if (!isPosInt(this.#maxSize)) {\n          throw new TypeError(\n            'maxSize must be a positive integer if specified'\n          )\n        }\n      }\n      if (!isPosInt(this.maxEntrySize)) {\n        throw new TypeError(\n          'maxEntrySize must be a positive integer if specified'\n        )\n      }\n      this.#initializeSizeTracking()\n    }\n\n    this.allowStale = !!allowStale\n    this.noDeleteOnStaleGet = !!noDeleteOnStaleGet\n    this.updateAgeOnGet = !!updateAgeOnGet\n    this.updateAgeOnHas = !!updateAgeOnHas\n    this.ttlResolution =\n      isPosInt(ttlResolution) || ttlResolution === 0\n        ? ttlResolution\n        : 1\n    this.ttlAutopurge = !!ttlAutopurge\n    this.ttl = ttl || 0\n    if (this.ttl) {\n      if (!isPosInt(this.ttl)) {\n        throw new TypeError(\n          'ttl must be a positive integer if specified'\n        )\n      }\n      this.#initializeTTLTracking()\n    }\n\n    // do not allow completely unbounded caches\n    if (this.#max === 0 && this.ttl === 0 && this.#maxSize === 0) {\n      throw new TypeError(\n        'At least one of max, maxSize, or ttl is required'\n      )\n    }\n    if (!this.ttlAutopurge && !this.#max && !this.#maxSize) {\n      const code = 'LRU_CACHE_UNBOUNDED'\n      if (shouldWarn(code)) {\n        warned.add(code)\n        const msg =\n          'TTL caching without ttlAutopurge, max, or maxSize can ' +\n          'result in unbounded memory consumption.'\n        emitWarning(msg, 'UnboundedCacheWarning', code, LRUCache)\n      }\n    }\n  }\n\n  /**\n   * Return the number of ms left in the item's TTL. If item is not in cache,\n   * returns `0`. Returns `Infinity` if item is in cache without a defined TTL.\n   */\n  getRemainingTTL(key: K) {\n    return this.#keyMap.has(key) ? Infinity : 0\n  }\n\n  #initializeTTLTracking() {\n    const ttls = new ZeroArray(this.#max)\n    const starts = new ZeroArray(this.#max)\n    this.#ttls = ttls\n    this.#starts = starts\n\n    this.#setItemTTL = (index, ttl, start = perf.now()) => {\n      starts[index] = ttl !== 0 ? start : 0\n      ttls[index] = ttl\n      if (ttl !== 0 && this.ttlAutopurge) {\n        const t = setTimeout(() => {\n          if (this.#isStale(index)) {\n            this.#delete(this.#keyList[index] as K, 'expire')\n          }\n        }, ttl + 1)\n        // unref() not supported on all platforms\n        /* c8 ignore start */\n        if (t.unref) {\n          t.unref()\n        }\n        /* c8 ignore stop */\n      }\n    }\n\n    this.#updateItemAge = index => {\n      starts[index] = ttls[index] !== 0 ? perf.now() : 0\n    }\n\n    this.#statusTTL = (status, index) => {\n      if (ttls[index]) {\n        const ttl = ttls[index]\n        const start = starts[index]\n        /* c8 ignore next */\n        if (!ttl || !start) return\n        status.ttl = ttl\n        status.start = start\n        status.now = cachedNow || getNow()\n        const age = status.now - start\n        status.remainingTTL = ttl - age\n      }\n    }\n\n    // debounce calls to perf.now() to 1s so we're not hitting\n    // that costly call repeatedly.\n    let cachedNow = 0\n    const getNow = () => {\n      const n = perf.now()\n      if (this.ttlResolution > 0) {\n        cachedNow = n\n        const t = setTimeout(\n          () => (cachedNow = 0),\n          this.ttlResolution\n        )\n        // not available on all platforms\n        /* c8 ignore start */\n        if (t.unref) {\n          t.unref()\n        }\n        /* c8 ignore stop */\n      }\n      return n\n    }\n\n    this.getRemainingTTL = key => {\n      const index = this.#keyMap.get(key)\n      if (index === undefined) {\n        return 0\n      }\n      const ttl = ttls[index]\n      const start = starts[index]\n      if (!ttl || !start) {\n        return Infinity\n      }\n      const age = (cachedNow || getNow()) - start\n      return ttl - age\n    }\n\n    this.#isStale = index => {\n      const s = starts[index]\n      const t = ttls[index]\n      return !!t && !!s && (cachedNow || getNow()) - s > t\n    }\n  }\n\n  // conditionally set private methods related to TTL\n  #updateItemAge: (index: Index) => void = () => {}\n  #statusTTL: (status: LRUCache.Status, index: Index) => void =\n    () => {}\n  #setItemTTL: (\n    index: Index,\n    ttl: LRUCache.Milliseconds,\n    start?: LRUCache.Milliseconds\n    // ignore because we never call this if we're not already in TTL mode\n    /* c8 ignore start */\n  ) => void = () => {}\n  /* c8 ignore stop */\n\n  #isStale: (index: Index) => boolean = () => false\n\n  #initializeSizeTracking() {\n    const sizes = new ZeroArray(this.#max)\n    this.#calculatedSize = 0\n    this.#sizes = sizes\n    this.#removeItemSize = index => {\n      this.#calculatedSize -= sizes[index] as number\n      sizes[index] = 0\n    }\n    this.#requireSize = (k, v, size, sizeCalculation) => {\n      // provisionally accept background fetches.\n      // actual value size will be checked when they return.\n      if (this.#isBackgroundFetch(v)) {\n        return 0\n      }\n      if (!isPosInt(size)) {\n        if (sizeCalculation) {\n          if (typeof sizeCalculation !== 'function') {\n            throw new TypeError('sizeCalculation must be a function')\n          }\n          size = sizeCalculation(v, k)\n          if (!isPosInt(size)) {\n            throw new TypeError(\n              'sizeCalculation return invalid (expect positive integer)'\n            )\n          }\n        } else {\n          throw new TypeError(\n            'invalid size value (must be positive integer). ' +\n              'When maxSize or maxEntrySize is used, sizeCalculation ' +\n              'or size must be set.'\n          )\n        }\n      }\n      return size\n    }\n    this.#addItemSize = (\n      index: Index,\n      size: LRUCache.Size,\n      status?: LRUCache.Status\n    ) => {\n      sizes[index] = size\n      if (this.#maxSize) {\n        const maxSize = this.#maxSize - (sizes[index] as number)\n        while (this.#calculatedSize > maxSize) {\n          this.#evict(true)\n        }\n      }\n      this.#calculatedSize += sizes[index] as number\n      if (status) {\n        status.entrySize = size\n        status.totalCalculatedSize = this.#calculatedSize\n      }\n    }\n  }\n\n  #removeItemSize: (index: Index) => void = _i => {}\n  #addItemSize: (\n    index: Index,\n    size: LRUCache.Size,\n    status?: LRUCache.Status\n  ) => void = (_i, _s, _st) => {}\n  #requireSize: (\n    k: K,\n    v: V | BackgroundFetch,\n    size?: LRUCache.Size,\n    sizeCalculation?: LRUCache.SizeCalculator\n  ) => LRUCache.Size = (\n    _k: K,\n    _v: V | BackgroundFetch,\n    size?: LRUCache.Size,\n    sizeCalculation?: LRUCache.SizeCalculator\n  ) => {\n    if (size || sizeCalculation) {\n      throw new TypeError(\n        'cannot set size without setting maxSize or maxEntrySize on cache'\n      )\n    }\n    return 0\n  };\n\n  *#indexes({ allowStale = this.allowStale } = {}) {\n    if (this.#size) {\n      for (let i = this.#tail; true; ) {\n        if (!this.#isValidIndex(i)) {\n          break\n        }\n        if (allowStale || !this.#isStale(i)) {\n          yield i\n        }\n        if (i === this.#head) {\n          break\n        } else {\n          i = this.#prev[i] as Index\n        }\n      }\n    }\n  }\n\n  *#rindexes({ allowStale = this.allowStale } = {}) {\n    if (this.#size) {\n      for (let i = this.#head; true; ) {\n        if (!this.#isValidIndex(i)) {\n          break\n        }\n        if (allowStale || !this.#isStale(i)) {\n          yield i\n        }\n        if (i === this.#tail) {\n          break\n        } else {\n          i = this.#next[i] as Index\n        }\n      }\n    }\n  }\n\n  #isValidIndex(index: Index) {\n    return (\n      index !== undefined &&\n      this.#keyMap.get(this.#keyList[index] as K) === index\n    )\n  }\n\n  /**\n   * Return a generator yielding `[key, value]` pairs,\n   * in order from most recently used to least recently used.\n   */\n  *entries() {\n    for (const i of this.#indexes()) {\n      if (\n        this.#valList[i] !== undefined &&\n        this.#keyList[i] !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield [this.#keyList[i], this.#valList[i]] as [K, V]\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.entries}\n   *\n   * Return a generator yielding `[key, value]` pairs,\n   * in order from least recently used to most recently used.\n   */\n  *rentries() {\n    for (const i of this.#rindexes()) {\n      if (\n        this.#valList[i] !== undefined &&\n        this.#keyList[i] !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield [this.#keyList[i], this.#valList[i]]\n      }\n    }\n  }\n\n  /**\n   * Return a generator yielding the keys in the cache,\n   * in order from most recently used to least recently used.\n   */\n  *keys() {\n    for (const i of this.#indexes()) {\n      const k = this.#keyList[i]\n      if (\n        k !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield k\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.keys}\n   *\n   * Return a generator yielding the keys in the cache,\n   * in order from least recently used to most recently used.\n   */\n  *rkeys() {\n    for (const i of this.#rindexes()) {\n      const k = this.#keyList[i]\n      if (\n        k !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield k\n      }\n    }\n  }\n\n  /**\n   * Return a generator yielding the values in the cache,\n   * in order from most recently used to least recently used.\n   */\n  *values() {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      if (\n        v !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield this.#valList[i] as V\n      }\n    }\n  }\n\n  /**\n   * Inverse order version of {@link LRUCache.values}\n   *\n   * Return a generator yielding the values in the cache,\n   * in order from least recently used to most recently used.\n   */\n  *rvalues() {\n    for (const i of this.#rindexes()) {\n      const v = this.#valList[i]\n      if (\n        v !== undefined &&\n        !this.#isBackgroundFetch(this.#valList[i])\n      ) {\n        yield this.#valList[i]\n      }\n    }\n  }\n\n  /**\n   * Iterating over the cache itself yields the same results as\n   * {@link LRUCache.entries}\n   */\n  [Symbol.iterator]() {\n    return this.entries()\n  }\n\n  /**\n   * A String value that is used in the creation of the default string\n   * description of an object. Called by the built-in method\n   * `Object.prototype.toString`.\n   */\n  [Symbol.toStringTag] = 'LRUCache'\n\n  /**\n   * Find a value for which the supplied fn method returns a truthy value,\n   * similar to `Array.find()`. fn is called as `fn(value, key, cache)`.\n   */\n  find(\n    fn: (v: V, k: K, self: LRUCache) => boolean,\n    getOptions: LRUCache.GetOptions = {}\n  ) {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v)\n        ? v.__staleWhileFetching\n        : v\n      if (value === undefined) continue\n      if (fn(value, this.#keyList[i] as K, this)) {\n        return this.get(this.#keyList[i] as K, getOptions)\n      }\n    }\n  }\n\n  /**\n   * Call the supplied function on each item in the cache, in order from most\n   * recently used to least recently used.\n   *\n   * `fn` is called as `fn(value, key, cache)`.\n   *\n   * If `thisp` is provided, function will be called in the `this`-context of\n   * the provided object, or the cache if no `thisp` object is provided.\n   *\n   * Does not update age or recenty of use, or iterate over stale values.\n   */\n  forEach(\n    fn: (v: V, k: K, self: LRUCache) => any,\n    thisp: any = this\n  ) {\n    for (const i of this.#indexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v)\n        ? v.__staleWhileFetching\n        : v\n      if (value === undefined) continue\n      fn.call(thisp, value, this.#keyList[i] as K, this)\n    }\n  }\n\n  /**\n   * The same as {@link LRUCache.forEach} but items are iterated over in\n   * reverse order.  (ie, less recently used items are iterated over first.)\n   */\n  rforEach(\n    fn: (v: V, k: K, self: LRUCache) => any,\n    thisp: any = this\n  ) {\n    for (const i of this.#rindexes()) {\n      const v = this.#valList[i]\n      const value = this.#isBackgroundFetch(v)\n        ? v.__staleWhileFetching\n        : v\n      if (value === undefined) continue\n      fn.call(thisp, value, this.#keyList[i] as K, this)\n    }\n  }\n\n  /**\n   * Delete any stale entries. Returns true if anything was removed,\n   * false otherwise.\n   */\n  purgeStale() {\n    let deleted = false\n    for (const i of this.#rindexes({ allowStale: true })) {\n      if (this.#isStale(i)) {\n        this.#delete(this.#keyList[i] as K, 'expire')\n        deleted = true\n      }\n    }\n    return deleted\n  }\n\n  /**\n   * Get the extended info about a given entry, to get its value, size, and\n   * TTL info simultaneously. Returns `undefined` if the key is not present.\n   *\n   * Unlike {@link LRUCache#dump}, which is designed to be portable and survive\n   * serialization, the `start` value is always the current timestamp, and the\n   * `ttl` is a calculated remaining time to live (negative if expired).\n   *\n   * Always returns stale values, if their info is found in the cache, so be\n   * sure to check for expirations (ie, a negative {@link LRUCache.Entry#ttl})\n   * if relevant.\n   */\n  info(key: K): LRUCache.Entry | undefined {\n    const i = this.#keyMap.get(key)\n    if (i === undefined) return undefined\n    const v = this.#valList[i]\n    const value: V | undefined = this.#isBackgroundFetch(v)\n      ? v.__staleWhileFetching\n      : v\n    if (value === undefined) return undefined\n    const entry: LRUCache.Entry = { value }\n    if (this.#ttls && this.#starts) {\n      const ttl = this.#ttls[i]\n      const start = this.#starts[i]\n      if (ttl && start) {\n        const remain = ttl - (perf.now() - start)\n        entry.ttl = remain\n        entry.start = Date.now()\n      }\n    }\n    if (this.#sizes) {\n      entry.size = this.#sizes[i]\n    }\n    return entry\n  }\n\n  /**\n   * Return an array of [key, {@link LRUCache.Entry}] tuples which can be\n   * passed to {@link LRLUCache#load}.\n   *\n   * The `start` fields are calculated relative to a portable `Date.now()`\n   * timestamp, even if `performance.now()` is available.\n   *\n   * Stale entries are always included in the `dump`, even if\n   * {@link LRUCache.OptionsBase.allowStale} is false.\n   *\n   * Note: this returns an actual array, not a generator, so it can be more\n   * easily passed around.\n   */\n  dump() {\n    const arr: [K, LRUCache.Entry][] = []\n    for (const i of this.#indexes({ allowStale: true })) {\n      const key = this.#keyList[i]\n      const v = this.#valList[i]\n      const value: V | undefined = this.#isBackgroundFetch(v)\n        ? v.__staleWhileFetching\n        : v\n      if (value === undefined || key === undefined) continue\n      const entry: LRUCache.Entry = { value }\n      if (this.#ttls && this.#starts) {\n        entry.ttl = this.#ttls[i]\n        // always dump the start relative to a portable timestamp\n        // it's ok for this to be a bit slow, it's a rare operation.\n        const age = perf.now() - (this.#starts[i] as number)\n        entry.start = Math.floor(Date.now() - age)\n      }\n      if (this.#sizes) {\n        entry.size = this.#sizes[i]\n      }\n      arr.unshift([key, entry])\n    }\n    return arr\n  }\n\n  /**\n   * Reset the cache and load in the items in entries in the order listed.\n   *\n   * The shape of the resulting cache may be different if the same options are\n   * not used in both caches.\n   *\n   * The `start` fields are assumed to be calculated relative to a portable\n   * `Date.now()` timestamp, even if `performance.now()` is available.\n   */\n  load(arr: [K, LRUCache.Entry][]) {\n    this.clear()\n    for (const [key, entry] of arr) {\n      if (entry.start) {\n        // entry.start is a portable timestamp, but we may be using\n        // node's performance.now(), so calculate the offset, so that\n        // we get the intended remaining TTL, no matter how long it's\n        // been on ice.\n        //\n        // it's ok for this to be a bit slow, it's a rare operation.\n        const age = Date.now() - entry.start\n        entry.start = perf.now() - age\n      }\n      this.set(key, entry.value, entry)\n    }\n  }\n\n  /**\n   * Add a value to the cache.\n   *\n   * Note: if `undefined` is specified as a value, this is an alias for\n   * {@link LRUCache#delete}\n   *\n   * Fields on the {@link LRUCache.SetOptions} options param will override\n   * their corresponding values in the constructor options for the scope\n   * of this single `set()` operation.\n   *\n   * If `start` is provided, then that will set the effective start\n   * time for the TTL calculation. Note that this must be a previous\n   * value of `performance.now()` if supported, or a previous value of\n   * `Date.now()` if not.\n   *\n   * Options object may also include `size`, which will prevent\n   * calling the `sizeCalculation` function and just use the specified\n   * number if it is a positive integer, and `noDisposeOnSet` which\n   * will prevent calling a `dispose` function in the case of\n   * overwrites.\n   *\n   * If the `size` (or return value of `sizeCalculation`) for a given\n   * entry is greater than `maxEntrySize`, then the item will not be\n   * added to the cache.\n   *\n   * Will update the recency of the entry.\n   *\n   * If the value is `undefined`, then this is an alias for\n   * `cache.delete(key)`. `undefined` is never stored in the cache.\n   */\n  set(\n    k: K,\n    v: V | BackgroundFetch | undefined,\n    setOptions: LRUCache.SetOptions = {}\n  ) {\n    if (v === undefined) {\n      this.delete(k)\n      return this\n    }\n    const {\n      ttl = this.ttl,\n      start,\n      noDisposeOnSet = this.noDisposeOnSet,\n      sizeCalculation = this.sizeCalculation,\n      status,\n    } = setOptions\n    let { noUpdateTTL = this.noUpdateTTL } = setOptions\n\n    const size = this.#requireSize(\n      k,\n      v,\n      setOptions.size || 0,\n      sizeCalculation\n    )\n    // if the item doesn't fit, don't do anything\n    // NB: maxEntrySize set to maxSize by default\n    if (this.maxEntrySize && size > this.maxEntrySize) {\n      if (status) {\n        status.set = 'miss'\n        status.maxEntrySizeExceeded = true\n      }\n      // have to delete, in case something is there already.\n      this.#delete(k, 'set')\n      return this\n    }\n    let index = this.#size === 0 ? undefined : this.#keyMap.get(k)\n    if (index === undefined) {\n      // addition\n      index = (\n        this.#size === 0\n          ? this.#tail\n          : this.#free.length !== 0\n          ? this.#free.pop()\n          : this.#size === this.#max\n          ? this.#evict(false)\n          : this.#size\n      ) as Index\n      this.#keyList[index] = k\n      this.#valList[index] = v\n      this.#keyMap.set(k, index)\n      this.#next[this.#tail] = index\n      this.#prev[index] = this.#tail\n      this.#tail = index\n      this.#size++\n      this.#addItemSize(index, size, status)\n      if (status) status.set = 'add'\n      noUpdateTTL = false\n    } else {\n      // update\n      this.#moveToTail(index)\n      const oldVal = this.#valList[index] as V | BackgroundFetch\n      if (v !== oldVal) {\n        if (this.#hasFetchMethod && this.#isBackgroundFetch(oldVal)) {\n          oldVal.__abortController.abort(new Error('replaced'))\n          const { __staleWhileFetching: s } = oldVal\n          if (s !== undefined && !noDisposeOnSet) {\n            if (this.#hasDispose) {\n              this.#dispose?.(s as V, k, 'set')\n            }\n            if (this.#hasDisposeAfter) {\n              this.#disposed?.push([s as V, k, 'set'])\n            }\n          }\n        } else if (!noDisposeOnSet) {\n          if (this.#hasDispose) {\n            this.#dispose?.(oldVal as V, k, 'set')\n          }\n          if (this.#hasDisposeAfter) {\n            this.#disposed?.push([oldVal as V, k, 'set'])\n          }\n        }\n        this.#removeItemSize(index)\n        this.#addItemSize(index, size, status)\n        this.#valList[index] = v\n        if (status) {\n          status.set = 'replace'\n          const oldValue =\n            oldVal && this.#isBackgroundFetch(oldVal)\n              ? oldVal.__staleWhileFetching\n              : oldVal\n          if (oldValue !== undefined) status.oldValue = oldValue\n        }\n      } else if (status) {\n        status.set = 'update'\n      }\n    }\n    if (ttl !== 0 && !this.#ttls) {\n      this.#initializeTTLTracking()\n    }\n    if (this.#ttls) {\n      if (!noUpdateTTL) {\n        this.#setItemTTL(index, ttl, start)\n      }\n      if (status) this.#statusTTL(status, index)\n    }\n    if (!noDisposeOnSet && this.#hasDisposeAfter && this.#disposed) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n    return this\n  }\n\n  /**\n   * Evict the least recently used item, returning its value or\n   * `undefined` if cache is empty.\n   */\n  pop(): V | undefined {\n    try {\n      while (this.#size) {\n        const val = this.#valList[this.#head]\n        this.#evict(true)\n        if (this.#isBackgroundFetch(val)) {\n          if (val.__staleWhileFetching) {\n            return val.__staleWhileFetching\n          }\n        } else if (val !== undefined) {\n          return val\n        }\n      }\n    } finally {\n      if (this.#hasDisposeAfter && this.#disposed) {\n        const dt = this.#disposed\n        let task: DisposeTask | undefined\n        while ((task = dt?.shift())) {\n          this.#disposeAfter?.(...task)\n        }\n      }\n    }\n  }\n\n  #evict(free: boolean) {\n    const head = this.#head\n    const k = this.#keyList[head] as K\n    const v = this.#valList[head] as V\n    if (this.#hasFetchMethod && this.#isBackgroundFetch(v)) {\n      v.__abortController.abort(new Error('evicted'))\n    } else if (this.#hasDispose || this.#hasDisposeAfter) {\n      if (this.#hasDispose) {\n        this.#dispose?.(v, k, 'evict')\n      }\n      if (this.#hasDisposeAfter) {\n        this.#disposed?.push([v, k, 'evict'])\n      }\n    }\n    this.#removeItemSize(head)\n    // if we aren't about to use the index, then null these out\n    if (free) {\n      this.#keyList[head] = undefined\n      this.#valList[head] = undefined\n      this.#free.push(head)\n    }\n    if (this.#size === 1) {\n      this.#head = this.#tail = 0 as Index\n      this.#free.length = 0\n    } else {\n      this.#head = this.#next[head] as Index\n    }\n    this.#keyMap.delete(k)\n    this.#size--\n    return head\n  }\n\n  /**\n   * Check if a key is in the cache, without updating the recency of use.\n   * Will return false if the item is stale, even though it is technically\n   * in the cache.\n   *\n   * Check if a key is in the cache, without updating the recency of\n   * use. Age is updated if {@link LRUCache.OptionsBase.updateAgeOnHas} is set\n   * to `true` in either the options or the constructor.\n   *\n   * Will return `false` if the item is stale, even though it is technically in\n   * the cache. The difference can be determined (if it matters) by using a\n   * `status` argument, and inspecting the `has` field.\n   *\n   * Will not update item age unless\n   * {@link LRUCache.OptionsBase.updateAgeOnHas} is set.\n   */\n  has(k: K, hasOptions: LRUCache.HasOptions = {}) {\n    const { updateAgeOnHas = this.updateAgeOnHas, status } =\n      hasOptions\n    const index = this.#keyMap.get(k)\n    if (index !== undefined) {\n      const v = this.#valList[index]\n      if (\n        this.#isBackgroundFetch(v) &&\n        v.__staleWhileFetching === undefined\n      ) {\n        return false\n      }\n      if (!this.#isStale(index)) {\n        if (updateAgeOnHas) {\n          this.#updateItemAge(index)\n        }\n        if (status) {\n          status.has = 'hit'\n          this.#statusTTL(status, index)\n        }\n        return true\n      } else if (status) {\n        status.has = 'stale'\n        this.#statusTTL(status, index)\n      }\n    } else if (status) {\n      status.has = 'miss'\n    }\n    return false\n  }\n\n  /**\n   * Like {@link LRUCache#get} but doesn't update recency or delete stale\n   * items.\n   *\n   * Returns `undefined` if the item is stale, unless\n   * {@link LRUCache.OptionsBase.allowStale} is set.\n   */\n  peek(k: K, peekOptions: LRUCache.PeekOptions = {}) {\n    const { allowStale = this.allowStale } = peekOptions\n    const index = this.#keyMap.get(k)\n    if (\n      index === undefined ||\n      (!allowStale && this.#isStale(index))\n    ) {\n      return\n    }\n    const v = this.#valList[index]\n    // either stale and allowed, or forcing a refresh of non-stale value\n    return this.#isBackgroundFetch(v) ? v.__staleWhileFetching : v\n  }\n\n  #backgroundFetch(\n    k: K,\n    index: Index | undefined,\n    options: LRUCache.FetchOptions,\n    context: any\n  ): BackgroundFetch {\n    const v = index === undefined ? undefined : this.#valList[index]\n    if (this.#isBackgroundFetch(v)) {\n      return v\n    }\n\n    const ac = new AC()\n    const { signal } = options\n    // when/if our AC signals, then stop listening to theirs.\n    signal?.addEventListener('abort', () => ac.abort(signal.reason), {\n      signal: ac.signal,\n    })\n\n    const fetchOpts = {\n      signal: ac.signal,\n      options,\n      context,\n    }\n\n    const cb = (\n      v: V | undefined,\n      updateCache = false\n    ): V | undefined => {\n      const { aborted } = ac.signal\n      const ignoreAbort = options.ignoreFetchAbort && v !== undefined\n      if (options.status) {\n        if (aborted && !updateCache) {\n          options.status.fetchAborted = true\n          options.status.fetchError = ac.signal.reason\n          if (ignoreAbort) options.status.fetchAbortIgnored = true\n        } else {\n          options.status.fetchResolved = true\n        }\n      }\n      if (aborted && !ignoreAbort && !updateCache) {\n        return fetchFail(ac.signal.reason)\n      }\n      // either we didn't abort, and are still here, or we did, and ignored\n      const bf = p as BackgroundFetch\n      if (this.#valList[index as Index] === p) {\n        if (v === undefined) {\n          if (bf.__staleWhileFetching) {\n            this.#valList[index as Index] = bf.__staleWhileFetching\n          } else {\n            this.#delete(k, 'fetch')\n          }\n        } else {\n          if (options.status) options.status.fetchUpdated = true\n          this.set(k, v, fetchOpts.options)\n        }\n      }\n      return v\n    }\n\n    const eb = (er: any) => {\n      if (options.status) {\n        options.status.fetchRejected = true\n        options.status.fetchError = er\n      }\n      return fetchFail(er)\n    }\n\n    const fetchFail = (er: any): V | undefined => {\n      const { aborted } = ac.signal\n      const allowStaleAborted =\n        aborted && options.allowStaleOnFetchAbort\n      const allowStale =\n        allowStaleAborted || options.allowStaleOnFetchRejection\n      const noDelete = allowStale || options.noDeleteOnFetchRejection\n      const bf = p as BackgroundFetch\n      if (this.#valList[index as Index] === p) {\n        // if we allow stale on fetch rejections, then we need to ensure that\n        // the stale value is not removed from the cache when the fetch fails.\n        const del = !noDelete || bf.__staleWhileFetching === undefined\n        if (del) {\n          this.#delete(k, 'fetch')\n        } else if (!allowStaleAborted) {\n          // still replace the *promise* with the stale value,\n          // since we are done with the promise at this point.\n          // leave it untouched if we're still waiting for an\n          // aborted background fetch that hasn't yet returned.\n          this.#valList[index as Index] = bf.__staleWhileFetching\n        }\n      }\n      if (allowStale) {\n        if (options.status && bf.__staleWhileFetching !== undefined) {\n          options.status.returnedStale = true\n        }\n        return bf.__staleWhileFetching\n      } else if (bf.__returned === bf) {\n        throw er\n      }\n    }\n\n    const pcall = (\n      res: (v: V | undefined) => void,\n      rej: (e: any) => void\n    ) => {\n      const fmp = this.#fetchMethod?.(k, v, fetchOpts)\n      if (fmp && fmp instanceof Promise) {\n        fmp.then(v => res(v === undefined ? undefined : v), rej)\n      }\n      // ignored, we go until we finish, regardless.\n      // defer check until we are actually aborting,\n      // so fetchMethod can override.\n      ac.signal.addEventListener('abort', () => {\n        if (\n          !options.ignoreFetchAbort ||\n          options.allowStaleOnFetchAbort\n        ) {\n          res(undefined)\n          // when it eventually resolves, update the cache.\n          if (options.allowStaleOnFetchAbort) {\n            res = v => cb(v, true)\n          }\n        }\n      })\n    }\n\n    if (options.status) options.status.fetchDispatched = true\n    const p = new Promise(pcall).then(cb, eb)\n    const bf: BackgroundFetch = Object.assign(p, {\n      __abortController: ac,\n      __staleWhileFetching: v,\n      __returned: undefined,\n    })\n\n    if (index === undefined) {\n      // internal, don't expose status.\n      this.set(k, bf, { ...fetchOpts.options, status: undefined })\n      index = this.#keyMap.get(k)\n    } else {\n      this.#valList[index] = bf\n    }\n    return bf\n  }\n\n  #isBackgroundFetch(p: any): p is BackgroundFetch {\n    if (!this.#hasFetchMethod) return false\n    const b = p as BackgroundFetch\n    return (\n      !!b &&\n      b instanceof Promise &&\n      b.hasOwnProperty('__staleWhileFetching') &&\n      b.__abortController instanceof AC\n    )\n  }\n\n  /**\n   * Make an asynchronous cached fetch using the\n   * {@link LRUCache.OptionsBase.fetchMethod} function.\n   *\n   * If the value is in the cache and not stale, then the returned\n   * Promise resolves to the value.\n   *\n   * If not in the cache, or beyond its TTL staleness, then\n   * `fetchMethod(key, staleValue, { options, signal, context })` is\n   * called, and the value returned will be added to the cache once\n   * resolved.\n   *\n   * If called with `allowStale`, and an asynchronous fetch is\n   * currently in progress to reload a stale value, then the former\n   * stale value will be returned.\n   *\n   * If called with `forceRefresh`, then the cached item will be\n   * re-fetched, even if it is not stale. However, if `allowStale` is also\n   * set, then the old value will still be returned. This is useful\n   * in cases where you want to force a reload of a cached value. If\n   * a background fetch is already in progress, then `forceRefresh`\n   * has no effect.\n   *\n   * If multiple fetches for the same key are issued, then they will all be\n   * coalesced into a single call to fetchMethod.\n   *\n   * Note that this means that handling options such as\n   * {@link LRUCache.OptionsBase.allowStaleOnFetchAbort},\n   * {@link LRUCache.FetchOptions.signal},\n   * and {@link LRUCache.OptionsBase.allowStaleOnFetchRejection} will be\n   * determined by the FIRST fetch() call for a given key.\n   *\n   * This is a known (fixable) shortcoming which will be addresed on when\n   * someone complains about it, as the fix would involve added complexity and\n   * may not be worth the costs for this edge case.\n   *\n   * If {@link LRUCache.OptionsBase.fetchMethod} is not specified, then this is\n   * effectively an alias for `Promise.resolve(cache.get(key))`.\n   *\n   * When the fetch method resolves to a value, if the fetch has not\n   * been aborted due to deletion, eviction, or being overwritten,\n   * then it is added to the cache using the options provided.\n   *\n   * If the key is evicted or deleted before the `fetchMethod`\n   * resolves, then the AbortSignal passed to the `fetchMethod` will\n   * receive an `abort` event, and the promise returned by `fetch()`\n   * will reject with the reason for the abort.\n   *\n   * If a `signal` is passed to the `fetch()` call, then aborting the\n   * signal will abort the fetch and cause the `fetch()` promise to\n   * reject with the reason provided.\n   *\n   * **Setting `context`**\n   *\n   * If an `FC` type is set to a type other than `unknown`, `void`, or\n   * `undefined` in the {@link LRUCache} constructor, then all\n   * calls to `cache.fetch()` _must_ provide a `context` option. If\n   * set to `undefined` or `void`, then calls to fetch _must not_\n   * provide a `context` option.\n   *\n   * The `context` param allows you to provide arbitrary data that\n   * might be relevant in the course of fetching the data. It is only\n   * relevant for the course of a single `fetch()` operation, and\n   * discarded afterwards.\n   *\n   * **Note: `fetch()` calls are inflight-unique**\n   *\n   * If you call `fetch()` multiple times with the same key value,\n   * then every call after the first will resolve on the same\n   * promise1,\n   * _even if they have different settings that would otherwise change\n   * the behavior of the fetch_, such as `noDeleteOnFetchRejection`\n   * or `ignoreFetchAbort`.\n   *\n   * In most cases, this is not a problem (in fact, only fetching\n   * something once is what you probably want, if you're caching in\n   * the first place). If you are changing the fetch() options\n   * dramatically between runs, there's a good chance that you might\n   * be trying to fit divergent semantics into a single object, and\n   * would be better off with multiple cache instances.\n   *\n   * **1**: Ie, they're not the \"same Promise\", but they resolve at\n   * the same time, because they're both waiting on the same\n   * underlying fetchMethod response.\n   */\n\n  fetch(\n    k: K,\n    fetchOptions: unknown extends FC\n      ? LRUCache.FetchOptions\n      : FC extends undefined | void\n      ? LRUCache.FetchOptionsNoContext\n      : LRUCache.FetchOptionsWithContext\n  ): Promise\n\n  // this overload not allowed if context is required\n  fetch(\n    k: unknown extends FC\n      ? K\n      : FC extends undefined | void\n      ? K\n      : never,\n    fetchOptions?: unknown extends FC\n      ? LRUCache.FetchOptions\n      : FC extends undefined | void\n      ? LRUCache.FetchOptionsNoContext\n      : never\n  ): Promise\n\n  async fetch(\n    k: K,\n    fetchOptions: LRUCache.FetchOptions = {}\n  ): Promise {\n    const {\n      // get options\n      allowStale = this.allowStale,\n      updateAgeOnGet = this.updateAgeOnGet,\n      noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n      // set options\n      ttl = this.ttl,\n      noDisposeOnSet = this.noDisposeOnSet,\n      size = 0,\n      sizeCalculation = this.sizeCalculation,\n      noUpdateTTL = this.noUpdateTTL,\n      // fetch exclusive options\n      noDeleteOnFetchRejection = this.noDeleteOnFetchRejection,\n      allowStaleOnFetchRejection = this.allowStaleOnFetchRejection,\n      ignoreFetchAbort = this.ignoreFetchAbort,\n      allowStaleOnFetchAbort = this.allowStaleOnFetchAbort,\n      context,\n      forceRefresh = false,\n      status,\n      signal,\n    } = fetchOptions\n\n    if (!this.#hasFetchMethod) {\n      if (status) status.fetch = 'get'\n      return this.get(k, {\n        allowStale,\n        updateAgeOnGet,\n        noDeleteOnStaleGet,\n        status,\n      })\n    }\n\n    const options = {\n      allowStale,\n      updateAgeOnGet,\n      noDeleteOnStaleGet,\n      ttl,\n      noDisposeOnSet,\n      size,\n      sizeCalculation,\n      noUpdateTTL,\n      noDeleteOnFetchRejection,\n      allowStaleOnFetchRejection,\n      allowStaleOnFetchAbort,\n      ignoreFetchAbort,\n      status,\n      signal,\n    }\n\n    let index = this.#keyMap.get(k)\n    if (index === undefined) {\n      if (status) status.fetch = 'miss'\n      const p = this.#backgroundFetch(k, index, options, context)\n      return (p.__returned = p)\n    } else {\n      // in cache, maybe already fetching\n      const v = this.#valList[index]\n      if (this.#isBackgroundFetch(v)) {\n        const stale =\n          allowStale && v.__staleWhileFetching !== undefined\n        if (status) {\n          status.fetch = 'inflight'\n          if (stale) status.returnedStale = true\n        }\n        return stale ? v.__staleWhileFetching : (v.__returned = v)\n      }\n\n      // if we force a refresh, that means do NOT serve the cached value,\n      // unless we are already in the process of refreshing the cache.\n      const isStale = this.#isStale(index)\n      if (!forceRefresh && !isStale) {\n        if (status) status.fetch = 'hit'\n        this.#moveToTail(index)\n        if (updateAgeOnGet) {\n          this.#updateItemAge(index)\n        }\n        if (status) this.#statusTTL(status, index)\n        return v\n      }\n\n      // ok, it is stale or a forced refresh, and not already fetching.\n      // refresh the cache.\n      const p = this.#backgroundFetch(k, index, options, context)\n      const hasStale = p.__staleWhileFetching !== undefined\n      const staleVal = hasStale && allowStale\n      if (status) {\n        status.fetch = isStale ? 'stale' : 'refresh'\n        if (staleVal && isStale) status.returnedStale = true\n      }\n      return staleVal ? p.__staleWhileFetching : (p.__returned = p)\n    }\n  }\n\n  /**\n   * In some cases, `cache.fetch()` may resolve to `undefined`, either because\n   * a {@link LRUCache.OptionsBase#fetchMethod} was not provided (turning\n   * `cache.fetch(k)` into just an async wrapper around `cache.get(k)`) or\n   * because `ignoreFetchAbort` was specified (either to the constructor or\n   * in the {@link LRUCache.FetchOptions}). Also, the\n   * {@link OptionsBase.fetchMethod} may return `undefined` or `void`, making\n   * the test even more complicated.\n   *\n   * Because inferring the cases where `undefined` might be returned are so\n   * cumbersome, but testing for `undefined` can also be annoying, this method\n   * can be used, which will reject if `this.fetch()` resolves to undefined.\n   */\n  forceFetch(\n    k: K,\n    fetchOptions: unknown extends FC\n      ? LRUCache.FetchOptions\n      : FC extends undefined | void\n      ? LRUCache.FetchOptionsNoContext\n      : LRUCache.FetchOptionsWithContext\n  ): Promise\n  // this overload not allowed if context is required\n  forceFetch(\n    k: unknown extends FC\n      ? K\n      : FC extends undefined | void\n      ? K\n      : never,\n    fetchOptions?: unknown extends FC\n      ? LRUCache.FetchOptions\n      : FC extends undefined | void\n      ? LRUCache.FetchOptionsNoContext\n      : never\n  ): Promise\n  async forceFetch(\n    k: K,\n    fetchOptions: LRUCache.FetchOptions = {}\n  ): Promise {\n    const v = await this.fetch(\n      k,\n      fetchOptions as unknown extends FC\n        ? LRUCache.FetchOptions\n        : FC extends undefined | void\n        ? LRUCache.FetchOptionsNoContext\n        : LRUCache.FetchOptionsWithContext\n    )\n    if (v === undefined) throw new Error('fetch() returned undefined')\n    return v\n  }\n\n  /**\n   * If the key is found in the cache, then this is equivalent to\n   * {@link LRUCache#get}. If not, in the cache, then calculate the value using\n   * the {@link LRUCache.OptionsBase.memoMethod}, and add it to the cache.\n   *\n   * If an `FC` type is set to a type other than `unknown`, `void`, or\n   * `undefined` in the LRUCache constructor, then all calls to `cache.memo()`\n   * _must_ provide a `context` option. If set to `undefined` or `void`, then\n   * calls to memo _must not_ provide a `context` option.\n   *\n   * The `context` param allows you to provide arbitrary data that might be\n   * relevant in the course of fetching the data. It is only relevant for the\n   * course of a single `memo()` operation, and discarded afterwards.\n   */\n  memo(\n    k: K,\n    memoOptions: unknown extends FC\n      ? LRUCache.MemoOptions\n      : FC extends undefined | void\n      ? LRUCache.MemoOptionsNoContext\n      : LRUCache.MemoOptionsWithContext\n  ): V\n  // this overload not allowed if context is required\n  memo(\n    k: unknown extends FC\n      ? K\n      : FC extends undefined | void\n      ? K\n      : never,\n    memoOptions?: unknown extends FC\n      ? LRUCache.MemoOptions\n      : FC extends undefined | void\n      ? LRUCache.MemoOptionsNoContext\n      : never\n  ): V\n  memo(k: K, memoOptions: LRUCache.MemoOptions = {}) {\n    const memoMethod = this.#memoMethod\n    if (!memoMethod) {\n      throw new Error('no memoMethod provided to constructor')\n    }\n    const { context, forceRefresh, ...options } = memoOptions\n    const v = this.get(k, options)\n    if (!forceRefresh && v !== undefined) return v\n    const vv = memoMethod(k, v, {\n      options,\n      context,\n    } as LRUCache.MemoizerOptions)\n    this.set(k, vv, options)\n    return vv\n  }\n\n  /**\n   * Return a value from the cache. Will update the recency of the cache\n   * entry found.\n   *\n   * If the key is not found, get() will return `undefined`.\n   */\n  get(k: K, getOptions: LRUCache.GetOptions = {}) {\n    const {\n      allowStale = this.allowStale,\n      updateAgeOnGet = this.updateAgeOnGet,\n      noDeleteOnStaleGet = this.noDeleteOnStaleGet,\n      status,\n    } = getOptions\n    const index = this.#keyMap.get(k)\n    if (index !== undefined) {\n      const value = this.#valList[index]\n      const fetching = this.#isBackgroundFetch(value)\n      if (status) this.#statusTTL(status, index)\n      if (this.#isStale(index)) {\n        if (status) status.get = 'stale'\n        // delete only if not an in-flight background fetch\n        if (!fetching) {\n          if (!noDeleteOnStaleGet) {\n            this.#delete(k, 'expire')\n          }\n          if (status && allowStale) status.returnedStale = true\n          return allowStale ? value : undefined\n        } else {\n          if (\n            status &&\n            allowStale &&\n            value.__staleWhileFetching !== undefined\n          ) {\n            status.returnedStale = true\n          }\n          return allowStale ? value.__staleWhileFetching : undefined\n        }\n      } else {\n        if (status) status.get = 'hit'\n        // if we're currently fetching it, we don't actually have it yet\n        // it's not stale, which means this isn't a staleWhileRefetching.\n        // If it's not stale, and fetching, AND has a __staleWhileFetching\n        // value, then that means the user fetched with {forceRefresh:true},\n        // so it's safe to return that value.\n        if (fetching) {\n          return value.__staleWhileFetching\n        }\n        this.#moveToTail(index)\n        if (updateAgeOnGet) {\n          this.#updateItemAge(index)\n        }\n        return value\n      }\n    } else if (status) {\n      status.get = 'miss'\n    }\n  }\n\n  #connect(p: Index, n: Index) {\n    this.#prev[n] = p\n    this.#next[p] = n\n  }\n\n  #moveToTail(index: Index): void {\n    // if tail already, nothing to do\n    // if head, move head to next[index]\n    // else\n    //   move next[prev[index]] to next[index] (head has no prev)\n    //   move prev[next[index]] to prev[index]\n    // prev[index] = tail\n    // next[tail] = index\n    // tail = index\n    if (index !== this.#tail) {\n      if (index === this.#head) {\n        this.#head = this.#next[index] as Index\n      } else {\n        this.#connect(\n          this.#prev[index] as Index,\n          this.#next[index] as Index\n        )\n      }\n      this.#connect(this.#tail, index)\n      this.#tail = index\n    }\n  }\n\n  /**\n   * Deletes a key out of the cache.\n   *\n   * Returns true if the key was deleted, false otherwise.\n   */\n  delete(k: K) {\n    return this.#delete(k, 'delete')\n  }\n\n  #delete(k: K, reason: LRUCache.DisposeReason) {\n    let deleted = false\n    if (this.#size !== 0) {\n      const index = this.#keyMap.get(k)\n      if (index !== undefined) {\n        deleted = true\n        if (this.#size === 1) {\n          this.#clear(reason)\n        } else {\n          this.#removeItemSize(index)\n          const v = this.#valList[index]\n          if (this.#isBackgroundFetch(v)) {\n            v.__abortController.abort(new Error('deleted'))\n          } else if (this.#hasDispose || this.#hasDisposeAfter) {\n            if (this.#hasDispose) {\n              this.#dispose?.(v as V, k, reason)\n            }\n            if (this.#hasDisposeAfter) {\n              this.#disposed?.push([v as V, k, reason])\n            }\n          }\n          this.#keyMap.delete(k)\n          this.#keyList[index] = undefined\n          this.#valList[index] = undefined\n          if (index === this.#tail) {\n            this.#tail = this.#prev[index] as Index\n          } else if (index === this.#head) {\n            this.#head = this.#next[index] as Index\n          } else {\n            const pi = this.#prev[index] as number\n            this.#next[pi] = this.#next[index] as number\n            const ni = this.#next[index] as number\n            this.#prev[ni] = this.#prev[index] as number\n          }\n          this.#size--\n          this.#free.push(index)\n        }\n      }\n    }\n    if (this.#hasDisposeAfter && this.#disposed?.length) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n    return deleted\n  }\n\n  /**\n   * Clear the cache entirely, throwing away all values.\n   */\n  clear() {\n    return this.#clear('delete')\n  }\n  #clear(reason: LRUCache.DisposeReason) {\n    for (const index of this.#rindexes({ allowStale: true })) {\n      const v = this.#valList[index]\n      if (this.#isBackgroundFetch(v)) {\n        v.__abortController.abort(new Error('deleted'))\n      } else {\n        const k = this.#keyList[index]\n        if (this.#hasDispose) {\n          this.#dispose?.(v as V, k as K, reason)\n        }\n        if (this.#hasDisposeAfter) {\n          this.#disposed?.push([v as V, k as K, reason])\n        }\n      }\n    }\n\n    this.#keyMap.clear()\n    this.#valList.fill(undefined)\n    this.#keyList.fill(undefined)\n    if (this.#ttls && this.#starts) {\n      this.#ttls.fill(0)\n      this.#starts.fill(0)\n    }\n    if (this.#sizes) {\n      this.#sizes.fill(0)\n    }\n    this.#head = 0 as Index\n    this.#tail = 0 as Index\n    this.#free.length = 0\n    this.#calculatedSize = 0\n    this.#size = 0\n    if (this.#hasDisposeAfter && this.#disposed) {\n      const dt = this.#disposed\n      let task: DisposeTask | undefined\n      while ((task = dt?.shift())) {\n        this.#disposeAfter?.(...task)\n      }\n    }\n  }\n}\n","const proc =\n  typeof process === 'object' && process\n    ? process\n    : {\n        stdout: null,\n        stderr: null,\n      }\nimport { EventEmitter } from 'node:events'\nimport Stream from 'node:stream'\nimport { StringDecoder } from 'node:string_decoder'\n\n/**\n * Same as StringDecoder, but exposing the `lastNeed` flag on the type\n */\ntype SD = StringDecoder & { lastNeed: boolean }\n\nexport type { SD, Pipe, PipeProxyErrors }\n\n/**\n * Return true if the argument is a Minipass stream, Node stream, or something\n * else that Minipass can interact with.\n */\nexport const isStream = (\n  s: any\n): s is Minipass.Readable | Minipass.Writable =>\n  !!s &&\n  typeof s === 'object' &&\n  (s instanceof Minipass ||\n    s instanceof Stream ||\n    isReadable(s) ||\n    isWritable(s))\n\n/**\n * Return true if the argument is a valid {@link Minipass.Readable}\n */\nexport const isReadable = (s: any): s is Minipass.Readable =>\n  !!s &&\n  typeof s === 'object' &&\n  s instanceof EventEmitter &&\n  typeof (s as Minipass.Readable).pipe === 'function' &&\n  // node core Writable streams have a pipe() method, but it throws\n  (s as Minipass.Readable).pipe !== Stream.Writable.prototype.pipe\n\n/**\n * Return true if the argument is a valid {@link Minipass.Writable}\n */\nexport const isWritable = (s: any): s is Minipass.Readable =>\n  !!s &&\n  typeof s === 'object' &&\n  s instanceof EventEmitter &&\n  typeof (s as Minipass.Writable).write === 'function' &&\n  typeof (s as Minipass.Writable).end === 'function'\n\nconst EOF = Symbol('EOF')\nconst MAYBE_EMIT_END = Symbol('maybeEmitEnd')\nconst EMITTED_END = Symbol('emittedEnd')\nconst EMITTING_END = Symbol('emittingEnd')\nconst EMITTED_ERROR = Symbol('emittedError')\nconst CLOSED = Symbol('closed')\nconst READ = Symbol('read')\nconst FLUSH = Symbol('flush')\nconst FLUSHCHUNK = Symbol('flushChunk')\nconst ENCODING = Symbol('encoding')\nconst DECODER = Symbol('decoder')\nconst FLOWING = Symbol('flowing')\nconst PAUSED = Symbol('paused')\nconst RESUME = Symbol('resume')\nconst BUFFER = Symbol('buffer')\nconst PIPES = Symbol('pipes')\nconst BUFFERLENGTH = Symbol('bufferLength')\nconst BUFFERPUSH = Symbol('bufferPush')\nconst BUFFERSHIFT = Symbol('bufferShift')\nconst OBJECTMODE = Symbol('objectMode')\n// internal event when stream is destroyed\nconst DESTROYED = Symbol('destroyed')\n// internal event when stream has an error\nconst ERROR = Symbol('error')\nconst EMITDATA = Symbol('emitData')\nconst EMITEND = Symbol('emitEnd')\nconst EMITEND2 = Symbol('emitEnd2')\nconst ASYNC = Symbol('async')\nconst ABORT = Symbol('abort')\nconst ABORTED = Symbol('aborted')\nconst SIGNAL = Symbol('signal')\nconst DATALISTENERS = Symbol('dataListeners')\nconst DISCARDED = Symbol('discarded')\n\nconst defer = (fn: (...a: any[]) => any) => Promise.resolve().then(fn)\nconst nodefer = (fn: (...a: any[]) => any) => fn()\n\n// events that mean 'the stream is over'\n// these are treated specially, and re-emitted\n// if they are listened for after emitting.\ntype EndishEvent = 'end' | 'finish' | 'prefinish'\nconst isEndish = (ev: any): ev is EndishEvent =>\n  ev === 'end' || ev === 'finish' || ev === 'prefinish'\n\nconst isArrayBufferLike = (b: any): b is ArrayBufferLike =>\n  b instanceof ArrayBuffer ||\n  (!!b &&\n    typeof b === 'object' &&\n    b.constructor &&\n    b.constructor.name === 'ArrayBuffer' &&\n    b.byteLength >= 0)\n\nconst isArrayBufferView = (b: any): b is ArrayBufferView =>\n  !Buffer.isBuffer(b) && ArrayBuffer.isView(b)\n\n/**\n * Options that may be passed to stream.pipe()\n */\nexport interface PipeOptions {\n  /**\n   * end the destination stream when the source stream ends\n   */\n  end?: boolean\n  /**\n   * proxy errors from the source stream to the destination stream\n   */\n  proxyErrors?: boolean\n}\n\n/**\n * Internal class representing a pipe to a destination stream.\n *\n * @internal\n */\nclass Pipe {\n  src: Minipass\n  dest: Minipass\n  opts: PipeOptions\n  ondrain: () => any\n  constructor(\n    src: Minipass,\n    dest: Minipass.Writable,\n    opts: PipeOptions\n  ) {\n    this.src = src\n    this.dest = dest as Minipass\n    this.opts = opts\n    this.ondrain = () => src[RESUME]()\n    this.dest.on('drain', this.ondrain)\n  }\n  unpipe() {\n    this.dest.removeListener('drain', this.ondrain)\n  }\n  // only here for the prototype\n  /* c8 ignore start */\n  proxyErrors(_er: any) {}\n  /* c8 ignore stop */\n  end() {\n    this.unpipe()\n    if (this.opts.end) this.dest.end()\n  }\n}\n\n/**\n * Internal class representing a pipe to a destination stream where\n * errors are proxied.\n *\n * @internal\n */\nclass PipeProxyErrors extends Pipe {\n  unpipe() {\n    this.src.removeListener('error', this.proxyErrors)\n    super.unpipe()\n  }\n  constructor(\n    src: Minipass,\n    dest: Minipass.Writable,\n    opts: PipeOptions\n  ) {\n    super(src, dest, opts)\n    this.proxyErrors = (er: Error) => this.dest.emit('error', er)\n    src.on('error', this.proxyErrors)\n  }\n}\n\nexport namespace Minipass {\n  /**\n   * Encoding used to create a stream that outputs strings rather than\n   * Buffer objects.\n   */\n  export type Encoding = BufferEncoding | 'buffer' | null\n\n  /**\n   * Any stream that Minipass can pipe into\n   */\n  export type Writable =\n    | Minipass\n    | NodeJS.WriteStream\n    | (NodeJS.WriteStream & { fd: number })\n    | (EventEmitter & {\n        end(): any\n        write(chunk: any, ...args: any[]): any\n      })\n\n  /**\n   * Any stream that can be read from\n   */\n  export type Readable =\n    | Minipass\n    | NodeJS.ReadStream\n    | (NodeJS.ReadStream & { fd: number })\n    | (EventEmitter & {\n        pause(): any\n        resume(): any\n        pipe(...destArgs: any[]): any\n      })\n\n  /**\n   * Utility type that can be iterated sync or async\n   */\n  export type DualIterable = Iterable & AsyncIterable\n\n  type EventArguments = Record\n\n  /**\n   * The listing of events that a Minipass class can emit.\n   * Extend this when extending the Minipass class, and pass as\n   * the third template argument.  The key is the name of the event,\n   * and the value is the argument list.\n   *\n   * Any undeclared events will still be allowed, but the handler will get\n   * arguments as `unknown[]`.\n   */\n  export interface Events\n    extends EventArguments {\n    readable: []\n    data: [chunk: RType]\n    error: [er: unknown]\n    abort: [reason: unknown]\n    drain: []\n    resume: []\n    end: []\n    finish: []\n    prefinish: []\n    close: []\n    [DESTROYED]: [er?: unknown]\n    [ERROR]: [er: unknown]\n  }\n\n  /**\n   * String or buffer-like data that can be joined and sliced\n   */\n  export type ContiguousData =\n    | Buffer\n    | ArrayBufferLike\n    | ArrayBufferView\n    | string\n  export type BufferOrString = Buffer | string\n\n  /**\n   * Options passed to the Minipass constructor.\n   */\n  export type SharedOptions = {\n    /**\n     * Defer all data emission and other events until the end of the\n     * current tick, similar to Node core streams\n     */\n    async?: boolean\n    /**\n     * A signal which will abort the stream\n     */\n    signal?: AbortSignal\n    /**\n     * Output string encoding. Set to `null` or `'buffer'` (or omit) to\n     * emit Buffer objects rather than strings.\n     *\n     * Conflicts with `objectMode`\n     */\n    encoding?: BufferEncoding | null | 'buffer'\n    /**\n     * Output data exactly as it was written, supporting non-buffer/string\n     * data (such as arbitrary objects, falsey values, etc.)\n     *\n     * Conflicts with `encoding`\n     */\n    objectMode?: boolean\n  }\n\n  /**\n   * Options for a string encoded output\n   */\n  export type EncodingOptions = SharedOptions & {\n    encoding: BufferEncoding\n    objectMode?: false\n  }\n\n  /**\n   * Options for contiguous data buffer output\n   */\n  export type BufferOptions = SharedOptions & {\n    encoding?: null | 'buffer'\n    objectMode?: false\n  }\n\n  /**\n   * Options for objectMode arbitrary output\n   */\n  export type ObjectModeOptions = SharedOptions & {\n    objectMode: true\n    encoding?: null\n  }\n\n  /**\n   * Utility type to determine allowed options based on read type\n   */\n  export type Options =\n    | ObjectModeOptions\n    | (T extends string\n        ? EncodingOptions\n        : T extends Buffer\n        ? BufferOptions\n        : SharedOptions)\n}\n\nconst isObjectModeOptions = (\n  o: Minipass.SharedOptions\n): o is Minipass.ObjectModeOptions => !!o.objectMode\n\nconst isEncodingOptions = (\n  o: Minipass.SharedOptions\n): o is Minipass.EncodingOptions =>\n  !o.objectMode && !!o.encoding && o.encoding !== 'buffer'\n\n/**\n * Main export, the Minipass class\n *\n * `RType` is the type of data emitted, defaults to Buffer\n *\n * `WType` is the type of data to be written, if RType is buffer or string,\n * then any {@link Minipass.ContiguousData} is allowed.\n *\n * `Events` is the set of event handler signatures that this object\n * will emit, see {@link Minipass.Events}\n */\nexport class Minipass<\n    RType extends unknown = Buffer,\n    WType extends unknown = RType extends Minipass.BufferOrString\n      ? Minipass.ContiguousData\n      : RType,\n    Events extends Minipass.Events = Minipass.Events\n  >\n  extends EventEmitter\n  implements Minipass.DualIterable\n{\n  [FLOWING]: boolean = false;\n  [PAUSED]: boolean = false;\n  [PIPES]: Pipe[] = [];\n  [BUFFER]: RType[] = [];\n  [OBJECTMODE]: boolean;\n  [ENCODING]: BufferEncoding | null;\n  [ASYNC]: boolean;\n  [DECODER]: SD | null;\n  [EOF]: boolean = false;\n  [EMITTED_END]: boolean = false;\n  [EMITTING_END]: boolean = false;\n  [CLOSED]: boolean = false;\n  [EMITTED_ERROR]: unknown = null;\n  [BUFFERLENGTH]: number = 0;\n  [DESTROYED]: boolean = false;\n  [SIGNAL]?: AbortSignal;\n  [ABORTED]: boolean = false;\n  [DATALISTENERS]: number = 0;\n  [DISCARDED]: boolean = false\n\n  /**\n   * true if the stream can be written\n   */\n  writable: boolean = true\n  /**\n   * true if the stream can be read\n   */\n  readable: boolean = true\n\n  /**\n   * If `RType` is Buffer, then options do not need to be provided.\n   * Otherwise, an options object must be provided to specify either\n   * {@link Minipass.SharedOptions.objectMode} or\n   * {@link Minipass.SharedOptions.encoding}, as appropriate.\n   */\n  constructor(\n    ...args:\n      | [Minipass.ObjectModeOptions]\n      | (RType extends Buffer\n          ? [] | [Minipass.Options]\n          : [Minipass.Options])\n  ) {\n    const options: Minipass.Options = (args[0] ||\n      {}) as Minipass.Options\n    super()\n    if (options.objectMode && typeof options.encoding === 'string') {\n      throw new TypeError(\n        'Encoding and objectMode may not be used together'\n      )\n    }\n    if (isObjectModeOptions(options)) {\n      this[OBJECTMODE] = true\n      this[ENCODING] = null\n    } else if (isEncodingOptions(options)) {\n      this[ENCODING] = options.encoding\n      this[OBJECTMODE] = false\n    } else {\n      this[OBJECTMODE] = false\n      this[ENCODING] = null\n    }\n    this[ASYNC] = !!options.async\n    this[DECODER] = this[ENCODING]\n      ? (new StringDecoder(this[ENCODING]) as SD)\n      : null\n\n    //@ts-ignore - private option for debugging and testing\n    if (options && options.debugExposeBuffer === true) {\n      Object.defineProperty(this, 'buffer', { get: () => this[BUFFER] })\n    }\n    //@ts-ignore - private option for debugging and testing\n    if (options && options.debugExposePipes === true) {\n      Object.defineProperty(this, 'pipes', { get: () => this[PIPES] })\n    }\n\n    const { signal } = options\n    if (signal) {\n      this[SIGNAL] = signal\n      if (signal.aborted) {\n        this[ABORT]()\n      } else {\n        signal.addEventListener('abort', () => this[ABORT]())\n      }\n    }\n  }\n\n  /**\n   * The amount of data stored in the buffer waiting to be read.\n   *\n   * For Buffer strings, this will be the total byte length.\n   * For string encoding streams, this will be the string character length,\n   * according to JavaScript's `string.length` logic.\n   * For objectMode streams, this is a count of the items waiting to be\n   * emitted.\n   */\n  get bufferLength() {\n    return this[BUFFERLENGTH]\n  }\n\n  /**\n   * The `BufferEncoding` currently in use, or `null`\n   */\n  get encoding() {\n    return this[ENCODING]\n  }\n\n  /**\n   * @deprecated - This is a read only property\n   */\n  set encoding(_enc) {\n    throw new Error('Encoding must be set at instantiation time')\n  }\n\n  /**\n   * @deprecated - Encoding may only be set at instantiation time\n   */\n  setEncoding(_enc: Minipass.Encoding) {\n    throw new Error('Encoding must be set at instantiation time')\n  }\n\n  /**\n   * True if this is an objectMode stream\n   */\n  get objectMode() {\n    return this[OBJECTMODE]\n  }\n\n  /**\n   * @deprecated - This is a read-only property\n   */\n  set objectMode(_om) {\n    throw new Error('objectMode must be set at instantiation time')\n  }\n\n  /**\n   * true if this is an async stream\n   */\n  get ['async'](): boolean {\n    return this[ASYNC]\n  }\n  /**\n   * Set to true to make this stream async.\n   *\n   * Once set, it cannot be unset, as this would potentially cause incorrect\n   * behavior.  Ie, a sync stream can be made async, but an async stream\n   * cannot be safely made sync.\n   */\n  set ['async'](a: boolean) {\n    this[ASYNC] = this[ASYNC] || !!a\n  }\n\n  // drop everything and get out of the flow completely\n  [ABORT]() {\n    this[ABORTED] = true\n    this.emit('abort', this[SIGNAL]?.reason)\n    this.destroy(this[SIGNAL]?.reason)\n  }\n\n  /**\n   * True if the stream has been aborted.\n   */\n  get aborted() {\n    return this[ABORTED]\n  }\n  /**\n   * No-op setter. Stream aborted status is set via the AbortSignal provided\n   * in the constructor options.\n   */\n  set aborted(_) {}\n\n  /**\n   * Write data into the stream\n   *\n   * If the chunk written is a string, and encoding is not specified, then\n   * `utf8` will be assumed. If the stream encoding matches the encoding of\n   * a written string, and the state of the string decoder allows it, then\n   * the string will be passed through to either the output or the internal\n   * buffer without any processing. Otherwise, it will be turned into a\n   * Buffer object for processing into the desired encoding.\n   *\n   * If provided, `cb` function is called immediately before return for\n   * sync streams, or on next tick for async streams, because for this\n   * base class, a chunk is considered \"processed\" once it is accepted\n   * and either emitted or buffered. That is, the callback does not indicate\n   * that the chunk has been eventually emitted, though of course child\n   * classes can override this function to do whatever processing is required\n   * and call `super.write(...)` only once processing is completed.\n   */\n  write(chunk: WType, cb?: () => void): boolean\n  write(\n    chunk: WType,\n    encoding?: Minipass.Encoding,\n    cb?: () => void\n  ): boolean\n  write(\n    chunk: WType,\n    encoding?: Minipass.Encoding | (() => void),\n    cb?: () => void\n  ): boolean {\n    if (this[ABORTED]) return false\n    if (this[EOF]) throw new Error('write after end')\n\n    if (this[DESTROYED]) {\n      this.emit(\n        'error',\n        Object.assign(\n          new Error('Cannot call write after a stream was destroyed'),\n          { code: 'ERR_STREAM_DESTROYED' }\n        )\n      )\n      return true\n    }\n\n    if (typeof encoding === 'function') {\n      cb = encoding\n      encoding = 'utf8'\n    }\n\n    if (!encoding) encoding = 'utf8'\n\n    const fn = this[ASYNC] ? defer : nodefer\n\n    // convert array buffers and typed array views into buffers\n    // at some point in the future, we may want to do the opposite!\n    // leave strings and buffers as-is\n    // anything is only allowed if in object mode, so throw\n    if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {\n      if (isArrayBufferView(chunk)) {\n        //@ts-ignore - sinful unsafe type changing\n        chunk = Buffer.from(\n          chunk.buffer,\n          chunk.byteOffset,\n          chunk.byteLength\n        )\n      } else if (isArrayBufferLike(chunk)) {\n        //@ts-ignore - sinful unsafe type changing\n        chunk = Buffer.from(chunk)\n      } else if (typeof chunk !== 'string') {\n        throw new Error(\n          'Non-contiguous data written to non-objectMode stream'\n        )\n      }\n    }\n\n    // handle object mode up front, since it's simpler\n    // this yields better performance, fewer checks later.\n    if (this[OBJECTMODE]) {\n      // maybe impossible?\n      /* c8 ignore start */\n      if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n      /* c8 ignore stop */\n\n      if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n      else this[BUFFERPUSH](chunk as unknown as RType)\n\n      if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n      if (cb) fn(cb)\n\n      return this[FLOWING]\n    }\n\n    // at this point the chunk is a buffer or string\n    // don't buffer it up or send it to the decoder\n    if (!(chunk as Minipass.BufferOrString).length) {\n      if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n      if (cb) fn(cb)\n      return this[FLOWING]\n    }\n\n    // fast-path writing strings of same encoding to a stream with\n    // an empty buffer, skipping the buffer/decoder dance\n    if (\n      typeof chunk === 'string' &&\n      // unless it is a string already ready for us to use\n      !(encoding === this[ENCODING] && !this[DECODER]?.lastNeed)\n    ) {\n      //@ts-ignore - sinful unsafe type change\n      chunk = Buffer.from(chunk, encoding)\n    }\n\n    if (Buffer.isBuffer(chunk) && this[ENCODING]) {\n      //@ts-ignore - sinful unsafe type change\n      chunk = this[DECODER].write(chunk)\n    }\n\n    // Note: flushing CAN potentially switch us into not-flowing mode\n    if (this[FLOWING] && this[BUFFERLENGTH] !== 0) this[FLUSH](true)\n\n    if (this[FLOWING]) this.emit('data', chunk as unknown as RType)\n    else this[BUFFERPUSH](chunk as unknown as RType)\n\n    if (this[BUFFERLENGTH] !== 0) this.emit('readable')\n\n    if (cb) fn(cb)\n\n    return this[FLOWING]\n  }\n\n  /**\n   * Low-level explicit read method.\n   *\n   * In objectMode, the argument is ignored, and one item is returned if\n   * available.\n   *\n   * `n` is the number of bytes (or in the case of encoding streams,\n   * characters) to consume. If `n` is not provided, then the entire buffer\n   * is returned, or `null` is returned if no data is available.\n   *\n   * If `n` is greater that the amount of data in the internal buffer,\n   * then `null` is returned.\n   */\n  read(n?: number | null): RType | null {\n    if (this[DESTROYED]) return null\n    this[DISCARDED] = false\n\n    if (\n      this[BUFFERLENGTH] === 0 ||\n      n === 0 ||\n      (n && n > this[BUFFERLENGTH])\n    ) {\n      this[MAYBE_EMIT_END]()\n      return null\n    }\n\n    if (this[OBJECTMODE]) n = null\n\n    if (this[BUFFER].length > 1 && !this[OBJECTMODE]) {\n      // not object mode, so if we have an encoding, then RType is string\n      // otherwise, must be Buffer\n      this[BUFFER] = [\n        (this[ENCODING]\n          ? this[BUFFER].join('')\n          : Buffer.concat(\n              this[BUFFER] as Buffer[],\n              this[BUFFERLENGTH]\n            )) as RType,\n      ]\n    }\n\n    const ret = this[READ](n || null, this[BUFFER][0] as RType)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [READ](n: number | null, chunk: RType) {\n    if (this[OBJECTMODE]) this[BUFFERSHIFT]()\n    else {\n      const c = chunk as Minipass.BufferOrString\n      if (n === c.length || n === null) this[BUFFERSHIFT]()\n      else if (typeof c === 'string') {\n        this[BUFFER][0] = c.slice(n) as RType\n        chunk = c.slice(0, n) as RType\n        this[BUFFERLENGTH] -= n\n      } else {\n        this[BUFFER][0] = c.subarray(n) as RType\n        chunk = c.subarray(0, n) as RType\n        this[BUFFERLENGTH] -= n\n      }\n    }\n\n    this.emit('data', chunk)\n\n    if (!this[BUFFER].length && !this[EOF]) this.emit('drain')\n\n    return chunk\n  }\n\n  /**\n   * End the stream, optionally providing a final write.\n   *\n   * See {@link Minipass#write} for argument descriptions\n   */\n  end(cb?: () => void): this\n  end(chunk: WType, cb?: () => void): this\n  end(chunk: WType, encoding?: Minipass.Encoding, cb?: () => void): this\n  end(\n    chunk?: WType | (() => void),\n    encoding?: Minipass.Encoding | (() => void),\n    cb?: () => void\n  ): this {\n    if (typeof chunk === 'function') {\n      cb = chunk as () => void\n      chunk = undefined\n    }\n    if (typeof encoding === 'function') {\n      cb = encoding\n      encoding = 'utf8'\n    }\n    if (chunk !== undefined) this.write(chunk, encoding)\n    if (cb) this.once('end', cb)\n    this[EOF] = true\n    this.writable = false\n\n    // if we haven't written anything, then go ahead and emit,\n    // even if we're not reading.\n    // we'll re-emit if a new 'end' listener is added anyway.\n    // This makes MP more suitable to write-only use cases.\n    if (this[FLOWING] || !this[PAUSED]) this[MAYBE_EMIT_END]()\n    return this\n  }\n\n  // don't let the internal resume be overwritten\n  [RESUME]() {\n    if (this[DESTROYED]) return\n\n    if (!this[DATALISTENERS] && !this[PIPES].length) {\n      this[DISCARDED] = true\n    }\n    this[PAUSED] = false\n    this[FLOWING] = true\n    this.emit('resume')\n    if (this[BUFFER].length) this[FLUSH]()\n    else if (this[EOF]) this[MAYBE_EMIT_END]()\n    else this.emit('drain')\n  }\n\n  /**\n   * Resume the stream if it is currently in a paused state\n   *\n   * If called when there are no pipe destinations or `data` event listeners,\n   * this will place the stream in a \"discarded\" state, where all data will\n   * be thrown away. The discarded state is removed if a pipe destination or\n   * data handler is added, if pause() is called, or if any synchronous or\n   * asynchronous iteration is started.\n   */\n  resume() {\n    return this[RESUME]()\n  }\n\n  /**\n   * Pause the stream\n   */\n  pause() {\n    this[FLOWING] = false\n    this[PAUSED] = true\n    this[DISCARDED] = false\n  }\n\n  /**\n   * true if the stream has been forcibly destroyed\n   */\n  get destroyed() {\n    return this[DESTROYED]\n  }\n\n  /**\n   * true if the stream is currently in a flowing state, meaning that\n   * any writes will be immediately emitted.\n   */\n  get flowing() {\n    return this[FLOWING]\n  }\n\n  /**\n   * true if the stream is currently in a paused state\n   */\n  get paused() {\n    return this[PAUSED]\n  }\n\n  [BUFFERPUSH](chunk: RType) {\n    if (this[OBJECTMODE]) this[BUFFERLENGTH] += 1\n    else this[BUFFERLENGTH] += (chunk as Minipass.BufferOrString).length\n    this[BUFFER].push(chunk)\n  }\n\n  [BUFFERSHIFT](): RType {\n    if (this[OBJECTMODE]) this[BUFFERLENGTH] -= 1\n    else\n      this[BUFFERLENGTH] -= (\n        this[BUFFER][0] as Minipass.BufferOrString\n      ).length\n    return this[BUFFER].shift() as RType\n  }\n\n  [FLUSH](noDrain: boolean = false) {\n    do {} while (\n      this[FLUSHCHUNK](this[BUFFERSHIFT]()) &&\n      this[BUFFER].length\n    )\n\n    if (!noDrain && !this[BUFFER].length && !this[EOF]) this.emit('drain')\n  }\n\n  [FLUSHCHUNK](chunk: RType) {\n    this.emit('data', chunk)\n    return this[FLOWING]\n  }\n\n  /**\n   * Pipe all data emitted by this stream into the destination provided.\n   *\n   * Triggers the flow of data.\n   */\n  pipe(dest: W, opts?: PipeOptions): W {\n    if (this[DESTROYED]) return dest\n    this[DISCARDED] = false\n\n    const ended = this[EMITTED_END]\n    opts = opts || {}\n    if (dest === proc.stdout || dest === proc.stderr) opts.end = false\n    else opts.end = opts.end !== false\n    opts.proxyErrors = !!opts.proxyErrors\n\n    // piping an ended stream ends immediately\n    if (ended) {\n      if (opts.end) dest.end()\n    } else {\n      // \"as\" here just ignores the WType, which pipes don't care about,\n      // since they're only consuming from us, and writing to the dest\n      this[PIPES].push(\n        !opts.proxyErrors\n          ? new Pipe(this as Minipass, dest, opts)\n          : new PipeProxyErrors(this as Minipass, dest, opts)\n      )\n      if (this[ASYNC]) defer(() => this[RESUME]())\n      else this[RESUME]()\n    }\n\n    return dest\n  }\n\n  /**\n   * Fully unhook a piped destination stream.\n   *\n   * If the destination stream was the only consumer of this stream (ie,\n   * there are no other piped destinations or `'data'` event listeners)\n   * then the flow of data will stop until there is another consumer or\n   * {@link Minipass#resume} is explicitly called.\n   */\n  unpipe(dest: W) {\n    const p = this[PIPES].find(p => p.dest === dest)\n    if (p) {\n      if (this[PIPES].length === 1) {\n        if (this[FLOWING] && this[DATALISTENERS] === 0) {\n          this[FLOWING] = false\n        }\n        this[PIPES] = []\n      } else this[PIPES].splice(this[PIPES].indexOf(p), 1)\n      p.unpipe()\n    }\n  }\n\n  /**\n   * Alias for {@link Minipass#on}\n   */\n  addListener(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ): this {\n    return this.on(ev, handler)\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.on`, with the following\n   * behavior differences to prevent data loss and unnecessary hangs:\n   *\n   * - Adding a 'data' event handler will trigger the flow of data\n   *\n   * - Adding a 'readable' event handler when there is data waiting to be read\n   *   will cause 'readable' to be emitted immediately.\n   *\n   * - Adding an 'endish' event handler ('end', 'finish', etc.) which has\n   *   already passed will cause the event to be emitted immediately and all\n   *   handlers removed.\n   *\n   * - Adding an 'error' event handler after an error has been emitted will\n   *   cause the event to be re-emitted immediately with the error previously\n   *   raised.\n   */\n  on(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ): this {\n    const ret = super.on(\n      ev as string | symbol,\n      handler as (...a: any[]) => any\n    )\n    if (ev === 'data') {\n      this[DISCARDED] = false\n      this[DATALISTENERS]++\n      if (!this[PIPES].length && !this[FLOWING]) {\n        this[RESUME]()\n      }\n    } else if (ev === 'readable' && this[BUFFERLENGTH] !== 0) {\n      super.emit('readable')\n    } else if (isEndish(ev) && this[EMITTED_END]) {\n      super.emit(ev)\n      this.removeAllListeners(ev)\n    } else if (ev === 'error' && this[EMITTED_ERROR]) {\n      const h = handler as (...a: Events['error']) => any\n      if (this[ASYNC]) defer(() => h.call(this, this[EMITTED_ERROR]))\n      else h.call(this, this[EMITTED_ERROR])\n    }\n    return ret\n  }\n\n  /**\n   * Alias for {@link Minipass#off}\n   */\n  removeListener(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ) {\n    return this.off(ev, handler)\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.off`\n   *\n   * If a 'data' event handler is removed, and it was the last consumer\n   * (ie, there are no pipe destinations or other 'data' event listeners),\n   * then the flow of data will stop until there is another consumer or\n   * {@link Minipass#resume} is explicitly called.\n   */\n  off(\n    ev: Event,\n    handler: (...args: Events[Event]) => any\n  ) {\n    const ret = super.off(\n      ev as string | symbol,\n      handler as (...a: any[]) => any\n    )\n    // if we previously had listeners, and now we don't, and we don't\n    // have any pipes, then stop the flow, unless it's been explicitly\n    // put in a discarded flowing state via stream.resume().\n    if (ev === 'data') {\n      this[DATALISTENERS] = this.listeners('data').length\n      if (\n        this[DATALISTENERS] === 0 &&\n        !this[DISCARDED] &&\n        !this[PIPES].length\n      ) {\n        this[FLOWING] = false\n      }\n    }\n    return ret\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.removeAllListeners`\n   *\n   * If all 'data' event handlers are removed, and they were the last consumer\n   * (ie, there are no pipe destinations), then the flow of data will stop\n   * until there is another consumer or {@link Minipass#resume} is explicitly\n   * called.\n   */\n  removeAllListeners(ev?: Event) {\n    const ret = super.removeAllListeners(ev as string | symbol | undefined)\n    if (ev === 'data' || ev === undefined) {\n      this[DATALISTENERS] = 0\n      if (!this[DISCARDED] && !this[PIPES].length) {\n        this[FLOWING] = false\n      }\n    }\n    return ret\n  }\n\n  /**\n   * true if the 'end' event has been emitted\n   */\n  get emittedEnd() {\n    return this[EMITTED_END]\n  }\n\n  [MAYBE_EMIT_END]() {\n    if (\n      !this[EMITTING_END] &&\n      !this[EMITTED_END] &&\n      !this[DESTROYED] &&\n      this[BUFFER].length === 0 &&\n      this[EOF]\n    ) {\n      this[EMITTING_END] = true\n      this.emit('end')\n      this.emit('prefinish')\n      this.emit('finish')\n      if (this[CLOSED]) this.emit('close')\n      this[EMITTING_END] = false\n    }\n  }\n\n  /**\n   * Mostly identical to `EventEmitter.emit`, with the following\n   * behavior differences to prevent data loss and unnecessary hangs:\n   *\n   * If the stream has been destroyed, and the event is something other\n   * than 'close' or 'error', then `false` is returned and no handlers\n   * are called.\n   *\n   * If the event is 'end', and has already been emitted, then the event\n   * is ignored. If the stream is in a paused or non-flowing state, then\n   * the event will be deferred until data flow resumes. If the stream is\n   * async, then handlers will be called on the next tick rather than\n   * immediately.\n   *\n   * If the event is 'close', and 'end' has not yet been emitted, then\n   * the event will be deferred until after 'end' is emitted.\n   *\n   * If the event is 'error', and an AbortSignal was provided for the stream,\n   * and there are no listeners, then the event is ignored, matching the\n   * behavior of node core streams in the presense of an AbortSignal.\n   *\n   * If the event is 'finish' or 'prefinish', then all listeners will be\n   * removed after emitting the event, to prevent double-firing.\n   */\n  emit(\n    ev: Event,\n    ...args: Events[Event]\n  ): boolean {\n    const data = args[0]\n    // error and close are only events allowed after calling destroy()\n    if (\n      ev !== 'error' &&\n      ev !== 'close' &&\n      ev !== DESTROYED &&\n      this[DESTROYED]\n    ) {\n      return false\n    } else if (ev === 'data') {\n      return !this[OBJECTMODE] && !data\n        ? false\n        : this[ASYNC]\n        ? (defer(() => this[EMITDATA](data as RType)), true)\n        : this[EMITDATA](data as RType)\n    } else if (ev === 'end') {\n      return this[EMITEND]()\n    } else if (ev === 'close') {\n      this[CLOSED] = true\n      // don't emit close before 'end' and 'finish'\n      if (!this[EMITTED_END] && !this[DESTROYED]) return false\n      const ret = super.emit('close')\n      this.removeAllListeners('close')\n      return ret\n    } else if (ev === 'error') {\n      this[EMITTED_ERROR] = data\n      super.emit(ERROR, data)\n      const ret =\n        !this[SIGNAL] || this.listeners('error').length\n          ? super.emit('error', data)\n          : false\n      this[MAYBE_EMIT_END]()\n      return ret\n    } else if (ev === 'resume') {\n      const ret = super.emit('resume')\n      this[MAYBE_EMIT_END]()\n      return ret\n    } else if (ev === 'finish' || ev === 'prefinish') {\n      const ret = super.emit(ev)\n      this.removeAllListeners(ev)\n      return ret\n    }\n\n    // Some other unknown event\n    const ret = super.emit(ev as string, ...args)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [EMITDATA](data: RType) {\n    for (const p of this[PIPES]) {\n      if (p.dest.write(data as RType) === false) this.pause()\n    }\n    const ret = this[DISCARDED] ? false : super.emit('data', data)\n    this[MAYBE_EMIT_END]()\n    return ret\n  }\n\n  [EMITEND]() {\n    if (this[EMITTED_END]) return false\n\n    this[EMITTED_END] = true\n    this.readable = false\n    return this[ASYNC]\n      ? (defer(() => this[EMITEND2]()), true)\n      : this[EMITEND2]()\n  }\n\n  [EMITEND2]() {\n    if (this[DECODER]) {\n      const data = this[DECODER].end()\n      if (data) {\n        for (const p of this[PIPES]) {\n          p.dest.write(data as RType)\n        }\n        if (!this[DISCARDED]) super.emit('data', data)\n      }\n    }\n\n    for (const p of this[PIPES]) {\n      p.end()\n    }\n    const ret = super.emit('end')\n    this.removeAllListeners('end')\n    return ret\n  }\n\n  /**\n   * Return a Promise that resolves to an array of all emitted data once\n   * the stream ends.\n   */\n  async collect(): Promise {\n    const buf: RType[] & { dataLength: number } = Object.assign([], {\n      dataLength: 0,\n    })\n    if (!this[OBJECTMODE]) buf.dataLength = 0\n    // set the promise first, in case an error is raised\n    // by triggering the flow here.\n    const p = this.promise()\n    this.on('data', c => {\n      buf.push(c)\n      if (!this[OBJECTMODE])\n        buf.dataLength += (c as Minipass.BufferOrString).length\n    })\n    await p\n    return buf\n  }\n\n  /**\n   * Return a Promise that resolves to the concatenation of all emitted data\n   * once the stream ends.\n   *\n   * Not allowed on objectMode streams.\n   */\n  async concat(): Promise {\n    if (this[OBJECTMODE]) {\n      throw new Error('cannot concat in objectMode')\n    }\n    const buf = await this.collect()\n    return (\n      this[ENCODING]\n        ? buf.join('')\n        : Buffer.concat(buf as Buffer[], buf.dataLength)\n    ) as RType\n  }\n\n  /**\n   * Return a void Promise that resolves once the stream ends.\n   */\n  async promise(): Promise {\n    return new Promise((resolve, reject) => {\n      this.on(DESTROYED, () => reject(new Error('stream destroyed')))\n      this.on('error', er => reject(er))\n      this.on('end', () => resolve())\n    })\n  }\n\n  /**\n   * Asynchronous `for await of` iteration.\n   *\n   * This will continue emitting all chunks until the stream terminates.\n   */\n  [Symbol.asyncIterator](): AsyncGenerator {\n    // set this up front, in case the consumer doesn't call next()\n    // right away.\n    this[DISCARDED] = false\n    let stopped = false\n    const stop = async (): Promise> => {\n      this.pause()\n      stopped = true\n      return { value: undefined, done: true }\n    }\n    const next = (): Promise> => {\n      if (stopped) return stop()\n      const res = this.read()\n      if (res !== null) return Promise.resolve({ done: false, value: res })\n\n      if (this[EOF]) return stop()\n\n      let resolve!: (res: IteratorResult) => void\n      let reject!: (er: unknown) => void\n      const onerr = (er: unknown) => {\n        this.off('data', ondata)\n        this.off('end', onend)\n        this.off(DESTROYED, ondestroy)\n        stop()\n        reject(er)\n      }\n      const ondata = (value: RType) => {\n        this.off('error', onerr)\n        this.off('end', onend)\n        this.off(DESTROYED, ondestroy)\n        this.pause()\n        resolve({ value, done: !!this[EOF] })\n      }\n      const onend = () => {\n        this.off('error', onerr)\n        this.off('data', ondata)\n        this.off(DESTROYED, ondestroy)\n        stop()\n        resolve({ done: true, value: undefined })\n      }\n      const ondestroy = () => onerr(new Error('stream destroyed'))\n      return new Promise>((res, rej) => {\n        reject = rej\n        resolve = res\n        this.once(DESTROYED, ondestroy)\n        this.once('error', onerr)\n        this.once('end', onend)\n        this.once('data', ondata)\n      })\n    }\n\n    return {\n      next,\n      throw: stop,\n      return: stop,\n      [Symbol.asyncIterator]() {\n        return this\n      },\n      [Symbol.asyncDispose]: async () => {},\n    }\n  }\n\n  /**\n   * Synchronous `for of` iteration.\n   *\n   * The iteration will terminate when the internal buffer runs out, even\n   * if the stream has not yet terminated.\n   */\n  [Symbol.iterator](): Generator {\n    // set this up front, in case the consumer doesn't call next()\n    // right away.\n    this[DISCARDED] = false\n    let stopped = false\n    const stop = (): IteratorReturnResult => {\n      this.pause()\n      this.off(ERROR, stop)\n      this.off(DESTROYED, stop)\n      this.off('end', stop)\n      stopped = true\n      return { done: true, value: undefined }\n    }\n\n    const next = (): IteratorResult => {\n      if (stopped) return stop()\n      const value = this.read()\n      return value === null ? stop() : { done: false, value }\n    }\n\n    this.once('end', stop)\n    this.once(ERROR, stop)\n    this.once(DESTROYED, stop)\n\n    return {\n      next,\n      throw: stop,\n      return: stop,\n      [Symbol.iterator]() {\n        return this\n      },\n      [Symbol.dispose]: () => {},\n    }\n  }\n\n  /**\n   * Destroy a stream, preventing it from being used for any further purpose.\n   *\n   * If the stream has a `close()` method, then it will be called on\n   * destruction.\n   *\n   * After destruction, any attempt to write data, read data, or emit most\n   * events will be ignored.\n   *\n   * If an error argument is provided, then it will be emitted in an\n   * 'error' event.\n   */\n  destroy(er?: unknown) {\n    if (this[DESTROYED]) {\n      if (er) this.emit('error', er)\n      else this.emit(DESTROYED)\n      return this\n    }\n\n    this[DESTROYED] = true\n    this[DISCARDED] = true\n\n    // throw away all buffered data, it's never coming out\n    this[BUFFER].length = 0\n    this[BUFFERLENGTH] = 0\n\n    const wc = this as Minipass & {\n      close?: () => void\n    }\n    if (typeof wc.close === 'function' && !this[CLOSED]) wc.close()\n\n    if (er) this.emit('error', er)\n    // if no error to emit, still reject pending promises\n    else this.emit(DESTROYED)\n\n    return this\n  }\n\n  /**\n   * Alias for {@link isStream}\n   *\n   * Former export location, maintained for backwards compatibility.\n   *\n   * @deprecated\n   */\n  static get isStream() {\n    return isStream\n  }\n}\n","import { LRUCache } from 'lru-cache'\nimport { posix, win32 } from 'node:path'\n\nimport { fileURLToPath } from 'node:url'\n\nimport {\n  lstatSync,\n  readdir as readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync as rps,\n} from 'fs'\nimport * as actualFS from 'node:fs'\n\nconst realpathSync = rps.native\n// TODO: test perf of fs/promises realpath vs realpathCB,\n// since the promises one uses realpath.native\n\nimport { lstat, readdir, readlink, realpath } from 'node:fs/promises'\n\nimport { Minipass } from 'minipass'\nimport type { Dirent, Stats } from 'node:fs'\n\n/**\n * An object that will be used to override the default `fs`\n * methods.  Any methods that are not overridden will use Node's\n * built-in implementations.\n *\n * - lstatSync\n * - readdir (callback `withFileTypes` Dirent variant, used for\n *   readdirCB and most walks)\n * - readdirSync\n * - readlinkSync\n * - realpathSync\n * - promises: Object containing the following async methods:\n *   - lstat\n *   - readdir (Dirent variant only)\n *   - readlink\n *   - realpath\n */\nexport interface FSOption {\n  lstatSync?: (path: string) => Stats\n  readdir?: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n  ) => void\n  readdirSync?: (\n    path: string,\n    options: { withFileTypes: true },\n  ) => Dirent[]\n  readlinkSync?: (path: string) => string\n  realpathSync?: (path: string) => string\n  promises?: {\n    lstat?: (path: string) => Promise\n    readdir?: (\n      path: string,\n      options: { withFileTypes: true },\n    ) => Promise\n    readlink?: (path: string) => Promise\n    realpath?: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\ninterface FSValue {\n  lstatSync: (path: string) => Stats\n  readdir: (\n    path: string,\n    options: { withFileTypes: true },\n    cb: (er: NodeJS.ErrnoException | null, entries?: Dirent[]) => any,\n  ) => void\n  readdirSync: (path: string, options: { withFileTypes: true }) => Dirent[]\n  readlinkSync: (path: string) => string\n  realpathSync: (path: string) => string\n  promises: {\n    lstat: (path: string) => Promise\n    readdir: (\n      path: string,\n      options: { withFileTypes: true },\n    ) => Promise\n    readlink: (path: string) => Promise\n    realpath: (path: string) => Promise\n    [k: string]: any\n  }\n  [k: string]: any\n}\n\nconst defaultFS: FSValue = {\n  lstatSync,\n  readdir: readdirCB,\n  readdirSync,\n  readlinkSync,\n  realpathSync,\n  promises: {\n    lstat,\n    readdir,\n    readlink,\n    realpath,\n  },\n}\n\n// if they just gave us require('fs') then use our default\nconst fsFromOption = (fsOption?: FSOption): FSValue =>\n  !fsOption || fsOption === defaultFS || fsOption === actualFS ?\n    defaultFS\n  : {\n      ...defaultFS,\n      ...fsOption,\n      promises: {\n        ...defaultFS.promises,\n        ...(fsOption.promises || {}),\n      },\n    }\n\n// turn something like //?/c:/ into c:\\\nconst uncDriveRegexp = /^\\\\\\\\\\?\\\\([a-z]:)\\\\?$/i\nconst uncToDrive = (rootPath: string): string =>\n  rootPath.replace(/\\//g, '\\\\').replace(uncDriveRegexp, '$1\\\\')\n\n// windows paths are separated by either / or \\\nconst eitherSep = /[\\\\\\/]/\n\nconst UNKNOWN = 0 // may not even exist, for all we know\nconst IFIFO = 0b0001\nconst IFCHR = 0b0010\nconst IFDIR = 0b0100\nconst IFBLK = 0b0110\nconst IFREG = 0b1000\nconst IFLNK = 0b1010\nconst IFSOCK = 0b1100\nconst IFMT = 0b1111\n\nexport type Type =\n  | 'Unknown'\n  | 'FIFO'\n  | 'CharacterDevice'\n  | 'Directory'\n  | 'BlockDevice'\n  | 'File'\n  | 'SymbolicLink'\n  | 'Socket'\n\n// mask to unset low 4 bits\nconst IFMT_UNKNOWN = ~IFMT\n\n// set after successfully calling readdir() and getting entries.\nconst READDIR_CALLED = 0b0000_0001_0000\n// set after a successful lstat()\nconst LSTAT_CALLED = 0b0000_0010_0000\n// set if an entry (or one of its parents) is definitely not a dir\nconst ENOTDIR = 0b0000_0100_0000\n// set if an entry (or one of its parents) does not exist\n// (can also be set on lstat errors like EACCES or ENAMETOOLONG)\nconst ENOENT = 0b0000_1000_0000\n// cannot have child entries -- also verify &IFMT is either IFDIR or IFLNK\n// set if we fail to readlink\nconst ENOREADLINK = 0b0001_0000_0000\n// set if we know realpath() will fail\nconst ENOREALPATH = 0b0010_0000_0000\n\nconst ENOCHILD = ENOTDIR | ENOENT | ENOREALPATH\nconst TYPEMASK = 0b0011_1111_1111\n\nconst entToType = (s: Dirent | Stats) =>\n  s.isFile() ? IFREG\n  : s.isDirectory() ? IFDIR\n  : s.isSymbolicLink() ? IFLNK\n  : s.isCharacterDevice() ? IFCHR\n  : s.isBlockDevice() ? IFBLK\n  : s.isSocket() ? IFSOCK\n  : s.isFIFO() ? IFIFO\n  : UNKNOWN\n\n// normalize unicode path names\nconst normalizeCache = new Map()\nconst normalize = (s: string) => {\n  const c = normalizeCache.get(s)\n  if (c) return c\n  const n = s.normalize('NFKD')\n  normalizeCache.set(s, n)\n  return n\n}\n\nconst normalizeNocaseCache = new Map()\nconst normalizeNocase = (s: string) => {\n  const c = normalizeNocaseCache.get(s)\n  if (c) return c\n  const n = normalize(s.toLowerCase())\n  normalizeNocaseCache.set(s, n)\n  return n\n}\n\n/**\n * Options that may be provided to the Path constructor\n */\nexport interface PathOpts {\n  fullpath?: string\n  relative?: string\n  relativePosix?: string\n  parent?: PathBase\n  /**\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * An LRUCache for storing resolved path strings or Path objects.\n * @internal\n */\nexport class ResolveCache extends LRUCache {\n  constructor() {\n    super({ max: 256 })\n  }\n}\n\n// In order to prevent blowing out the js heap by allocating hundreds of\n// thousands of Path entries when walking extremely large trees, the \"children\"\n// in this tree are represented by storing an array of Path entries in an\n// LRUCache, indexed by the parent.  At any time, Path.children() may return an\n// empty array, indicating that it doesn't know about any of its children, and\n// thus has to rebuild that cache.  This is fine, it just means that we don't\n// benefit as much from having the cached entries, but huge directory walks\n// don't blow out the stack, and smaller ones are still as fast as possible.\n//\n//It does impose some complexity when building up the readdir data, because we\n//need to pass a reference to the children array that we started with.\n\n/**\n * an LRUCache for storing child entries.\n * @internal\n */\nexport class ChildrenCache extends LRUCache {\n  constructor(maxSize: number = 16 * 1024) {\n    super({\n      maxSize,\n      // parent + children\n      sizeCalculation: a => a.length + 1,\n    })\n  }\n}\n\n/**\n * Array of Path objects, plus a marker indicating the first provisional entry\n *\n * @internal\n */\nexport type Children = PathBase[] & { provisional: number }\n\nconst setAsCwd = Symbol('PathScurry setAsCwd')\n\n/**\n * Path objects are sort of like a super-powered\n * {@link https://nodejs.org/docs/latest/api/fs.html#class-fsdirent fs.Dirent}\n *\n * Each one represents a single filesystem entry on disk, which may or may not\n * exist. It includes methods for reading various types of information via\n * lstat, readlink, and readdir, and caches all information to the greatest\n * degree possible.\n *\n * Note that fs operations that would normally throw will instead return an\n * \"empty\" value. This is in order to prevent excessive overhead from error\n * stack traces.\n */\nexport abstract class PathBase implements Dirent {\n  /**\n   * the basename of this path\n   *\n   * **Important**: *always* test the path name against any test string\n   * usingthe {@link isNamed} method, and not by directly comparing this\n   * string. Otherwise, unicode path strings that the system sees as identical\n   * will not be properly treated as the same path, leading to incorrect\n   * behavior and possible security issues.\n   */\n  name: string\n  /**\n   * the Path entry corresponding to the path root.\n   *\n   * @internal\n   */\n  root: PathBase\n  /**\n   * All roots found within the current PathScurry family\n   *\n   * @internal\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * a reference to the parent path, or undefined in the case of root entries\n   *\n   * @internal\n   */\n  parent?: PathBase\n  /**\n   * boolean indicating whether paths are compared case-insensitively\n   * @internal\n   */\n  nocase: boolean\n\n  /**\n   * boolean indicating that this path is the current working directory\n   * of the PathScurry collection that contains it.\n   */\n  isCWD: boolean = false\n\n  /**\n   * the string or regexp used to split paths. On posix, it is `'/'`, and on\n   * windows it is a RegExp matching either `'/'` or `'\\\\'`\n   */\n  abstract splitSep: string | RegExp\n  /**\n   * The path separator string to use when joining paths\n   */\n  abstract sep: string\n\n  // potential default fs override\n  #fs: FSValue\n\n  // Stats fields\n  #dev?: number\n  get dev() {\n    return this.#dev\n  }\n  #mode?: number\n  get mode() {\n    return this.#mode\n  }\n  #nlink?: number\n  get nlink() {\n    return this.#nlink\n  }\n  #uid?: number\n  get uid() {\n    return this.#uid\n  }\n  #gid?: number\n  get gid() {\n    return this.#gid\n  }\n  #rdev?: number\n  get rdev() {\n    return this.#rdev\n  }\n  #blksize?: number\n  get blksize() {\n    return this.#blksize\n  }\n  #ino?: number\n  get ino() {\n    return this.#ino\n  }\n  #size?: number\n  get size() {\n    return this.#size\n  }\n  #blocks?: number\n  get blocks() {\n    return this.#blocks\n  }\n  #atimeMs?: number\n  get atimeMs() {\n    return this.#atimeMs\n  }\n  #mtimeMs?: number\n  get mtimeMs() {\n    return this.#mtimeMs\n  }\n  #ctimeMs?: number\n  get ctimeMs() {\n    return this.#ctimeMs\n  }\n  #birthtimeMs?: number\n  get birthtimeMs() {\n    return this.#birthtimeMs\n  }\n  #atime?: Date\n  get atime() {\n    return this.#atime\n  }\n  #mtime?: Date\n  get mtime() {\n    return this.#mtime\n  }\n  #ctime?: Date\n  get ctime() {\n    return this.#ctime\n  }\n  #birthtime?: Date\n  get birthtime() {\n    return this.#birthtime\n  }\n\n  #matchName: string\n  #depth?: number\n  #fullpath?: string\n  #fullpathPosix?: string\n  #relative?: string\n  #relativePosix?: string\n  #type: number\n  #children: ChildrenCache\n  #linkTarget?: PathBase\n  #realpath?: PathBase\n\n  /**\n   * This property is for compatibility with the Dirent class as of\n   * Node v20, where Dirent['parentPath'] refers to the path of the\n   * directory that was passed to readdir. For root entries, it's the path\n   * to the entry itself.\n   */\n  get parentPath(): string {\n    return (this.parent || this).fullpath()\n  }\n\n  /**\n   * Deprecated alias for Dirent['parentPath'] Somewhat counterintuitively,\n   * this property refers to the *parent* path, not the path object itself.\n   */\n  get path(): string {\n    return this.parentPath\n  }\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    this.name = name\n    this.#matchName = nocase ? normalizeNocase(name) : normalize(name)\n    this.#type = type & TYPEMASK\n    this.nocase = nocase\n    this.roots = roots\n    this.root = root || this\n    this.#children = children\n    this.#fullpath = opts.fullpath\n    this.#relative = opts.relative\n    this.#relativePosix = opts.relativePosix\n    this.parent = opts.parent\n    if (this.parent) {\n      this.#fs = this.parent.#fs\n    } else {\n      this.#fs = fsFromOption(opts.fs)\n    }\n  }\n\n  /**\n   * Returns the depth of the Path object from its root.\n   *\n   * For example, a path at `/foo/bar` would have a depth of 2.\n   */\n  depth(): number {\n    if (this.#depth !== undefined) return this.#depth\n    if (!this.parent) return (this.#depth = 0)\n    return (this.#depth = this.parent.depth() + 1)\n  }\n\n  /**\n   * @internal\n   */\n  abstract getRootString(path: string): string\n  /**\n   * @internal\n   */\n  abstract getRoot(rootPath: string): PathBase\n  /**\n   * @internal\n   */\n  abstract newChild(name: string, type?: number, opts?: PathOpts): PathBase\n\n  /**\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Get the Path object referenced by the string path, resolved from this Path\n   */\n  resolve(path?: string): PathBase {\n    if (!path) {\n      return this\n    }\n    const rootPath = this.getRootString(path)\n    const dir = path.substring(rootPath.length)\n    const dirParts = dir.split(this.splitSep)\n    const result: PathBase =\n      rootPath ?\n        this.getRoot(rootPath).#resolveParts(dirParts)\n      : this.#resolveParts(dirParts)\n    return result\n  }\n\n  #resolveParts(dirParts: string[]) {\n    let p: PathBase = this\n    for (const part of dirParts) {\n      p = p.child(part)\n    }\n    return p\n  }\n\n  /**\n   * Returns the cached children Path objects, if still available.  If they\n   * have fallen out of the cache, then returns an empty array, and resets the\n   * READDIR_CALLED bit, so that future calls to readdir() will require an fs\n   * lookup.\n   *\n   * @internal\n   */\n  children(): Children {\n    const cached = this.#children.get(this)\n    if (cached) {\n      return cached\n    }\n    const children: Children = Object.assign([], { provisional: 0 })\n    this.#children.set(this, children)\n    this.#type &= ~READDIR_CALLED\n    return children\n  }\n\n  /**\n   * Resolves a path portion and returns or creates the child Path.\n   *\n   * Returns `this` if pathPart is `''` or `'.'`, or `parent` if pathPart is\n   * `'..'`.\n   *\n   * This should not be called directly.  If `pathPart` contains any path\n   * separators, it will lead to unsafe undefined behavior.\n   *\n   * Use `Path.resolve()` instead.\n   *\n   * @internal\n   */\n  child(pathPart: string, opts?: PathOpts): PathBase {\n    if (pathPart === '' || pathPart === '.') {\n      return this\n    }\n    if (pathPart === '..') {\n      return this.parent || this\n    }\n\n    // find the child\n    const children = this.children()\n    const name =\n      this.nocase ? normalizeNocase(pathPart) : normalize(pathPart)\n    for (const p of children) {\n      if (p.#matchName === name) {\n        return p\n      }\n    }\n\n    // didn't find it, create provisional child, since it might not\n    // actually exist.  If we know the parent isn't a dir, then\n    // in fact it CAN'T exist.\n    const s = this.parent ? this.sep : ''\n    const fullpath =\n      this.#fullpath ? this.#fullpath + s + pathPart : undefined\n    const pchild = this.newChild(pathPart, UNKNOWN, {\n      ...opts,\n      parent: this,\n      fullpath,\n    })\n\n    if (!this.canReaddir()) {\n      pchild.#type |= ENOENT\n    }\n\n    // don't have to update provisional, because if we have real children,\n    // then provisional is set to children.length, otherwise a lower number\n    children.push(pchild)\n    return pchild\n  }\n\n  /**\n   * The relative path from the cwd. If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpath()\n   */\n  relative(): string {\n    if (this.isCWD) return ''\n    if (this.#relative !== undefined) {\n      return this.#relative\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relative = this.name)\n    }\n    const pv = p.relative()\n    return pv + (!pv || !p.parent ? '' : this.sep) + name\n  }\n\n  /**\n   * The relative path from the cwd, using / as the path separator.\n   * If it does not share an ancestor with\n   * the cwd, then this ends up being equivalent to the fullpathPosix()\n   * On posix systems, this is identical to relative().\n   */\n  relativePosix(): string {\n    if (this.sep === '/') return this.relative()\n    if (this.isCWD) return ''\n    if (this.#relativePosix !== undefined) return this.#relativePosix\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#relativePosix = this.fullpathPosix())\n    }\n    const pv = p.relativePosix()\n    return pv + (!pv || !p.parent ? '' : '/') + name\n  }\n\n  /**\n   * The fully resolved path string for this Path entry\n   */\n  fullpath(): string {\n    if (this.#fullpath !== undefined) {\n      return this.#fullpath\n    }\n    const name = this.name\n    const p = this.parent\n    if (!p) {\n      return (this.#fullpath = this.name)\n    }\n    const pv = p.fullpath()\n    const fp = pv + (!p.parent ? '' : this.sep) + name\n    return (this.#fullpath = fp)\n  }\n\n  /**\n   * On platforms other than windows, this is identical to fullpath.\n   *\n   * On windows, this is overridden to return the forward-slash form of the\n   * full UNC path.\n   */\n  fullpathPosix(): string {\n    if (this.#fullpathPosix !== undefined) return this.#fullpathPosix\n    if (this.sep === '/') return (this.#fullpathPosix = this.fullpath())\n    if (!this.parent) {\n      const p = this.fullpath().replace(/\\\\/g, '/')\n      if (/^[a-z]:\\//i.test(p)) {\n        return (this.#fullpathPosix = `//?/${p}`)\n      } else {\n        return (this.#fullpathPosix = p)\n      }\n    }\n    const p = this.parent\n    const pfpp = p.fullpathPosix()\n    const fpp = pfpp + (!pfpp || !p.parent ? '' : '/') + this.name\n    return (this.#fullpathPosix = fpp)\n  }\n\n  /**\n   * Is the Path of an unknown type?\n   *\n   * Note that we might know *something* about it if there has been a previous\n   * filesystem operation, for example that it does not exist, or is not a\n   * link, or whether it has child entries.\n   */\n  isUnknown(): boolean {\n    return (this.#type & IFMT) === UNKNOWN\n  }\n\n  isType(type: Type): boolean {\n    return this[`is${type}`]()\n  }\n\n  getType(): Type {\n    return (\n      this.isUnknown() ? 'Unknown'\n      : this.isDirectory() ? 'Directory'\n      : this.isFile() ? 'File'\n      : this.isSymbolicLink() ? 'SymbolicLink'\n      : this.isFIFO() ? 'FIFO'\n      : this.isCharacterDevice() ? 'CharacterDevice'\n      : this.isBlockDevice() ? 'BlockDevice'\n      : /* c8 ignore start */ this.isSocket() ? 'Socket'\n      : 'Unknown'\n    )\n    /* c8 ignore stop */\n  }\n\n  /**\n   * Is the Path a regular file?\n   */\n  isFile(): boolean {\n    return (this.#type & IFMT) === IFREG\n  }\n\n  /**\n   * Is the Path a directory?\n   */\n  isDirectory(): boolean {\n    return (this.#type & IFMT) === IFDIR\n  }\n\n  /**\n   * Is the path a character device?\n   */\n  isCharacterDevice(): boolean {\n    return (this.#type & IFMT) === IFCHR\n  }\n\n  /**\n   * Is the path a block device?\n   */\n  isBlockDevice(): boolean {\n    return (this.#type & IFMT) === IFBLK\n  }\n\n  /**\n   * Is the path a FIFO pipe?\n   */\n  isFIFO(): boolean {\n    return (this.#type & IFMT) === IFIFO\n  }\n\n  /**\n   * Is the path a socket?\n   */\n  isSocket(): boolean {\n    return (this.#type & IFMT) === IFSOCK\n  }\n\n  /**\n   * Is the path a symbolic link?\n   */\n  isSymbolicLink(): boolean {\n    return (this.#type & IFLNK) === IFLNK\n  }\n\n  /**\n   * Return the entry if it has been subject of a successful lstat, or\n   * undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* simply\n   * mean that we haven't called lstat on it.\n   */\n  lstatCached(): PathBase | undefined {\n    return this.#type & LSTAT_CALLED ? this : undefined\n  }\n\n  /**\n   * Return the cached link target if the entry has been the subject of a\n   * successful readlink, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readlink() has been called at some point.\n   */\n  readlinkCached(): PathBase | undefined {\n    return this.#linkTarget\n  }\n\n  /**\n   * Returns the cached realpath target if the entry has been the subject\n   * of a successful realpath, or undefined otherwise.\n   *\n   * Does not read the filesystem, so an undefined result *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * realpath() has been called at some point.\n   */\n  realpathCached(): PathBase | undefined {\n    return this.#realpath\n  }\n\n  /**\n   * Returns the cached child Path entries array if the entry has been the\n   * subject of a successful readdir(), or [] otherwise.\n   *\n   * Does not read the filesystem, so an empty array *could* just mean we\n   * don't have any cached data. Only use it if you are very sure that a\n   * readdir() has been called recently enough to still be valid.\n   */\n  readdirCached(): PathBase[] {\n    const children = this.children()\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * Return true if it's worth trying to readlink.  Ie, we don't (yet) have\n   * any indication that readlink will definitely fail.\n   *\n   * Returns false if the path is known to not be a symlink, if a previous\n   * readlink failed, or if the entry does not exist.\n   */\n  canReadlink(): boolean {\n    if (this.#linkTarget) return true\n    if (!this.parent) return false\n    // cases where it cannot possibly succeed\n    const ifmt = this.#type & IFMT\n    return !(\n      (ifmt !== UNKNOWN && ifmt !== IFLNK) ||\n      this.#type & ENOREADLINK ||\n      this.#type & ENOENT\n    )\n  }\n\n  /**\n   * Return true if readdir has previously been successfully called on this\n   * path, indicating that cachedReaddir() is likely valid.\n   */\n  calledReaddir(): boolean {\n    return !!(this.#type & READDIR_CALLED)\n  }\n\n  /**\n   * Returns true if the path is known to not exist. That is, a previous lstat\n   * or readdir failed to verify its existence when that would have been\n   * expected, or a parent entry was marked either enoent or enotdir.\n   */\n  isENOENT(): boolean {\n    return !!(this.#type & ENOENT)\n  }\n\n  /**\n   * Return true if the path is a match for the given path name.  This handles\n   * case sensitivity and unicode normalization.\n   *\n   * Note: even on case-sensitive systems, it is **not** safe to test the\n   * equality of the `.name` property to determine whether a given pathname\n   * matches, due to unicode normalization mismatches.\n   *\n   * Always use this method instead of testing the `path.name` property\n   * directly.\n   */\n  isNamed(n: string): boolean {\n    return !this.nocase ?\n        this.#matchName === normalize(n)\n      : this.#matchName === normalizeNocase(n)\n  }\n\n  /**\n   * Return the Path object corresponding to the target of a symbolic link.\n   *\n   * If the Path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   */\n  async readlink(): Promise {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = await this.#fs.promises.readlink(this.fullpath())\n      const linkTarget = (await this.parent.realpath())?.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  /**\n   * Synchronous {@link PathBase.readlink}\n   */\n  readlinkSync(): PathBase | undefined {\n    const target = this.#linkTarget\n    if (target) {\n      return target\n    }\n    if (!this.canReadlink()) {\n      return undefined\n    }\n    /* c8 ignore start */\n    // already covered by the canReadlink test, here for ts grumples\n    if (!this.parent) {\n      return undefined\n    }\n    /* c8 ignore stop */\n    try {\n      const read = this.#fs.readlinkSync(this.fullpath())\n      const linkTarget = this.parent.realpathSync()?.resolve(read)\n      if (linkTarget) {\n        return (this.#linkTarget = linkTarget)\n      }\n    } catch (er) {\n      this.#readlinkFail((er as NodeJS.ErrnoException).code)\n      return undefined\n    }\n  }\n\n  #readdirSuccess(children: Children) {\n    // succeeded, mark readdir called bit\n    this.#type |= READDIR_CALLED\n    // mark all remaining provisional children as ENOENT\n    for (let p = children.provisional; p < children.length; p++) {\n      const c = children[p]\n      if (c) c.#markENOENT()\n    }\n  }\n\n  #markENOENT() {\n    // mark as UNKNOWN and ENOENT\n    if (this.#type & ENOENT) return\n    this.#type = (this.#type | ENOENT) & IFMT_UNKNOWN\n    this.#markChildrenENOENT()\n  }\n\n  #markChildrenENOENT() {\n    // all children are provisional and do not exist\n    const children = this.children()\n    children.provisional = 0\n    for (const p of children) {\n      p.#markENOENT()\n    }\n  }\n\n  #markENOREALPATH() {\n    this.#type |= ENOREALPATH\n    this.#markENOTDIR()\n  }\n\n  // save the information when we know the entry is not a dir\n  #markENOTDIR() {\n    // entry is not a directory, so any children can't exist.\n    // this *should* be impossible, since any children created\n    // after it's been marked ENOTDIR should be marked ENOENT,\n    // so it won't even get to this point.\n    /* c8 ignore start */\n    if (this.#type & ENOTDIR) return\n    /* c8 ignore stop */\n    let t = this.#type\n    // this could happen if we stat a dir, then delete it,\n    // then try to read it or one of its children.\n    if ((t & IFMT) === IFDIR) t &= IFMT_UNKNOWN\n    this.#type = t | ENOTDIR\n    this.#markChildrenENOENT()\n  }\n\n  #readdirFail(code: string = '') {\n    // markENOTDIR and markENOENT also set provisional=0\n    if (code === 'ENOTDIR' || code === 'EPERM') {\n      this.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      this.#markENOENT()\n    } else {\n      this.children().provisional = 0\n    }\n  }\n\n  #lstatFail(code: string = '') {\n    // Windows just raises ENOENT in this case, disable for win CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR') {\n      // already know it has a parent by this point\n      const p = this.parent as PathBase\n      p.#markENOTDIR()\n    } else if (code === 'ENOENT') {\n      /* c8 ignore stop */\n      this.#markENOENT()\n    }\n  }\n\n  #readlinkFail(code: string = '') {\n    let ter = this.#type\n    ter |= ENOREADLINK\n    if (code === 'ENOENT') ter |= ENOENT\n    // windows gets a weird error when you try to readlink a file\n    if (code === 'EINVAL' || code === 'UNKNOWN') {\n      // exists, but not a symlink, we don't know WHAT it is, so remove\n      // all IFMT bits.\n      ter &= IFMT_UNKNOWN\n    }\n    this.#type = ter\n    // windows just gets ENOENT in this case.  We do cover the case,\n    // just disabled because it's impossible on Windows CI\n    /* c8 ignore start */\n    if (code === 'ENOTDIR' && this.parent) {\n      this.parent.#markENOTDIR()\n    }\n    /* c8 ignore stop */\n  }\n\n  #readdirAddChild(e: Dirent, c: Children) {\n    return (\n      this.#readdirMaybePromoteChild(e, c) ||\n      this.#readdirAddNewChild(e, c)\n    )\n  }\n\n  #readdirAddNewChild(e: Dirent, c: Children): PathBase {\n    // alloc new entry at head, so it's never provisional\n    const type = entToType(e)\n    const child = this.newChild(e.name, type, { parent: this })\n    const ifmt = child.#type & IFMT\n    if (ifmt !== IFDIR && ifmt !== IFLNK && ifmt !== UNKNOWN) {\n      child.#type |= ENOTDIR\n    }\n    c.unshift(child)\n    c.provisional++\n    return child\n  }\n\n  #readdirMaybePromoteChild(e: Dirent, c: Children): PathBase | undefined {\n    for (let p = c.provisional; p < c.length; p++) {\n      const pchild = c[p]\n      const name =\n        this.nocase ? normalizeNocase(e.name) : normalize(e.name)\n      if (name !== pchild!.#matchName) {\n        continue\n      }\n\n      return this.#readdirPromoteChild(e, pchild!, p, c)\n    }\n  }\n\n  #readdirPromoteChild(\n    e: Dirent,\n    p: PathBase,\n    index: number,\n    c: Children,\n  ): PathBase {\n    const v = p.name\n    // retain any other flags, but set ifmt from dirent\n    p.#type = (p.#type & IFMT_UNKNOWN) | entToType(e)\n    // case sensitivity fixing when we learn the true name.\n    if (v !== e.name) p.name = e.name\n\n    // just advance provisional index (potentially off the list),\n    // otherwise we have to splice/pop it out and re-insert at head\n    if (index !== c.provisional) {\n      if (index === c.length - 1) c.pop()\n      else c.splice(index, 1)\n      c.unshift(p)\n    }\n    c.provisional++\n    return p\n  }\n\n  /**\n   * Call lstat() on this Path, and update all known information that can be\n   * determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(): Promise {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(await this.#fs.promises.lstat(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  /**\n   * synchronous {@link PathBase.lstat}\n   */\n  lstatSync(): PathBase | undefined {\n    if ((this.#type & ENOENT) === 0) {\n      try {\n        this.#applyStat(this.#fs.lstatSync(this.fullpath()))\n        return this\n      } catch (er) {\n        this.#lstatFail((er as NodeJS.ErrnoException).code)\n      }\n    }\n  }\n\n  #applyStat(st: Stats) {\n    const {\n      atime,\n      atimeMs,\n      birthtime,\n      birthtimeMs,\n      blksize,\n      blocks,\n      ctime,\n      ctimeMs,\n      dev,\n      gid,\n      ino,\n      mode,\n      mtime,\n      mtimeMs,\n      nlink,\n      rdev,\n      size,\n      uid,\n    } = st\n    this.#atime = atime\n    this.#atimeMs = atimeMs\n    this.#birthtime = birthtime\n    this.#birthtimeMs = birthtimeMs\n    this.#blksize = blksize\n    this.#blocks = blocks\n    this.#ctime = ctime\n    this.#ctimeMs = ctimeMs\n    this.#dev = dev\n    this.#gid = gid\n    this.#ino = ino\n    this.#mode = mode\n    this.#mtime = mtime\n    this.#mtimeMs = mtimeMs\n    this.#nlink = nlink\n    this.#rdev = rdev\n    this.#size = size\n    this.#uid = uid\n    const ifmt = entToType(st)\n    // retain any other flags, but set the ifmt\n    this.#type = (this.#type & IFMT_UNKNOWN) | ifmt | LSTAT_CALLED\n    if (ifmt !== UNKNOWN && ifmt !== IFDIR && ifmt !== IFLNK) {\n      this.#type |= ENOTDIR\n    }\n  }\n\n  #onReaddirCB: ((\n    er: NodeJS.ErrnoException | null,\n    entries: Path[],\n  ) => any)[] = []\n  #readdirCBInFlight: boolean = false\n  #callOnReaddirCB(children: Path[]) {\n    this.#readdirCBInFlight = false\n    const cbs = this.#onReaddirCB.slice()\n    this.#onReaddirCB.length = 0\n    cbs.forEach(cb => cb(null, children))\n  }\n\n  /**\n   * Standard node-style callback interface to get list of directory entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * @param cb The callback called with (er, entries).  Note that the `er`\n   * param is somewhat extraneous, as all readdir() errors are handled and\n   * simply result in an empty set of entries being returned.\n   * @param allowZalgo Boolean indicating that immediately known results should\n   * *not* be deferred with `queueMicrotask`. Defaults to `false`. Release\n   * zalgo at your peril, the dark pony lord is devious and unforgiving.\n   */\n  readdirCB(\n    cb: (er: NodeJS.ErrnoException | null, entries: PathBase[]) => any,\n    allowZalgo: boolean = false,\n  ): void {\n    if (!this.canReaddir()) {\n      if (allowZalgo) cb(null, [])\n      else queueMicrotask(() => cb(null, []))\n      return\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      const c = children.slice(0, children.provisional)\n      if (allowZalgo) cb(null, c)\n      else queueMicrotask(() => cb(null, c))\n      return\n    }\n\n    // don't have to worry about zalgo at this point.\n    this.#onReaddirCB.push(cb)\n    if (this.#readdirCBInFlight) {\n      return\n    }\n    this.#readdirCBInFlight = true\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    this.#fs.readdir(fullpath, { withFileTypes: true }, (er, entries) => {\n      if (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      } else {\n        // if we didn't get an error, we always get entries.\n        //@ts-ignore\n        for (const e of entries) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      }\n      this.#callOnReaddirCB(children.slice(0, children.provisional))\n      return\n    })\n  }\n\n  #asyncReaddirInFlight?: Promise\n\n  /**\n   * Return an array of known child entries.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async readdir(): Promise {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    if (this.#asyncReaddirInFlight) {\n      await this.#asyncReaddirInFlight\n    } else {\n      /* c8 ignore start */\n      let resolve: () => void = () => {}\n      /* c8 ignore stop */\n      this.#asyncReaddirInFlight = new Promise(\n        res => (resolve = res),\n      )\n      try {\n        for (const e of await this.#fs.promises.readdir(fullpath, {\n          withFileTypes: true,\n        })) {\n          this.#readdirAddChild(e, children)\n        }\n        this.#readdirSuccess(children)\n      } catch (er) {\n        this.#readdirFail((er as NodeJS.ErrnoException).code)\n        children.provisional = 0\n      }\n      this.#asyncReaddirInFlight = undefined\n      resolve()\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  /**\n   * synchronous {@link PathBase.readdir}\n   */\n  readdirSync(): PathBase[] {\n    if (!this.canReaddir()) {\n      return []\n    }\n\n    const children = this.children()\n    if (this.calledReaddir()) {\n      return children.slice(0, children.provisional)\n    }\n\n    // else read the directory, fill up children\n    // de-provisionalize any provisional children.\n    const fullpath = this.fullpath()\n    try {\n      for (const e of this.#fs.readdirSync(fullpath, {\n        withFileTypes: true,\n      })) {\n        this.#readdirAddChild(e, children)\n      }\n      this.#readdirSuccess(children)\n    } catch (er) {\n      this.#readdirFail((er as NodeJS.ErrnoException).code)\n      children.provisional = 0\n    }\n    return children.slice(0, children.provisional)\n  }\n\n  canReaddir() {\n    if (this.#type & ENOCHILD) return false\n    const ifmt = IFMT & this.#type\n    // we always set ENOTDIR when setting IFMT, so should be impossible\n    /* c8 ignore start */\n    if (!(ifmt === UNKNOWN || ifmt === IFDIR || ifmt === IFLNK)) {\n      return false\n    }\n    /* c8 ignore stop */\n    return true\n  }\n\n  shouldWalk(\n    dirs: Set,\n    walkFilter?: (e: PathBase) => boolean,\n  ): boolean {\n    return (\n      (this.#type & IFDIR) === IFDIR &&\n      !(this.#type & ENOCHILD) &&\n      !dirs.has(this) &&\n      (!walkFilter || walkFilter(this))\n    )\n  }\n\n  /**\n   * Return the Path object corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   * On success, returns a Path object.\n   */\n  async realpath(): Promise {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = await this.#fs.promises.realpath(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch (_) {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Synchronous {@link realpath}\n   */\n  realpathSync(): PathBase | undefined {\n    if (this.#realpath) return this.#realpath\n    if ((ENOREALPATH | ENOREADLINK | ENOENT) & this.#type) return undefined\n    try {\n      const rp = this.#fs.realpathSync(this.fullpath())\n      return (this.#realpath = this.resolve(rp))\n    } catch (_) {\n      this.#markENOREALPATH()\n    }\n  }\n\n  /**\n   * Internal method to mark this Path object as the scurry cwd,\n   * called by {@link PathScurry#chdir}\n   *\n   * @internal\n   */\n  [setAsCwd](oldCwd: PathBase): void {\n    if (oldCwd === this) return\n    oldCwd.isCWD = false\n    this.isCWD = true\n\n    const changed = new Set([])\n    let rp = []\n    let p: PathBase = this\n    while (p && p.parent) {\n      changed.add(p)\n      p.#relative = rp.join(this.sep)\n      p.#relativePosix = rp.join('/')\n      p = p.parent\n      rp.push('..')\n    }\n    // now un-memoize parents of old cwd\n    p = oldCwd\n    while (p && p.parent && !changed.has(p)) {\n      p.#relative = undefined\n      p.#relativePosix = undefined\n      p = p.parent\n    }\n  }\n}\n\n/**\n * Path class used on win32 systems\n *\n * Uses `'\\\\'` as the path separator for returned paths, either `'\\\\'` or `'/'`\n * as the path separator for parsing paths.\n */\nexport class PathWin32 extends PathBase {\n  /**\n   * Separator for generating path strings.\n   */\n  sep: '\\\\' = '\\\\'\n  /**\n   * Separator for parsing path strings.\n   */\n  splitSep: RegExp = eitherSep\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathWin32(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts,\n    )\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return win32.parse(path).root\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(rootPath: string): PathBase {\n    rootPath = uncToDrive(rootPath.toUpperCase())\n    if (rootPath === this.root.name) {\n      return this.root\n    }\n    // ok, not that one, check if it matches another we know about\n    for (const [compare, root] of Object.entries(this.roots)) {\n      if (this.sameRoot(rootPath, compare)) {\n        return (this.roots[rootPath] = root)\n      }\n    }\n    // otherwise, have to create a new one.\n    return (this.roots[rootPath] = new PathScurryWin32(\n      rootPath,\n      this,\n    ).root)\n  }\n\n  /**\n   * @internal\n   */\n  sameRoot(rootPath: string, compare: string = this.root.name): boolean {\n    // windows can (rarely) have case-sensitive filesystem, but\n    // UNC and drive letters are always case-insensitive, and canonically\n    // represented uppercase.\n    rootPath = rootPath\n      .toUpperCase()\n      .replace(/\\//g, '\\\\')\n      .replace(uncDriveRegexp, '$1\\\\')\n    return rootPath === compare\n  }\n}\n\n/**\n * Path class used on all posix systems.\n *\n * Uses `'/'` as the path separator.\n */\nexport class PathPosix extends PathBase {\n  /**\n   * separator for parsing path strings\n   */\n  splitSep: '/' = '/'\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n\n  /**\n   * Do not create new Path objects directly.  They should always be accessed\n   * via the PathScurry class or other methods on the Path class.\n   *\n   * @internal\n   */\n  constructor(\n    name: string,\n    type: number = UNKNOWN,\n    root: PathBase | undefined,\n    roots: { [k: string]: PathBase },\n    nocase: boolean,\n    children: ChildrenCache,\n    opts: PathOpts,\n  ) {\n    super(name, type, root, roots, nocase, children, opts)\n  }\n\n  /**\n   * @internal\n   */\n  getRootString(path: string): string {\n    return path.startsWith('/') ? '/' : ''\n  }\n\n  /**\n   * @internal\n   */\n  getRoot(_rootPath: string): PathBase {\n    return this.root\n  }\n\n  /**\n   * @internal\n   */\n  newChild(name: string, type: number = UNKNOWN, opts: PathOpts = {}) {\n    return new PathPosix(\n      name,\n      type,\n      this.root,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      opts,\n    )\n  }\n}\n\n/**\n * Options that may be provided to the PathScurry constructor\n */\nexport interface PathScurryOpts {\n  /**\n   * perform case-insensitive path matching. Default based on platform\n   * subclass.\n   */\n  nocase?: boolean\n  /**\n   * Number of Path entries to keep in the cache of Path child references.\n   *\n   * Setting this higher than 65536 will dramatically increase the data\n   * consumption and construction time overhead of each PathScurry.\n   *\n   * Setting this value to 256 or lower will significantly reduce the data\n   * consumption and construction time overhead, but may also reduce resolve()\n   * and readdir() performance on large filesystems.\n   *\n   * Default `16384`.\n   */\n  childrenCacheSize?: number\n  /**\n   * An object that overrides the built-in functions from the fs and\n   * fs/promises modules.\n   *\n   * See {@link FSOption}\n   */\n  fs?: FSOption\n}\n\n/**\n * The base class for all PathScurry classes, providing the interface for path\n * resolution and filesystem operations.\n *\n * Typically, you should *not* instantiate this class directly, but rather one\n * of the platform-specific classes, or the exported {@link PathScurry} which\n * defaults to the current platform.\n */\nexport abstract class PathScurryBase {\n  /**\n   * The root Path entry for the current working directory of this Scurry\n   */\n  root: PathBase\n  /**\n   * The string path for the root of this Scurry's current working directory\n   */\n  rootPath: string\n  /**\n   * A collection of all roots encountered, referenced by rootPath\n   */\n  roots: { [k: string]: PathBase }\n  /**\n   * The Path entry corresponding to this PathScurry's current working directory.\n   */\n  cwd: PathBase\n  #resolveCache: ResolveCache\n  #resolvePosixCache: ResolveCache\n  #children: ChildrenCache\n  /**\n   * Perform path comparisons case-insensitively.\n   *\n   * Defaults true on Darwin and Windows systems, false elsewhere.\n   */\n  nocase: boolean\n\n  /**\n   * The path separator used for parsing paths\n   *\n   * `'/'` on Posix systems, either `'/'` or `'\\\\'` on Windows\n   */\n  abstract sep: string | RegExp\n\n  #fs: FSValue\n\n  /**\n   * This class should not be instantiated directly.\n   *\n   * Use PathScurryWin32, PathScurryDarwin, PathScurryPosix, or PathScurry\n   *\n   * @internal\n   */\n  constructor(\n    cwd: URL | string = process.cwd(),\n    pathImpl: typeof win32 | typeof posix,\n    sep: string | RegExp,\n    {\n      nocase,\n      childrenCacheSize = 16 * 1024,\n      fs = defaultFS,\n    }: PathScurryOpts = {},\n  ) {\n    this.#fs = fsFromOption(fs)\n    if (cwd instanceof URL || cwd.startsWith('file://')) {\n      cwd = fileURLToPath(cwd)\n    }\n    // resolve and split root, and then add to the store.\n    // this is the only time we call path.resolve()\n    const cwdPath = pathImpl.resolve(cwd)\n    this.roots = Object.create(null)\n    this.rootPath = this.parseRootPath(cwdPath)\n    this.#resolveCache = new ResolveCache()\n    this.#resolvePosixCache = new ResolveCache()\n    this.#children = new ChildrenCache(childrenCacheSize)\n\n    const split = cwdPath.substring(this.rootPath.length).split(sep)\n    // resolve('/') leaves '', splits to [''], we don't want that.\n    if (split.length === 1 && !split[0]) {\n      split.pop()\n    }\n    /* c8 ignore start */\n    if (nocase === undefined) {\n      throw new TypeError(\n        'must provide nocase setting to PathScurryBase ctor',\n      )\n    }\n    /* c8 ignore stop */\n    this.nocase = nocase\n    this.root = this.newRoot(this.#fs)\n    this.roots[this.rootPath] = this.root\n    let prev: PathBase = this.root\n    let len = split.length - 1\n    const joinSep = pathImpl.sep\n    let abs = this.rootPath\n    let sawFirst = false\n    for (const part of split) {\n      const l = len--\n      prev = prev.child(part, {\n        relative: new Array(l).fill('..').join(joinSep),\n        relativePosix: new Array(l).fill('..').join('/'),\n        fullpath: (abs += (sawFirst ? '' : joinSep) + part),\n      })\n      sawFirst = true\n    }\n    this.cwd = prev\n  }\n\n  /**\n   * Get the depth of a provided path, string, or the cwd\n   */\n  depth(path: Path | string = this.cwd): number {\n    if (typeof path === 'string') {\n      path = this.cwd.resolve(path)\n    }\n    return path.depth()\n  }\n\n  /**\n   * Parse the root portion of a path string\n   *\n   * @internal\n   */\n  abstract parseRootPath(dir: string): string\n  /**\n   * create a new Path to use as root during construction.\n   *\n   * @internal\n   */\n  abstract newRoot(fs: FSValue): PathBase\n  /**\n   * Determine whether a given path string is absolute\n   */\n  abstract isAbsolute(p: string): boolean\n\n  /**\n   * Return the cache of child entries.  Exposed so subclasses can create\n   * child Path objects in a platform-specific way.\n   *\n   * @internal\n   */\n  childrenCache() {\n    return this.#children\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolve(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolveCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpath()\n    this.#resolveCache.set(r, result)\n    return result\n  }\n\n  /**\n   * Resolve one or more path strings to a resolved string, returning\n   * the posix path.  Identical to .resolve() on posix systems, but on\n   * windows will return a forward-slash separated UNC path.\n   *\n   * Same interface as require('path').resolve.\n   *\n   * Much faster than path.resolve() when called multiple times for the same\n   * path, because the resolved Path objects are cached.  Much slower\n   * otherwise.\n   */\n  resolvePosix(...paths: string[]): string {\n    // first figure out the minimum number of paths we have to test\n    // we always start at cwd, but any absolutes will bump the start\n    let r = ''\n    for (let i = paths.length - 1; i >= 0; i--) {\n      const p = paths[i]\n      if (!p || p === '.') continue\n      r = r ? `${p}/${r}` : p\n      if (this.isAbsolute(p)) {\n        break\n      }\n    }\n    const cached = this.#resolvePosixCache.get(r)\n    if (cached !== undefined) {\n      return cached\n    }\n    const result = this.cwd.resolve(r).fullpathPosix()\n    this.#resolvePosixCache.set(r, result)\n    return result\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or entry\n   */\n  relative(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relative()\n  }\n\n  /**\n   * find the relative path from the cwd to the supplied path string or\n   * entry, using / as the path delimiter, even on Windows.\n   */\n  relativePosix(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.relativePosix()\n  }\n\n  /**\n   * Return the basename for the provided string or Path object\n   */\n  basename(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.name\n  }\n\n  /**\n   * Return the dirname for the provided string or Path object\n   */\n  dirname(entry: PathBase | string = this.cwd): string {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return (entry.parent || entry).fullpath()\n  }\n\n  /**\n   * Return an array of known child entries.\n   *\n   * First argument may be either a string, or a Path object.\n   *\n   * If the Path cannot or does not contain any children, then an empty array\n   * is returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   *\n   * Unlike `fs.readdir()`, the `withFileTypes` option defaults to `true`. Set\n   * `{ withFileTypes: false }` to return strings.\n   */\n\n  readdir(): Promise\n  readdir(opts: { withFileTypes: true }): Promise\n  readdir(opts: { withFileTypes: false }): Promise\n  readdir(opts: { withFileTypes: boolean }): Promise\n  readdir(entry: PathBase | string): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: true },\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: false },\n  ): Promise\n  readdir(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean },\n  ): Promise\n  async readdir(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else {\n      const p = await entry.readdir()\n      return withFileTypes ? p : p.map(e => e.name)\n    }\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readdir}\n   */\n  readdirSync(): PathBase[]\n  readdirSync(opts: { withFileTypes: true }): PathBase[]\n  readdirSync(opts: { withFileTypes: false }): string[]\n  readdirSync(opts: { withFileTypes: boolean }): PathBase[] | string[]\n  readdirSync(entry: PathBase | string): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: true },\n  ): PathBase[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: false },\n  ): string[]\n  readdirSync(\n    entry: PathBase | string,\n    opts: { withFileTypes: boolean },\n  ): PathBase[] | string[]\n  readdirSync(\n    entry: PathBase | string | { withFileTypes: boolean } = this.cwd,\n    opts: { withFileTypes: boolean } = {\n      withFileTypes: true,\n    },\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const { withFileTypes = true } = opts\n    if (!entry.canReaddir()) {\n      return []\n    } else if (withFileTypes) {\n      return entry.readdirSync()\n    } else {\n      return entry.readdirSync().map(e => e.name)\n    }\n  }\n\n  /**\n   * Call lstat() on the string or Path object, and update all known\n   * information that can be determined.\n   *\n   * Note that unlike `fs.lstat()`, the returned value does not contain some\n   * information, such as `mode`, `dev`, `nlink`, and `ino`.  If that\n   * information is required, you will need to call `fs.lstat` yourself.\n   *\n   * If the Path refers to a nonexistent file, or if the lstat call fails for\n   * any reason, `undefined` is returned.  Otherwise the updated Path object is\n   * returned.\n   *\n   * Results are cached, and thus may be out of date if the filesystem is\n   * mutated.\n   */\n  async lstat(\n    entry: string | PathBase = this.cwd,\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstat()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.lstat}\n   */\n  lstatSync(entry: string | PathBase = this.cwd): PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    }\n    return entry.lstatSync()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to the target of a\n   * symbolic link.\n   *\n   * If the path is not a symbolic link, or if the readlink call fails for any\n   * reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  readlink(): Promise\n  readlink(opt: { withFileTypes: false }): Promise\n  readlink(opt: { withFileTypes: true }): Promise\n  readlink(opt: {\n    withFileTypes: boolean\n  }): Promise\n  readlink(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): Promise\n  readlink(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): Promise\n  async readlink(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.readlink()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * synchronous {@link PathScurryBase.readlink}\n   */\n  readlinkSync(): string | undefined\n  readlinkSync(opt: { withFileTypes: false }): string | undefined\n  readlinkSync(opt: { withFileTypes: true }): PathBase | undefined\n  readlinkSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): string | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): string | PathBase | undefined\n  readlinkSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.readlinkSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Return the Path object or string path corresponding to path as resolved\n   * by realpath(3).\n   *\n   * If the realpath call fails for any reason, `undefined` is returned.\n   *\n   * Result is cached, and thus may be outdated if the filesystem is mutated.\n   *\n   * `{withFileTypes}` option defaults to `false`.\n   *\n   * On success, returns a Path object if `withFileTypes` option is true,\n   * otherwise a string.\n   */\n  realpath(): Promise\n  realpath(opt: { withFileTypes: false }): Promise\n  realpath(opt: { withFileTypes: true }): Promise\n  realpath(opt: {\n    withFileTypes: boolean\n  }): Promise\n  realpath(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): Promise\n  realpath(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): Promise\n  async realpath(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = await entry.realpath()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  realpathSync(): string | undefined\n  realpathSync(opt: { withFileTypes: false }): string | undefined\n  realpathSync(opt: { withFileTypes: true }): PathBase | undefined\n  realpathSync(opt: {\n    withFileTypes: boolean\n  }): PathBase | string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt?: { withFileTypes: false },\n  ): string | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: true },\n  ): PathBase | undefined\n  realpathSync(\n    entry: string | PathBase,\n    opt: { withFileTypes: boolean },\n  ): string | PathBase | undefined\n  realpathSync(\n    entry: string | PathBase | { withFileTypes: boolean } = this.cwd,\n    { withFileTypes }: { withFileTypes: boolean } = {\n      withFileTypes: false,\n    },\n  ): string | PathBase | undefined {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      withFileTypes = entry.withFileTypes\n      entry = this.cwd\n    }\n    const e = entry.realpathSync()\n    return withFileTypes ? e : e?.fullpath()\n  }\n\n  /**\n   * Asynchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walk(): Promise\n  walk(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Promise\n  walk(opts: WalkOptionsWithFileTypesFalse): Promise\n  walk(opts: WalkOptions): Promise\n  walk(entry: string | PathBase): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Promise\n  walk(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Promise\n  async walk(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Promise {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const walk = (\n      dir: PathBase,\n      cb: (er?: NodeJS.ErrnoException) => void,\n    ) => {\n      dirs.add(dir)\n      dir.readdirCB((er, entries) => {\n        /* c8 ignore start */\n        if (er) {\n          return cb(er)\n        }\n        /* c8 ignore stop */\n        let len = entries.length\n        if (!len) return cb()\n        const next = () => {\n          if (--len === 0) {\n            cb()\n          }\n        }\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            results.push(withFileTypes ? e : e.fullpath())\n          }\n          if (follow && e.isSymbolicLink()) {\n            e.realpath()\n              .then(r => (r?.isUnknown() ? r.lstat() : r))\n              .then(r =>\n                r?.shouldWalk(dirs, walkFilter) ? walk(r, next) : next(),\n              )\n          } else {\n            if (e.shouldWalk(dirs, walkFilter)) {\n              walk(e, next)\n            } else {\n              next()\n            }\n          }\n        }\n      }, true) // zalgooooooo\n    }\n\n    const start = entry\n    return new Promise((res, rej) => {\n      walk(start, er => {\n        /* c8 ignore start */\n        if (er) return rej(er)\n        /* c8 ignore stop */\n        res(results as PathBase[] | string[])\n      })\n    })\n  }\n\n  /**\n   * Synchronously walk the directory tree, returning an array of\n   * all path strings or Path objects found.\n   *\n   * Note that this will be extremely memory-hungry on large filesystems.\n   * In such cases, it may be better to use the stream or async iterator\n   * walk implementation.\n   */\n  walkSync(): PathBase[]\n  walkSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): PathBase[]\n  walkSync(opts: WalkOptionsWithFileTypesFalse): string[]\n  walkSync(opts: WalkOptions): string[] | PathBase[]\n  walkSync(entry: string | PathBase): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): PathBase[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): string[]\n  walkSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): PathBase[] | string[]\n  walkSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): PathBase[] | string[] {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results: (string | PathBase)[] = []\n    if (!filter || filter(entry)) {\n      results.push(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          results.push(withFileTypes ? e : e.fullpath())\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n    return results as string[] | PathBase[]\n  }\n\n  /**\n   * Support for `for await`\n   *\n   * Alias for {@link PathScurryBase.iterate}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n\n  /**\n   * Async generator form of {@link PathScurryBase.walk}\n   *\n   * Note: As of Node 19, this is very slow, compared to other methods of\n   * walking, especially if most/all of the directory tree has been previously\n   * walked.  Consider using {@link PathScurryBase.stream} if memory overhead\n   * and backpressure are concerns, or {@link PathScurryBase.walk} if not.\n   */\n  iterate(): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): AsyncGenerator\n  iterate(\n    opts: WalkOptionsWithFileTypesFalse,\n  ): AsyncGenerator\n  iterate(opts: WalkOptions): AsyncGenerator\n  iterate(entry: string | PathBase): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): AsyncGenerator\n  iterate(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    options: WalkOptions = {},\n  ): AsyncGenerator {\n    // iterating async over the stream is significantly more performant,\n    // especially in the warm-cache scenario, because it buffers up directory\n    // entries in the background instead of waiting for a yield for each one.\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      options = entry\n      entry = this.cwd\n    }\n    return this.stream(entry, options)[Symbol.asyncIterator]()\n  }\n\n  /**\n   * Iterating over a PathScurry performs a synchronous walk.\n   *\n   * Alias for {@link PathScurryBase.iterateSync}\n   */\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  iterateSync(): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Generator\n  iterateSync(\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Generator\n  iterateSync(opts: WalkOptions): Generator\n  iterateSync(entry: string | PathBase): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Generator\n  iterateSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Generator\n  *iterateSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Generator {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    if (!filter || filter(entry)) {\n      yield withFileTypes ? entry : entry.fullpath()\n    }\n    const dirs = new Set([entry])\n    for (const dir of dirs) {\n      const entries = dir.readdirSync()\n      for (const e of entries) {\n        if (!filter || filter(e)) {\n          yield withFileTypes ? e : e.fullpath()\n        }\n        let r: PathBase | undefined = e\n        if (e.isSymbolicLink()) {\n          if (!(follow && (r = e.realpathSync()))) continue\n          if (r.isUnknown()) r.lstatSync()\n        }\n        if (r.shouldWalk(dirs, walkFilter)) {\n          dirs.add(r)\n        }\n      }\n    }\n  }\n\n  /**\n   * Stream form of {@link PathScurryBase.walk}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   */\n  stream(): Minipass\n  stream(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Minipass\n  stream(opts: WalkOptionsWithFileTypesFalse): Minipass\n  stream(opts: WalkOptions): Minipass\n  stream(entry: string | PathBase): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Minipass\n  stream(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Minipass | Minipass\n  stream(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const dirs = new Set()\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n\n        processing++\n        dirs.add(dir)\n\n        const onReaddir = (\n          er: null | NodeJS.ErrnoException,\n          entries: PathBase[],\n          didRealpaths: boolean = false,\n        ) => {\n          /* c8 ignore start */\n          if (er) return results.emit('error', er)\n          /* c8 ignore stop */\n          if (follow && !didRealpaths) {\n            const promises: Promise[] = []\n            for (const e of entries) {\n              if (e.isSymbolicLink()) {\n                promises.push(\n                  e\n                    .realpath()\n                    .then((r: PathBase | undefined) =>\n                      r?.isUnknown() ? r.lstat() : r,\n                    ),\n                )\n              }\n            }\n            if (promises.length) {\n              Promise.all(promises).then(() =>\n                onReaddir(null, entries, true),\n              )\n              return\n            }\n          }\n\n          for (const e of entries) {\n            if (e && (!filter || filter(e))) {\n              if (!results.write(withFileTypes ? e : e.fullpath())) {\n                paused = true\n              }\n            }\n          }\n\n          processing--\n          for (const e of entries) {\n            const r = e.realpathCached() || e\n            if (r.shouldWalk(dirs, walkFilter)) {\n              queue.push(r)\n            }\n          }\n          if (paused && !results.flowing) {\n            results.once('drain', process)\n          } else if (!sync) {\n            process()\n          }\n        }\n\n        // zalgo containment\n        let sync = true\n        dir.readdirCB(onReaddir, true)\n        sync = false\n      }\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  /**\n   * Synchronous form of {@link PathScurryBase.stream}\n   *\n   * Returns a Minipass stream that emits {@link PathBase} objects by default,\n   * or strings if `{ withFileTypes: false }` is set in the options.\n   *\n   * Will complete the walk in a single tick if the stream is consumed fully.\n   * Otherwise, will pause as needed for stream backpressure.\n   */\n  streamSync(): Minipass\n  streamSync(\n    opts: WalkOptionsWithFileTypesTrue | WalkOptionsWithFileTypesUnset,\n  ): Minipass\n  streamSync(opts: WalkOptionsWithFileTypesFalse): Minipass\n  streamSync(opts: WalkOptions): Minipass\n  streamSync(entry: string | PathBase): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesUnset | WalkOptionsWithFileTypesTrue,\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptionsWithFileTypesFalse,\n  ): Minipass\n  streamSync(\n    entry: string | PathBase,\n    opts: WalkOptions,\n  ): Minipass | Minipass\n  streamSync(\n    entry: string | PathBase | WalkOptions = this.cwd,\n    opts: WalkOptions = {},\n  ): Minipass | Minipass {\n    if (typeof entry === 'string') {\n      entry = this.cwd.resolve(entry)\n    } else if (!(entry instanceof PathBase)) {\n      opts = entry\n      entry = this.cwd\n    }\n    const {\n      withFileTypes = true,\n      follow = false,\n      filter,\n      walkFilter,\n    } = opts\n    const results = new Minipass({ objectMode: true })\n    const dirs = new Set()\n    if (!filter || filter(entry)) {\n      results.write(withFileTypes ? entry : entry.fullpath())\n    }\n    const queue: PathBase[] = [entry]\n    let processing = 0\n    const process = () => {\n      let paused = false\n      while (!paused) {\n        const dir = queue.shift()\n        if (!dir) {\n          if (processing === 0) results.end()\n          return\n        }\n        processing++\n        dirs.add(dir)\n\n        const entries = dir.readdirSync()\n        for (const e of entries) {\n          if (!filter || filter(e)) {\n            if (!results.write(withFileTypes ? e : e.fullpath())) {\n              paused = true\n            }\n          }\n        }\n        processing--\n        for (const e of entries) {\n          let r: PathBase | undefined = e\n          if (e.isSymbolicLink()) {\n            if (!(follow && (r = e.realpathSync()))) continue\n            if (r.isUnknown()) r.lstatSync()\n          }\n          if (r.shouldWalk(dirs, walkFilter)) {\n            queue.push(r)\n          }\n        }\n      }\n      if (paused && !results.flowing) results.once('drain', process)\n    }\n    process()\n    return results as Minipass | Minipass\n  }\n\n  chdir(path: string | Path = this.cwd) {\n    const oldCwd = this.cwd\n    this.cwd = typeof path === 'string' ? this.cwd.resolve(path) : path\n    this.cwd[setAsCwd](oldCwd)\n  }\n}\n\n/**\n * Options provided to all walk methods.\n */\nexport interface WalkOptions {\n  /**\n   * Return results as {@link PathBase} objects rather than strings.\n   * When set to false, results are fully resolved paths, as returned by\n   * {@link PathBase.fullpath}.\n   * @default true\n   */\n  withFileTypes?: boolean\n\n  /**\n   *  Attempt to read directory entries from symbolic links. Otherwise, only\n   *  actual directories are traversed. Regardless of this setting, a given\n   *  target path will only ever be walked once, meaning that a symbolic link\n   *  to a previously traversed directory will never be followed.\n   *\n   *  Setting this imposes a slight performance penalty, because `readlink`\n   *  must be called on all symbolic links encountered, in order to avoid\n   *  infinite cycles.\n   * @default false\n   */\n  follow?: boolean\n\n  /**\n   * Only return entries where the provided function returns true.\n   *\n   * This will not prevent directories from being traversed, even if they do\n   * not pass the filter, though it will prevent directories themselves from\n   * being included in the result set.  See {@link walkFilter}\n   *\n   * Asynchronous functions are not supported here.\n   *\n   * By default, if no filter is provided, all entries and traversed\n   * directories are included.\n   */\n  filter?: (entry: PathBase) => boolean\n\n  /**\n   * Only traverse directories (and in the case of {@link follow} being set to\n   * true, symbolic links to directories) if the provided function returns\n   * true.\n   *\n   * This will not prevent directories from being included in the result set,\n   * even if they do not pass the supplied filter function.  See {@link filter}\n   * to do that.\n   *\n   * Asynchronous functions are not supported here.\n   */\n  walkFilter?: (entry: PathBase) => boolean\n}\n\nexport type WalkOptionsWithFileTypesUnset = WalkOptions & {\n  withFileTypes?: undefined\n}\nexport type WalkOptionsWithFileTypesTrue = WalkOptions & {\n  withFileTypes: true\n}\nexport type WalkOptionsWithFileTypesFalse = WalkOptions & {\n  withFileTypes: false\n}\n\n/**\n * Windows implementation of {@link PathScurryBase}\n *\n * Defaults to case insensitve, uses `'\\\\'` to generate path strings.  Uses\n * {@link PathWin32} for Path objects.\n */\nexport class PathScurryWin32 extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '\\\\' = '\\\\'\n\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = true } = opts\n    super(cwd, win32, '\\\\', { ...opts, nocase })\n    this.nocase = nocase\n    for (let p: PathBase | undefined = this.cwd; p; p = p.parent) {\n      p.nocase = this.nocase\n    }\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(dir: string): string {\n    // if the path starts with a single separator, it's not a UNC, and we'll\n    // just get separator as the root, and driveFromUNC will return \\\n    // In that case, mount \\ on the root from the cwd.\n    return win32.parse(dir).root.toUpperCase()\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathWin32(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs },\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return (\n      p.startsWith('/') || p.startsWith('\\\\') || /^[a-z]:(\\/|\\\\)/i.test(p)\n    )\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for all posix systems other than Darwin.\n *\n * Defaults to case-sensitive matching, uses `'/'` to generate path strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryPosix extends PathScurryBase {\n  /**\n   * separator for generating path strings\n   */\n  sep: '/' = '/'\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = false } = opts\n    super(cwd, posix, '/', { ...opts, nocase })\n    this.nocase = nocase\n  }\n\n  /**\n   * @internal\n   */\n  parseRootPath(_dir: string): string {\n    return '/'\n  }\n\n  /**\n   * @internal\n   */\n  newRoot(fs: FSValue) {\n    return new PathPosix(\n      this.rootPath,\n      IFDIR,\n      undefined,\n      this.roots,\n      this.nocase,\n      this.childrenCache(),\n      { fs },\n    )\n  }\n\n  /**\n   * Return true if the provided path string is an absolute path\n   */\n  isAbsolute(p: string): boolean {\n    return p.startsWith('/')\n  }\n}\n\n/**\n * {@link PathScurryBase} implementation for Darwin (macOS) systems.\n *\n * Defaults to case-insensitive matching, uses `'/'` for generating path\n * strings.\n *\n * Uses {@link PathPosix} for Path objects.\n */\nexport class PathScurryDarwin extends PathScurryPosix {\n  constructor(\n    cwd: URL | string = process.cwd(),\n    opts: PathScurryOpts = {},\n  ) {\n    const { nocase = true } = opts\n    super(cwd, { ...opts, nocase })\n  }\n}\n\n/**\n * Default {@link PathBase} implementation for the current platform.\n *\n * {@link PathWin32} on Windows systems, {@link PathPosix} on all others.\n */\nexport const Path = process.platform === 'win32' ? PathWin32 : PathPosix\nexport type Path = PathBase | InstanceType\n\n/**\n * Default {@link PathScurryBase} implementation for the current platform.\n *\n * {@link PathScurryWin32} on Windows systems, {@link PathScurryDarwin} on\n * Darwin (macOS) systems, {@link PathScurryPosix} on all others.\n */\nexport const PathScurry:\n  | typeof PathScurryWin32\n  | typeof PathScurryDarwin\n  | typeof PathScurryPosix =\n  process.platform === 'win32' ? PathScurryWin32\n  : process.platform === 'darwin' ? PathScurryDarwin\n  : PathScurryPosix\nexport type PathScurry = PathScurryBase | InstanceType\n","// this is just a very light wrapper around 2 arrays with an offset index\n\nimport { GLOBSTAR } from 'minimatch'\nexport type MMPattern = string | RegExp | typeof GLOBSTAR\n\n// an array of length >= 1\nexport type PatternList = [p: MMPattern, ...rest: MMPattern[]]\nexport type UNCPatternList = [\n  p0: '',\n  p1: '',\n  p2: string,\n  p3: string,\n  ...rest: MMPattern[],\n]\nexport type DrivePatternList = [p0: string, ...rest: MMPattern[]]\nexport type AbsolutePatternList = [p0: '', ...rest: MMPattern[]]\nexport type GlobList = [p: string, ...rest: string[]]\n\nconst isPatternList = (pl: MMPattern[]): pl is PatternList =>\n  pl.length >= 1\nconst isGlobList = (gl: string[]): gl is GlobList => gl.length >= 1\n\n/**\n * An immutable-ish view on an array of glob parts and their parsed\n * results\n */\nexport class Pattern {\n  readonly #patternList: PatternList\n  readonly #globList: GlobList\n  readonly #index: number\n  readonly length: number\n  readonly #platform: NodeJS.Platform\n  #rest?: Pattern | null\n  #globString?: string\n  #isDrive?: boolean\n  #isUNC?: boolean\n  #isAbsolute?: boolean\n  #followGlobstar: boolean = true\n\n  constructor(\n    patternList: MMPattern[],\n    globList: string[],\n    index: number,\n    platform: NodeJS.Platform,\n  ) {\n    if (!isPatternList(patternList)) {\n      throw new TypeError('empty pattern list')\n    }\n    if (!isGlobList(globList)) {\n      throw new TypeError('empty glob list')\n    }\n    if (globList.length !== patternList.length) {\n      throw new TypeError('mismatched pattern list and glob list lengths')\n    }\n    this.length = patternList.length\n    if (index < 0 || index >= this.length) {\n      throw new TypeError('index out of range')\n    }\n    this.#patternList = patternList\n    this.#globList = globList\n    this.#index = index\n    this.#platform = platform\n\n    // normalize root entries of absolute patterns on initial creation.\n    if (this.#index === 0) {\n      // c: => ['c:/']\n      // C:/ => ['C:/']\n      // C:/x => ['C:/', 'x']\n      // //host/share => ['//host/share/']\n      // //host/share/ => ['//host/share/']\n      // //host/share/x => ['//host/share/', 'x']\n      // /etc => ['/', 'etc']\n      // / => ['/']\n      if (this.isUNC()) {\n        // '' / '' / 'host' / 'share'\n        const [p0, p1, p2, p3, ...prest] = this.#patternList\n        const [g0, g1, g2, g3, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = [p0, p1, p2, p3, ''].join('/')\n        const g = [g0, g1, g2, g3, ''].join('/')\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      } else if (this.isDrive() || this.isAbsolute()) {\n        const [p1, ...prest] = this.#patternList\n        const [g1, ...grest] = this.#globList\n        if (prest[0] === '') {\n          // ends in /\n          prest.shift()\n          grest.shift()\n        }\n        const p = (p1 as string) + '/'\n        const g = g1 + '/'\n        this.#patternList = [p, ...prest]\n        this.#globList = [g, ...grest]\n        this.length = this.#patternList.length\n      }\n    }\n  }\n\n  /**\n   * The first entry in the parsed list of patterns\n   */\n  pattern(): MMPattern {\n    return this.#patternList[this.#index] as MMPattern\n  }\n\n  /**\n   * true of if pattern() returns a string\n   */\n  isString(): boolean {\n    return typeof this.#patternList[this.#index] === 'string'\n  }\n  /**\n   * true of if pattern() returns GLOBSTAR\n   */\n  isGlobstar(): boolean {\n    return this.#patternList[this.#index] === GLOBSTAR\n  }\n  /**\n   * true if pattern() returns a regexp\n   */\n  isRegExp(): boolean {\n    return this.#patternList[this.#index] instanceof RegExp\n  }\n\n  /**\n   * The /-joined set of glob parts that make up this pattern\n   */\n  globString(): string {\n    return (this.#globString =\n      this.#globString ||\n      (this.#index === 0 ?\n        this.isAbsolute() ?\n          this.#globList[0] + this.#globList.slice(1).join('/')\n        : this.#globList.join('/')\n      : this.#globList.slice(this.#index).join('/')))\n  }\n\n  /**\n   * true if there are more pattern parts after this one\n   */\n  hasMore(): boolean {\n    return this.length > this.#index + 1\n  }\n\n  /**\n   * The rest of the pattern after this part, or null if this is the end\n   */\n  rest(): Pattern | null {\n    if (this.#rest !== undefined) return this.#rest\n    if (!this.hasMore()) return (this.#rest = null)\n    this.#rest = new Pattern(\n      this.#patternList,\n      this.#globList,\n      this.#index + 1,\n      this.#platform,\n    )\n    this.#rest.#isAbsolute = this.#isAbsolute\n    this.#rest.#isUNC = this.#isUNC\n    this.#rest.#isDrive = this.#isDrive\n    return this.#rest\n  }\n\n  /**\n   * true if the pattern represents a //unc/path/ on windows\n   */\n  isUNC(): boolean {\n    const pl = this.#patternList\n    return this.#isUNC !== undefined ?\n        this.#isUNC\n      : (this.#isUNC =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          pl[0] === '' &&\n          pl[1] === '' &&\n          typeof pl[2] === 'string' &&\n          !!pl[2] &&\n          typeof pl[3] === 'string' &&\n          !!pl[3])\n  }\n\n  // pattern like C:/...\n  // split = ['C:', ...]\n  // XXX: would be nice to handle patterns like `c:*` to test the cwd\n  // in c: for *, but I don't know of a way to even figure out what that\n  // cwd is without actually chdir'ing into it?\n  /**\n   * True if the pattern starts with a drive letter on Windows\n   */\n  isDrive(): boolean {\n    const pl = this.#patternList\n    return this.#isDrive !== undefined ?\n        this.#isDrive\n      : (this.#isDrive =\n          this.#platform === 'win32' &&\n          this.#index === 0 &&\n          this.length > 1 &&\n          typeof pl[0] === 'string' &&\n          /^[a-z]:$/i.test(pl[0]))\n  }\n\n  // pattern = '/' or '/...' or '/x/...'\n  // split = ['', ''] or ['', ...] or ['', 'x', ...]\n  // Drive and UNC both considered absolute on windows\n  /**\n   * True if the pattern is rooted on an absolute path\n   */\n  isAbsolute(): boolean {\n    const pl = this.#patternList\n    return this.#isAbsolute !== undefined ?\n        this.#isAbsolute\n      : (this.#isAbsolute =\n          (pl[0] === '' && pl.length > 1) ||\n          this.isDrive() ||\n          this.isUNC())\n  }\n\n  /**\n   * consume the root of the pattern, and return it\n   */\n  root(): string {\n    const p = this.#patternList[0]\n    return (\n        typeof p === 'string' && this.isAbsolute() && this.#index === 0\n      ) ?\n        p\n      : ''\n  }\n\n  /**\n   * Check to see if the current globstar pattern is allowed to follow\n   * a symbolic link.\n   */\n  checkFollowGlobstar(): boolean {\n    return !(\n      this.#index === 0 ||\n      !this.isGlobstar() ||\n      !this.#followGlobstar\n    )\n  }\n\n  /**\n   * Mark that the current globstar pattern is following a symbolic link\n   */\n  markFollowGlobstar(): boolean {\n    if (this.#index === 0 || !this.isGlobstar() || !this.#followGlobstar)\n      return false\n    this.#followGlobstar = false\n    return true\n  }\n}\n","// give it a pattern, and it'll be able to tell you if\n// a given path should be ignored.\n// Ignoring a path ignores its children if the pattern ends in /**\n// Ignores are always parsed in dot:true mode\n\nimport { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\nexport interface IgnoreLike {\n  ignored?: (p: Path) => boolean\n  childrenIgnored?: (p: Path) => boolean\n  add?: (ignore: string) => void\n}\n\nconst defaultPlatform: NodeJS.Platform =\n  (\n    typeof process === 'object' &&\n    process &&\n    typeof process.platform === 'string'\n  ) ?\n    process.platform\n  : 'linux'\n\n/**\n * Class used to process ignored patterns\n */\nexport class Ignore implements IgnoreLike {\n  relative: Minimatch[]\n  relativeChildren: Minimatch[]\n  absolute: Minimatch[]\n  absoluteChildren: Minimatch[]\n  platform: NodeJS.Platform\n  mmopts: MinimatchOptions\n\n  constructor(\n    ignored: string[],\n    {\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      platform = defaultPlatform,\n    }: GlobWalkerOpts,\n  ) {\n    this.relative = []\n    this.absolute = []\n    this.relativeChildren = []\n    this.absoluteChildren = []\n    this.platform = platform\n    this.mmopts = {\n      dot: true,\n      nobrace,\n      nocase,\n      noext,\n      noglobstar,\n      optimizationLevel: 2,\n      platform,\n      nocomment: true,\n      nonegate: true,\n    }\n    for (const ign of ignored) this.add(ign)\n  }\n\n  add(ign: string) {\n    // this is a little weird, but it gives us a clean set of optimized\n    // minimatch matchers, without getting tripped up if one of them\n    // ends in /** inside a brace section, and it's only inefficient at\n    // the start of the walk, not along it.\n    // It'd be nice if the Pattern class just had a .test() method, but\n    // handling globstars is a bit of a pita, and that code already lives\n    // in minimatch anyway.\n    // Another way would be if maybe Minimatch could take its set/globParts\n    // as an option, and then we could at least just use Pattern to test\n    // for absolute-ness.\n    // Yet another way, Minimatch could take an array of glob strings, and\n    // a cwd option, and do the right thing.\n    const mm = new Minimatch(ign, this.mmopts)\n    for (let i = 0; i < mm.set.length; i++) {\n      const parsed = mm.set[i]\n      const globParts = mm.globParts[i]\n      /* c8 ignore start */\n      if (!parsed || !globParts) {\n        throw new Error('invalid pattern object')\n      }\n      // strip off leading ./ portions\n      // https://github.com/isaacs/node-glob/issues/570\n      while (parsed[0] === '.' && globParts[0] === '.') {\n        parsed.shift()\n        globParts.shift()\n      }\n      /* c8 ignore stop */\n      const p = new Pattern(parsed, globParts, 0, this.platform)\n      const m = new Minimatch(p.globString(), this.mmopts)\n      const children = globParts[globParts.length - 1] === '**'\n      const absolute = p.isAbsolute()\n      if (absolute) this.absolute.push(m)\n      else this.relative.push(m)\n      if (children) {\n        if (absolute) this.absoluteChildren.push(m)\n        else this.relativeChildren.push(m)\n      }\n    }\n  }\n\n  ignored(p: Path): boolean {\n    const fullpath = p.fullpath()\n    const fullpaths = `${fullpath}/`\n    const relative = p.relative() || '.'\n    const relatives = `${relative}/`\n    for (const m of this.relative) {\n      if (m.match(relative) || m.match(relatives)) return true\n    }\n    for (const m of this.absolute) {\n      if (m.match(fullpath) || m.match(fullpaths)) return true\n    }\n    return false\n  }\n\n  childrenIgnored(p: Path): boolean {\n    const fullpath = p.fullpath() + '/'\n    const relative = (p.relative() || '.') + '/'\n    for (const m of this.relativeChildren) {\n      if (m.match(relative)) return true\n    }\n    for (const m of this.absoluteChildren) {\n      if (m.match(fullpath)) return true\n    }\n    return false\n  }\n}\n","// synchronous utility for filtering entries and calculating subwalks\n\nimport { GLOBSTAR, MMRegExp } from 'minimatch'\nimport { Path } from 'path-scurry'\nimport { MMPattern, Pattern } from './pattern.js'\nimport { GlobWalkerOpts } from './walker.js'\n\n/**\n * A cache of which patterns have been processed for a given Path\n */\nexport class HasWalkedCache {\n  store: Map>\n  constructor(store: Map> = new Map()) {\n    this.store = store\n  }\n  copy() {\n    return new HasWalkedCache(new Map(this.store))\n  }\n  hasWalked(target: Path, pattern: Pattern) {\n    return this.store.get(target.fullpath())?.has(pattern.globString())\n  }\n  storeWalked(target: Path, pattern: Pattern) {\n    const fullpath = target.fullpath()\n    const cached = this.store.get(fullpath)\n    if (cached) cached.add(pattern.globString())\n    else this.store.set(fullpath, new Set([pattern.globString()]))\n  }\n}\n\n/**\n * A record of which paths have been matched in a given walk step,\n * and whether they only are considered a match if they are a directory,\n * and whether their absolute or relative path should be returned.\n */\nexport class MatchRecord {\n  store: Map = new Map()\n  add(target: Path, absolute: boolean, ifDir: boolean) {\n    const n = (absolute ? 2 : 0) | (ifDir ? 1 : 0)\n    const current = this.store.get(target)\n    this.store.set(target, current === undefined ? n : n & current)\n  }\n  // match, absolute, ifdir\n  entries(): [Path, boolean, boolean][] {\n    return [...this.store.entries()].map(([path, n]) => [\n      path,\n      !!(n & 2),\n      !!(n & 1),\n    ])\n  }\n}\n\n/**\n * A collection of patterns that must be processed in a subsequent step\n * for a given path.\n */\nexport class SubWalks {\n  store: Map = new Map()\n  add(target: Path, pattern: Pattern) {\n    if (!target.canReaddir()) {\n      return\n    }\n    const subs = this.store.get(target)\n    if (subs) {\n      if (!subs.find(p => p.globString() === pattern.globString())) {\n        subs.push(pattern)\n      }\n    } else this.store.set(target, [pattern])\n  }\n  get(target: Path): Pattern[] {\n    const subs = this.store.get(target)\n    /* c8 ignore start */\n    if (!subs) {\n      throw new Error('attempting to walk unknown path')\n    }\n    /* c8 ignore stop */\n    return subs\n  }\n  entries(): [Path, Pattern[]][] {\n    return this.keys().map(k => [k, this.store.get(k) as Pattern[]])\n  }\n  keys(): Path[] {\n    return [...this.store.keys()].filter(t => t.canReaddir())\n  }\n}\n\n/**\n * The class that processes patterns for a given path.\n *\n * Handles child entry filtering, and determining whether a path's\n * directory contents must be read.\n */\nexport class Processor {\n  hasWalkedCache: HasWalkedCache\n  matches = new MatchRecord()\n  subwalks = new SubWalks()\n  patterns?: Pattern[]\n  follow: boolean\n  dot: boolean\n  opts: GlobWalkerOpts\n\n  constructor(opts: GlobWalkerOpts, hasWalkedCache?: HasWalkedCache) {\n    this.opts = opts\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.hasWalkedCache =\n      hasWalkedCache ? hasWalkedCache.copy() : new HasWalkedCache()\n  }\n\n  processPatterns(target: Path, patterns: Pattern[]) {\n    this.patterns = patterns\n    const processingSet: [Path, Pattern][] = patterns.map(p => [target, p])\n\n    // map of paths to the magic-starting subwalks they need to walk\n    // first item in patterns is the filter\n\n    for (let [t, pattern] of processingSet) {\n      this.hasWalkedCache.storeWalked(t, pattern)\n\n      const root = pattern.root()\n      const absolute = pattern.isAbsolute() && this.opts.absolute !== false\n\n      // start absolute patterns at root\n      if (root) {\n        t = t.resolve(\n          root === '/' && this.opts.root !== undefined ?\n            this.opts.root\n          : root,\n        )\n        const rest = pattern.rest()\n        if (!rest) {\n          this.matches.add(t, true, false)\n          continue\n        } else {\n          pattern = rest\n        }\n      }\n\n      if (t.isENOENT()) continue\n\n      let p: MMPattern\n      let rest: Pattern | null\n      let changed = false\n      while (\n        typeof (p = pattern.pattern()) === 'string' &&\n        (rest = pattern.rest())\n      ) {\n        const c = t.resolve(p)\n        t = c\n        pattern = rest\n        changed = true\n      }\n      p = pattern.pattern()\n      rest = pattern.rest()\n      if (changed) {\n        if (this.hasWalkedCache.hasWalked(t, pattern)) continue\n        this.hasWalkedCache.storeWalked(t, pattern)\n      }\n\n      // now we have either a final string for a known entry,\n      // more strings for an unknown entry,\n      // or a pattern starting with magic, mounted on t.\n      if (typeof p === 'string') {\n        // must not be final entry, otherwise we would have\n        // concatenated it earlier.\n        const ifDir = p === '..' || p === '' || p === '.'\n        this.matches.add(t.resolve(p), absolute, ifDir)\n        continue\n      } else if (p === GLOBSTAR) {\n        // if no rest, match and subwalk pattern\n        // if rest, process rest and subwalk pattern\n        // if it's a symlink, but we didn't get here by way of a\n        // globstar match (meaning it's the first time THIS globstar\n        // has traversed a symlink), then we follow it. Otherwise, stop.\n        if (\n          !t.isSymbolicLink() ||\n          this.follow ||\n          pattern.checkFollowGlobstar()\n        ) {\n          this.subwalks.add(t, pattern)\n        }\n        const rp = rest?.pattern()\n        const rrest = rest?.rest()\n        if (!rest || ((rp === '' || rp === '.') && !rrest)) {\n          // only HAS to be a dir if it ends in **/ or **/.\n          // but ending in ** will match files as well.\n          this.matches.add(t, absolute, rp === '' || rp === '.')\n        } else {\n          if (rp === '..') {\n            // this would mean you're matching **/.. at the fs root,\n            // and no thanks, I'm not gonna test that specific case.\n            /* c8 ignore start */\n            const tp = t.parent || t\n            /* c8 ignore stop */\n            if (!rrest) this.matches.add(tp, absolute, true)\n            else if (!this.hasWalkedCache.hasWalked(tp, rrest)) {\n              this.subwalks.add(tp, rrest)\n            }\n          }\n        }\n      } else if (p instanceof RegExp) {\n        this.subwalks.add(t, pattern)\n      }\n    }\n\n    return this\n  }\n\n  subwalkTargets(): Path[] {\n    return this.subwalks.keys()\n  }\n\n  child() {\n    return new Processor(this.opts, this.hasWalkedCache)\n  }\n\n  // return a new Processor containing the subwalks for each\n  // child entry, and a set of matches, and\n  // a hasWalkedCache that's a copy of this one\n  // then we're going to call\n  filterEntries(parent: Path, entries: Path[]): Processor {\n    const patterns = this.subwalks.get(parent)\n    // put matches and entry walks into the results processor\n    const results = this.child()\n    for (const e of entries) {\n      for (const pattern of patterns) {\n        const absolute = pattern.isAbsolute()\n        const p = pattern.pattern()\n        const rest = pattern.rest()\n        if (p === GLOBSTAR) {\n          results.testGlobstar(e, pattern, rest, absolute)\n        } else if (p instanceof RegExp) {\n          results.testRegExp(e, p, rest, absolute)\n        } else {\n          results.testString(e, p, rest, absolute)\n        }\n      }\n    }\n    return results\n  }\n\n  testGlobstar(\n    e: Path,\n    pattern: Pattern,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    if (this.dot || !e.name.startsWith('.')) {\n      if (!pattern.hasMore()) {\n        this.matches.add(e, absolute, false)\n      }\n      if (e.canReaddir()) {\n        // if we're in follow mode or it's not a symlink, just keep\n        // testing the same pattern. If there's more after the globstar,\n        // then this symlink consumes the globstar. If not, then we can\n        // follow at most ONE symlink along the way, so we mark it, which\n        // also checks to ensure that it wasn't already marked.\n        if (this.follow || !e.isSymbolicLink()) {\n          this.subwalks.add(e, pattern)\n        } else if (e.isSymbolicLink()) {\n          if (rest && pattern.checkFollowGlobstar()) {\n            this.subwalks.add(e, rest)\n          } else if (pattern.markFollowGlobstar()) {\n            this.subwalks.add(e, pattern)\n          }\n        }\n      }\n    }\n    // if the NEXT thing matches this entry, then also add\n    // the rest.\n    if (rest) {\n      const rp = rest.pattern()\n      if (\n        typeof rp === 'string' &&\n        // dots and empty were handled already\n        rp !== '..' &&\n        rp !== '' &&\n        rp !== '.'\n      ) {\n        this.testString(e, rp, rest.rest(), absolute)\n      } else if (rp === '..') {\n        /* c8 ignore start */\n        const ep = e.parent || e\n        /* c8 ignore stop */\n        this.subwalks.add(ep, rest)\n      } else if (rp instanceof RegExp) {\n        this.testRegExp(e, rp, rest.rest(), absolute)\n      }\n    }\n  }\n\n  testRegExp(\n    e: Path,\n    p: MMRegExp,\n    rest: Pattern | null,\n    absolute: boolean,\n  ) {\n    if (!p.test(e.name)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n\n  testString(e: Path, p: string, rest: Pattern | null, absolute: boolean) {\n    // should never happen?\n    if (!e.isNamed(p)) return\n    if (!rest) {\n      this.matches.add(e, absolute, false)\n    } else {\n      this.subwalks.add(e, rest)\n    }\n  }\n}\n","/**\n * Single-use utility classes to provide functionality to the {@link Glob}\n * methods.\n *\n * @module\n */\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport { Ignore, IgnoreLike } from './ignore.js'\n\n// XXX can we somehow make it so that it NEVER processes a given path more than\n// once, enough that the match set tracking is no longer needed?  that'd speed\n// things up a lot.  Or maybe bring back nounique, and skip it in that case?\n\n// a single minimatch set entry with 1 or more parts\nimport { Pattern } from './pattern.js'\nimport { Processor } from './processor.js'\n\nexport interface GlobWalkerOpts {\n  absolute?: boolean\n  allowWindowsEscape?: boolean\n  cwd?: string | URL\n  dot?: boolean\n  dotRelative?: boolean\n  follow?: boolean\n  ignore?: string | string[] | IgnoreLike\n  mark?: boolean\n  matchBase?: boolean\n  // Note: maxDepth here means \"maximum actual Path.depth()\",\n  // not \"maximum depth beyond cwd\"\n  maxDepth?: number\n  nobrace?: boolean\n  nocase?: boolean\n  nodir?: boolean\n  noext?: boolean\n  noglobstar?: boolean\n  platform?: NodeJS.Platform\n  posix?: boolean\n  realpath?: boolean\n  root?: string\n  stat?: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape?: boolean\n  withFileTypes?: boolean\n  includeChildMatches?: boolean\n}\n\nexport type GWOFileTypesTrue = GlobWalkerOpts & {\n  withFileTypes: true\n}\nexport type GWOFileTypesFalse = GlobWalkerOpts & {\n  withFileTypes: false\n}\nexport type GWOFileTypesUnset = GlobWalkerOpts & {\n  withFileTypes?: undefined\n}\n\nexport type Result =\n  O extends GWOFileTypesTrue ? Path\n  : O extends GWOFileTypesFalse ? string\n  : O extends GWOFileTypesUnset ? string\n  : Path | string\n\nexport type Matches =\n  O extends GWOFileTypesTrue ? Set\n  : O extends GWOFileTypesFalse ? Set\n  : O extends GWOFileTypesUnset ? Set\n  : Set\n\nexport type MatchStream = Minipass<\n  Result,\n  Result\n>\n\nconst makeIgnore = (\n  ignore: string | string[] | IgnoreLike,\n  opts: GlobWalkerOpts,\n): IgnoreLike =>\n  typeof ignore === 'string' ? new Ignore([ignore], opts)\n  : Array.isArray(ignore) ? new Ignore(ignore, opts)\n  : ignore\n\n/**\n * basic walking utilities that all the glob walker types use\n */\nexport abstract class GlobUtil {\n  path: Path\n  patterns: Pattern[]\n  opts: O\n  seen: Set = new Set()\n  paused: boolean = false\n  aborted: boolean = false\n  #onResume: (() => any)[] = []\n  #ignore?: IgnoreLike\n  #sep: '\\\\' | '/'\n  signal?: AbortSignal\n  maxDepth: number\n  includeChildMatches: boolean\n\n  constructor(patterns: Pattern[], path: Path, opts: O)\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    this.patterns = patterns\n    this.path = path\n    this.opts = opts\n    this.#sep = !opts.posix && opts.platform === 'win32' ? '\\\\' : '/'\n    this.includeChildMatches = opts.includeChildMatches !== false\n    if (opts.ignore || !this.includeChildMatches) {\n      this.#ignore = makeIgnore(opts.ignore ?? [], opts)\n      if (\n        !this.includeChildMatches &&\n        typeof this.#ignore.add !== 'function'\n      ) {\n        const m = 'cannot ignore child matches, ignore lacks add() method.'\n        throw new Error(m)\n      }\n    }\n    // ignore, always set with maxDepth, but it's optional on the\n    // GlobOptions type\n    /* c8 ignore start */\n    this.maxDepth = opts.maxDepth || Infinity\n    /* c8 ignore stop */\n    if (opts.signal) {\n      this.signal = opts.signal\n      this.signal.addEventListener('abort', () => {\n        this.#onResume.length = 0\n      })\n    }\n  }\n\n  #ignored(path: Path): boolean {\n    return this.seen.has(path) || !!this.#ignore?.ignored?.(path)\n  }\n  #childrenIgnored(path: Path): boolean {\n    return !!this.#ignore?.childrenIgnored?.(path)\n  }\n\n  // backpressure mechanism\n  pause() {\n    this.paused = true\n  }\n  resume() {\n    /* c8 ignore start */\n    if (this.signal?.aborted) return\n    /* c8 ignore stop */\n    this.paused = false\n    let fn: (() => any) | undefined = undefined\n    while (!this.paused && (fn = this.#onResume.shift())) {\n      fn()\n    }\n  }\n  onResume(fn: () => any) {\n    if (this.signal?.aborted) return\n    /* c8 ignore start */\n    if (!this.paused) {\n      fn()\n    } else {\n      /* c8 ignore stop */\n      this.#onResume.push(fn)\n    }\n  }\n\n  // do the requisite realpath/stat checking, and return the path\n  // to add or undefined to filter it out.\n  async matchCheck(e: Path, ifDir: boolean): Promise {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    if (this.opts.realpath) {\n      rpc = e.realpathCached() || (await e.realpath())\n      if (!rpc) return undefined\n      e = rpc\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? await e.lstat() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = await s.realpath()\n      /* c8 ignore start */\n      if (target && (target.isUnknown() || this.opts.stat)) {\n        await target.lstat()\n      }\n      /* c8 ignore stop */\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  matchCheckTest(e: Path | undefined, ifDir: boolean): Path | undefined {\n    return (\n        e &&\n          (this.maxDepth === Infinity || e.depth() <= this.maxDepth) &&\n          (!ifDir || e.canReaddir()) &&\n          (!this.opts.nodir || !e.isDirectory()) &&\n          (!this.opts.nodir ||\n            !this.opts.follow ||\n            !e.isSymbolicLink() ||\n            !e.realpathCached()?.isDirectory()) &&\n          !this.#ignored(e)\n      ) ?\n        e\n      : undefined\n  }\n\n  matchCheckSync(e: Path, ifDir: boolean): Path | undefined {\n    if (ifDir && this.opts.nodir) return undefined\n    let rpc: Path | undefined\n    if (this.opts.realpath) {\n      rpc = e.realpathCached() || e.realpathSync()\n      if (!rpc) return undefined\n      e = rpc\n    }\n    const needStat = e.isUnknown() || this.opts.stat\n    const s = needStat ? e.lstatSync() : e\n    if (this.opts.follow && this.opts.nodir && s?.isSymbolicLink()) {\n      const target = s.realpathSync()\n      if (target && (target?.isUnknown() || this.opts.stat)) {\n        target.lstatSync()\n      }\n    }\n    return this.matchCheckTest(s, ifDir)\n  }\n\n  abstract matchEmit(p: Result): void\n  abstract matchEmit(p: string | Path): void\n\n  matchFinish(e: Path, absolute: boolean) {\n    if (this.#ignored(e)) return\n    // we know we have an ignore if this is false, but TS doesn't\n    if (!this.includeChildMatches && this.#ignore?.add) {\n      const ign = `${e.relativePosix()}/**`\n      this.#ignore.add(ign)\n    }\n    const abs =\n      this.opts.absolute === undefined ? absolute : this.opts.absolute\n    this.seen.add(e)\n    const mark = this.opts.mark && e.isDirectory() ? this.#sep : ''\n    // ok, we have what we need!\n    if (this.opts.withFileTypes) {\n      this.matchEmit(e)\n    } else if (abs) {\n      const abs = this.opts.posix ? e.fullpathPosix() : e.fullpath()\n      this.matchEmit(abs + mark)\n    } else {\n      const rel = this.opts.posix ? e.relativePosix() : e.relative()\n      const pre =\n        this.opts.dotRelative && !rel.startsWith('..' + this.#sep) ?\n          '.' + this.#sep\n        : ''\n      this.matchEmit(!rel ? '.' + mark : pre + rel + mark)\n    }\n  }\n\n  async match(e: Path, absolute: boolean, ifDir: boolean): Promise {\n    const p = await this.matchCheck(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  matchSync(e: Path, absolute: boolean, ifDir: boolean): void {\n    const p = this.matchCheckSync(e, ifDir)\n    if (p) this.matchFinish(p, absolute)\n  }\n\n  walkCB(target: Path, patterns: Pattern[], cb: () => any) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) cb()\n    /* c8 ignore stop */\n    this.walkCB2(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) cb()\n    if (this.paused) {\n      this.onResume(() => this.walkCB2(target, patterns, processor, cb))\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      tasks++\n      this.match(m, absolute, ifDir).then(() => next())\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const childrenCached = t.readdirCached()\n      if (t.calledReaddir())\n        this.walkCB3(t, childrenCached, processor, next)\n      else {\n        t.readdirCB(\n          (_, entries) => this.walkCB3(t, entries, processor, next),\n          true,\n        )\n      }\n    }\n\n    next()\n  }\n\n  walkCB3(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    processor = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      tasks++\n      this.match(m, absolute, ifDir).then(() => next())\n    }\n    for (const [target, patterns] of processor.subwalks.entries()) {\n      tasks++\n      this.walkCB2(target, patterns, processor.child(), next)\n    }\n\n    next()\n  }\n\n  walkCBSync(target: Path, patterns: Pattern[], cb: () => any) {\n    /* c8 ignore start */\n    if (this.signal?.aborted) cb()\n    /* c8 ignore stop */\n    this.walkCB2Sync(target, patterns, new Processor(this.opts), cb)\n  }\n\n  walkCB2Sync(\n    target: Path,\n    patterns: Pattern[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    if (this.#childrenIgnored(target)) return cb()\n    if (this.signal?.aborted) cb()\n    if (this.paused) {\n      this.onResume(() =>\n        this.walkCB2Sync(target, patterns, processor, cb),\n      )\n      return\n    }\n    processor.processPatterns(target, patterns)\n\n    // done processing.  all of the above is sync, can be abstracted out.\n    // subwalks is a map of paths to the entry filters they need\n    // matches is a map of paths to [absolute, ifDir] tuples.\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, absolute, ifDir)\n    }\n\n    for (const t of processor.subwalkTargets()) {\n      if (this.maxDepth !== Infinity && t.depth() >= this.maxDepth) {\n        continue\n      }\n      tasks++\n      const children = t.readdirSync()\n      this.walkCB3Sync(t, children, processor, next)\n    }\n\n    next()\n  }\n\n  walkCB3Sync(\n    target: Path,\n    entries: Path[],\n    processor: Processor,\n    cb: () => any,\n  ) {\n    processor = processor.filterEntries(target, entries)\n\n    let tasks = 1\n    const next = () => {\n      if (--tasks === 0) cb()\n    }\n\n    for (const [m, absolute, ifDir] of processor.matches.entries()) {\n      if (this.#ignored(m)) continue\n      this.matchSync(m, absolute, ifDir)\n    }\n    for (const [target, patterns] of processor.subwalks.entries()) {\n      tasks++\n      this.walkCB2Sync(target, patterns, processor.child(), next)\n    }\n\n    next()\n  }\n}\n\nexport class GlobWalker<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  matches = new Set>()\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n  }\n\n  matchEmit(e: Result): void {\n    this.matches.add(e)\n  }\n\n  async walk(): Promise>> {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      await this.path.lstat()\n    }\n    await new Promise((res, rej) => {\n      this.walkCB(this.path, this.patterns, () => {\n        if (this.signal?.aborted) {\n          rej(this.signal.reason)\n        } else {\n          res(this.matches)\n        }\n      })\n    })\n    return this.matches\n  }\n\n  walkSync(): Set> {\n    if (this.signal?.aborted) throw this.signal.reason\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    // nothing for the callback to do, because this never pauses\n    this.walkCBSync(this.path, this.patterns, () => {\n      if (this.signal?.aborted) throw this.signal.reason\n    })\n    return this.matches\n  }\n}\n\nexport class GlobStream<\n  O extends GlobWalkerOpts = GlobWalkerOpts,\n> extends GlobUtil {\n  results: Minipass, Result>\n\n  constructor(patterns: Pattern[], path: Path, opts: O) {\n    super(patterns, path, opts)\n    this.results = new Minipass, Result>({\n      signal: this.signal,\n      objectMode: true,\n    })\n    this.results.on('drain', () => this.resume())\n    this.results.on('resume', () => this.resume())\n  }\n\n  matchEmit(e: Result): void {\n    this.results.write(e)\n    if (!this.results.flowing) this.pause()\n  }\n\n  stream(): MatchStream {\n    const target = this.path\n    if (target.isUnknown()) {\n      target.lstat().then(() => {\n        this.walkCB(target, this.patterns, () => this.results.end())\n      })\n    } else {\n      this.walkCB(target, this.patterns, () => this.results.end())\n    }\n    return this.results\n  }\n\n  streamSync(): MatchStream {\n    if (this.path.isUnknown()) {\n      this.path.lstatSync()\n    }\n    this.walkCBSync(this.path, this.patterns, () => this.results.end())\n    return this.results\n  }\n}\n","import { Minimatch, MinimatchOptions } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { fileURLToPath } from 'node:url'\nimport {\n  FSOption,\n  Path,\n  PathScurry,\n  PathScurryDarwin,\n  PathScurryPosix,\n  PathScurryWin32,\n} from 'path-scurry'\nimport { IgnoreLike } from './ignore.js'\nimport { Pattern } from './pattern.js'\nimport { GlobStream, GlobWalker } from './walker.js'\n\nexport type MatchSet = Minimatch['set']\nexport type GlobParts = Exclude\n\n// if no process global, just call it linux.\n// so we default to case-sensitive, / separators\nconst defaultPlatform: NodeJS.Platform =\n  (\n    typeof process === 'object' &&\n    process &&\n    typeof process.platform === 'string'\n  ) ?\n    process.platform\n  : 'linux'\n\n/**\n * A `GlobOptions` object may be provided to any of the exported methods, and\n * must be provided to the `Glob` constructor.\n *\n * All options are optional, boolean, and false by default, unless otherwise\n * noted.\n *\n * All resolved options are added to the Glob object as properties.\n *\n * If you are running many `glob` operations, you can pass a Glob object as the\n * `options` argument to a subsequent operation to share the previously loaded\n * cache.\n */\nexport interface GlobOptions {\n  /**\n   * Set to `true` to always receive absolute paths for\n   * matched files. Set to `false` to always return relative paths.\n   *\n   * When this option is not set, absolute paths are returned for patterns\n   * that are absolute, and otherwise paths are returned that are relative\n   * to the `cwd` setting.\n   *\n   * This does _not_ make an extra system call to get\n   * the realpath, it only does string path resolution.\n   *\n   * Conflicts with {@link withFileTypes}\n   */\n  absolute?: boolean\n\n  /**\n   * Set to false to enable {@link windowsPathsNoEscape}\n   *\n   * @deprecated\n   */\n  allowWindowsEscape?: boolean\n\n  /**\n   * The current working directory in which to search. Defaults to\n   * `process.cwd()`.\n   *\n   * May be eiher a string path or a `file://` URL object or string.\n   */\n  cwd?: string | URL\n\n  /**\n   * Include `.dot` files in normal matches and `globstar`\n   * matches. Note that an explicit dot in a portion of the pattern\n   * will always match dot files.\n   */\n  dot?: boolean\n\n  /**\n   * Prepend all relative path strings with `./` (or `.\\` on Windows).\n   *\n   * Without this option, returned relative paths are \"bare\", so instead of\n   * returning `'./foo/bar'`, they are returned as `'foo/bar'`.\n   *\n   * Relative patterns starting with `'../'` are not prepended with `./`, even\n   * if this option is set.\n   */\n  dotRelative?: boolean\n\n  /**\n   * Follow symlinked directories when expanding `**`\n   * patterns. This can result in a lot of duplicate references in\n   * the presence of cyclic links, and make performance quite bad.\n   *\n   * By default, a `**` in a pattern will follow 1 symbolic link if\n   * it is not the first item in the pattern, or none if it is the\n   * first item in the pattern, following the same behavior as Bash.\n   */\n  follow?: boolean\n\n  /**\n   * string or string[], or an object with `ignore` and `ignoreChildren`\n   * methods.\n   *\n   * If a string or string[] is provided, then this is treated as a glob\n   * pattern or array of glob patterns to exclude from matches. To ignore all\n   * children within a directory, as well as the entry itself, append `'/**'`\n   * to the ignore pattern.\n   *\n   * **Note** `ignore` patterns are _always_ in `dot:true` mode, regardless of\n   * any other settings.\n   *\n   * If an object is provided that has `ignored(path)` and/or\n   * `childrenIgnored(path)` methods, then these methods will be called to\n   * determine whether any Path is a match or if its children should be\n   * traversed, respectively.\n   */\n  ignore?: string | string[] | IgnoreLike\n\n  /**\n   * Treat brace expansion like `{a,b}` as a \"magic\" pattern. Has no\n   * effect if {@link nobrace} is set.\n   *\n   * Only has effect on the {@link hasMagic} function.\n   */\n  magicalBraces?: boolean\n\n  /**\n   * Add a `/` character to directory matches. Note that this requires\n   * additional stat calls in some cases.\n   */\n  mark?: boolean\n\n  /**\n   * Perform a basename-only match if the pattern does not contain any slash\n   * characters. That is, `*.js` would be treated as equivalent to\n   * `**\\/*.js`, matching all js files in all directories.\n   */\n  matchBase?: boolean\n\n  /**\n   * Limit the directory traversal to a given depth below the cwd.\n   * Note that this does NOT prevent traversal to sibling folders,\n   * root patterns, and so on. It only limits the maximum folder depth\n   * that the walk will descend, relative to the cwd.\n   */\n  maxDepth?: number\n\n  /**\n   * Do not expand `{a,b}` and `{1..3}` brace sets.\n   */\n  nobrace?: boolean\n\n  /**\n   * Perform a case-insensitive match. This defaults to `true` on macOS and\n   * Windows systems, and `false` on all others.\n   *\n   * **Note** `nocase` should only be explicitly set when it is\n   * known that the filesystem's case sensitivity differs from the\n   * platform default. If set `true` on case-sensitive file\n   * systems, or `false` on case-insensitive file systems, then the\n   * walk may return more or less results than expected.\n   */\n  nocase?: boolean\n\n  /**\n   * Do not match directories, only files. (Note: to match\n   * _only_ directories, put a `/` at the end of the pattern.)\n   */\n  nodir?: boolean\n\n  /**\n   * Do not match \"extglob\" patterns such as `+(a|b)`.\n   */\n  noext?: boolean\n\n  /**\n   * Do not match `**` against multiple filenames. (Ie, treat it as a normal\n   * `*` instead.)\n   *\n   * Conflicts with {@link matchBase}\n   */\n  noglobstar?: boolean\n\n  /**\n   * Defaults to value of `process.platform` if available, or `'linux'` if\n   * not. Setting `platform:'win32'` on non-Windows systems may cause strange\n   * behavior.\n   */\n  platform?: NodeJS.Platform\n\n  /**\n   * Set to true to call `fs.realpath` on all of the\n   * results. In the case of an entry that cannot be resolved, the\n   * entry is omitted. This incurs a slight performance penalty, of\n   * course, because of the added system calls.\n   */\n  realpath?: boolean\n\n  /**\n   *\n   * A string path resolved against the `cwd` option, which\n   * is used as the starting point for absolute patterns that start\n   * with `/`, (but not drive letters or UNC paths on Windows).\n   *\n   * Note that this _doesn't_ necessarily limit the walk to the\n   * `root` directory, and doesn't affect the cwd starting point for\n   * non-absolute patterns. A pattern containing `..` will still be\n   * able to traverse out of the root directory, if it is not an\n   * actual root directory on the filesystem, and any non-absolute\n   * patterns will be matched in the `cwd`. For example, the\n   * pattern `/../*` with `{root:'/some/path'}` will return all\n   * files in `/some`, not all files in `/some/path`. The pattern\n   * `*` with `{root:'/some/path'}` will return all the entries in\n   * the cwd, not the entries in `/some/path`.\n   *\n   * To start absolute and non-absolute patterns in the same\n   * path, you can use `{root:''}`. However, be aware that on\n   * Windows systems, a pattern like `x:/*` or `//host/share/*` will\n   * _always_ start in the `x:/` or `//host/share` directory,\n   * regardless of the `root` setting.\n   */\n  root?: string\n\n  /**\n   * A [PathScurry](http://npm.im/path-scurry) object used\n   * to traverse the file system. If the `nocase` option is set\n   * explicitly, then any provided `scurry` object must match this\n   * setting.\n   */\n  scurry?: PathScurry\n\n  /**\n   * Call `lstat()` on all entries, whether required or not to determine\n   * if it's a valid match. When used with {@link withFileTypes}, this means\n   * that matches will include data such as modified time, permissions, and\n   * so on.  Note that this will incur a performance cost due to the added\n   * system calls.\n   */\n  stat?: boolean\n\n  /**\n   * An AbortSignal which will cancel the Glob walk when\n   * triggered.\n   */\n  signal?: AbortSignal\n\n  /**\n   * Use `\\\\` as a path separator _only_, and\n   *  _never_ as an escape character. If set, all `\\\\` characters are\n   *  replaced with `/` in the pattern.\n   *\n   *  Note that this makes it **impossible** to match against paths\n   *  containing literal glob pattern characters, but allows matching\n   *  with patterns constructed using `path.join()` and\n   *  `path.resolve()` on Windows platforms, mimicking the (buggy!)\n   *  behavior of Glob v7 and before on Windows. Please use with\n   *  caution, and be mindful of [the caveat below about Windows\n   *  paths](#windows). (For legacy reasons, this is also set if\n   *  `allowWindowsEscape` is set to the exact value `false`.)\n   */\n  windowsPathsNoEscape?: boolean\n\n  /**\n   * Return [PathScurry](http://npm.im/path-scurry)\n   * `Path` objects instead of strings. These are similar to a\n   * NodeJS `Dirent` object, but with additional methods and\n   * properties.\n   *\n   * Conflicts with {@link absolute}\n   */\n  withFileTypes?: boolean\n\n  /**\n   * An fs implementation to override some or all of the defaults.  See\n   * http://npm.im/path-scurry for details about what can be overridden.\n   */\n  fs?: FSOption\n\n  /**\n   * Just passed along to Minimatch.  Note that this makes all pattern\n   * matching operations slower and *extremely* noisy.\n   */\n  debug?: boolean\n\n  /**\n   * Return `/` delimited paths, even on Windows.\n   *\n   * On posix systems, this has no effect.  But, on Windows, it means that\n   * paths will be `/` delimited, and absolute paths will be their full\n   * resolved UNC forms, eg instead of `'C:\\\\foo\\\\bar'`, it would return\n   * `'//?/C:/foo/bar'`\n   */\n  posix?: boolean\n\n  /**\n   * Do not match any children of any matches. For example, the pattern\n   * `**\\/foo` would match `a/foo`, but not `a/foo/b/foo` in this mode.\n   *\n   * This is especially useful for cases like \"find all `node_modules`\n   * folders, but not the ones in `node_modules`\".\n   *\n   * In order to support this, the `Ignore` implementation must support an\n   * `add(pattern: string)` method. If using the default `Ignore` class, then\n   * this is fine, but if this is set to `false`, and a custom `Ignore` is\n   * provided that does not have an `add()` method, then it will throw an\n   * error.\n   *\n   * **Caveat** It *only* ignores matches that would be a descendant of a\n   * previous match, and only if that descendant is matched *after* the\n   * ancestor is encountered. Since the file system walk happens in\n   * indeterminate order, it's possible that a match will already be added\n   * before its ancestor, if multiple or braced patterns are used.\n   *\n   * For example:\n   *\n   * ```ts\n   * const results = await glob([\n   *   // likely to match first, since it's just a stat\n   *   'a/b/c/d/e/f',\n   *\n   *   // this pattern is more complicated! It must to various readdir()\n   *   // calls and test the results against a regular expression, and that\n   *   // is certainly going to take a little bit longer.\n   *   //\n   *   // So, later on, it encounters a match at 'a/b/c/d/e', but it's too\n   *   // late to ignore a/b/c/d/e/f, because it's already been emitted.\n   *   'a/[bdf]/?/[a-z]/*',\n   * ], { includeChildMatches: false })\n   * ```\n   *\n   * It's best to only set this to `false` if you can be reasonably sure that\n   * no components of the pattern will potentially match one another's file\n   * system descendants, or if the occasional included child entry will not\n   * cause problems.\n   *\n   * @default true\n   */\n  includeChildMatches?: boolean\n}\n\nexport type GlobOptionsWithFileTypesTrue = GlobOptions & {\n  withFileTypes: true\n  // string options not relevant if returning Path objects.\n  absolute?: undefined\n  mark?: undefined\n  posix?: undefined\n}\n\nexport type GlobOptionsWithFileTypesFalse = GlobOptions & {\n  withFileTypes?: false\n}\n\nexport type GlobOptionsWithFileTypesUnset = GlobOptions & {\n  withFileTypes?: undefined\n}\n\nexport type Result =\n  Opts extends GlobOptionsWithFileTypesTrue ? Path\n  : Opts extends GlobOptionsWithFileTypesFalse ? string\n  : Opts extends GlobOptionsWithFileTypesUnset ? string\n  : string | Path\nexport type Results = Result[]\n\nexport type FileTypes =\n  Opts extends GlobOptionsWithFileTypesTrue ? true\n  : Opts extends GlobOptionsWithFileTypesFalse ? false\n  : Opts extends GlobOptionsWithFileTypesUnset ? false\n  : boolean\n\n/**\n * An object that can perform glob pattern traversals.\n */\nexport class Glob implements GlobOptions {\n  absolute?: boolean\n  cwd: string\n  root?: string\n  dot: boolean\n  dotRelative: boolean\n  follow: boolean\n  ignore?: string | string[] | IgnoreLike\n  magicalBraces: boolean\n  mark?: boolean\n  matchBase: boolean\n  maxDepth: number\n  nobrace: boolean\n  nocase: boolean\n  nodir: boolean\n  noext: boolean\n  noglobstar: boolean\n  pattern: string[]\n  platform: NodeJS.Platform\n  realpath: boolean\n  scurry: PathScurry\n  stat: boolean\n  signal?: AbortSignal\n  windowsPathsNoEscape: boolean\n  withFileTypes: FileTypes\n  includeChildMatches: boolean\n\n  /**\n   * The options provided to the constructor.\n   */\n  opts: Opts\n\n  /**\n   * An array of parsed immutable {@link Pattern} objects.\n   */\n  patterns: Pattern[]\n\n  /**\n   * All options are stored as properties on the `Glob` object.\n   *\n   * See {@link GlobOptions} for full options descriptions.\n   *\n   * Note that a previous `Glob` object can be passed as the\n   * `GlobOptions` to another `Glob` instantiation to re-use settings\n   * and caches with a new pattern.\n   *\n   * Traversal functions can be called multiple times to run the walk\n   * again.\n   */\n  constructor(pattern: string | string[], opts: Opts) {\n    /* c8 ignore start */\n    if (!opts) throw new TypeError('glob options required')\n    /* c8 ignore stop */\n    this.withFileTypes = !!opts.withFileTypes as FileTypes\n    this.signal = opts.signal\n    this.follow = !!opts.follow\n    this.dot = !!opts.dot\n    this.dotRelative = !!opts.dotRelative\n    this.nodir = !!opts.nodir\n    this.mark = !!opts.mark\n    if (!opts.cwd) {\n      this.cwd = ''\n    } else if (opts.cwd instanceof URL || opts.cwd.startsWith('file://')) {\n      opts.cwd = fileURLToPath(opts.cwd)\n    }\n    this.cwd = opts.cwd || ''\n    this.root = opts.root\n    this.magicalBraces = !!opts.magicalBraces\n    this.nobrace = !!opts.nobrace\n    this.noext = !!opts.noext\n    this.realpath = !!opts.realpath\n    this.absolute = opts.absolute\n    this.includeChildMatches = opts.includeChildMatches !== false\n\n    this.noglobstar = !!opts.noglobstar\n    this.matchBase = !!opts.matchBase\n    this.maxDepth =\n      typeof opts.maxDepth === 'number' ? opts.maxDepth : Infinity\n    this.stat = !!opts.stat\n    this.ignore = opts.ignore\n\n    if (this.withFileTypes && this.absolute !== undefined) {\n      throw new Error('cannot set absolute and withFileTypes:true')\n    }\n\n    if (typeof pattern === 'string') {\n      pattern = [pattern]\n    }\n\n    this.windowsPathsNoEscape =\n      !!opts.windowsPathsNoEscape ||\n      (opts as { allowWindowsEscape?: boolean }).allowWindowsEscape ===\n        false\n\n    if (this.windowsPathsNoEscape) {\n      pattern = pattern.map(p => p.replace(/\\\\/g, '/'))\n    }\n\n    if (this.matchBase) {\n      if (opts.noglobstar) {\n        throw new TypeError('base matching requires globstar')\n      }\n      pattern = pattern.map(p => (p.includes('/') ? p : `./**/${p}`))\n    }\n\n    this.pattern = pattern\n\n    this.platform = opts.platform || defaultPlatform\n    this.opts = { ...opts, platform: this.platform }\n    if (opts.scurry) {\n      this.scurry = opts.scurry\n      if (\n        opts.nocase !== undefined &&\n        opts.nocase !== opts.scurry.nocase\n      ) {\n        throw new Error('nocase option contradicts provided scurry option')\n      }\n    } else {\n      const Scurry =\n        opts.platform === 'win32' ? PathScurryWin32\n        : opts.platform === 'darwin' ? PathScurryDarwin\n        : opts.platform ? PathScurryPosix\n        : PathScurry\n      this.scurry = new Scurry(this.cwd, {\n        nocase: opts.nocase,\n        fs: opts.fs,\n      })\n    }\n    this.nocase = this.scurry.nocase\n\n    // If you do nocase:true on a case-sensitive file system, then\n    // we need to use regexps instead of strings for non-magic\n    // path portions, because statting `aBc` won't return results\n    // for the file `AbC` for example.\n    const nocaseMagicOnly =\n      this.platform === 'darwin' || this.platform === 'win32'\n\n    const mmo: MinimatchOptions = {\n      // default nocase based on platform\n      ...opts,\n      dot: this.dot,\n      matchBase: this.matchBase,\n      nobrace: this.nobrace,\n      nocase: this.nocase,\n      nocaseMagicOnly,\n      nocomment: true,\n      noext: this.noext,\n      nonegate: true,\n      optimizationLevel: 2,\n      platform: this.platform,\n      windowsPathsNoEscape: this.windowsPathsNoEscape,\n      debug: !!this.opts.debug,\n    }\n\n    const mms = this.pattern.map(p => new Minimatch(p, mmo))\n    const [matchSet, globParts] = mms.reduce(\n      (set: [MatchSet, GlobParts], m) => {\n        set[0].push(...m.set)\n        set[1].push(...m.globParts)\n        return set\n      },\n      [[], []],\n    )\n    this.patterns = matchSet.map((set, i) => {\n      const g = globParts[i]\n      /* c8 ignore start */\n      if (!g) throw new Error('invalid pattern object')\n      /* c8 ignore stop */\n      return new Pattern(set, g, 0, this.platform)\n    })\n  }\n\n  /**\n   * Returns a Promise that resolves to the results array.\n   */\n  async walk(): Promise>\n  async walk(): Promise<(string | Path)[]> {\n    // Walkers always return array of Path objects, so we just have to\n    // coerce them into the right shape.  It will have already called\n    // realpath() if the option was set to do so, so we know that's cached.\n    // start out knowing the cwd, at least\n    return [\n      ...(await new GlobWalker(this.patterns, this.scurry.cwd, {\n        ...this.opts,\n        maxDepth:\n          this.maxDepth !== Infinity ?\n            this.maxDepth + this.scurry.cwd.depth()\n          : Infinity,\n        platform: this.platform,\n        nocase: this.nocase,\n        includeChildMatches: this.includeChildMatches,\n      }).walk()),\n    ]\n  }\n\n  /**\n   * synchronous {@link Glob.walk}\n   */\n  walkSync(): Results\n  walkSync(): (string | Path)[] {\n    return [\n      ...new GlobWalker(this.patterns, this.scurry.cwd, {\n        ...this.opts,\n        maxDepth:\n          this.maxDepth !== Infinity ?\n            this.maxDepth + this.scurry.cwd.depth()\n          : Infinity,\n        platform: this.platform,\n        nocase: this.nocase,\n        includeChildMatches: this.includeChildMatches,\n      }).walkSync(),\n    ]\n  }\n\n  /**\n   * Stream results asynchronously.\n   */\n  stream(): Minipass, Result>\n  stream(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).stream()\n  }\n\n  /**\n   * Stream results synchronously.\n   */\n  streamSync(): Minipass, Result>\n  streamSync(): Minipass {\n    return new GlobStream(this.patterns, this.scurry.cwd, {\n      ...this.opts,\n      maxDepth:\n        this.maxDepth !== Infinity ?\n          this.maxDepth + this.scurry.cwd.depth()\n        : Infinity,\n      platform: this.platform,\n      nocase: this.nocase,\n      includeChildMatches: this.includeChildMatches,\n    }).streamSync()\n  }\n\n  /**\n   * Default sync iteration function. Returns a Generator that\n   * iterates over the results.\n   */\n  iterateSync(): Generator, void, void> {\n    return this.streamSync()[Symbol.iterator]()\n  }\n  [Symbol.iterator]() {\n    return this.iterateSync()\n  }\n\n  /**\n   * Default async iteration function. Returns an AsyncGenerator that\n   * iterates over the results.\n   */\n  iterate(): AsyncGenerator, void, void> {\n    return this.stream()[Symbol.asyncIterator]()\n  }\n  [Symbol.asyncIterator]() {\n    return this.iterate()\n  }\n}\n","import { Minimatch } from 'minimatch'\nimport { GlobOptions } from './glob.js'\n\n/**\n * Return true if the patterns provided contain any magic glob characters,\n * given the options provided.\n *\n * Brace expansion is not considered \"magic\" unless the `magicalBraces` option\n * is set, as brace expansion just turns one string into an array of strings.\n * So a pattern like `'x{a,b}y'` would return `false`, because `'xay'` and\n * `'xby'` both do not contain any magic glob characters, and it's treated the\n * same as if you had called it on `['xay', 'xby']`. When `magicalBraces:true`\n * is in the options, brace expansion _is_ treated as a pattern having magic.\n */\nexport const hasMagic = (\n  pattern: string | string[],\n  options: GlobOptions = {},\n): boolean => {\n  if (!Array.isArray(pattern)) {\n    pattern = [pattern]\n  }\n  for (const p of pattern) {\n    if (new Minimatch(p, options).hasMagic()) return true\n  }\n  return false\n}\n","import { escape, unescape } from 'minimatch'\nimport { Minipass } from 'minipass'\nimport { Path } from 'path-scurry'\nimport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nimport { Glob } from './glob.js'\nimport { hasMagic } from './has-magic.js'\n\nexport { escape, unescape } from 'minimatch'\nexport type {\n  FSOption,\n  Path,\n  WalkOptions,\n  WalkOptionsWithFileTypesTrue,\n  WalkOptionsWithFileTypesUnset,\n} from 'path-scurry'\nexport { Glob } from './glob.js'\nexport type {\n  GlobOptions,\n  GlobOptionsWithFileTypesFalse,\n  GlobOptionsWithFileTypesTrue,\n  GlobOptionsWithFileTypesUnset,\n} from './glob.js'\nexport { hasMagic } from './has-magic.js'\nexport { Ignore } from './ignore.js'\nexport type { IgnoreLike } from './ignore.js'\nexport type { MatchStream } from './walker.js'\n\n/**\n * Syncronous form of {@link globStream}. Will read all the matches as fast as\n * you consume them, even all in a single tick if you consume them immediately,\n * but will still respond to backpressure if they're not consumed immediately.\n */\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesUnset,\n): Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Minipass | Minipass\nexport function globStreamSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).streamSync()\n}\n\n/**\n * Return a stream that emits all the strings or `Path` objects and\n * then emits `end` when completed.\n */\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions,\n): Minipass | Minipass\nexport function globStream(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).stream()\n}\n\n/**\n * Synchronous form of {@link glob}\n */\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Path[]\nexport function globSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Path[] | string[]\nexport function globSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).walkSync()\n}\n\n/**\n * Perform an asynchronous glob search for the pattern(s) specified. Returns\n * [Path](https://isaacs.github.io/path-scurry/classes/PathBase) objects if the\n * {@link withFileTypes} option is set to `true`. See {@link GlobOptions} for\n * full option descriptions.\n */\nasync function glob_(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions,\n): Promise\nasync function glob_(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).walk()\n}\n\n/**\n * Return a sync iterator for walking glob pattern matches.\n */\nexport function globIterateSync(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions,\n): Generator | Generator\nexport function globIterateSync(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).iterateSync()\n}\n\n/**\n * Return an async iterator for walking glob pattern matches.\n */\nexport function globIterate(\n  pattern: string | string[],\n  options?: GlobOptionsWithFileTypesUnset | undefined,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesTrue,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptionsWithFileTypesFalse,\n): AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions,\n): AsyncGenerator | AsyncGenerator\nexport function globIterate(\n  pattern: string | string[],\n  options: GlobOptions = {},\n) {\n  return new Glob(pattern, options).iterate()\n}\n\n// aliases: glob.sync.stream() glob.stream.sync() glob.sync() etc\nexport const streamSync = globStreamSync\nexport const stream = Object.assign(globStream, { sync: globStreamSync })\nexport const iterateSync = globIterateSync\nexport const iterate = Object.assign(globIterate, {\n  sync: globIterateSync,\n})\nexport const sync = Object.assign(globSync, {\n  stream: globStreamSync,\n  iterate: globIterateSync,\n})\n\nexport const glob = Object.assign(glob_, {\n  glob: glob_,\n  globSync,\n  sync,\n  globStream,\n  stream,\n  globStreamSync,\n  streamSync,\n  globIterate,\n  iterate,\n  globIterateSync,\n  iterateSync,\n  Glob,\n  hasMagic,\n  escape,\n  unescape,\n})\nglob.glob = glob\n","/**\n * archiver-utils\n *\n * Copyright (c) 2012-2014 Chris Talkington, contributors.\n * Licensed under the MIT license.\n * https://github.com/archiverjs/node-archiver/blob/master/LICENSE-MIT\n */\nvar fs = require('graceful-fs');\nvar path = require('path');\n\nvar flatten = require('lodash/flatten');\nvar difference = require('lodash/difference');\nvar union = require('lodash/union');\nvar isPlainObject = require('lodash/isPlainObject');\n\nvar glob = require('glob');\n\nvar file = module.exports = {};\n\nvar pathSeparatorRe = /[\\/\\\\]/g;\n\n// Process specified wildcard glob patterns or filenames against a\n// callback, excluding and uniquing files in the result set.\nvar processPatterns = function(patterns, fn) {\n  // Filepaths to return.\n  var result = [];\n  // Iterate over flattened patterns array.\n  flatten(patterns).forEach(function(pattern) {\n    // If the first character is ! it should be omitted\n    var exclusion = pattern.indexOf('!') === 0;\n    // If the pattern is an exclusion, remove the !\n    if (exclusion) { pattern = pattern.slice(1); }\n    // Find all matching files for this pattern.\n    var matches = fn(pattern);\n    if (exclusion) {\n      // If an exclusion, remove matching files.\n      result = difference(result, matches);\n    } else {\n      // Otherwise add matching files.\n      result = union(result, matches);\n    }\n  });\n  return result;\n};\n\n// True if the file path exists.\nfile.exists = function() {\n  var filepath = path.join.apply(path, arguments);\n  return fs.existsSync(filepath);\n};\n\n// Return an array of all file paths that match the given wildcard patterns.\nfile.expand = function(...args) {\n  // If the first argument is an options object, save those options to pass\n  // into the File.prototype.glob.sync method.\n  var options = isPlainObject(args[0]) ? args.shift() : {};\n  // Use the first argument if it's an Array, otherwise convert the arguments\n  // object to an array and use that.\n  var patterns = Array.isArray(args[0]) ? args[0] : args;\n  // Return empty set if there are no patterns or filepaths.\n  if (patterns.length === 0) { return []; }\n  // Return all matching filepaths.\n  var matches = processPatterns(patterns, function(pattern) {\n    // Find all matching files for this pattern.\n    return glob.sync(pattern, options);\n  });\n  // Filter result set?\n  if (options.filter) {\n    matches = matches.filter(function(filepath) {\n      filepath = path.join(options.cwd || '', filepath);\n      try {\n        if (typeof options.filter === 'function') {\n          return options.filter(filepath);\n        } else {\n          // If the file is of the right type and exists, this should work.\n          return fs.statSync(filepath)[options.filter]();\n        }\n      } catch(e) {\n        // Otherwise, it's probably not the right type.\n        return false;\n      }\n    });\n  }\n  return matches;\n};\n\n// Build a multi task \"files\" object dynamically.\nfile.expandMapping = function(patterns, destBase, options) {\n  options = Object.assign({\n    rename: function(destBase, destPath) {\n      return path.join(destBase || '', destPath);\n    }\n  }, options);\n  var files = [];\n  var fileByDest = {};\n  // Find all files matching pattern, using passed-in options.\n  file.expand(options, patterns).forEach(function(src) {\n    var destPath = src;\n    // Flatten?\n    if (options.flatten) {\n      destPath = path.basename(destPath);\n    }\n    // Change the extension?\n    if (options.ext) {\n      destPath = destPath.replace(/(\\.[^\\/]*)?$/, options.ext);\n    }\n    // Generate destination filename.\n    var dest = options.rename(destBase, destPath, options);\n    // Prepend cwd to src path if necessary.\n    if (options.cwd) { src = path.join(options.cwd, src); }\n    // Normalize filepaths to be unix-style.\n    dest = dest.replace(pathSeparatorRe, '/');\n    src = src.replace(pathSeparatorRe, '/');\n    // Map correct src path to dest path.\n    if (fileByDest[dest]) {\n      // If dest already exists, push this src onto that dest's src array.\n      fileByDest[dest].src.push(src);\n    } else {\n      // Otherwise create a new src-dest file mapping object.\n      files.push({\n        src: [src],\n        dest: dest,\n      });\n      // And store a reference for later use.\n      fileByDest[dest] = files[files.length - 1];\n    }\n  });\n  return files;\n};\n\n// reusing bits of grunt's multi-task source normalization\nfile.normalizeFilesArray = function(data) {\n  var files = [];\n\n  data.forEach(function(obj) {\n    var prop;\n    if ('src' in obj || 'dest' in obj) {\n      files.push(obj);\n    }\n  });\n\n  if (files.length === 0) {\n    return [];\n  }\n\n  files = _(files).chain().forEach(function(obj) {\n    if (!('src' in obj) || !obj.src) { return; }\n    // Normalize .src properties to flattened array.\n    if (Array.isArray(obj.src)) {\n      obj.src = flatten(obj.src);\n    } else {\n      obj.src = [obj.src];\n    }\n  }).map(function(obj) {\n    // Build options object, removing unwanted properties.\n    var expandOptions = Object.assign({}, obj);\n    delete expandOptions.src;\n    delete expandOptions.dest;\n\n    // Expand file mappings.\n    if (obj.expand) {\n      return file.expandMapping(obj.src, obj.dest, expandOptions).map(function(mapObj) {\n        // Copy obj properties to result.\n        var result = Object.assign({}, obj);\n        // Make a clone of the orig obj available.\n        result.orig = Object.assign({}, obj);\n        // Set .src and .dest, processing both as templates.\n        result.src = mapObj.src;\n        result.dest = mapObj.dest;\n        // Remove unwanted properties.\n        ['expand', 'cwd', 'flatten', 'rename', 'ext'].forEach(function(prop) {\n          delete result[prop];\n        });\n        return result;\n      });\n    }\n\n    // Copy obj properties to result, adding an .orig property.\n    var result = Object.assign({}, obj);\n    // Make a clone of the orig obj available.\n    result.orig = Object.assign({}, obj);\n\n    if ('src' in result) {\n      // Expose an expand-on-demand getter method as .src.\n      Object.defineProperty(result, 'src', {\n        enumerable: true,\n        get: function fn() {\n          var src;\n          if (!('result' in fn)) {\n            src = obj.src;\n            // If src is an array, flatten it. Otherwise, make it into an array.\n            src = Array.isArray(src) ? flatten(src) : [src];\n            // Expand src files, memoizing result.\n            fn.result = file.expand(expandOptions, src);\n          }\n          return fn.result;\n        }\n      });\n    }\n\n    if ('dest' in result) {\n      result.dest = obj.dest;\n    }\n\n    return result;\n  }).flatten().value();\n\n  return files;\n};\n","/**\n * archiver-utils\n *\n * Copyright (c) 2015 Chris Talkington.\n * Licensed under the MIT license.\n * https://github.com/archiverjs/archiver-utils/blob/master/LICENSE\n */\nvar fs = require('graceful-fs');\nvar path = require('path');\nvar isStream = require('is-stream');\nvar lazystream = require('lazystream');\nvar normalizePath = require('normalize-path');\nvar defaults = require('lodash/defaults');\n\nvar Stream = require('stream').Stream;\nvar PassThrough = require('readable-stream').PassThrough;\n\nvar utils = module.exports = {};\nutils.file = require('./file.js');\n\nutils.collectStream = function(source, callback) {\n  var collection = [];\n  var size = 0;\n\n  source.on('error', callback);\n\n  source.on('data', function(chunk) {\n    collection.push(chunk);\n    size += chunk.length;\n  });\n\n  source.on('end', function() {\n    var buf = Buffer.alloc(size);\n    var offset = 0;\n\n    collection.forEach(function(data) {\n      data.copy(buf, offset);\n      offset += data.length;\n    });\n\n    callback(null, buf);\n  });\n};\n\nutils.dateify = function(dateish) {\n  dateish = dateish || new Date();\n\n  if (dateish instanceof Date) {\n    dateish = dateish;\n  } else if (typeof dateish === 'string') {\n    dateish = new Date(dateish);\n  } else {\n    dateish = new Date();\n  }\n\n  return dateish;\n};\n\n// this is slightly different from lodash version\nutils.defaults = function(object, source, guard) {\n  var args = arguments;\n  args[0] = args[0] || {};\n\n  return defaults(...args);\n};\n\nutils.isStream = function(source) {\n  return isStream(source);\n};\n\nutils.lazyReadStream = function(filepath) {\n  return new lazystream.Readable(function() {\n    return fs.createReadStream(filepath);\n  });\n};\n\nutils.normalizeInputSource = function(source) {\n  if (source === null) {\n    return Buffer.alloc(0);\n  } else if (typeof source === 'string') {\n    return Buffer.from(source);\n  } else if (utils.isStream(source)) {\n    // Always pipe through a PassThrough stream to guarantee pausing the stream if it's already flowing,\n    // since it will only be processed in a (distant) future iteration of the event loop, and will lose\n    // data if already flowing now.\n    return source.pipe(new PassThrough());\n  }\n\n  return source;\n};\n\nutils.sanitizePath = function(filepath) {\n  return normalizePath(filepath, false).replace(/^\\w+:/, '').replace(/^(\\.\\.\\/|\\/)+/, '');\n};\n\nutils.trailingSlashIt = function(str) {\n  return str.slice(-1) !== '/' ? str + '/' : str;\n};\n\nutils.unixifyPath = function(filepath) {\n  return normalizePath(filepath, false).replace(/^\\w+:/, '');\n};\n\nutils.walkdir = function(dirpath, base, callback) {\n  var results = [];\n\n  if (typeof base === 'function') {\n    callback = base;\n    base = dirpath;\n  }\n\n  fs.readdir(dirpath, function(err, list) {\n    var i = 0;\n    var file;\n    var filepath;\n\n    if (err) {\n      return callback(err);\n    }\n\n    (function next() {\n      file = list[i++];\n\n      if (!file) {\n        return callback(null, results);\n      }\n\n      filepath = path.join(dirpath, file);\n\n      fs.stat(filepath, function(err, stats) {\n        results.push({\n          path: filepath,\n          relative: path.relative(base, filepath).replace(/\\\\/g, '/'),\n          stats: stats\n        });\n\n        if (stats && stats.isDirectory()) {\n          utils.walkdir(filepath, base, function(err, res) {\n\t    if(err){\n\t      return callback(err);\n\t    }\n\n            res.forEach(function(dirEntry) {\n              results.push(dirEntry);\n            });\n\t\t  \n            next();  \n          });\n        } else {\n          next();\n        }\n      });\n    })();\n  });\n};\n","/**\n * Archiver Core\n *\n * @ignore\n * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE}\n * @copyright (c) 2012-2014 Chris Talkington, contributors.\n */\n\nvar util = require('util');\n\nconst ERROR_CODES = {\n  'ABORTED': 'archive was aborted',\n  'DIRECTORYDIRPATHREQUIRED': 'diretory dirpath argument must be a non-empty string value',\n  'DIRECTORYFUNCTIONINVALIDDATA': 'invalid data returned by directory custom data function',\n  'ENTRYNAMEREQUIRED': 'entry name must be a non-empty string value',\n  'FILEFILEPATHREQUIRED': 'file filepath argument must be a non-empty string value',\n  'FINALIZING': 'archive already finalizing',\n  'QUEUECLOSED': 'queue closed',\n  'NOENDMETHOD': 'no suitable finalize/end method defined by module',\n  'DIRECTORYNOTSUPPORTED': 'support for directory entries not defined by module',\n  'FORMATSET': 'archive format already set',\n  'INPUTSTEAMBUFFERREQUIRED': 'input source must be valid Stream or Buffer instance',\n  'MODULESET': 'module already set',\n  'SYMLINKNOTSUPPORTED': 'support for symlink entries not defined by module',\n  'SYMLINKFILEPATHREQUIRED': 'symlink filepath argument must be a non-empty string value',\n  'SYMLINKTARGETREQUIRED': 'symlink target argument must be a non-empty string value',\n  'ENTRYNOTSUPPORTED': 'entry not supported'\n};\n\nfunction ArchiverError(code, data) {\n  Error.captureStackTrace(this, this.constructor);\n  //this.name = this.constructor.name;\n  this.message = ERROR_CODES[code] || code;\n  this.code = code;\n  this.data = data;\n}\n\nutil.inherits(ArchiverError, Error);\n\nexports = module.exports = ArchiverError;","'use strict'\n\n/*\n  This file is a reduced and adapted version of the main lib/internal/per_context/primordials.js file defined at\n\n  https://github.com/nodejs/node/blob/main/lib/internal/per_context/primordials.js\n\n  Don't try to replace with the original file and keep it up to date with the upstream file.\n*/\n\n// This is a simplified version of AggregateError\nclass AggregateError extends Error {\n  constructor(errors) {\n    if (!Array.isArray(errors)) {\n      throw new TypeError(`Expected input to be an Array, got ${typeof errors}`)\n    }\n    let message = ''\n    for (let i = 0; i < errors.length; i++) {\n      message += `    ${errors[i].stack}\\n`\n    }\n    super(message)\n    this.name = 'AggregateError'\n    this.errors = errors\n  }\n}\nmodule.exports = {\n  AggregateError,\n  ArrayIsArray(self) {\n    return Array.isArray(self)\n  },\n  ArrayPrototypeIncludes(self, el) {\n    return self.includes(el)\n  },\n  ArrayPrototypeIndexOf(self, el) {\n    return self.indexOf(el)\n  },\n  ArrayPrototypeJoin(self, sep) {\n    return self.join(sep)\n  },\n  ArrayPrototypeMap(self, fn) {\n    return self.map(fn)\n  },\n  ArrayPrototypePop(self, el) {\n    return self.pop(el)\n  },\n  ArrayPrototypePush(self, el) {\n    return self.push(el)\n  },\n  ArrayPrototypeSlice(self, start, end) {\n    return self.slice(start, end)\n  },\n  Error,\n  FunctionPrototypeCall(fn, thisArgs, ...args) {\n    return fn.call(thisArgs, ...args)\n  },\n  FunctionPrototypeSymbolHasInstance(self, instance) {\n    return Function.prototype[Symbol.hasInstance].call(self, instance)\n  },\n  MathFloor: Math.floor,\n  Number,\n  NumberIsInteger: Number.isInteger,\n  NumberIsNaN: Number.isNaN,\n  NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER,\n  NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER,\n  NumberParseInt: Number.parseInt,\n  ObjectDefineProperties(self, props) {\n    return Object.defineProperties(self, props)\n  },\n  ObjectDefineProperty(self, name, prop) {\n    return Object.defineProperty(self, name, prop)\n  },\n  ObjectGetOwnPropertyDescriptor(self, name) {\n    return Object.getOwnPropertyDescriptor(self, name)\n  },\n  ObjectKeys(obj) {\n    return Object.keys(obj)\n  },\n  ObjectSetPrototypeOf(target, proto) {\n    return Object.setPrototypeOf(target, proto)\n  },\n  Promise,\n  PromisePrototypeCatch(self, fn) {\n    return self.catch(fn)\n  },\n  PromisePrototypeThen(self, thenFn, catchFn) {\n    return self.then(thenFn, catchFn)\n  },\n  PromiseReject(err) {\n    return Promise.reject(err)\n  },\n  PromiseResolve(val) {\n    return Promise.resolve(val)\n  },\n  ReflectApply: Reflect.apply,\n  RegExpPrototypeTest(self, value) {\n    return self.test(value)\n  },\n  SafeSet: Set,\n  String,\n  StringPrototypeSlice(self, start, end) {\n    return self.slice(start, end)\n  },\n  StringPrototypeToLowerCase(self) {\n    return self.toLowerCase()\n  },\n  StringPrototypeToUpperCase(self) {\n    return self.toUpperCase()\n  },\n  StringPrototypeTrim(self) {\n    return self.trim()\n  },\n  Symbol,\n  SymbolFor: Symbol.for,\n  SymbolAsyncIterator: Symbol.asyncIterator,\n  SymbolHasInstance: Symbol.hasInstance,\n  SymbolIterator: Symbol.iterator,\n  SymbolDispose: Symbol.dispose || Symbol('Symbol.dispose'),\n  SymbolAsyncDispose: Symbol.asyncDispose || Symbol('Symbol.asyncDispose'),\n  TypedArrayPrototypeSet(self, buf, len) {\n    return self.set(buf, len)\n  },\n  Boolean,\n  Uint8Array\n}\n","'use strict'\n\n/*\n  This file is a reduced and adapted version of the main lib/internal/util/inspect.js file defined at\n\n  https://github.com/nodejs/node/blob/main/lib/internal/util/inspect.js\n\n  Don't try to replace with the original file and keep it up to date with the upstream file.\n*/\nmodule.exports = {\n  format(format, ...args) {\n    // Simplified version of https://nodejs.org/api/util.html#utilformatformat-args\n    return format.replace(/%([sdifj])/g, function (...[_unused, type]) {\n      const replacement = args.shift()\n      if (type === 'f') {\n        return replacement.toFixed(6)\n      } else if (type === 'j') {\n        return JSON.stringify(replacement)\n      } else if (type === 's' && typeof replacement === 'object') {\n        const ctor = replacement.constructor !== Object ? replacement.constructor.name : ''\n        return `${ctor} {}`.trim()\n      } else {\n        return replacement.toString()\n      }\n    })\n  },\n  inspect(value) {\n    // Vastly simplified version of https://nodejs.org/api/util.html#utilinspectobject-options\n    switch (typeof value) {\n      case 'string':\n        if (value.includes(\"'\")) {\n          if (!value.includes('\"')) {\n            return `\"${value}\"`\n          } else if (!value.includes('`') && !value.includes('${')) {\n            return `\\`${value}\\``\n          }\n        }\n        return `'${value}'`\n      case 'number':\n        if (isNaN(value)) {\n          return 'NaN'\n        } else if (Object.is(value, -0)) {\n          return String(value)\n        }\n        return value\n      case 'bigint':\n        return `${String(value)}n`\n      case 'boolean':\n      case 'undefined':\n        return String(value)\n      case 'object':\n        return '{}'\n    }\n  }\n}\n","'use strict'\n\nconst { format, inspect } = require('./util/inspect')\nconst { AggregateError: CustomAggregateError } = require('./primordials')\n\n/*\n  This file is a reduced and adapted version of the main lib/internal/errors.js file defined at\n\n  https://github.com/nodejs/node/blob/main/lib/internal/errors.js\n\n  Don't try to replace with the original file and keep it up to date (starting from E(...) definitions)\n  with the upstream file.\n*/\n\nconst AggregateError = globalThis.AggregateError || CustomAggregateError\nconst kIsNodeError = Symbol('kIsNodeError')\nconst kTypes = [\n  'string',\n  'function',\n  'number',\n  'object',\n  // Accept 'Function' and 'Object' as alternative to the lower cased version.\n  'Function',\n  'Object',\n  'boolean',\n  'bigint',\n  'symbol'\n]\nconst classRegExp = /^([A-Z][a-z0-9]*)+$/\nconst nodeInternalPrefix = '__node_internal_'\nconst codes = {}\nfunction assert(value, message) {\n  if (!value) {\n    throw new codes.ERR_INTERNAL_ASSERTION(message)\n  }\n}\n\n// Only use this for integers! Decimal numbers do not work with this function.\nfunction addNumericalSeparator(val) {\n  let res = ''\n  let i = val.length\n  const start = val[0] === '-' ? 1 : 0\n  for (; i >= start + 4; i -= 3) {\n    res = `_${val.slice(i - 3, i)}${res}`\n  }\n  return `${val.slice(0, i)}${res}`\n}\nfunction getMessage(key, msg, args) {\n  if (typeof msg === 'function') {\n    assert(\n      msg.length <= args.length,\n      // Default options do not count.\n      `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).`\n    )\n    return msg(...args)\n  }\n  const expectedLength = (msg.match(/%[dfijoOs]/g) || []).length\n  assert(\n    expectedLength === args.length,\n    `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).`\n  )\n  if (args.length === 0) {\n    return msg\n  }\n  return format(msg, ...args)\n}\nfunction E(code, message, Base) {\n  if (!Base) {\n    Base = Error\n  }\n  class NodeError extends Base {\n    constructor(...args) {\n      super(getMessage(code, message, args))\n    }\n    toString() {\n      return `${this.name} [${code}]: ${this.message}`\n    }\n  }\n  Object.defineProperties(NodeError.prototype, {\n    name: {\n      value: Base.name,\n      writable: true,\n      enumerable: false,\n      configurable: true\n    },\n    toString: {\n      value() {\n        return `${this.name} [${code}]: ${this.message}`\n      },\n      writable: true,\n      enumerable: false,\n      configurable: true\n    }\n  })\n  NodeError.prototype.code = code\n  NodeError.prototype[kIsNodeError] = true\n  codes[code] = NodeError\n}\nfunction hideStackFrames(fn) {\n  // We rename the functions that will be hidden to cut off the stacktrace\n  // at the outermost one\n  const hidden = nodeInternalPrefix + fn.name\n  Object.defineProperty(fn, 'name', {\n    value: hidden\n  })\n  return fn\n}\nfunction aggregateTwoErrors(innerError, outerError) {\n  if (innerError && outerError && innerError !== outerError) {\n    if (Array.isArray(outerError.errors)) {\n      // If `outerError` is already an `AggregateError`.\n      outerError.errors.push(innerError)\n      return outerError\n    }\n    const err = new AggregateError([outerError, innerError], outerError.message)\n    err.code = outerError.code\n    return err\n  }\n  return innerError || outerError\n}\nclass AbortError extends Error {\n  constructor(message = 'The operation was aborted', options = undefined) {\n    if (options !== undefined && typeof options !== 'object') {\n      throw new codes.ERR_INVALID_ARG_TYPE('options', 'Object', options)\n    }\n    super(message, options)\n    this.code = 'ABORT_ERR'\n    this.name = 'AbortError'\n  }\n}\nE('ERR_ASSERTION', '%s', Error)\nE(\n  'ERR_INVALID_ARG_TYPE',\n  (name, expected, actual) => {\n    assert(typeof name === 'string', \"'name' must be a string\")\n    if (!Array.isArray(expected)) {\n      expected = [expected]\n    }\n    let msg = 'The '\n    if (name.endsWith(' argument')) {\n      // For cases like 'first argument'\n      msg += `${name} `\n    } else {\n      msg += `\"${name}\" ${name.includes('.') ? 'property' : 'argument'} `\n    }\n    msg += 'must be '\n    const types = []\n    const instances = []\n    const other = []\n    for (const value of expected) {\n      assert(typeof value === 'string', 'All expected entries have to be of type string')\n      if (kTypes.includes(value)) {\n        types.push(value.toLowerCase())\n      } else if (classRegExp.test(value)) {\n        instances.push(value)\n      } else {\n        assert(value !== 'object', 'The value \"object\" should be written as \"Object\"')\n        other.push(value)\n      }\n    }\n\n    // Special handle `object` in case other instances are allowed to outline\n    // the differences between each other.\n    if (instances.length > 0) {\n      const pos = types.indexOf('object')\n      if (pos !== -1) {\n        types.splice(types, pos, 1)\n        instances.push('Object')\n      }\n    }\n    if (types.length > 0) {\n      switch (types.length) {\n        case 1:\n          msg += `of type ${types[0]}`\n          break\n        case 2:\n          msg += `one of type ${types[0]} or ${types[1]}`\n          break\n        default: {\n          const last = types.pop()\n          msg += `one of type ${types.join(', ')}, or ${last}`\n        }\n      }\n      if (instances.length > 0 || other.length > 0) {\n        msg += ' or '\n      }\n    }\n    if (instances.length > 0) {\n      switch (instances.length) {\n        case 1:\n          msg += `an instance of ${instances[0]}`\n          break\n        case 2:\n          msg += `an instance of ${instances[0]} or ${instances[1]}`\n          break\n        default: {\n          const last = instances.pop()\n          msg += `an instance of ${instances.join(', ')}, or ${last}`\n        }\n      }\n      if (other.length > 0) {\n        msg += ' or '\n      }\n    }\n    switch (other.length) {\n      case 0:\n        break\n      case 1:\n        if (other[0].toLowerCase() !== other[0]) {\n          msg += 'an '\n        }\n        msg += `${other[0]}`\n        break\n      case 2:\n        msg += `one of ${other[0]} or ${other[1]}`\n        break\n      default: {\n        const last = other.pop()\n        msg += `one of ${other.join(', ')}, or ${last}`\n      }\n    }\n    if (actual == null) {\n      msg += `. Received ${actual}`\n    } else if (typeof actual === 'function' && actual.name) {\n      msg += `. Received function ${actual.name}`\n    } else if (typeof actual === 'object') {\n      var _actual$constructor\n      if (\n        (_actual$constructor = actual.constructor) !== null &&\n        _actual$constructor !== undefined &&\n        _actual$constructor.name\n      ) {\n        msg += `. Received an instance of ${actual.constructor.name}`\n      } else {\n        const inspected = inspect(actual, {\n          depth: -1\n        })\n        msg += `. Received ${inspected}`\n      }\n    } else {\n      let inspected = inspect(actual, {\n        colors: false\n      })\n      if (inspected.length > 25) {\n        inspected = `${inspected.slice(0, 25)}...`\n      }\n      msg += `. Received type ${typeof actual} (${inspected})`\n    }\n    return msg\n  },\n  TypeError\n)\nE(\n  'ERR_INVALID_ARG_VALUE',\n  (name, value, reason = 'is invalid') => {\n    let inspected = inspect(value)\n    if (inspected.length > 128) {\n      inspected = inspected.slice(0, 128) + '...'\n    }\n    const type = name.includes('.') ? 'property' : 'argument'\n    return `The ${type} '${name}' ${reason}. Received ${inspected}`\n  },\n  TypeError\n)\nE(\n  'ERR_INVALID_RETURN_VALUE',\n  (input, name, value) => {\n    var _value$constructor\n    const type =\n      value !== null &&\n      value !== undefined &&\n      (_value$constructor = value.constructor) !== null &&\n      _value$constructor !== undefined &&\n      _value$constructor.name\n        ? `instance of ${value.constructor.name}`\n        : `type ${typeof value}`\n    return `Expected ${input} to be returned from the \"${name}\"` + ` function but got ${type}.`\n  },\n  TypeError\n)\nE(\n  'ERR_MISSING_ARGS',\n  (...args) => {\n    assert(args.length > 0, 'At least one arg needs to be specified')\n    let msg\n    const len = args.length\n    args = (Array.isArray(args) ? args : [args]).map((a) => `\"${a}\"`).join(' or ')\n    switch (len) {\n      case 1:\n        msg += `The ${args[0]} argument`\n        break\n      case 2:\n        msg += `The ${args[0]} and ${args[1]} arguments`\n        break\n      default:\n        {\n          const last = args.pop()\n          msg += `The ${args.join(', ')}, and ${last} arguments`\n        }\n        break\n    }\n    return `${msg} must be specified`\n  },\n  TypeError\n)\nE(\n  'ERR_OUT_OF_RANGE',\n  (str, range, input) => {\n    assert(range, 'Missing \"range\" argument')\n    let received\n    if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n      received = addNumericalSeparator(String(input))\n    } else if (typeof input === 'bigint') {\n      received = String(input)\n      const limit = BigInt(2) ** BigInt(32)\n      if (input > limit || input < -limit) {\n        received = addNumericalSeparator(received)\n      }\n      received += 'n'\n    } else {\n      received = inspect(input)\n    }\n    return `The value of \"${str}\" is out of range. It must be ${range}. Received ${received}`\n  },\n  RangeError\n)\nE('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times', Error)\nE('ERR_METHOD_NOT_IMPLEMENTED', 'The %s method is not implemented', Error)\nE('ERR_STREAM_ALREADY_FINISHED', 'Cannot call %s after a stream was finished', Error)\nE('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable', Error)\nE('ERR_STREAM_DESTROYED', 'Cannot call %s after a stream was destroyed', Error)\nE('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError)\nE('ERR_STREAM_PREMATURE_CLOSE', 'Premature close', Error)\nE('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF', Error)\nE('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event', Error)\nE('ERR_STREAM_WRITE_AFTER_END', 'write after end', Error)\nE('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s', TypeError)\nmodule.exports = {\n  AbortError,\n  aggregateTwoErrors: hideStackFrames(aggregateTwoErrors),\n  hideStackFrames,\n  codes\n}\n","'use strict'\n\nconst bufferModule = require('buffer')\nconst { format, inspect } = require('./util/inspect')\nconst {\n  codes: { ERR_INVALID_ARG_TYPE }\n} = require('./errors')\nconst { kResistStopPropagation, AggregateError, SymbolDispose } = require('./primordials')\nconst AbortSignal = globalThis.AbortSignal || require('abort-controller').AbortSignal\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nconst AsyncFunction = Object.getPrototypeOf(async function () {}).constructor\nconst Blob = globalThis.Blob || bufferModule.Blob\n/* eslint-disable indent */\nconst isBlob =\n  typeof Blob !== 'undefined'\n    ? function isBlob(b) {\n        // eslint-disable-next-line indent\n        return b instanceof Blob\n      }\n    : function isBlob(b) {\n        return false\n      }\n/* eslint-enable indent */\n\nconst validateAbortSignal = (signal, name) => {\n  if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) {\n    throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal)\n  }\n}\nconst validateFunction = (value, name) => {\n  if (typeof value !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE(name, 'Function', value)\n  }\n}\nmodule.exports = {\n  AggregateError,\n  kEmptyObject: Object.freeze({}),\n  once(callback) {\n    let called = false\n    return function (...args) {\n      if (called) {\n        return\n      }\n      called = true\n      callback.apply(this, args)\n    }\n  },\n  createDeferredPromise: function () {\n    let resolve\n    let reject\n\n    // eslint-disable-next-line promise/param-names\n    const promise = new Promise((res, rej) => {\n      resolve = res\n      reject = rej\n    })\n    return {\n      promise,\n      resolve,\n      reject\n    }\n  },\n  promisify(fn) {\n    return new Promise((resolve, reject) => {\n      fn((err, ...args) => {\n        if (err) {\n          return reject(err)\n        }\n        return resolve(...args)\n      })\n    })\n  },\n  debuglog() {\n    return function () {}\n  },\n  format,\n  inspect,\n  types: {\n    isAsyncFunction(fn) {\n      return fn instanceof AsyncFunction\n    },\n    isArrayBufferView(arr) {\n      return ArrayBuffer.isView(arr)\n    }\n  },\n  isBlob,\n  deprecate(fn, message) {\n    return fn\n  },\n  addAbortListener:\n    require('events').addAbortListener ||\n    function addAbortListener(signal, listener) {\n      if (signal === undefined) {\n        throw new ERR_INVALID_ARG_TYPE('signal', 'AbortSignal', signal)\n      }\n      validateAbortSignal(signal, 'signal')\n      validateFunction(listener, 'listener')\n      let removeEventListener\n      if (signal.aborted) {\n        queueMicrotask(() => listener())\n      } else {\n        signal.addEventListener('abort', listener, {\n          __proto__: null,\n          once: true,\n          [kResistStopPropagation]: true\n        })\n        removeEventListener = () => {\n          signal.removeEventListener('abort', listener)\n        }\n      }\n      return {\n        __proto__: null,\n        [SymbolDispose]() {\n          var _removeEventListener\n          ;(_removeEventListener = removeEventListener) === null || _removeEventListener === undefined\n            ? undefined\n            : _removeEventListener()\n        }\n      }\n    },\n  AbortSignalAny:\n    AbortSignal.any ||\n    function AbortSignalAny(signals) {\n      // Fast path if there is only one signal.\n      if (signals.length === 1) {\n        return signals[0]\n      }\n      const ac = new AbortController()\n      const abort = () => ac.abort()\n      signals.forEach((signal) => {\n        validateAbortSignal(signal, 'signals')\n        signal.addEventListener('abort', abort, {\n          once: true\n        })\n      })\n      ac.signal.addEventListener(\n        'abort',\n        () => {\n          signals.forEach((signal) => signal.removeEventListener('abort', abort))\n        },\n        {\n          once: true\n        }\n      )\n      return ac.signal\n    }\n}\nmodule.exports.promisify.custom = Symbol.for('nodejs.util.promisify.custom')\n","/* eslint jsdoc/require-jsdoc: \"error\" */\n\n'use strict'\n\nconst {\n  ArrayIsArray,\n  ArrayPrototypeIncludes,\n  ArrayPrototypeJoin,\n  ArrayPrototypeMap,\n  NumberIsInteger,\n  NumberIsNaN,\n  NumberMAX_SAFE_INTEGER,\n  NumberMIN_SAFE_INTEGER,\n  NumberParseInt,\n  ObjectPrototypeHasOwnProperty,\n  RegExpPrototypeExec,\n  String,\n  StringPrototypeToUpperCase,\n  StringPrototypeTrim\n} = require('../ours/primordials')\nconst {\n  hideStackFrames,\n  codes: { ERR_SOCKET_BAD_PORT, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_OUT_OF_RANGE, ERR_UNKNOWN_SIGNAL }\n} = require('../ours/errors')\nconst { normalizeEncoding } = require('../ours/util')\nconst { isAsyncFunction, isArrayBufferView } = require('../ours/util').types\nconst signals = {}\n\n/**\n * @param {*} value\n * @returns {boolean}\n */\nfunction isInt32(value) {\n  return value === (value | 0)\n}\n\n/**\n * @param {*} value\n * @returns {boolean}\n */\nfunction isUint32(value) {\n  return value === value >>> 0\n}\nconst octalReg = /^[0-7]+$/\nconst modeDesc = 'must be a 32-bit unsigned integer or an octal string'\n\n/**\n * Parse and validate values that will be converted into mode_t (the S_*\n * constants). Only valid numbers and octal strings are allowed. They could be\n * converted to 32-bit unsigned integers or non-negative signed integers in the\n * C++ land, but any value higher than 0o777 will result in platform-specific\n * behaviors.\n * @param {*} value Values to be validated\n * @param {string} name Name of the argument\n * @param {number} [def] If specified, will be returned for invalid values\n * @returns {number}\n */\nfunction parseFileMode(value, name, def) {\n  if (typeof value === 'undefined') {\n    value = def\n  }\n  if (typeof value === 'string') {\n    if (RegExpPrototypeExec(octalReg, value) === null) {\n      throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc)\n    }\n    value = NumberParseInt(value, 8)\n  }\n  validateUint32(value, name)\n  return value\n}\n\n/**\n * @callback validateInteger\n * @param {*} value\n * @param {string} name\n * @param {number} [min]\n * @param {number} [max]\n * @returns {asserts value is number}\n */\n\n/** @type {validateInteger} */\nconst validateInteger = hideStackFrames((value, name, min = NumberMIN_SAFE_INTEGER, max = NumberMAX_SAFE_INTEGER) => {\n  if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n  if (!NumberIsInteger(value)) throw new ERR_OUT_OF_RANGE(name, 'an integer', value)\n  if (value < min || value > max) throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value)\n})\n\n/**\n * @callback validateInt32\n * @param {*} value\n * @param {string} name\n * @param {number} [min]\n * @param {number} [max]\n * @returns {asserts value is number}\n */\n\n/** @type {validateInt32} */\nconst validateInt32 = hideStackFrames((value, name, min = -2147483648, max = 2147483647) => {\n  // The defaults for min and max correspond to the limits of 32-bit integers.\n  if (typeof value !== 'number') {\n    throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n  }\n  if (!NumberIsInteger(value)) {\n    throw new ERR_OUT_OF_RANGE(name, 'an integer', value)\n  }\n  if (value < min || value > max) {\n    throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value)\n  }\n})\n\n/**\n * @callback validateUint32\n * @param {*} value\n * @param {string} name\n * @param {number|boolean} [positive=false]\n * @returns {asserts value is number}\n */\n\n/** @type {validateUint32} */\nconst validateUint32 = hideStackFrames((value, name, positive = false) => {\n  if (typeof value !== 'number') {\n    throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n  }\n  if (!NumberIsInteger(value)) {\n    throw new ERR_OUT_OF_RANGE(name, 'an integer', value)\n  }\n  const min = positive ? 1 : 0\n  // 2 ** 32 === 4294967296\n  const max = 4294967295\n  if (value < min || value > max) {\n    throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value)\n  }\n})\n\n/**\n * @callback validateString\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is string}\n */\n\n/** @type {validateString} */\nfunction validateString(value, name) {\n  if (typeof value !== 'string') throw new ERR_INVALID_ARG_TYPE(name, 'string', value)\n}\n\n/**\n * @callback validateNumber\n * @param {*} value\n * @param {string} name\n * @param {number} [min]\n * @param {number} [max]\n * @returns {asserts value is number}\n */\n\n/** @type {validateNumber} */\nfunction validateNumber(value, name, min = undefined, max) {\n  if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n  if (\n    (min != null && value < min) ||\n    (max != null && value > max) ||\n    ((min != null || max != null) && NumberIsNaN(value))\n  ) {\n    throw new ERR_OUT_OF_RANGE(\n      name,\n      `${min != null ? `>= ${min}` : ''}${min != null && max != null ? ' && ' : ''}${max != null ? `<= ${max}` : ''}`,\n      value\n    )\n  }\n}\n\n/**\n * @callback validateOneOf\n * @template T\n * @param {T} value\n * @param {string} name\n * @param {T[]} oneOf\n */\n\n/** @type {validateOneOf} */\nconst validateOneOf = hideStackFrames((value, name, oneOf) => {\n  if (!ArrayPrototypeIncludes(oneOf, value)) {\n    const allowed = ArrayPrototypeJoin(\n      ArrayPrototypeMap(oneOf, (v) => (typeof v === 'string' ? `'${v}'` : String(v))),\n      ', '\n    )\n    const reason = 'must be one of: ' + allowed\n    throw new ERR_INVALID_ARG_VALUE(name, value, reason)\n  }\n})\n\n/**\n * @callback validateBoolean\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is boolean}\n */\n\n/** @type {validateBoolean} */\nfunction validateBoolean(value, name) {\n  if (typeof value !== 'boolean') throw new ERR_INVALID_ARG_TYPE(name, 'boolean', value)\n}\n\n/**\n * @param {any} options\n * @param {string} key\n * @param {boolean} defaultValue\n * @returns {boolean}\n */\nfunction getOwnPropertyValueOrDefault(options, key, defaultValue) {\n  return options == null || !ObjectPrototypeHasOwnProperty(options, key) ? defaultValue : options[key]\n}\n\n/**\n * @callback validateObject\n * @param {*} value\n * @param {string} name\n * @param {{\n *   allowArray?: boolean,\n *   allowFunction?: boolean,\n *   nullable?: boolean\n * }} [options]\n */\n\n/** @type {validateObject} */\nconst validateObject = hideStackFrames((value, name, options = null) => {\n  const allowArray = getOwnPropertyValueOrDefault(options, 'allowArray', false)\n  const allowFunction = getOwnPropertyValueOrDefault(options, 'allowFunction', false)\n  const nullable = getOwnPropertyValueOrDefault(options, 'nullable', false)\n  if (\n    (!nullable && value === null) ||\n    (!allowArray && ArrayIsArray(value)) ||\n    (typeof value !== 'object' && (!allowFunction || typeof value !== 'function'))\n  ) {\n    throw new ERR_INVALID_ARG_TYPE(name, 'Object', value)\n  }\n})\n\n/**\n * @callback validateDictionary - We are using the Web IDL Standard definition\n *                                of \"dictionary\" here, which means any value\n *                                whose Type is either Undefined, Null, or\n *                                Object (which includes functions).\n * @param {*} value\n * @param {string} name\n * @see https://webidl.spec.whatwg.org/#es-dictionary\n * @see https://tc39.es/ecma262/#table-typeof-operator-results\n */\n\n/** @type {validateDictionary} */\nconst validateDictionary = hideStackFrames((value, name) => {\n  if (value != null && typeof value !== 'object' && typeof value !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE(name, 'a dictionary', value)\n  }\n})\n\n/**\n * @callback validateArray\n * @param {*} value\n * @param {string} name\n * @param {number} [minLength]\n * @returns {asserts value is any[]}\n */\n\n/** @type {validateArray} */\nconst validateArray = hideStackFrames((value, name, minLength = 0) => {\n  if (!ArrayIsArray(value)) {\n    throw new ERR_INVALID_ARG_TYPE(name, 'Array', value)\n  }\n  if (value.length < minLength) {\n    const reason = `must be longer than ${minLength}`\n    throw new ERR_INVALID_ARG_VALUE(name, value, reason)\n  }\n})\n\n/**\n * @callback validateStringArray\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is string[]}\n */\n\n/** @type {validateStringArray} */\nfunction validateStringArray(value, name) {\n  validateArray(value, name)\n  for (let i = 0; i < value.length; i++) {\n    validateString(value[i], `${name}[${i}]`)\n  }\n}\n\n/**\n * @callback validateBooleanArray\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is boolean[]}\n */\n\n/** @type {validateBooleanArray} */\nfunction validateBooleanArray(value, name) {\n  validateArray(value, name)\n  for (let i = 0; i < value.length; i++) {\n    validateBoolean(value[i], `${name}[${i}]`)\n  }\n}\n\n/**\n * @callback validateAbortSignalArray\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is AbortSignal[]}\n */\n\n/** @type {validateAbortSignalArray} */\nfunction validateAbortSignalArray(value, name) {\n  validateArray(value, name)\n  for (let i = 0; i < value.length; i++) {\n    const signal = value[i]\n    const indexedName = `${name}[${i}]`\n    if (signal == null) {\n      throw new ERR_INVALID_ARG_TYPE(indexedName, 'AbortSignal', signal)\n    }\n    validateAbortSignal(signal, indexedName)\n  }\n}\n\n/**\n * @param {*} signal\n * @param {string} [name='signal']\n * @returns {asserts signal is keyof signals}\n */\nfunction validateSignalName(signal, name = 'signal') {\n  validateString(signal, name)\n  if (signals[signal] === undefined) {\n    if (signals[StringPrototypeToUpperCase(signal)] !== undefined) {\n      throw new ERR_UNKNOWN_SIGNAL(signal + ' (signals must use all capital letters)')\n    }\n    throw new ERR_UNKNOWN_SIGNAL(signal)\n  }\n}\n\n/**\n * @callback validateBuffer\n * @param {*} buffer\n * @param {string} [name='buffer']\n * @returns {asserts buffer is ArrayBufferView}\n */\n\n/** @type {validateBuffer} */\nconst validateBuffer = hideStackFrames((buffer, name = 'buffer') => {\n  if (!isArrayBufferView(buffer)) {\n    throw new ERR_INVALID_ARG_TYPE(name, ['Buffer', 'TypedArray', 'DataView'], buffer)\n  }\n})\n\n/**\n * @param {string} data\n * @param {string} encoding\n */\nfunction validateEncoding(data, encoding) {\n  const normalizedEncoding = normalizeEncoding(encoding)\n  const length = data.length\n  if (normalizedEncoding === 'hex' && length % 2 !== 0) {\n    throw new ERR_INVALID_ARG_VALUE('encoding', encoding, `is invalid for data of length ${length}`)\n  }\n}\n\n/**\n * Check that the port number is not NaN when coerced to a number,\n * is an integer and that it falls within the legal range of port numbers.\n * @param {*} port\n * @param {string} [name='Port']\n * @param {boolean} [allowZero=true]\n * @returns {number}\n */\nfunction validatePort(port, name = 'Port', allowZero = true) {\n  if (\n    (typeof port !== 'number' && typeof port !== 'string') ||\n    (typeof port === 'string' && StringPrototypeTrim(port).length === 0) ||\n    +port !== +port >>> 0 ||\n    port > 0xffff ||\n    (port === 0 && !allowZero)\n  ) {\n    throw new ERR_SOCKET_BAD_PORT(name, port, allowZero)\n  }\n  return port | 0\n}\n\n/**\n * @callback validateAbortSignal\n * @param {*} signal\n * @param {string} name\n */\n\n/** @type {validateAbortSignal} */\nconst validateAbortSignal = hideStackFrames((signal, name) => {\n  if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) {\n    throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal)\n  }\n})\n\n/**\n * @callback validateFunction\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is Function}\n */\n\n/** @type {validateFunction} */\nconst validateFunction = hideStackFrames((value, name) => {\n  if (typeof value !== 'function') throw new ERR_INVALID_ARG_TYPE(name, 'Function', value)\n})\n\n/**\n * @callback validatePlainFunction\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is Function}\n */\n\n/** @type {validatePlainFunction} */\nconst validatePlainFunction = hideStackFrames((value, name) => {\n  if (typeof value !== 'function' || isAsyncFunction(value)) throw new ERR_INVALID_ARG_TYPE(name, 'Function', value)\n})\n\n/**\n * @callback validateUndefined\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is undefined}\n */\n\n/** @type {validateUndefined} */\nconst validateUndefined = hideStackFrames((value, name) => {\n  if (value !== undefined) throw new ERR_INVALID_ARG_TYPE(name, 'undefined', value)\n})\n\n/**\n * @template T\n * @param {T} value\n * @param {string} name\n * @param {T[]} union\n */\nfunction validateUnion(value, name, union) {\n  if (!ArrayPrototypeIncludes(union, value)) {\n    throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value)\n  }\n}\n\n/*\n  The rules for the Link header field are described here:\n  https://www.rfc-editor.org/rfc/rfc8288.html#section-3\n\n  This regex validates any string surrounded by angle brackets\n  (not necessarily a valid URI reference) followed by zero or more\n  link-params separated by semicolons.\n*/\nconst linkValueRegExp = /^(?:<[^>]*>)(?:\\s*;\\s*[^;\"\\s]+(?:=(\")?[^;\"\\s]*\\1)?)*$/\n\n/**\n * @param {any} value\n * @param {string} name\n */\nfunction validateLinkHeaderFormat(value, name) {\n  if (typeof value === 'undefined' || !RegExpPrototypeExec(linkValueRegExp, value)) {\n    throw new ERR_INVALID_ARG_VALUE(\n      name,\n      value,\n      'must be an array or string of format \"; rel=preload; as=style\"'\n    )\n  }\n}\n\n/**\n * @param {any} hints\n * @return {string}\n */\nfunction validateLinkHeaderValue(hints) {\n  if (typeof hints === 'string') {\n    validateLinkHeaderFormat(hints, 'hints')\n    return hints\n  } else if (ArrayIsArray(hints)) {\n    const hintsLength = hints.length\n    let result = ''\n    if (hintsLength === 0) {\n      return result\n    }\n    for (let i = 0; i < hintsLength; i++) {\n      const link = hints[i]\n      validateLinkHeaderFormat(link, 'hints')\n      result += link\n      if (i !== hintsLength - 1) {\n        result += ', '\n      }\n    }\n    return result\n  }\n  throw new ERR_INVALID_ARG_VALUE(\n    'hints',\n    hints,\n    'must be an array or string of format \"; rel=preload; as=style\"'\n  )\n}\nmodule.exports = {\n  isInt32,\n  isUint32,\n  parseFileMode,\n  validateArray,\n  validateStringArray,\n  validateBooleanArray,\n  validateAbortSignalArray,\n  validateBoolean,\n  validateBuffer,\n  validateDictionary,\n  validateEncoding,\n  validateFunction,\n  validateInt32,\n  validateInteger,\n  validateNumber,\n  validateObject,\n  validateOneOf,\n  validatePlainFunction,\n  validatePort,\n  validateSignalName,\n  validateString,\n  validateUint32,\n  validateUndefined,\n  validateUnion,\n  validateAbortSignal,\n  validateLinkHeaderValue\n}\n","'use strict'\n\nconst { SymbolAsyncIterator, SymbolIterator, SymbolFor } = require('../../ours/primordials')\n\n// We need to use SymbolFor to make these globally available\n// for interopt with readable-stream, i.e. readable-stream\n// and node core needs to be able to read/write private state\n// from each other for proper interoperability.\nconst kIsDestroyed = SymbolFor('nodejs.stream.destroyed')\nconst kIsErrored = SymbolFor('nodejs.stream.errored')\nconst kIsReadable = SymbolFor('nodejs.stream.readable')\nconst kIsWritable = SymbolFor('nodejs.stream.writable')\nconst kIsDisturbed = SymbolFor('nodejs.stream.disturbed')\nconst kIsClosedPromise = SymbolFor('nodejs.webstream.isClosedPromise')\nconst kControllerErrorFunction = SymbolFor('nodejs.webstream.controllerErrorFunction')\nfunction isReadableNodeStream(obj, strict = false) {\n  var _obj$_readableState\n  return !!(\n    (\n      obj &&\n      typeof obj.pipe === 'function' &&\n      typeof obj.on === 'function' &&\n      (!strict || (typeof obj.pause === 'function' && typeof obj.resume === 'function')) &&\n      (!obj._writableState ||\n        ((_obj$_readableState = obj._readableState) === null || _obj$_readableState === undefined\n          ? undefined\n          : _obj$_readableState.readable) !== false) &&\n      // Duplex\n      (!obj._writableState || obj._readableState)\n    ) // Writable has .pipe.\n  )\n}\nfunction isWritableNodeStream(obj) {\n  var _obj$_writableState\n  return !!(\n    (\n      obj &&\n      typeof obj.write === 'function' &&\n      typeof obj.on === 'function' &&\n      (!obj._readableState ||\n        ((_obj$_writableState = obj._writableState) === null || _obj$_writableState === undefined\n          ? undefined\n          : _obj$_writableState.writable) !== false)\n    ) // Duplex\n  )\n}\nfunction isDuplexNodeStream(obj) {\n  return !!(\n    obj &&\n    typeof obj.pipe === 'function' &&\n    obj._readableState &&\n    typeof obj.on === 'function' &&\n    typeof obj.write === 'function'\n  )\n}\nfunction isNodeStream(obj) {\n  return (\n    obj &&\n    (obj._readableState ||\n      obj._writableState ||\n      (typeof obj.write === 'function' && typeof obj.on === 'function') ||\n      (typeof obj.pipe === 'function' && typeof obj.on === 'function'))\n  )\n}\nfunction isReadableStream(obj) {\n  return !!(\n    obj &&\n    !isNodeStream(obj) &&\n    typeof obj.pipeThrough === 'function' &&\n    typeof obj.getReader === 'function' &&\n    typeof obj.cancel === 'function'\n  )\n}\nfunction isWritableStream(obj) {\n  return !!(obj && !isNodeStream(obj) && typeof obj.getWriter === 'function' && typeof obj.abort === 'function')\n}\nfunction isTransformStream(obj) {\n  return !!(obj && !isNodeStream(obj) && typeof obj.readable === 'object' && typeof obj.writable === 'object')\n}\nfunction isWebStream(obj) {\n  return isReadableStream(obj) || isWritableStream(obj) || isTransformStream(obj)\n}\nfunction isIterable(obj, isAsync) {\n  if (obj == null) return false\n  if (isAsync === true) return typeof obj[SymbolAsyncIterator] === 'function'\n  if (isAsync === false) return typeof obj[SymbolIterator] === 'function'\n  return typeof obj[SymbolAsyncIterator] === 'function' || typeof obj[SymbolIterator] === 'function'\n}\nfunction isDestroyed(stream) {\n  if (!isNodeStream(stream)) return null\n  const wState = stream._writableState\n  const rState = stream._readableState\n  const state = wState || rState\n  return !!(stream.destroyed || stream[kIsDestroyed] || (state !== null && state !== undefined && state.destroyed))\n}\n\n// Have been end():d.\nfunction isWritableEnded(stream) {\n  if (!isWritableNodeStream(stream)) return null\n  if (stream.writableEnded === true) return true\n  const wState = stream._writableState\n  if (wState !== null && wState !== undefined && wState.errored) return false\n  if (typeof (wState === null || wState === undefined ? undefined : wState.ended) !== 'boolean') return null\n  return wState.ended\n}\n\n// Have emitted 'finish'.\nfunction isWritableFinished(stream, strict) {\n  if (!isWritableNodeStream(stream)) return null\n  if (stream.writableFinished === true) return true\n  const wState = stream._writableState\n  if (wState !== null && wState !== undefined && wState.errored) return false\n  if (typeof (wState === null || wState === undefined ? undefined : wState.finished) !== 'boolean') return null\n  return !!(wState.finished || (strict === false && wState.ended === true && wState.length === 0))\n}\n\n// Have been push(null):d.\nfunction isReadableEnded(stream) {\n  if (!isReadableNodeStream(stream)) return null\n  if (stream.readableEnded === true) return true\n  const rState = stream._readableState\n  if (!rState || rState.errored) return false\n  if (typeof (rState === null || rState === undefined ? undefined : rState.ended) !== 'boolean') return null\n  return rState.ended\n}\n\n// Have emitted 'end'.\nfunction isReadableFinished(stream, strict) {\n  if (!isReadableNodeStream(stream)) return null\n  const rState = stream._readableState\n  if (rState !== null && rState !== undefined && rState.errored) return false\n  if (typeof (rState === null || rState === undefined ? undefined : rState.endEmitted) !== 'boolean') return null\n  return !!(rState.endEmitted || (strict === false && rState.ended === true && rState.length === 0))\n}\nfunction isReadable(stream) {\n  if (stream && stream[kIsReadable] != null) return stream[kIsReadable]\n  if (typeof (stream === null || stream === undefined ? undefined : stream.readable) !== 'boolean') return null\n  if (isDestroyed(stream)) return false\n  return isReadableNodeStream(stream) && stream.readable && !isReadableFinished(stream)\n}\nfunction isWritable(stream) {\n  if (stream && stream[kIsWritable] != null) return stream[kIsWritable]\n  if (typeof (stream === null || stream === undefined ? undefined : stream.writable) !== 'boolean') return null\n  if (isDestroyed(stream)) return false\n  return isWritableNodeStream(stream) && stream.writable && !isWritableEnded(stream)\n}\nfunction isFinished(stream, opts) {\n  if (!isNodeStream(stream)) {\n    return null\n  }\n  if (isDestroyed(stream)) {\n    return true\n  }\n  if ((opts === null || opts === undefined ? undefined : opts.readable) !== false && isReadable(stream)) {\n    return false\n  }\n  if ((opts === null || opts === undefined ? undefined : opts.writable) !== false && isWritable(stream)) {\n    return false\n  }\n  return true\n}\nfunction isWritableErrored(stream) {\n  var _stream$_writableStat, _stream$_writableStat2\n  if (!isNodeStream(stream)) {\n    return null\n  }\n  if (stream.writableErrored) {\n    return stream.writableErrored\n  }\n  return (_stream$_writableStat =\n    (_stream$_writableStat2 = stream._writableState) === null || _stream$_writableStat2 === undefined\n      ? undefined\n      : _stream$_writableStat2.errored) !== null && _stream$_writableStat !== undefined\n    ? _stream$_writableStat\n    : null\n}\nfunction isReadableErrored(stream) {\n  var _stream$_readableStat, _stream$_readableStat2\n  if (!isNodeStream(stream)) {\n    return null\n  }\n  if (stream.readableErrored) {\n    return stream.readableErrored\n  }\n  return (_stream$_readableStat =\n    (_stream$_readableStat2 = stream._readableState) === null || _stream$_readableStat2 === undefined\n      ? undefined\n      : _stream$_readableStat2.errored) !== null && _stream$_readableStat !== undefined\n    ? _stream$_readableStat\n    : null\n}\nfunction isClosed(stream) {\n  if (!isNodeStream(stream)) {\n    return null\n  }\n  if (typeof stream.closed === 'boolean') {\n    return stream.closed\n  }\n  const wState = stream._writableState\n  const rState = stream._readableState\n  if (\n    typeof (wState === null || wState === undefined ? undefined : wState.closed) === 'boolean' ||\n    typeof (rState === null || rState === undefined ? undefined : rState.closed) === 'boolean'\n  ) {\n    return (\n      (wState === null || wState === undefined ? undefined : wState.closed) ||\n      (rState === null || rState === undefined ? undefined : rState.closed)\n    )\n  }\n  if (typeof stream._closed === 'boolean' && isOutgoingMessage(stream)) {\n    return stream._closed\n  }\n  return null\n}\nfunction isOutgoingMessage(stream) {\n  return (\n    typeof stream._closed === 'boolean' &&\n    typeof stream._defaultKeepAlive === 'boolean' &&\n    typeof stream._removedConnection === 'boolean' &&\n    typeof stream._removedContLen === 'boolean'\n  )\n}\nfunction isServerResponse(stream) {\n  return typeof stream._sent100 === 'boolean' && isOutgoingMessage(stream)\n}\nfunction isServerRequest(stream) {\n  var _stream$req\n  return (\n    typeof stream._consuming === 'boolean' &&\n    typeof stream._dumped === 'boolean' &&\n    ((_stream$req = stream.req) === null || _stream$req === undefined ? undefined : _stream$req.upgradeOrConnect) ===\n      undefined\n  )\n}\nfunction willEmitClose(stream) {\n  if (!isNodeStream(stream)) return null\n  const wState = stream._writableState\n  const rState = stream._readableState\n  const state = wState || rState\n  return (\n    (!state && isServerResponse(stream)) || !!(state && state.autoDestroy && state.emitClose && state.closed === false)\n  )\n}\nfunction isDisturbed(stream) {\n  var _stream$kIsDisturbed\n  return !!(\n    stream &&\n    ((_stream$kIsDisturbed = stream[kIsDisturbed]) !== null && _stream$kIsDisturbed !== undefined\n      ? _stream$kIsDisturbed\n      : stream.readableDidRead || stream.readableAborted)\n  )\n}\nfunction isErrored(stream) {\n  var _ref,\n    _ref2,\n    _ref3,\n    _ref4,\n    _ref5,\n    _stream$kIsErrored,\n    _stream$_readableStat3,\n    _stream$_writableStat3,\n    _stream$_readableStat4,\n    _stream$_writableStat4\n  return !!(\n    stream &&\n    ((_ref =\n      (_ref2 =\n        (_ref3 =\n          (_ref4 =\n            (_ref5 =\n              (_stream$kIsErrored = stream[kIsErrored]) !== null && _stream$kIsErrored !== undefined\n                ? _stream$kIsErrored\n                : stream.readableErrored) !== null && _ref5 !== undefined\n              ? _ref5\n              : stream.writableErrored) !== null && _ref4 !== undefined\n            ? _ref4\n            : (_stream$_readableStat3 = stream._readableState) === null || _stream$_readableStat3 === undefined\n            ? undefined\n            : _stream$_readableStat3.errorEmitted) !== null && _ref3 !== undefined\n          ? _ref3\n          : (_stream$_writableStat3 = stream._writableState) === null || _stream$_writableStat3 === undefined\n          ? undefined\n          : _stream$_writableStat3.errorEmitted) !== null && _ref2 !== undefined\n        ? _ref2\n        : (_stream$_readableStat4 = stream._readableState) === null || _stream$_readableStat4 === undefined\n        ? undefined\n        : _stream$_readableStat4.errored) !== null && _ref !== undefined\n      ? _ref\n      : (_stream$_writableStat4 = stream._writableState) === null || _stream$_writableStat4 === undefined\n      ? undefined\n      : _stream$_writableStat4.errored)\n  )\n}\nmodule.exports = {\n  isDestroyed,\n  kIsDestroyed,\n  isDisturbed,\n  kIsDisturbed,\n  isErrored,\n  kIsErrored,\n  isReadable,\n  kIsReadable,\n  kIsClosedPromise,\n  kControllerErrorFunction,\n  kIsWritable,\n  isClosed,\n  isDuplexNodeStream,\n  isFinished,\n  isIterable,\n  isReadableNodeStream,\n  isReadableStream,\n  isReadableEnded,\n  isReadableFinished,\n  isReadableErrored,\n  isNodeStream,\n  isWebStream,\n  isWritable,\n  isWritableNodeStream,\n  isWritableStream,\n  isWritableEnded,\n  isWritableFinished,\n  isWritableErrored,\n  isServerRequest,\n  isServerResponse,\n  willEmitClose,\n  isTransformStream\n}\n","// Ported from https://github.com/mafintosh/end-of-stream with\n// permission from the author, Mathias Buus (@mafintosh).\n\n'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst { AbortError, codes } = require('../../ours/errors')\nconst { ERR_INVALID_ARG_TYPE, ERR_STREAM_PREMATURE_CLOSE } = codes\nconst { kEmptyObject, once } = require('../../ours/util')\nconst { validateAbortSignal, validateFunction, validateObject, validateBoolean } = require('../validators')\nconst { Promise, PromisePrototypeThen, SymbolDispose } = require('../../ours/primordials')\nconst {\n  isClosed,\n  isReadable,\n  isReadableNodeStream,\n  isReadableStream,\n  isReadableFinished,\n  isReadableErrored,\n  isWritable,\n  isWritableNodeStream,\n  isWritableStream,\n  isWritableFinished,\n  isWritableErrored,\n  isNodeStream,\n  willEmitClose: _willEmitClose,\n  kIsClosedPromise\n} = require('./utils')\nlet addAbortListener\nfunction isRequest(stream) {\n  return stream.setHeader && typeof stream.abort === 'function'\n}\nconst nop = () => {}\nfunction eos(stream, options, callback) {\n  var _options$readable, _options$writable\n  if (arguments.length === 2) {\n    callback = options\n    options = kEmptyObject\n  } else if (options == null) {\n    options = kEmptyObject\n  } else {\n    validateObject(options, 'options')\n  }\n  validateFunction(callback, 'callback')\n  validateAbortSignal(options.signal, 'options.signal')\n  callback = once(callback)\n  if (isReadableStream(stream) || isWritableStream(stream)) {\n    return eosWeb(stream, options, callback)\n  }\n  if (!isNodeStream(stream)) {\n    throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream)\n  }\n  const readable =\n    (_options$readable = options.readable) !== null && _options$readable !== undefined\n      ? _options$readable\n      : isReadableNodeStream(stream)\n  const writable =\n    (_options$writable = options.writable) !== null && _options$writable !== undefined\n      ? _options$writable\n      : isWritableNodeStream(stream)\n  const wState = stream._writableState\n  const rState = stream._readableState\n  const onlegacyfinish = () => {\n    if (!stream.writable) {\n      onfinish()\n    }\n  }\n\n  // TODO (ronag): Improve soft detection to include core modules and\n  // common ecosystem modules that do properly emit 'close' but fail\n  // this generic check.\n  let willEmitClose =\n    _willEmitClose(stream) && isReadableNodeStream(stream) === readable && isWritableNodeStream(stream) === writable\n  let writableFinished = isWritableFinished(stream, false)\n  const onfinish = () => {\n    writableFinished = true\n    // Stream should not be destroyed here. If it is that\n    // means that user space is doing something differently and\n    // we cannot trust willEmitClose.\n    if (stream.destroyed) {\n      willEmitClose = false\n    }\n    if (willEmitClose && (!stream.readable || readable)) {\n      return\n    }\n    if (!readable || readableFinished) {\n      callback.call(stream)\n    }\n  }\n  let readableFinished = isReadableFinished(stream, false)\n  const onend = () => {\n    readableFinished = true\n    // Stream should not be destroyed here. If it is that\n    // means that user space is doing something differently and\n    // we cannot trust willEmitClose.\n    if (stream.destroyed) {\n      willEmitClose = false\n    }\n    if (willEmitClose && (!stream.writable || writable)) {\n      return\n    }\n    if (!writable || writableFinished) {\n      callback.call(stream)\n    }\n  }\n  const onerror = (err) => {\n    callback.call(stream, err)\n  }\n  let closed = isClosed(stream)\n  const onclose = () => {\n    closed = true\n    const errored = isWritableErrored(stream) || isReadableErrored(stream)\n    if (errored && typeof errored !== 'boolean') {\n      return callback.call(stream, errored)\n    }\n    if (readable && !readableFinished && isReadableNodeStream(stream, true)) {\n      if (!isReadableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE())\n    }\n    if (writable && !writableFinished) {\n      if (!isWritableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE())\n    }\n    callback.call(stream)\n  }\n  const onclosed = () => {\n    closed = true\n    const errored = isWritableErrored(stream) || isReadableErrored(stream)\n    if (errored && typeof errored !== 'boolean') {\n      return callback.call(stream, errored)\n    }\n    callback.call(stream)\n  }\n  const onrequest = () => {\n    stream.req.on('finish', onfinish)\n  }\n  if (isRequest(stream)) {\n    stream.on('complete', onfinish)\n    if (!willEmitClose) {\n      stream.on('abort', onclose)\n    }\n    if (stream.req) {\n      onrequest()\n    } else {\n      stream.on('request', onrequest)\n    }\n  } else if (writable && !wState) {\n    // legacy streams\n    stream.on('end', onlegacyfinish)\n    stream.on('close', onlegacyfinish)\n  }\n\n  // Not all streams will emit 'close' after 'aborted'.\n  if (!willEmitClose && typeof stream.aborted === 'boolean') {\n    stream.on('aborted', onclose)\n  }\n  stream.on('end', onend)\n  stream.on('finish', onfinish)\n  if (options.error !== false) {\n    stream.on('error', onerror)\n  }\n  stream.on('close', onclose)\n  if (closed) {\n    process.nextTick(onclose)\n  } else if (\n    (wState !== null && wState !== undefined && wState.errorEmitted) ||\n    (rState !== null && rState !== undefined && rState.errorEmitted)\n  ) {\n    if (!willEmitClose) {\n      process.nextTick(onclosed)\n    }\n  } else if (\n    !readable &&\n    (!willEmitClose || isReadable(stream)) &&\n    (writableFinished || isWritable(stream) === false)\n  ) {\n    process.nextTick(onclosed)\n  } else if (\n    !writable &&\n    (!willEmitClose || isWritable(stream)) &&\n    (readableFinished || isReadable(stream) === false)\n  ) {\n    process.nextTick(onclosed)\n  } else if (rState && stream.req && stream.aborted) {\n    process.nextTick(onclosed)\n  }\n  const cleanup = () => {\n    callback = nop\n    stream.removeListener('aborted', onclose)\n    stream.removeListener('complete', onfinish)\n    stream.removeListener('abort', onclose)\n    stream.removeListener('request', onrequest)\n    if (stream.req) stream.req.removeListener('finish', onfinish)\n    stream.removeListener('end', onlegacyfinish)\n    stream.removeListener('close', onlegacyfinish)\n    stream.removeListener('finish', onfinish)\n    stream.removeListener('end', onend)\n    stream.removeListener('error', onerror)\n    stream.removeListener('close', onclose)\n  }\n  if (options.signal && !closed) {\n    const abort = () => {\n      // Keep it because cleanup removes it.\n      const endCallback = callback\n      cleanup()\n      endCallback.call(\n        stream,\n        new AbortError(undefined, {\n          cause: options.signal.reason\n        })\n      )\n    }\n    if (options.signal.aborted) {\n      process.nextTick(abort)\n    } else {\n      addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n      const disposable = addAbortListener(options.signal, abort)\n      const originalCallback = callback\n      callback = once((...args) => {\n        disposable[SymbolDispose]()\n        originalCallback.apply(stream, args)\n      })\n    }\n  }\n  return cleanup\n}\nfunction eosWeb(stream, options, callback) {\n  let isAborted = false\n  let abort = nop\n  if (options.signal) {\n    abort = () => {\n      isAborted = true\n      callback.call(\n        stream,\n        new AbortError(undefined, {\n          cause: options.signal.reason\n        })\n      )\n    }\n    if (options.signal.aborted) {\n      process.nextTick(abort)\n    } else {\n      addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n      const disposable = addAbortListener(options.signal, abort)\n      const originalCallback = callback\n      callback = once((...args) => {\n        disposable[SymbolDispose]()\n        originalCallback.apply(stream, args)\n      })\n    }\n  }\n  const resolverFn = (...args) => {\n    if (!isAborted) {\n      process.nextTick(() => callback.apply(stream, args))\n    }\n  }\n  PromisePrototypeThen(stream[kIsClosedPromise].promise, resolverFn, resolverFn)\n  return nop\n}\nfunction finished(stream, opts) {\n  var _opts\n  let autoCleanup = false\n  if (opts === null) {\n    opts = kEmptyObject\n  }\n  if ((_opts = opts) !== null && _opts !== undefined && _opts.cleanup) {\n    validateBoolean(opts.cleanup, 'cleanup')\n    autoCleanup = opts.cleanup\n  }\n  return new Promise((resolve, reject) => {\n    const cleanup = eos(stream, opts, (err) => {\n      if (autoCleanup) {\n        cleanup()\n      }\n      if (err) {\n        reject(err)\n      } else {\n        resolve()\n      }\n    })\n  })\n}\nmodule.exports = eos\nmodule.exports.finished = finished\n","'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst {\n  aggregateTwoErrors,\n  codes: { ERR_MULTIPLE_CALLBACK },\n  AbortError\n} = require('../../ours/errors')\nconst { Symbol } = require('../../ours/primordials')\nconst { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = require('./utils')\nconst kDestroy = Symbol('kDestroy')\nconst kConstruct = Symbol('kConstruct')\nfunction checkError(err, w, r) {\n  if (err) {\n    // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364\n    err.stack // eslint-disable-line no-unused-expressions\n\n    if (w && !w.errored) {\n      w.errored = err\n    }\n    if (r && !r.errored) {\n      r.errored = err\n    }\n  }\n}\n\n// Backwards compat. cb() is undocumented and unused in core but\n// unfortunately might be used by modules.\nfunction destroy(err, cb) {\n  const r = this._readableState\n  const w = this._writableState\n  // With duplex streams we use the writable side for state.\n  const s = w || r\n  if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) {\n    if (typeof cb === 'function') {\n      cb()\n    }\n    return this\n  }\n\n  // We set destroyed to true before firing error callbacks in order\n  // to make it re-entrance safe in case destroy() is called within callbacks\n  checkError(err, w, r)\n  if (w) {\n    w.destroyed = true\n  }\n  if (r) {\n    r.destroyed = true\n  }\n\n  // If still constructing then defer calling _destroy.\n  if (!s.constructed) {\n    this.once(kDestroy, function (er) {\n      _destroy(this, aggregateTwoErrors(er, err), cb)\n    })\n  } else {\n    _destroy(this, err, cb)\n  }\n  return this\n}\nfunction _destroy(self, err, cb) {\n  let called = false\n  function onDestroy(err) {\n    if (called) {\n      return\n    }\n    called = true\n    const r = self._readableState\n    const w = self._writableState\n    checkError(err, w, r)\n    if (w) {\n      w.closed = true\n    }\n    if (r) {\n      r.closed = true\n    }\n    if (typeof cb === 'function') {\n      cb(err)\n    }\n    if (err) {\n      process.nextTick(emitErrorCloseNT, self, err)\n    } else {\n      process.nextTick(emitCloseNT, self)\n    }\n  }\n  try {\n    self._destroy(err || null, onDestroy)\n  } catch (err) {\n    onDestroy(err)\n  }\n}\nfunction emitErrorCloseNT(self, err) {\n  emitErrorNT(self, err)\n  emitCloseNT(self)\n}\nfunction emitCloseNT(self) {\n  const r = self._readableState\n  const w = self._writableState\n  if (w) {\n    w.closeEmitted = true\n  }\n  if (r) {\n    r.closeEmitted = true\n  }\n  if ((w !== null && w !== undefined && w.emitClose) || (r !== null && r !== undefined && r.emitClose)) {\n    self.emit('close')\n  }\n}\nfunction emitErrorNT(self, err) {\n  const r = self._readableState\n  const w = self._writableState\n  if ((w !== null && w !== undefined && w.errorEmitted) || (r !== null && r !== undefined && r.errorEmitted)) {\n    return\n  }\n  if (w) {\n    w.errorEmitted = true\n  }\n  if (r) {\n    r.errorEmitted = true\n  }\n  self.emit('error', err)\n}\nfunction undestroy() {\n  const r = this._readableState\n  const w = this._writableState\n  if (r) {\n    r.constructed = true\n    r.closed = false\n    r.closeEmitted = false\n    r.destroyed = false\n    r.errored = null\n    r.errorEmitted = false\n    r.reading = false\n    r.ended = r.readable === false\n    r.endEmitted = r.readable === false\n  }\n  if (w) {\n    w.constructed = true\n    w.destroyed = false\n    w.closed = false\n    w.closeEmitted = false\n    w.errored = null\n    w.errorEmitted = false\n    w.finalCalled = false\n    w.prefinished = false\n    w.ended = w.writable === false\n    w.ending = w.writable === false\n    w.finished = w.writable === false\n  }\n}\nfunction errorOrDestroy(stream, err, sync) {\n  // We have tests that rely on errors being emitted\n  // in the same tick, so changing this is semver major.\n  // For now when you opt-in to autoDestroy we allow\n  // the error to be emitted nextTick. In a future\n  // semver major update we should change the default to this.\n\n  const r = stream._readableState\n  const w = stream._writableState\n  if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) {\n    return this\n  }\n  if ((r !== null && r !== undefined && r.autoDestroy) || (w !== null && w !== undefined && w.autoDestroy))\n    stream.destroy(err)\n  else if (err) {\n    // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364\n    err.stack // eslint-disable-line no-unused-expressions\n\n    if (w && !w.errored) {\n      w.errored = err\n    }\n    if (r && !r.errored) {\n      r.errored = err\n    }\n    if (sync) {\n      process.nextTick(emitErrorNT, stream, err)\n    } else {\n      emitErrorNT(stream, err)\n    }\n  }\n}\nfunction construct(stream, cb) {\n  if (typeof stream._construct !== 'function') {\n    return\n  }\n  const r = stream._readableState\n  const w = stream._writableState\n  if (r) {\n    r.constructed = false\n  }\n  if (w) {\n    w.constructed = false\n  }\n  stream.once(kConstruct, cb)\n  if (stream.listenerCount(kConstruct) > 1) {\n    // Duplex\n    return\n  }\n  process.nextTick(constructNT, stream)\n}\nfunction constructNT(stream) {\n  let called = false\n  function onConstruct(err) {\n    if (called) {\n      errorOrDestroy(stream, err !== null && err !== undefined ? err : new ERR_MULTIPLE_CALLBACK())\n      return\n    }\n    called = true\n    const r = stream._readableState\n    const w = stream._writableState\n    const s = w || r\n    if (r) {\n      r.constructed = true\n    }\n    if (w) {\n      w.constructed = true\n    }\n    if (s.destroyed) {\n      stream.emit(kDestroy, err)\n    } else if (err) {\n      errorOrDestroy(stream, err, true)\n    } else {\n      process.nextTick(emitConstructNT, stream)\n    }\n  }\n  try {\n    stream._construct((err) => {\n      process.nextTick(onConstruct, err)\n    })\n  } catch (err) {\n    process.nextTick(onConstruct, err)\n  }\n}\nfunction emitConstructNT(stream) {\n  stream.emit(kConstruct)\n}\nfunction isRequest(stream) {\n  return (stream === null || stream === undefined ? undefined : stream.setHeader) && typeof stream.abort === 'function'\n}\nfunction emitCloseLegacy(stream) {\n  stream.emit('close')\n}\nfunction emitErrorCloseLegacy(stream, err) {\n  stream.emit('error', err)\n  process.nextTick(emitCloseLegacy, stream)\n}\n\n// Normalize destroy for legacy.\nfunction destroyer(stream, err) {\n  if (!stream || isDestroyed(stream)) {\n    return\n  }\n  if (!err && !isFinished(stream)) {\n    err = new AbortError()\n  }\n\n  // TODO: Remove isRequest branches.\n  if (isServerRequest(stream)) {\n    stream.socket = null\n    stream.destroy(err)\n  } else if (isRequest(stream)) {\n    stream.abort()\n  } else if (isRequest(stream.req)) {\n    stream.req.abort()\n  } else if (typeof stream.destroy === 'function') {\n    stream.destroy(err)\n  } else if (typeof stream.close === 'function') {\n    // TODO: Don't lose err?\n    stream.close()\n  } else if (err) {\n    process.nextTick(emitErrorCloseLegacy, stream, err)\n  } else {\n    process.nextTick(emitCloseLegacy, stream)\n  }\n  if (!stream.destroyed) {\n    stream[kIsDestroyed] = true\n  }\n}\nmodule.exports = {\n  construct,\n  destroyer,\n  destroy,\n  undestroy,\n  errorOrDestroy\n}\n","'use strict'\n\nconst { ArrayIsArray, ObjectSetPrototypeOf } = require('../../ours/primordials')\nconst { EventEmitter: EE } = require('events')\nfunction Stream(opts) {\n  EE.call(this, opts)\n}\nObjectSetPrototypeOf(Stream.prototype, EE.prototype)\nObjectSetPrototypeOf(Stream, EE)\nStream.prototype.pipe = function (dest, options) {\n  const source = this\n  function ondata(chunk) {\n    if (dest.writable && dest.write(chunk) === false && source.pause) {\n      source.pause()\n    }\n  }\n  source.on('data', ondata)\n  function ondrain() {\n    if (source.readable && source.resume) {\n      source.resume()\n    }\n  }\n  dest.on('drain', ondrain)\n\n  // If the 'end' option is not supplied, dest.end() will be called when\n  // source gets the 'end' or 'close' events.  Only dest.end() once.\n  if (!dest._isStdio && (!options || options.end !== false)) {\n    source.on('end', onend)\n    source.on('close', onclose)\n  }\n  let didOnEnd = false\n  function onend() {\n    if (didOnEnd) return\n    didOnEnd = true\n    dest.end()\n  }\n  function onclose() {\n    if (didOnEnd) return\n    didOnEnd = true\n    if (typeof dest.destroy === 'function') dest.destroy()\n  }\n\n  // Don't leave dangling pipes when there are errors.\n  function onerror(er) {\n    cleanup()\n    if (EE.listenerCount(this, 'error') === 0) {\n      this.emit('error', er)\n    }\n  }\n  prependListener(source, 'error', onerror)\n  prependListener(dest, 'error', onerror)\n\n  // Remove all the event listeners that were added.\n  function cleanup() {\n    source.removeListener('data', ondata)\n    dest.removeListener('drain', ondrain)\n    source.removeListener('end', onend)\n    source.removeListener('close', onclose)\n    source.removeListener('error', onerror)\n    dest.removeListener('error', onerror)\n    source.removeListener('end', cleanup)\n    source.removeListener('close', cleanup)\n    dest.removeListener('close', cleanup)\n  }\n  source.on('end', cleanup)\n  source.on('close', cleanup)\n  dest.on('close', cleanup)\n  dest.emit('pipe', source)\n\n  // Allow for unix-like usage: A.pipe(B).pipe(C)\n  return dest\n}\nfunction prependListener(emitter, event, fn) {\n  // Sadly this is not cacheable as some libraries bundle their own\n  // event emitter implementation with them.\n  if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn)\n\n  // This is a hack to make sure that our error handler is attached before any\n  // userland ones.  NEVER DO THIS. This is here only because this code needs\n  // to continue to work with older versions of Node.js that do not include\n  // the prependListener() method. The goal is to eventually remove this hack.\n  if (!emitter._events || !emitter._events[event]) emitter.on(event, fn)\n  else if (ArrayIsArray(emitter._events[event])) emitter._events[event].unshift(fn)\n  else emitter._events[event] = [fn, emitter._events[event]]\n}\nmodule.exports = {\n  Stream,\n  prependListener\n}\n","'use strict'\n\nconst { SymbolDispose } = require('../../ours/primordials')\nconst { AbortError, codes } = require('../../ours/errors')\nconst { isNodeStream, isWebStream, kControllerErrorFunction } = require('./utils')\nconst eos = require('./end-of-stream')\nconst { ERR_INVALID_ARG_TYPE } = codes\nlet addAbortListener\n\n// This method is inlined here for readable-stream\n// It also does not allow for signal to not exist on the stream\n// https://github.com/nodejs/node/pull/36061#discussion_r533718029\nconst validateAbortSignal = (signal, name) => {\n  if (typeof signal !== 'object' || !('aborted' in signal)) {\n    throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal)\n  }\n}\nmodule.exports.addAbortSignal = function addAbortSignal(signal, stream) {\n  validateAbortSignal(signal, 'signal')\n  if (!isNodeStream(stream) && !isWebStream(stream)) {\n    throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream)\n  }\n  return module.exports.addAbortSignalNoValidate(signal, stream)\n}\nmodule.exports.addAbortSignalNoValidate = function (signal, stream) {\n  if (typeof signal !== 'object' || !('aborted' in signal)) {\n    return stream\n  }\n  const onAbort = isNodeStream(stream)\n    ? () => {\n        stream.destroy(\n          new AbortError(undefined, {\n            cause: signal.reason\n          })\n        )\n      }\n    : () => {\n        stream[kControllerErrorFunction](\n          new AbortError(undefined, {\n            cause: signal.reason\n          })\n        )\n      }\n  if (signal.aborted) {\n    onAbort()\n  } else {\n    addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n    const disposable = addAbortListener(signal, onAbort)\n    eos(stream, disposable[SymbolDispose])\n  }\n  return stream\n}\n","'use strict'\n\nconst { StringPrototypeSlice, SymbolIterator, TypedArrayPrototypeSet, Uint8Array } = require('../../ours/primordials')\nconst { Buffer } = require('buffer')\nconst { inspect } = require('../../ours/util')\nmodule.exports = class BufferList {\n  constructor() {\n    this.head = null\n    this.tail = null\n    this.length = 0\n  }\n  push(v) {\n    const entry = {\n      data: v,\n      next: null\n    }\n    if (this.length > 0) this.tail.next = entry\n    else this.head = entry\n    this.tail = entry\n    ++this.length\n  }\n  unshift(v) {\n    const entry = {\n      data: v,\n      next: this.head\n    }\n    if (this.length === 0) this.tail = entry\n    this.head = entry\n    ++this.length\n  }\n  shift() {\n    if (this.length === 0) return\n    const ret = this.head.data\n    if (this.length === 1) this.head = this.tail = null\n    else this.head = this.head.next\n    --this.length\n    return ret\n  }\n  clear() {\n    this.head = this.tail = null\n    this.length = 0\n  }\n  join(s) {\n    if (this.length === 0) return ''\n    let p = this.head\n    let ret = '' + p.data\n    while ((p = p.next) !== null) ret += s + p.data\n    return ret\n  }\n  concat(n) {\n    if (this.length === 0) return Buffer.alloc(0)\n    const ret = Buffer.allocUnsafe(n >>> 0)\n    let p = this.head\n    let i = 0\n    while (p) {\n      TypedArrayPrototypeSet(ret, p.data, i)\n      i += p.data.length\n      p = p.next\n    }\n    return ret\n  }\n\n  // Consumes a specified amount of bytes or characters from the buffered data.\n  consume(n, hasStrings) {\n    const data = this.head.data\n    if (n < data.length) {\n      // `slice` is the same for buffers and strings.\n      const slice = data.slice(0, n)\n      this.head.data = data.slice(n)\n      return slice\n    }\n    if (n === data.length) {\n      // First chunk is a perfect match.\n      return this.shift()\n    }\n    // Result spans more than one buffer.\n    return hasStrings ? this._getString(n) : this._getBuffer(n)\n  }\n  first() {\n    return this.head.data\n  }\n  *[SymbolIterator]() {\n    for (let p = this.head; p; p = p.next) {\n      yield p.data\n    }\n  }\n\n  // Consumes a specified amount of characters from the buffered data.\n  _getString(n) {\n    let ret = ''\n    let p = this.head\n    let c = 0\n    do {\n      const str = p.data\n      if (n > str.length) {\n        ret += str\n        n -= str.length\n      } else {\n        if (n === str.length) {\n          ret += str\n          ++c\n          if (p.next) this.head = p.next\n          else this.head = this.tail = null\n        } else {\n          ret += StringPrototypeSlice(str, 0, n)\n          this.head = p\n          p.data = StringPrototypeSlice(str, n)\n        }\n        break\n      }\n      ++c\n    } while ((p = p.next) !== null)\n    this.length -= c\n    return ret\n  }\n\n  // Consumes a specified amount of bytes from the buffered data.\n  _getBuffer(n) {\n    const ret = Buffer.allocUnsafe(n)\n    const retLen = n\n    let p = this.head\n    let c = 0\n    do {\n      const buf = p.data\n      if (n > buf.length) {\n        TypedArrayPrototypeSet(ret, buf, retLen - n)\n        n -= buf.length\n      } else {\n        if (n === buf.length) {\n          TypedArrayPrototypeSet(ret, buf, retLen - n)\n          ++c\n          if (p.next) this.head = p.next\n          else this.head = this.tail = null\n        } else {\n          TypedArrayPrototypeSet(ret, new Uint8Array(buf.buffer, buf.byteOffset, n), retLen - n)\n          this.head = p\n          p.data = buf.slice(n)\n        }\n        break\n      }\n      ++c\n    } while ((p = p.next) !== null)\n    this.length -= c\n    return ret\n  }\n\n  // Make sure the linked list only shows the minimal necessary information.\n  [Symbol.for('nodejs.util.inspect.custom')](_, options) {\n    return inspect(this, {\n      ...options,\n      // Only inspect one level.\n      depth: 0,\n      // It should not recurse.\n      customInspect: false\n    })\n  }\n}\n","'use strict'\n\nconst { MathFloor, NumberIsInteger } = require('../../ours/primordials')\nconst { validateInteger } = require('../validators')\nconst { ERR_INVALID_ARG_VALUE } = require('../../ours/errors').codes\nlet defaultHighWaterMarkBytes = 16 * 1024\nlet defaultHighWaterMarkObjectMode = 16\nfunction highWaterMarkFrom(options, isDuplex, duplexKey) {\n  return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null\n}\nfunction getDefaultHighWaterMark(objectMode) {\n  return objectMode ? defaultHighWaterMarkObjectMode : defaultHighWaterMarkBytes\n}\nfunction setDefaultHighWaterMark(objectMode, value) {\n  validateInteger(value, 'value', 0)\n  if (objectMode) {\n    defaultHighWaterMarkObjectMode = value\n  } else {\n    defaultHighWaterMarkBytes = value\n  }\n}\nfunction getHighWaterMark(state, options, duplexKey, isDuplex) {\n  const hwm = highWaterMarkFrom(options, isDuplex, duplexKey)\n  if (hwm != null) {\n    if (!NumberIsInteger(hwm) || hwm < 0) {\n      const name = isDuplex ? `options.${duplexKey}` : 'options.highWaterMark'\n      throw new ERR_INVALID_ARG_VALUE(name, hwm)\n    }\n    return MathFloor(hwm)\n  }\n\n  // Default value\n  return getDefaultHighWaterMark(state.objectMode)\n}\nmodule.exports = {\n  getHighWaterMark,\n  getDefaultHighWaterMark,\n  setDefaultHighWaterMark\n}\n","/*! safe-buffer. MIT License. Feross Aboukhadijeh  */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n  for (var key in src) {\n    dst[key] = src[key]\n  }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n  module.exports = buffer\n} else {\n  // Copy properties from require('buffer')\n  copyProps(buffer, exports)\n  exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n  return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n  if (typeof arg === 'number') {\n    throw new TypeError('Argument must not be a number')\n  }\n  return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n  if (typeof size !== 'number') {\n    throw new TypeError('Argument must be a number')\n  }\n  var buf = Buffer(size)\n  if (fill !== undefined) {\n    if (typeof encoding === 'string') {\n      buf.fill(fill, encoding)\n    } else {\n      buf.fill(fill)\n    }\n  } else {\n    buf.fill(0)\n  }\n  return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n  if (typeof size !== 'number') {\n    throw new TypeError('Argument must be a number')\n  }\n  return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n  if (typeof size !== 'number') {\n    throw new TypeError('Argument must be a number')\n  }\n  return buffer.SlowBuffer(size)\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n  encoding = '' + encoding;\n  switch (encoding && encoding.toLowerCase()) {\n    case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n      return true;\n    default:\n      return false;\n  }\n};\n\nfunction _normalizeEncoding(enc) {\n  if (!enc) return 'utf8';\n  var retried;\n  while (true) {\n    switch (enc) {\n      case 'utf8':\n      case 'utf-8':\n        return 'utf8';\n      case 'ucs2':\n      case 'ucs-2':\n      case 'utf16le':\n      case 'utf-16le':\n        return 'utf16le';\n      case 'latin1':\n      case 'binary':\n        return 'latin1';\n      case 'base64':\n      case 'ascii':\n      case 'hex':\n        return enc;\n      default:\n        if (retried) return; // undefined\n        enc = ('' + enc).toLowerCase();\n        retried = true;\n    }\n  }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n  var nenc = _normalizeEncoding(enc);\n  if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n  return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n  this.encoding = normalizeEncoding(encoding);\n  var nb;\n  switch (this.encoding) {\n    case 'utf16le':\n      this.text = utf16Text;\n      this.end = utf16End;\n      nb = 4;\n      break;\n    case 'utf8':\n      this.fillLast = utf8FillLast;\n      nb = 4;\n      break;\n    case 'base64':\n      this.text = base64Text;\n      this.end = base64End;\n      nb = 3;\n      break;\n    default:\n      this.write = simpleWrite;\n      this.end = simpleEnd;\n      return;\n  }\n  this.lastNeed = 0;\n  this.lastTotal = 0;\n  this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n  if (buf.length === 0) return '';\n  var r;\n  var i;\n  if (this.lastNeed) {\n    r = this.fillLast(buf);\n    if (r === undefined) return '';\n    i = this.lastNeed;\n    this.lastNeed = 0;\n  } else {\n    i = 0;\n  }\n  if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n  return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n  if (this.lastNeed <= buf.length) {\n    buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n    return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n  }\n  buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n  this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n  if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n  return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n  var j = buf.length - 1;\n  if (j < i) return 0;\n  var nb = utf8CheckByte(buf[j]);\n  if (nb >= 0) {\n    if (nb > 0) self.lastNeed = nb - 1;\n    return nb;\n  }\n  if (--j < i || nb === -2) return 0;\n  nb = utf8CheckByte(buf[j]);\n  if (nb >= 0) {\n    if (nb > 0) self.lastNeed = nb - 2;\n    return nb;\n  }\n  if (--j < i || nb === -2) return 0;\n  nb = utf8CheckByte(buf[j]);\n  if (nb >= 0) {\n    if (nb > 0) {\n      if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n    }\n    return nb;\n  }\n  return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n  if ((buf[0] & 0xC0) !== 0x80) {\n    self.lastNeed = 0;\n    return '\\ufffd';\n  }\n  if (self.lastNeed > 1 && buf.length > 1) {\n    if ((buf[1] & 0xC0) !== 0x80) {\n      self.lastNeed = 1;\n      return '\\ufffd';\n    }\n    if (self.lastNeed > 2 && buf.length > 2) {\n      if ((buf[2] & 0xC0) !== 0x80) {\n        self.lastNeed = 2;\n        return '\\ufffd';\n      }\n    }\n  }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n  var p = this.lastTotal - this.lastNeed;\n  var r = utf8CheckExtraBytes(this, buf, p);\n  if (r !== undefined) return r;\n  if (this.lastNeed <= buf.length) {\n    buf.copy(this.lastChar, p, 0, this.lastNeed);\n    return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n  }\n  buf.copy(this.lastChar, p, 0, buf.length);\n  this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n  var total = utf8CheckIncomplete(this, buf, i);\n  if (!this.lastNeed) return buf.toString('utf8', i);\n  this.lastTotal = total;\n  var end = buf.length - (total - this.lastNeed);\n  buf.copy(this.lastChar, 0, end);\n  return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n  var r = buf && buf.length ? this.write(buf) : '';\n  if (this.lastNeed) return r + '\\ufffd';\n  return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n  if ((buf.length - i) % 2 === 0) {\n    var r = buf.toString('utf16le', i);\n    if (r) {\n      var c = r.charCodeAt(r.length - 1);\n      if (c >= 0xD800 && c <= 0xDBFF) {\n        this.lastNeed = 2;\n        this.lastTotal = 4;\n        this.lastChar[0] = buf[buf.length - 2];\n        this.lastChar[1] = buf[buf.length - 1];\n        return r.slice(0, -1);\n      }\n    }\n    return r;\n  }\n  this.lastNeed = 1;\n  this.lastTotal = 2;\n  this.lastChar[0] = buf[buf.length - 1];\n  return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n  var r = buf && buf.length ? this.write(buf) : '';\n  if (this.lastNeed) {\n    var end = this.lastTotal - this.lastNeed;\n    return r + this.lastChar.toString('utf16le', 0, end);\n  }\n  return r;\n}\n\nfunction base64Text(buf, i) {\n  var n = (buf.length - i) % 3;\n  if (n === 0) return buf.toString('base64', i);\n  this.lastNeed = 3 - n;\n  this.lastTotal = 3;\n  if (n === 1) {\n    this.lastChar[0] = buf[buf.length - 1];\n  } else {\n    this.lastChar[0] = buf[buf.length - 2];\n    this.lastChar[1] = buf[buf.length - 1];\n  }\n  return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n  var r = buf && buf.length ? this.write(buf) : '';\n  if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n  return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n  return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n  return buf && buf.length ? this.write(buf) : '';\n}","'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } = require('../../ours/primordials')\nconst { Buffer } = require('buffer')\nconst { ERR_INVALID_ARG_TYPE, ERR_STREAM_NULL_VALUES } = require('../../ours/errors').codes\nfunction from(Readable, iterable, opts) {\n  let iterator\n  if (typeof iterable === 'string' || iterable instanceof Buffer) {\n    return new Readable({\n      objectMode: true,\n      ...opts,\n      read() {\n        this.push(iterable)\n        this.push(null)\n      }\n    })\n  }\n  let isAsync\n  if (iterable && iterable[SymbolAsyncIterator]) {\n    isAsync = true\n    iterator = iterable[SymbolAsyncIterator]()\n  } else if (iterable && iterable[SymbolIterator]) {\n    isAsync = false\n    iterator = iterable[SymbolIterator]()\n  } else {\n    throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable)\n  }\n  const readable = new Readable({\n    objectMode: true,\n    highWaterMark: 1,\n    // TODO(ronag): What options should be allowed?\n    ...opts\n  })\n\n  // Flag to protect against _read\n  // being called before last iteration completion.\n  let reading = false\n  readable._read = function () {\n    if (!reading) {\n      reading = true\n      next()\n    }\n  }\n  readable._destroy = function (error, cb) {\n    PromisePrototypeThen(\n      close(error),\n      () => process.nextTick(cb, error),\n      // nextTick is here in case cb throws\n      (e) => process.nextTick(cb, e || error)\n    )\n  }\n  async function close(error) {\n    const hadError = error !== undefined && error !== null\n    const hasThrow = typeof iterator.throw === 'function'\n    if (hadError && hasThrow) {\n      const { value, done } = await iterator.throw(error)\n      await value\n      if (done) {\n        return\n      }\n    }\n    if (typeof iterator.return === 'function') {\n      const { value } = await iterator.return()\n      await value\n    }\n  }\n  async function next() {\n    for (;;) {\n      try {\n        const { value, done } = isAsync ? await iterator.next() : iterator.next()\n        if (done) {\n          readable.push(null)\n        } else {\n          const res = value && typeof value.then === 'function' ? await value : value\n          if (res === null) {\n            reading = false\n            throw new ERR_STREAM_NULL_VALUES()\n          } else if (readable.push(res)) {\n            continue\n          } else {\n            reading = false\n          }\n        }\n      } catch (err) {\n        readable.destroy(err)\n      }\n      break\n    }\n  }\n  return readable\n}\nmodule.exports = from\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst {\n  ArrayPrototypeIndexOf,\n  NumberIsInteger,\n  NumberIsNaN,\n  NumberParseInt,\n  ObjectDefineProperties,\n  ObjectKeys,\n  ObjectSetPrototypeOf,\n  Promise,\n  SafeSet,\n  SymbolAsyncDispose,\n  SymbolAsyncIterator,\n  Symbol\n} = require('../../ours/primordials')\nmodule.exports = Readable\nReadable.ReadableState = ReadableState\nconst { EventEmitter: EE } = require('events')\nconst { Stream, prependListener } = require('./legacy')\nconst { Buffer } = require('buffer')\nconst { addAbortSignal } = require('./add-abort-signal')\nconst eos = require('./end-of-stream')\nlet debug = require('../../ours/util').debuglog('stream', (fn) => {\n  debug = fn\n})\nconst BufferList = require('./buffer_list')\nconst destroyImpl = require('./destroy')\nconst { getHighWaterMark, getDefaultHighWaterMark } = require('./state')\nconst {\n  aggregateTwoErrors,\n  codes: {\n    ERR_INVALID_ARG_TYPE,\n    ERR_METHOD_NOT_IMPLEMENTED,\n    ERR_OUT_OF_RANGE,\n    ERR_STREAM_PUSH_AFTER_EOF,\n    ERR_STREAM_UNSHIFT_AFTER_END_EVENT\n  },\n  AbortError\n} = require('../../ours/errors')\nconst { validateObject } = require('../validators')\nconst kPaused = Symbol('kPaused')\nconst { StringDecoder } = require('string_decoder/')\nconst from = require('./from')\nObjectSetPrototypeOf(Readable.prototype, Stream.prototype)\nObjectSetPrototypeOf(Readable, Stream)\nconst nop = () => {}\nconst { errorOrDestroy } = destroyImpl\nconst kObjectMode = 1 << 0\nconst kEnded = 1 << 1\nconst kEndEmitted = 1 << 2\nconst kReading = 1 << 3\nconst kConstructed = 1 << 4\nconst kSync = 1 << 5\nconst kNeedReadable = 1 << 6\nconst kEmittedReadable = 1 << 7\nconst kReadableListening = 1 << 8\nconst kResumeScheduled = 1 << 9\nconst kErrorEmitted = 1 << 10\nconst kEmitClose = 1 << 11\nconst kAutoDestroy = 1 << 12\nconst kDestroyed = 1 << 13\nconst kClosed = 1 << 14\nconst kCloseEmitted = 1 << 15\nconst kMultiAwaitDrain = 1 << 16\nconst kReadingMore = 1 << 17\nconst kDataEmitted = 1 << 18\n\n// TODO(benjamingr) it is likely slower to do it this way than with free functions\nfunction makeBitMapDescriptor(bit) {\n  return {\n    enumerable: false,\n    get() {\n      return (this.state & bit) !== 0\n    },\n    set(value) {\n      if (value) this.state |= bit\n      else this.state &= ~bit\n    }\n  }\n}\nObjectDefineProperties(ReadableState.prototype, {\n  objectMode: makeBitMapDescriptor(kObjectMode),\n  ended: makeBitMapDescriptor(kEnded),\n  endEmitted: makeBitMapDescriptor(kEndEmitted),\n  reading: makeBitMapDescriptor(kReading),\n  // Stream is still being constructed and cannot be\n  // destroyed until construction finished or failed.\n  // Async construction is opt in, therefore we start as\n  // constructed.\n  constructed: makeBitMapDescriptor(kConstructed),\n  // A flag to be able to tell if the event 'readable'/'data' is emitted\n  // immediately, or on a later tick.  We set this to true at first, because\n  // any actions that shouldn't happen until \"later\" should generally also\n  // not happen before the first read call.\n  sync: makeBitMapDescriptor(kSync),\n  // Whenever we return null, then we set a flag to say\n  // that we're awaiting a 'readable' event emission.\n  needReadable: makeBitMapDescriptor(kNeedReadable),\n  emittedReadable: makeBitMapDescriptor(kEmittedReadable),\n  readableListening: makeBitMapDescriptor(kReadableListening),\n  resumeScheduled: makeBitMapDescriptor(kResumeScheduled),\n  // True if the error was already emitted and should not be thrown again.\n  errorEmitted: makeBitMapDescriptor(kErrorEmitted),\n  emitClose: makeBitMapDescriptor(kEmitClose),\n  autoDestroy: makeBitMapDescriptor(kAutoDestroy),\n  // Has it been destroyed.\n  destroyed: makeBitMapDescriptor(kDestroyed),\n  // Indicates whether the stream has finished destroying.\n  closed: makeBitMapDescriptor(kClosed),\n  // True if close has been emitted or would have been emitted\n  // depending on emitClose.\n  closeEmitted: makeBitMapDescriptor(kCloseEmitted),\n  multiAwaitDrain: makeBitMapDescriptor(kMultiAwaitDrain),\n  // If true, a maybeReadMore has been scheduled.\n  readingMore: makeBitMapDescriptor(kReadingMore),\n  dataEmitted: makeBitMapDescriptor(kDataEmitted)\n})\nfunction ReadableState(options, stream, isDuplex) {\n  // Duplex streams are both readable and writable, but share\n  // the same options object.\n  // However, some cases require setting options to different\n  // values for the readable and the writable sides of the duplex stream.\n  // These options can be provided separately as readableXXX and writableXXX.\n  if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof require('./duplex')\n\n  // Bit map field to store ReadableState more effciently with 1 bit per field\n  // instead of a V8 slot per field.\n  this.state = kEmitClose | kAutoDestroy | kConstructed | kSync\n  // Object stream flag. Used to make read(n) ignore n and to\n  // make all the buffer merging and length checks go away.\n  if (options && options.objectMode) this.state |= kObjectMode\n  if (isDuplex && options && options.readableObjectMode) this.state |= kObjectMode\n\n  // The point at which it stops calling _read() to fill the buffer\n  // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n  this.highWaterMark = options\n    ? getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex)\n    : getDefaultHighWaterMark(false)\n\n  // A linked list is used to store data chunks instead of an array because the\n  // linked list can remove elements from the beginning faster than\n  // array.shift().\n  this.buffer = new BufferList()\n  this.length = 0\n  this.pipes = []\n  this.flowing = null\n  this[kPaused] = null\n\n  // Should close be emitted on destroy. Defaults to true.\n  if (options && options.emitClose === false) this.state &= ~kEmitClose\n\n  // Should .destroy() be called after 'end' (and potentially 'finish').\n  if (options && options.autoDestroy === false) this.state &= ~kAutoDestroy\n\n  // Indicates whether the stream has errored. When true no further\n  // _read calls, 'data' or 'readable' events should occur. This is needed\n  // since when autoDestroy is disabled we need a way to tell whether the\n  // stream has failed.\n  this.errored = null\n\n  // Crypto is kind of old and crusty.  Historically, its default string\n  // encoding is 'binary' so we have to make this configurable.\n  // Everything else in the universe uses 'utf8', though.\n  this.defaultEncoding = (options && options.defaultEncoding) || 'utf8'\n\n  // Ref the piped dest which we need a drain event on it\n  // type: null | Writable | Set.\n  this.awaitDrainWriters = null\n  this.decoder = null\n  this.encoding = null\n  if (options && options.encoding) {\n    this.decoder = new StringDecoder(options.encoding)\n    this.encoding = options.encoding\n  }\n}\nfunction Readable(options) {\n  if (!(this instanceof Readable)) return new Readable(options)\n\n  // Checking for a Stream.Duplex instance is faster here instead of inside\n  // the ReadableState constructor, at least with V8 6.5.\n  const isDuplex = this instanceof require('./duplex')\n  this._readableState = new ReadableState(options, this, isDuplex)\n  if (options) {\n    if (typeof options.read === 'function') this._read = options.read\n    if (typeof options.destroy === 'function') this._destroy = options.destroy\n    if (typeof options.construct === 'function') this._construct = options.construct\n    if (options.signal && !isDuplex) addAbortSignal(options.signal, this)\n  }\n  Stream.call(this, options)\n  destroyImpl.construct(this, () => {\n    if (this._readableState.needReadable) {\n      maybeReadMore(this, this._readableState)\n    }\n  })\n}\nReadable.prototype.destroy = destroyImpl.destroy\nReadable.prototype._undestroy = destroyImpl.undestroy\nReadable.prototype._destroy = function (err, cb) {\n  cb(err)\n}\nReadable.prototype[EE.captureRejectionSymbol] = function (err) {\n  this.destroy(err)\n}\nReadable.prototype[SymbolAsyncDispose] = function () {\n  let error\n  if (!this.destroyed) {\n    error = this.readableEnded ? null : new AbortError()\n    this.destroy(error)\n  }\n  return new Promise((resolve, reject) => eos(this, (err) => (err && err !== error ? reject(err) : resolve(null))))\n}\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n  return readableAddChunk(this, chunk, encoding, false)\n}\n\n// Unshift should *always* be something directly out of read().\nReadable.prototype.unshift = function (chunk, encoding) {\n  return readableAddChunk(this, chunk, encoding, true)\n}\nfunction readableAddChunk(stream, chunk, encoding, addToFront) {\n  debug('readableAddChunk', chunk)\n  const state = stream._readableState\n  let err\n  if ((state.state & kObjectMode) === 0) {\n    if (typeof chunk === 'string') {\n      encoding = encoding || state.defaultEncoding\n      if (state.encoding !== encoding) {\n        if (addToFront && state.encoding) {\n          // When unshifting, if state.encoding is set, we have to save\n          // the string in the BufferList with the state encoding.\n          chunk = Buffer.from(chunk, encoding).toString(state.encoding)\n        } else {\n          chunk = Buffer.from(chunk, encoding)\n          encoding = ''\n        }\n      }\n    } else if (chunk instanceof Buffer) {\n      encoding = ''\n    } else if (Stream._isUint8Array(chunk)) {\n      chunk = Stream._uint8ArrayToBuffer(chunk)\n      encoding = ''\n    } else if (chunk != null) {\n      err = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk)\n    }\n  }\n  if (err) {\n    errorOrDestroy(stream, err)\n  } else if (chunk === null) {\n    state.state &= ~kReading\n    onEofChunk(stream, state)\n  } else if ((state.state & kObjectMode) !== 0 || (chunk && chunk.length > 0)) {\n    if (addToFront) {\n      if ((state.state & kEndEmitted) !== 0) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT())\n      else if (state.destroyed || state.errored) return false\n      else addChunk(stream, state, chunk, true)\n    } else if (state.ended) {\n      errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF())\n    } else if (state.destroyed || state.errored) {\n      return false\n    } else {\n      state.state &= ~kReading\n      if (state.decoder && !encoding) {\n        chunk = state.decoder.write(chunk)\n        if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false)\n        else maybeReadMore(stream, state)\n      } else {\n        addChunk(stream, state, chunk, false)\n      }\n    }\n  } else if (!addToFront) {\n    state.state &= ~kReading\n    maybeReadMore(stream, state)\n  }\n\n  // We can push more data if we are below the highWaterMark.\n  // Also, if we have no data yet, we can stand some more bytes.\n  // This is to work around cases where hwm=0, such as the repl.\n  return !state.ended && (state.length < state.highWaterMark || state.length === 0)\n}\nfunction addChunk(stream, state, chunk, addToFront) {\n  if (state.flowing && state.length === 0 && !state.sync && stream.listenerCount('data') > 0) {\n    // Use the guard to avoid creating `Set()` repeatedly\n    // when we have multiple pipes.\n    if ((state.state & kMultiAwaitDrain) !== 0) {\n      state.awaitDrainWriters.clear()\n    } else {\n      state.awaitDrainWriters = null\n    }\n    state.dataEmitted = true\n    stream.emit('data', chunk)\n  } else {\n    // Update the buffer info.\n    state.length += state.objectMode ? 1 : chunk.length\n    if (addToFront) state.buffer.unshift(chunk)\n    else state.buffer.push(chunk)\n    if ((state.state & kNeedReadable) !== 0) emitReadable(stream)\n  }\n  maybeReadMore(stream, state)\n}\nReadable.prototype.isPaused = function () {\n  const state = this._readableState\n  return state[kPaused] === true || state.flowing === false\n}\n\n// Backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n  const decoder = new StringDecoder(enc)\n  this._readableState.decoder = decoder\n  // If setEncoding(null), decoder.encoding equals utf8.\n  this._readableState.encoding = this._readableState.decoder.encoding\n  const buffer = this._readableState.buffer\n  // Iterate over current buffer to convert already stored Buffers:\n  let content = ''\n  for (const data of buffer) {\n    content += decoder.write(data)\n  }\n  buffer.clear()\n  if (content !== '') buffer.push(content)\n  this._readableState.length = content.length\n  return this\n}\n\n// Don't raise the hwm > 1GB.\nconst MAX_HWM = 0x40000000\nfunction computeNewHighWaterMark(n) {\n  if (n > MAX_HWM) {\n    throw new ERR_OUT_OF_RANGE('size', '<= 1GiB', n)\n  } else {\n    // Get the next highest power of 2 to prevent increasing hwm excessively in\n    // tiny amounts.\n    n--\n    n |= n >>> 1\n    n |= n >>> 2\n    n |= n >>> 4\n    n |= n >>> 8\n    n |= n >>> 16\n    n++\n  }\n  return n\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n  if (n <= 0 || (state.length === 0 && state.ended)) return 0\n  if ((state.state & kObjectMode) !== 0) return 1\n  if (NumberIsNaN(n)) {\n    // Only flow one buffer at a time.\n    if (state.flowing && state.length) return state.buffer.first().length\n    return state.length\n  }\n  if (n <= state.length) return n\n  return state.ended ? state.length : 0\n}\n\n// You can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n  debug('read', n)\n  // Same as parseInt(undefined, 10), however V8 7.3 performance regressed\n  // in this scenario, so we are doing it manually.\n  if (n === undefined) {\n    n = NaN\n  } else if (!NumberIsInteger(n)) {\n    n = NumberParseInt(n, 10)\n  }\n  const state = this._readableState\n  const nOrig = n\n\n  // If we're asking for more than the current hwm, then raise the hwm.\n  if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n)\n  if (n !== 0) state.state &= ~kEmittedReadable\n\n  // If we're doing read(0) to trigger a readable event, but we\n  // already have a bunch of data in the buffer, then just trigger\n  // the 'readable' event and move on.\n  if (\n    n === 0 &&\n    state.needReadable &&\n    ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)\n  ) {\n    debug('read: emitReadable', state.length, state.ended)\n    if (state.length === 0 && state.ended) endReadable(this)\n    else emitReadable(this)\n    return null\n  }\n  n = howMuchToRead(n, state)\n\n  // If we've ended, and we're now clear, then finish it up.\n  if (n === 0 && state.ended) {\n    if (state.length === 0) endReadable(this)\n    return null\n  }\n\n  // All the actual chunk generation logic needs to be\n  // *below* the call to _read.  The reason is that in certain\n  // synthetic stream cases, such as passthrough streams, _read\n  // may be a completely synchronous operation which may change\n  // the state of the read buffer, providing enough data when\n  // before there was *not* enough.\n  //\n  // So, the steps are:\n  // 1. Figure out what the state of things will be after we do\n  // a read from the buffer.\n  //\n  // 2. If that resulting state will trigger a _read, then call _read.\n  // Note that this may be asynchronous, or synchronous.  Yes, it is\n  // deeply ugly to write APIs this way, but that still doesn't mean\n  // that the Readable class should behave improperly, as streams are\n  // designed to be sync/async agnostic.\n  // Take note if the _read call is sync or async (ie, if the read call\n  // has returned yet), so that we know whether or not it's safe to emit\n  // 'readable' etc.\n  //\n  // 3. Actually pull the requested chunks out of the buffer and return.\n\n  // if we need a readable event, then we need to do some reading.\n  let doRead = (state.state & kNeedReadable) !== 0\n  debug('need readable', doRead)\n\n  // If we currently have less than the highWaterMark, then also read some.\n  if (state.length === 0 || state.length - n < state.highWaterMark) {\n    doRead = true\n    debug('length less than watermark', doRead)\n  }\n\n  // However, if we've ended, then there's no point, if we're already\n  // reading, then it's unnecessary, if we're constructing we have to wait,\n  // and if we're destroyed or errored, then it's not allowed,\n  if (state.ended || state.reading || state.destroyed || state.errored || !state.constructed) {\n    doRead = false\n    debug('reading, ended or constructing', doRead)\n  } else if (doRead) {\n    debug('do read')\n    state.state |= kReading | kSync\n    // If the length is currently zero, then we *need* a readable event.\n    if (state.length === 0) state.state |= kNeedReadable\n\n    // Call internal read method\n    try {\n      this._read(state.highWaterMark)\n    } catch (err) {\n      errorOrDestroy(this, err)\n    }\n    state.state &= ~kSync\n\n    // If _read pushed data synchronously, then `reading` will be false,\n    // and we need to re-evaluate how much data we can return to the user.\n    if (!state.reading) n = howMuchToRead(nOrig, state)\n  }\n  let ret\n  if (n > 0) ret = fromList(n, state)\n  else ret = null\n  if (ret === null) {\n    state.needReadable = state.length <= state.highWaterMark\n    n = 0\n  } else {\n    state.length -= n\n    if (state.multiAwaitDrain) {\n      state.awaitDrainWriters.clear()\n    } else {\n      state.awaitDrainWriters = null\n    }\n  }\n  if (state.length === 0) {\n    // If we have nothing in the buffer, then we want to know\n    // as soon as we *do* get something into the buffer.\n    if (!state.ended) state.needReadable = true\n\n    // If we tried to read() past the EOF, then emit end on the next tick.\n    if (nOrig !== n && state.ended) endReadable(this)\n  }\n  if (ret !== null && !state.errorEmitted && !state.closeEmitted) {\n    state.dataEmitted = true\n    this.emit('data', ret)\n  }\n  return ret\n}\nfunction onEofChunk(stream, state) {\n  debug('onEofChunk')\n  if (state.ended) return\n  if (state.decoder) {\n    const chunk = state.decoder.end()\n    if (chunk && chunk.length) {\n      state.buffer.push(chunk)\n      state.length += state.objectMode ? 1 : chunk.length\n    }\n  }\n  state.ended = true\n  if (state.sync) {\n    // If we are sync, wait until next tick to emit the data.\n    // Otherwise we risk emitting data in the flow()\n    // the readable code triggers during a read() call.\n    emitReadable(stream)\n  } else {\n    // Emit 'readable' now to make sure it gets picked up.\n    state.needReadable = false\n    state.emittedReadable = true\n    // We have to emit readable now that we are EOF. Modules\n    // in the ecosystem (e.g. dicer) rely on this event being sync.\n    emitReadable_(stream)\n  }\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow.  This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n  const state = stream._readableState\n  debug('emitReadable', state.needReadable, state.emittedReadable)\n  state.needReadable = false\n  if (!state.emittedReadable) {\n    debug('emitReadable', state.flowing)\n    state.emittedReadable = true\n    process.nextTick(emitReadable_, stream)\n  }\n}\nfunction emitReadable_(stream) {\n  const state = stream._readableState\n  debug('emitReadable_', state.destroyed, state.length, state.ended)\n  if (!state.destroyed && !state.errored && (state.length || state.ended)) {\n    stream.emit('readable')\n    state.emittedReadable = false\n  }\n\n  // The stream needs another readable event if:\n  // 1. It is not flowing, as the flow mechanism will take\n  //    care of it.\n  // 2. It is not ended.\n  // 3. It is below the highWaterMark, so we can schedule\n  //    another readable later.\n  state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark\n  flow(stream)\n}\n\n// At this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data.  that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n  if (!state.readingMore && state.constructed) {\n    state.readingMore = true\n    process.nextTick(maybeReadMore_, stream, state)\n  }\n}\nfunction maybeReadMore_(stream, state) {\n  // Attempt to read more data if we should.\n  //\n  // The conditions for reading more data are (one of):\n  // - Not enough data buffered (state.length < state.highWaterMark). The loop\n  //   is responsible for filling the buffer with enough data if such data\n  //   is available. If highWaterMark is 0 and we are not in the flowing mode\n  //   we should _not_ attempt to buffer any extra data. We'll get more data\n  //   when the stream consumer calls read() instead.\n  // - No data in the buffer, and the stream is in flowing mode. In this mode\n  //   the loop below is responsible for ensuring read() is called. Failing to\n  //   call read here would abort the flow and there's no other mechanism for\n  //   continuing the flow if the stream consumer has just subscribed to the\n  //   'data' event.\n  //\n  // In addition to the above conditions to keep reading data, the following\n  // conditions prevent the data from being read:\n  // - The stream has ended (state.ended).\n  // - There is already a pending 'read' operation (state.reading). This is a\n  //   case where the stream has called the implementation defined _read()\n  //   method, but they are processing the call asynchronously and have _not_\n  //   called push() with new data. In this case we skip performing more\n  //   read()s. The execution ends in this method again after the _read() ends\n  //   up calling push() with more data.\n  while (\n    !state.reading &&\n    !state.ended &&\n    (state.length < state.highWaterMark || (state.flowing && state.length === 0))\n  ) {\n    const len = state.length\n    debug('maybeReadMore read 0')\n    stream.read(0)\n    if (len === state.length)\n      // Didn't get any data, stop spinning.\n      break\n  }\n  state.readingMore = false\n}\n\n// Abstract method.  to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n  throw new ERR_METHOD_NOT_IMPLEMENTED('_read()')\n}\nReadable.prototype.pipe = function (dest, pipeOpts) {\n  const src = this\n  const state = this._readableState\n  if (state.pipes.length === 1) {\n    if (!state.multiAwaitDrain) {\n      state.multiAwaitDrain = true\n      state.awaitDrainWriters = new SafeSet(state.awaitDrainWriters ? [state.awaitDrainWriters] : [])\n    }\n  }\n  state.pipes.push(dest)\n  debug('pipe count=%d opts=%j', state.pipes.length, pipeOpts)\n  const doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr\n  const endFn = doEnd ? onend : unpipe\n  if (state.endEmitted) process.nextTick(endFn)\n  else src.once('end', endFn)\n  dest.on('unpipe', onunpipe)\n  function onunpipe(readable, unpipeInfo) {\n    debug('onunpipe')\n    if (readable === src) {\n      if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n        unpipeInfo.hasUnpiped = true\n        cleanup()\n      }\n    }\n  }\n  function onend() {\n    debug('onend')\n    dest.end()\n  }\n  let ondrain\n  let cleanedUp = false\n  function cleanup() {\n    debug('cleanup')\n    // Cleanup event handlers once the pipe is broken.\n    dest.removeListener('close', onclose)\n    dest.removeListener('finish', onfinish)\n    if (ondrain) {\n      dest.removeListener('drain', ondrain)\n    }\n    dest.removeListener('error', onerror)\n    dest.removeListener('unpipe', onunpipe)\n    src.removeListener('end', onend)\n    src.removeListener('end', unpipe)\n    src.removeListener('data', ondata)\n    cleanedUp = true\n\n    // If the reader is waiting for a drain event from this\n    // specific writer, then it would cause it to never start\n    // flowing again.\n    // So, if this is awaiting a drain, then we just call it now.\n    // If we don't know, then assume that we are waiting for one.\n    if (ondrain && state.awaitDrainWriters && (!dest._writableState || dest._writableState.needDrain)) ondrain()\n  }\n  function pause() {\n    // If the user unpiped during `dest.write()`, it is possible\n    // to get stuck in a permanently paused state if that write\n    // also returned false.\n    // => Check whether `dest` is still a piping destination.\n    if (!cleanedUp) {\n      if (state.pipes.length === 1 && state.pipes[0] === dest) {\n        debug('false write response, pause', 0)\n        state.awaitDrainWriters = dest\n        state.multiAwaitDrain = false\n      } else if (state.pipes.length > 1 && state.pipes.includes(dest)) {\n        debug('false write response, pause', state.awaitDrainWriters.size)\n        state.awaitDrainWriters.add(dest)\n      }\n      src.pause()\n    }\n    if (!ondrain) {\n      // When the dest drains, it reduces the awaitDrain counter\n      // on the source.  This would be more elegant with a .once()\n      // handler in flow(), but adding and removing repeatedly is\n      // too slow.\n      ondrain = pipeOnDrain(src, dest)\n      dest.on('drain', ondrain)\n    }\n  }\n  src.on('data', ondata)\n  function ondata(chunk) {\n    debug('ondata')\n    const ret = dest.write(chunk)\n    debug('dest.write', ret)\n    if (ret === false) {\n      pause()\n    }\n  }\n\n  // If the dest has an error, then stop piping into it.\n  // However, don't suppress the throwing behavior for this.\n  function onerror(er) {\n    debug('onerror', er)\n    unpipe()\n    dest.removeListener('error', onerror)\n    if (dest.listenerCount('error') === 0) {\n      const s = dest._writableState || dest._readableState\n      if (s && !s.errorEmitted) {\n        // User incorrectly emitted 'error' directly on the stream.\n        errorOrDestroy(dest, er)\n      } else {\n        dest.emit('error', er)\n      }\n    }\n  }\n\n  // Make sure our error handler is attached before userland ones.\n  prependListener(dest, 'error', onerror)\n\n  // Both close and finish should trigger unpipe, but only once.\n  function onclose() {\n    dest.removeListener('finish', onfinish)\n    unpipe()\n  }\n  dest.once('close', onclose)\n  function onfinish() {\n    debug('onfinish')\n    dest.removeListener('close', onclose)\n    unpipe()\n  }\n  dest.once('finish', onfinish)\n  function unpipe() {\n    debug('unpipe')\n    src.unpipe(dest)\n  }\n\n  // Tell the dest that it's being piped to.\n  dest.emit('pipe', src)\n\n  // Start the flow if it hasn't been started already.\n\n  if (dest.writableNeedDrain === true) {\n    pause()\n  } else if (!state.flowing) {\n    debug('pipe resume')\n    src.resume()\n  }\n  return dest\n}\nfunction pipeOnDrain(src, dest) {\n  return function pipeOnDrainFunctionResult() {\n    const state = src._readableState\n\n    // `ondrain` will call directly,\n    // `this` maybe not a reference to dest,\n    // so we use the real dest here.\n    if (state.awaitDrainWriters === dest) {\n      debug('pipeOnDrain', 1)\n      state.awaitDrainWriters = null\n    } else if (state.multiAwaitDrain) {\n      debug('pipeOnDrain', state.awaitDrainWriters.size)\n      state.awaitDrainWriters.delete(dest)\n    }\n    if ((!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) && src.listenerCount('data')) {\n      src.resume()\n    }\n  }\n}\nReadable.prototype.unpipe = function (dest) {\n  const state = this._readableState\n  const unpipeInfo = {\n    hasUnpiped: false\n  }\n\n  // If we're not piping anywhere, then do nothing.\n  if (state.pipes.length === 0) return this\n  if (!dest) {\n    // remove all.\n    const dests = state.pipes\n    state.pipes = []\n    this.pause()\n    for (let i = 0; i < dests.length; i++)\n      dests[i].emit('unpipe', this, {\n        hasUnpiped: false\n      })\n    return this\n  }\n\n  // Try to find the right one.\n  const index = ArrayPrototypeIndexOf(state.pipes, dest)\n  if (index === -1) return this\n  state.pipes.splice(index, 1)\n  if (state.pipes.length === 0) this.pause()\n  dest.emit('unpipe', this, unpipeInfo)\n  return this\n}\n\n// Set up data events if they are asked for\n// Ensure readable listeners eventually get something.\nReadable.prototype.on = function (ev, fn) {\n  const res = Stream.prototype.on.call(this, ev, fn)\n  const state = this._readableState\n  if (ev === 'data') {\n    // Update readableListening so that resume() may be a no-op\n    // a few lines down. This is needed to support once('readable').\n    state.readableListening = this.listenerCount('readable') > 0\n\n    // Try start flowing on next tick if stream isn't explicitly paused.\n    if (state.flowing !== false) this.resume()\n  } else if (ev === 'readable') {\n    if (!state.endEmitted && !state.readableListening) {\n      state.readableListening = state.needReadable = true\n      state.flowing = false\n      state.emittedReadable = false\n      debug('on readable', state.length, state.reading)\n      if (state.length) {\n        emitReadable(this)\n      } else if (!state.reading) {\n        process.nextTick(nReadingNextTick, this)\n      }\n    }\n  }\n  return res\n}\nReadable.prototype.addListener = Readable.prototype.on\nReadable.prototype.removeListener = function (ev, fn) {\n  const res = Stream.prototype.removeListener.call(this, ev, fn)\n  if (ev === 'readable') {\n    // We need to check if there is someone still listening to\n    // readable and reset the state. However this needs to happen\n    // after readable has been emitted but before I/O (nextTick) to\n    // support once('readable', fn) cycles. This means that calling\n    // resume within the same tick will have no\n    // effect.\n    process.nextTick(updateReadableListening, this)\n  }\n  return res\n}\nReadable.prototype.off = Readable.prototype.removeListener\nReadable.prototype.removeAllListeners = function (ev) {\n  const res = Stream.prototype.removeAllListeners.apply(this, arguments)\n  if (ev === 'readable' || ev === undefined) {\n    // We need to check if there is someone still listening to\n    // readable and reset the state. However this needs to happen\n    // after readable has been emitted but before I/O (nextTick) to\n    // support once('readable', fn) cycles. This means that calling\n    // resume within the same tick will have no\n    // effect.\n    process.nextTick(updateReadableListening, this)\n  }\n  return res\n}\nfunction updateReadableListening(self) {\n  const state = self._readableState\n  state.readableListening = self.listenerCount('readable') > 0\n  if (state.resumeScheduled && state[kPaused] === false) {\n    // Flowing needs to be set to true now, otherwise\n    // the upcoming resume will not flow.\n    state.flowing = true\n\n    // Crude way to check if we should resume.\n  } else if (self.listenerCount('data') > 0) {\n    self.resume()\n  } else if (!state.readableListening) {\n    state.flowing = null\n  }\n}\nfunction nReadingNextTick(self) {\n  debug('readable nexttick read 0')\n  self.read(0)\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n  const state = this._readableState\n  if (!state.flowing) {\n    debug('resume')\n    // We flow only if there is no one listening\n    // for readable, but we still have to call\n    // resume().\n    state.flowing = !state.readableListening\n    resume(this, state)\n  }\n  state[kPaused] = false\n  return this\n}\nfunction resume(stream, state) {\n  if (!state.resumeScheduled) {\n    state.resumeScheduled = true\n    process.nextTick(resume_, stream, state)\n  }\n}\nfunction resume_(stream, state) {\n  debug('resume', state.reading)\n  if (!state.reading) {\n    stream.read(0)\n  }\n  state.resumeScheduled = false\n  stream.emit('resume')\n  flow(stream)\n  if (state.flowing && !state.reading) stream.read(0)\n}\nReadable.prototype.pause = function () {\n  debug('call pause flowing=%j', this._readableState.flowing)\n  if (this._readableState.flowing !== false) {\n    debug('pause')\n    this._readableState.flowing = false\n    this.emit('pause')\n  }\n  this._readableState[kPaused] = true\n  return this\n}\nfunction flow(stream) {\n  const state = stream._readableState\n  debug('flow', state.flowing)\n  while (state.flowing && stream.read() !== null);\n}\n\n// Wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n  let paused = false\n\n  // TODO (ronag): Should this.destroy(err) emit\n  // 'error' on the wrapped stream? Would require\n  // a static factory method, e.g. Readable.wrap(stream).\n\n  stream.on('data', (chunk) => {\n    if (!this.push(chunk) && stream.pause) {\n      paused = true\n      stream.pause()\n    }\n  })\n  stream.on('end', () => {\n    this.push(null)\n  })\n  stream.on('error', (err) => {\n    errorOrDestroy(this, err)\n  })\n  stream.on('close', () => {\n    this.destroy()\n  })\n  stream.on('destroy', () => {\n    this.destroy()\n  })\n  this._read = () => {\n    if (paused && stream.resume) {\n      paused = false\n      stream.resume()\n    }\n  }\n\n  // Proxy all the other methods. Important when wrapping filters and duplexes.\n  const streamKeys = ObjectKeys(stream)\n  for (let j = 1; j < streamKeys.length; j++) {\n    const i = streamKeys[j]\n    if (this[i] === undefined && typeof stream[i] === 'function') {\n      this[i] = stream[i].bind(stream)\n    }\n  }\n  return this\n}\nReadable.prototype[SymbolAsyncIterator] = function () {\n  return streamToAsyncIterator(this)\n}\nReadable.prototype.iterator = function (options) {\n  if (options !== undefined) {\n    validateObject(options, 'options')\n  }\n  return streamToAsyncIterator(this, options)\n}\nfunction streamToAsyncIterator(stream, options) {\n  if (typeof stream.read !== 'function') {\n    stream = Readable.wrap(stream, {\n      objectMode: true\n    })\n  }\n  const iter = createAsyncIterator(stream, options)\n  iter.stream = stream\n  return iter\n}\nasync function* createAsyncIterator(stream, options) {\n  let callback = nop\n  function next(resolve) {\n    if (this === stream) {\n      callback()\n      callback = nop\n    } else {\n      callback = resolve\n    }\n  }\n  stream.on('readable', next)\n  let error\n  const cleanup = eos(\n    stream,\n    {\n      writable: false\n    },\n    (err) => {\n      error = err ? aggregateTwoErrors(error, err) : null\n      callback()\n      callback = nop\n    }\n  )\n  try {\n    while (true) {\n      const chunk = stream.destroyed ? null : stream.read()\n      if (chunk !== null) {\n        yield chunk\n      } else if (error) {\n        throw error\n      } else if (error === null) {\n        return\n      } else {\n        await new Promise(next)\n      }\n    }\n  } catch (err) {\n    error = aggregateTwoErrors(error, err)\n    throw error\n  } finally {\n    if (\n      (error || (options === null || options === undefined ? undefined : options.destroyOnReturn) !== false) &&\n      (error === undefined || stream._readableState.autoDestroy)\n    ) {\n      destroyImpl.destroyer(stream, null)\n    } else {\n      stream.off('readable', next)\n      cleanup()\n    }\n  }\n}\n\n// Making it explicit these properties are not enumerable\n// because otherwise some prototype manipulation in\n// userland will fail.\nObjectDefineProperties(Readable.prototype, {\n  readable: {\n    __proto__: null,\n    get() {\n      const r = this._readableState\n      // r.readable === false means that this is part of a Duplex stream\n      // where the readable side was disabled upon construction.\n      // Compat. The user might manually disable readable side through\n      // deprecated setter.\n      return !!r && r.readable !== false && !r.destroyed && !r.errorEmitted && !r.endEmitted\n    },\n    set(val) {\n      // Backwards compat.\n      if (this._readableState) {\n        this._readableState.readable = !!val\n      }\n    }\n  },\n  readableDidRead: {\n    __proto__: null,\n    enumerable: false,\n    get: function () {\n      return this._readableState.dataEmitted\n    }\n  },\n  readableAborted: {\n    __proto__: null,\n    enumerable: false,\n    get: function () {\n      return !!(\n        this._readableState.readable !== false &&\n        (this._readableState.destroyed || this._readableState.errored) &&\n        !this._readableState.endEmitted\n      )\n    }\n  },\n  readableHighWaterMark: {\n    __proto__: null,\n    enumerable: false,\n    get: function () {\n      return this._readableState.highWaterMark\n    }\n  },\n  readableBuffer: {\n    __proto__: null,\n    enumerable: false,\n    get: function () {\n      return this._readableState && this._readableState.buffer\n    }\n  },\n  readableFlowing: {\n    __proto__: null,\n    enumerable: false,\n    get: function () {\n      return this._readableState.flowing\n    },\n    set: function (state) {\n      if (this._readableState) {\n        this._readableState.flowing = state\n      }\n    }\n  },\n  readableLength: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._readableState.length\n    }\n  },\n  readableObjectMode: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._readableState ? this._readableState.objectMode : false\n    }\n  },\n  readableEncoding: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._readableState ? this._readableState.encoding : null\n    }\n  },\n  errored: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._readableState ? this._readableState.errored : null\n    }\n  },\n  closed: {\n    __proto__: null,\n    get() {\n      return this._readableState ? this._readableState.closed : false\n    }\n  },\n  destroyed: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._readableState ? this._readableState.destroyed : false\n    },\n    set(value) {\n      // We ignore the value if the stream\n      // has not been initialized yet.\n      if (!this._readableState) {\n        return\n      }\n\n      // Backward compatibility, the user is explicitly\n      // managing destroyed.\n      this._readableState.destroyed = value\n    }\n  },\n  readableEnded: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._readableState ? this._readableState.endEmitted : false\n    }\n  }\n})\nObjectDefineProperties(ReadableState.prototype, {\n  // Legacy getter for `pipesCount`.\n  pipesCount: {\n    __proto__: null,\n    get() {\n      return this.pipes.length\n    }\n  },\n  // Legacy property for `paused`.\n  paused: {\n    __proto__: null,\n    get() {\n      return this[kPaused] !== false\n    },\n    set(value) {\n      this[kPaused] = !!value\n    }\n  }\n})\n\n// Exposed for testing purposes only.\nReadable._fromList = fromList\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n  // nothing buffered.\n  if (state.length === 0) return null\n  let ret\n  if (state.objectMode) ret = state.buffer.shift()\n  else if (!n || n >= state.length) {\n    // Read it all, truncate the list.\n    if (state.decoder) ret = state.buffer.join('')\n    else if (state.buffer.length === 1) ret = state.buffer.first()\n    else ret = state.buffer.concat(state.length)\n    state.buffer.clear()\n  } else {\n    // read part of list.\n    ret = state.buffer.consume(n, state.decoder)\n  }\n  return ret\n}\nfunction endReadable(stream) {\n  const state = stream._readableState\n  debug('endReadable', state.endEmitted)\n  if (!state.endEmitted) {\n    state.ended = true\n    process.nextTick(endReadableNT, state, stream)\n  }\n}\nfunction endReadableNT(state, stream) {\n  debug('endReadableNT', state.endEmitted, state.length)\n\n  // Check that we didn't get one last unshift.\n  if (!state.errored && !state.closeEmitted && !state.endEmitted && state.length === 0) {\n    state.endEmitted = true\n    stream.emit('end')\n    if (stream.writable && stream.allowHalfOpen === false) {\n      process.nextTick(endWritableNT, stream)\n    } else if (state.autoDestroy) {\n      // In case of duplex streams we need a way to detect\n      // if the writable side is ready for autoDestroy as well.\n      const wState = stream._writableState\n      const autoDestroy =\n        !wState ||\n        (wState.autoDestroy &&\n          // We don't expect the writable to ever 'finish'\n          // if writable is explicitly set to false.\n          (wState.finished || wState.writable === false))\n      if (autoDestroy) {\n        stream.destroy()\n      }\n    }\n  }\n}\nfunction endWritableNT(stream) {\n  const writable = stream.writable && !stream.writableEnded && !stream.destroyed\n  if (writable) {\n    stream.end()\n  }\n}\nReadable.from = function (iterable, opts) {\n  return from(Readable, iterable, opts)\n}\nlet webStreamsAdapters\n\n// Lazy to avoid circular references\nfunction lazyWebStreams() {\n  if (webStreamsAdapters === undefined) webStreamsAdapters = {}\n  return webStreamsAdapters\n}\nReadable.fromWeb = function (readableStream, options) {\n  return lazyWebStreams().newStreamReadableFromReadableStream(readableStream, options)\n}\nReadable.toWeb = function (streamReadable, options) {\n  return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable, options)\n}\nReadable.wrap = function (src, options) {\n  var _ref, _src$readableObjectMo\n  return new Readable({\n    objectMode:\n      (_ref =\n        (_src$readableObjectMo = src.readableObjectMode) !== null && _src$readableObjectMo !== undefined\n          ? _src$readableObjectMo\n          : src.objectMode) !== null && _ref !== undefined\n        ? _ref\n        : true,\n    ...options,\n    destroy(err, callback) {\n      destroyImpl.destroyer(src, err)\n      callback(err)\n    }\n  }).wrap(src)\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst {\n  ArrayPrototypeSlice,\n  Error,\n  FunctionPrototypeSymbolHasInstance,\n  ObjectDefineProperty,\n  ObjectDefineProperties,\n  ObjectSetPrototypeOf,\n  StringPrototypeToLowerCase,\n  Symbol,\n  SymbolHasInstance\n} = require('../../ours/primordials')\nmodule.exports = Writable\nWritable.WritableState = WritableState\nconst { EventEmitter: EE } = require('events')\nconst Stream = require('./legacy').Stream\nconst { Buffer } = require('buffer')\nconst destroyImpl = require('./destroy')\nconst { addAbortSignal } = require('./add-abort-signal')\nconst { getHighWaterMark, getDefaultHighWaterMark } = require('./state')\nconst {\n  ERR_INVALID_ARG_TYPE,\n  ERR_METHOD_NOT_IMPLEMENTED,\n  ERR_MULTIPLE_CALLBACK,\n  ERR_STREAM_CANNOT_PIPE,\n  ERR_STREAM_DESTROYED,\n  ERR_STREAM_ALREADY_FINISHED,\n  ERR_STREAM_NULL_VALUES,\n  ERR_STREAM_WRITE_AFTER_END,\n  ERR_UNKNOWN_ENCODING\n} = require('../../ours/errors').codes\nconst { errorOrDestroy } = destroyImpl\nObjectSetPrototypeOf(Writable.prototype, Stream.prototype)\nObjectSetPrototypeOf(Writable, Stream)\nfunction nop() {}\nconst kOnFinished = Symbol('kOnFinished')\nfunction WritableState(options, stream, isDuplex) {\n  // Duplex streams are both readable and writable, but share\n  // the same options object.\n  // However, some cases require setting options to different\n  // values for the readable and the writable sides of the duplex stream,\n  // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n  if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof require('./duplex')\n\n  // Object stream flag to indicate whether or not this stream\n  // contains buffers or objects.\n  this.objectMode = !!(options && options.objectMode)\n  if (isDuplex) this.objectMode = this.objectMode || !!(options && options.writableObjectMode)\n\n  // The point at which write() starts returning false\n  // Note: 0 is a valid value, means that we always return false if\n  // the entire buffer is not flushed immediately on write().\n  this.highWaterMark = options\n    ? getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex)\n    : getDefaultHighWaterMark(false)\n\n  // if _final has been called.\n  this.finalCalled = false\n\n  // drain event flag.\n  this.needDrain = false\n  // At the start of calling end()\n  this.ending = false\n  // When end() has been called, and returned.\n  this.ended = false\n  // When 'finish' is emitted.\n  this.finished = false\n\n  // Has it been destroyed\n  this.destroyed = false\n\n  // Should we decode strings into buffers before passing to _write?\n  // this is here so that some node-core streams can optimize string\n  // handling at a lower level.\n  const noDecode = !!(options && options.decodeStrings === false)\n  this.decodeStrings = !noDecode\n\n  // Crypto is kind of old and crusty.  Historically, its default string\n  // encoding is 'binary' so we have to make this configurable.\n  // Everything else in the universe uses 'utf8', though.\n  this.defaultEncoding = (options && options.defaultEncoding) || 'utf8'\n\n  // Not an actual buffer we keep track of, but a measurement\n  // of how much we're waiting to get pushed to some underlying\n  // socket or file.\n  this.length = 0\n\n  // A flag to see when we're in the middle of a write.\n  this.writing = false\n\n  // When true all writes will be buffered until .uncork() call.\n  this.corked = 0\n\n  // A flag to be able to tell if the onwrite cb is called immediately,\n  // or on a later tick.  We set this to true at first, because any\n  // actions that shouldn't happen until \"later\" should generally also\n  // not happen before the first write call.\n  this.sync = true\n\n  // A flag to know if we're processing previously buffered items, which\n  // may call the _write() callback in the same tick, so that we don't\n  // end up in an overlapped onwrite situation.\n  this.bufferProcessing = false\n\n  // The callback that's passed to _write(chunk, cb).\n  this.onwrite = onwrite.bind(undefined, stream)\n\n  // The callback that the user supplies to write(chunk, encoding, cb).\n  this.writecb = null\n\n  // The amount that is being written when _write is called.\n  this.writelen = 0\n\n  // Storage for data passed to the afterWrite() callback in case of\n  // synchronous _write() completion.\n  this.afterWriteTickInfo = null\n  resetBuffer(this)\n\n  // Number of pending user-supplied write callbacks\n  // this must be 0 before 'finish' can be emitted.\n  this.pendingcb = 0\n\n  // Stream is still being constructed and cannot be\n  // destroyed until construction finished or failed.\n  // Async construction is opt in, therefore we start as\n  // constructed.\n  this.constructed = true\n\n  // Emit prefinish if the only thing we're waiting for is _write cbs\n  // This is relevant for synchronous Transform streams.\n  this.prefinished = false\n\n  // True if the error was already emitted and should not be thrown again.\n  this.errorEmitted = false\n\n  // Should close be emitted on destroy. Defaults to true.\n  this.emitClose = !options || options.emitClose !== false\n\n  // Should .destroy() be called after 'finish' (and potentially 'end').\n  this.autoDestroy = !options || options.autoDestroy !== false\n\n  // Indicates whether the stream has errored. When true all write() calls\n  // should return false. This is needed since when autoDestroy\n  // is disabled we need a way to tell whether the stream has failed.\n  this.errored = null\n\n  // Indicates whether the stream has finished destroying.\n  this.closed = false\n\n  // True if close has been emitted or would have been emitted\n  // depending on emitClose.\n  this.closeEmitted = false\n  this[kOnFinished] = []\n}\nfunction resetBuffer(state) {\n  state.buffered = []\n  state.bufferedIndex = 0\n  state.allBuffers = true\n  state.allNoop = true\n}\nWritableState.prototype.getBuffer = function getBuffer() {\n  return ArrayPrototypeSlice(this.buffered, this.bufferedIndex)\n}\nObjectDefineProperty(WritableState.prototype, 'bufferedRequestCount', {\n  __proto__: null,\n  get() {\n    return this.buffered.length - this.bufferedIndex\n  }\n})\nfunction Writable(options) {\n  // Writable ctor is applied to Duplexes, too.\n  // `realHasInstance` is necessary because using plain `instanceof`\n  // would return false, as no `_writableState` property is attached.\n\n  // Trying to use the custom `instanceof` for Writable here will also break the\n  // Node.js LazyTransform implementation, which has a non-trivial getter for\n  // `_writableState` that would lead to infinite recursion.\n\n  // Checking for a Stream.Duplex instance is faster here instead of inside\n  // the WritableState constructor, at least with V8 6.5.\n  const isDuplex = this instanceof require('./duplex')\n  if (!isDuplex && !FunctionPrototypeSymbolHasInstance(Writable, this)) return new Writable(options)\n  this._writableState = new WritableState(options, this, isDuplex)\n  if (options) {\n    if (typeof options.write === 'function') this._write = options.write\n    if (typeof options.writev === 'function') this._writev = options.writev\n    if (typeof options.destroy === 'function') this._destroy = options.destroy\n    if (typeof options.final === 'function') this._final = options.final\n    if (typeof options.construct === 'function') this._construct = options.construct\n    if (options.signal) addAbortSignal(options.signal, this)\n  }\n  Stream.call(this, options)\n  destroyImpl.construct(this, () => {\n    const state = this._writableState\n    if (!state.writing) {\n      clearBuffer(this, state)\n    }\n    finishMaybe(this, state)\n  })\n}\nObjectDefineProperty(Writable, SymbolHasInstance, {\n  __proto__: null,\n  value: function (object) {\n    if (FunctionPrototypeSymbolHasInstance(this, object)) return true\n    if (this !== Writable) return false\n    return object && object._writableState instanceof WritableState\n  }\n})\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n  errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE())\n}\nfunction _write(stream, chunk, encoding, cb) {\n  const state = stream._writableState\n  if (typeof encoding === 'function') {\n    cb = encoding\n    encoding = state.defaultEncoding\n  } else {\n    if (!encoding) encoding = state.defaultEncoding\n    else if (encoding !== 'buffer' && !Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding)\n    if (typeof cb !== 'function') cb = nop\n  }\n  if (chunk === null) {\n    throw new ERR_STREAM_NULL_VALUES()\n  } else if (!state.objectMode) {\n    if (typeof chunk === 'string') {\n      if (state.decodeStrings !== false) {\n        chunk = Buffer.from(chunk, encoding)\n        encoding = 'buffer'\n      }\n    } else if (chunk instanceof Buffer) {\n      encoding = 'buffer'\n    } else if (Stream._isUint8Array(chunk)) {\n      chunk = Stream._uint8ArrayToBuffer(chunk)\n      encoding = 'buffer'\n    } else {\n      throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk)\n    }\n  }\n  let err\n  if (state.ending) {\n    err = new ERR_STREAM_WRITE_AFTER_END()\n  } else if (state.destroyed) {\n    err = new ERR_STREAM_DESTROYED('write')\n  }\n  if (err) {\n    process.nextTick(cb, err)\n    errorOrDestroy(stream, err, true)\n    return err\n  }\n  state.pendingcb++\n  return writeOrBuffer(stream, state, chunk, encoding, cb)\n}\nWritable.prototype.write = function (chunk, encoding, cb) {\n  return _write(this, chunk, encoding, cb) === true\n}\nWritable.prototype.cork = function () {\n  this._writableState.corked++\n}\nWritable.prototype.uncork = function () {\n  const state = this._writableState\n  if (state.corked) {\n    state.corked--\n    if (!state.writing) clearBuffer(this, state)\n  }\n}\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n  // node::ParseEncoding() requires lower case.\n  if (typeof encoding === 'string') encoding = StringPrototypeToLowerCase(encoding)\n  if (!Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding)\n  this._writableState.defaultEncoding = encoding\n  return this\n}\n\n// If we're already writing something, then just put this\n// in the queue, and wait our turn.  Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, chunk, encoding, callback) {\n  const len = state.objectMode ? 1 : chunk.length\n  state.length += len\n\n  // stream._write resets state.length\n  const ret = state.length < state.highWaterMark\n  // We must ensure that previous needDrain will not be reset to false.\n  if (!ret) state.needDrain = true\n  if (state.writing || state.corked || state.errored || !state.constructed) {\n    state.buffered.push({\n      chunk,\n      encoding,\n      callback\n    })\n    if (state.allBuffers && encoding !== 'buffer') {\n      state.allBuffers = false\n    }\n    if (state.allNoop && callback !== nop) {\n      state.allNoop = false\n    }\n  } else {\n    state.writelen = len\n    state.writecb = callback\n    state.writing = true\n    state.sync = true\n    stream._write(chunk, encoding, state.onwrite)\n    state.sync = false\n  }\n\n  // Return false if errored or destroyed in order to break\n  // any synchronous while(stream.write(data)) loops.\n  return ret && !state.errored && !state.destroyed\n}\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n  state.writelen = len\n  state.writecb = cb\n  state.writing = true\n  state.sync = true\n  if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'))\n  else if (writev) stream._writev(chunk, state.onwrite)\n  else stream._write(chunk, encoding, state.onwrite)\n  state.sync = false\n}\nfunction onwriteError(stream, state, er, cb) {\n  --state.pendingcb\n  cb(er)\n  // Ensure callbacks are invoked even when autoDestroy is\n  // not enabled. Passing `er` here doesn't make sense since\n  // it's related to one specific write, not to the buffered\n  // writes.\n  errorBuffer(state)\n  // This can emit error, but error must always follow cb.\n  errorOrDestroy(stream, er)\n}\nfunction onwrite(stream, er) {\n  const state = stream._writableState\n  const sync = state.sync\n  const cb = state.writecb\n  if (typeof cb !== 'function') {\n    errorOrDestroy(stream, new ERR_MULTIPLE_CALLBACK())\n    return\n  }\n  state.writing = false\n  state.writecb = null\n  state.length -= state.writelen\n  state.writelen = 0\n  if (er) {\n    // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364\n    er.stack // eslint-disable-line no-unused-expressions\n\n    if (!state.errored) {\n      state.errored = er\n    }\n\n    // In case of duplex streams we need to notify the readable side of the\n    // error.\n    if (stream._readableState && !stream._readableState.errored) {\n      stream._readableState.errored = er\n    }\n    if (sync) {\n      process.nextTick(onwriteError, stream, state, er, cb)\n    } else {\n      onwriteError(stream, state, er, cb)\n    }\n  } else {\n    if (state.buffered.length > state.bufferedIndex) {\n      clearBuffer(stream, state)\n    }\n    if (sync) {\n      // It is a common case that the callback passed to .write() is always\n      // the same. In that case, we do not schedule a new nextTick(), but\n      // rather just increase a counter, to improve performance and avoid\n      // memory allocations.\n      if (state.afterWriteTickInfo !== null && state.afterWriteTickInfo.cb === cb) {\n        state.afterWriteTickInfo.count++\n      } else {\n        state.afterWriteTickInfo = {\n          count: 1,\n          cb,\n          stream,\n          state\n        }\n        process.nextTick(afterWriteTick, state.afterWriteTickInfo)\n      }\n    } else {\n      afterWrite(stream, state, 1, cb)\n    }\n  }\n}\nfunction afterWriteTick({ stream, state, count, cb }) {\n  state.afterWriteTickInfo = null\n  return afterWrite(stream, state, count, cb)\n}\nfunction afterWrite(stream, state, count, cb) {\n  const needDrain = !state.ending && !stream.destroyed && state.length === 0 && state.needDrain\n  if (needDrain) {\n    state.needDrain = false\n    stream.emit('drain')\n  }\n  while (count-- > 0) {\n    state.pendingcb--\n    cb()\n  }\n  if (state.destroyed) {\n    errorBuffer(state)\n  }\n  finishMaybe(stream, state)\n}\n\n// If there's something in the buffer waiting, then invoke callbacks.\nfunction errorBuffer(state) {\n  if (state.writing) {\n    return\n  }\n  for (let n = state.bufferedIndex; n < state.buffered.length; ++n) {\n    var _state$errored\n    const { chunk, callback } = state.buffered[n]\n    const len = state.objectMode ? 1 : chunk.length\n    state.length -= len\n    callback(\n      (_state$errored = state.errored) !== null && _state$errored !== undefined\n        ? _state$errored\n        : new ERR_STREAM_DESTROYED('write')\n    )\n  }\n  const onfinishCallbacks = state[kOnFinished].splice(0)\n  for (let i = 0; i < onfinishCallbacks.length; i++) {\n    var _state$errored2\n    onfinishCallbacks[i](\n      (_state$errored2 = state.errored) !== null && _state$errored2 !== undefined\n        ? _state$errored2\n        : new ERR_STREAM_DESTROYED('end')\n    )\n  }\n  resetBuffer(state)\n}\n\n// If there's something in the buffer waiting, then process it.\nfunction clearBuffer(stream, state) {\n  if (state.corked || state.bufferProcessing || state.destroyed || !state.constructed) {\n    return\n  }\n  const { buffered, bufferedIndex, objectMode } = state\n  const bufferedLength = buffered.length - bufferedIndex\n  if (!bufferedLength) {\n    return\n  }\n  let i = bufferedIndex\n  state.bufferProcessing = true\n  if (bufferedLength > 1 && stream._writev) {\n    state.pendingcb -= bufferedLength - 1\n    const callback = state.allNoop\n      ? nop\n      : (err) => {\n          for (let n = i; n < buffered.length; ++n) {\n            buffered[n].callback(err)\n          }\n        }\n    // Make a copy of `buffered` if it's going to be used by `callback` above,\n    // since `doWrite` will mutate the array.\n    const chunks = state.allNoop && i === 0 ? buffered : ArrayPrototypeSlice(buffered, i)\n    chunks.allBuffers = state.allBuffers\n    doWrite(stream, state, true, state.length, chunks, '', callback)\n    resetBuffer(state)\n  } else {\n    do {\n      const { chunk, encoding, callback } = buffered[i]\n      buffered[i++] = null\n      const len = objectMode ? 1 : chunk.length\n      doWrite(stream, state, false, len, chunk, encoding, callback)\n    } while (i < buffered.length && !state.writing)\n    if (i === buffered.length) {\n      resetBuffer(state)\n    } else if (i > 256) {\n      buffered.splice(0, i)\n      state.bufferedIndex = 0\n    } else {\n      state.bufferedIndex = i\n    }\n  }\n  state.bufferProcessing = false\n}\nWritable.prototype._write = function (chunk, encoding, cb) {\n  if (this._writev) {\n    this._writev(\n      [\n        {\n          chunk,\n          encoding\n        }\n      ],\n      cb\n    )\n  } else {\n    throw new ERR_METHOD_NOT_IMPLEMENTED('_write()')\n  }\n}\nWritable.prototype._writev = null\nWritable.prototype.end = function (chunk, encoding, cb) {\n  const state = this._writableState\n  if (typeof chunk === 'function') {\n    cb = chunk\n    chunk = null\n    encoding = null\n  } else if (typeof encoding === 'function') {\n    cb = encoding\n    encoding = null\n  }\n  let err\n  if (chunk !== null && chunk !== undefined) {\n    const ret = _write(this, chunk, encoding)\n    if (ret instanceof Error) {\n      err = ret\n    }\n  }\n\n  // .end() fully uncorks.\n  if (state.corked) {\n    state.corked = 1\n    this.uncork()\n  }\n  if (err) {\n    // Do nothing...\n  } else if (!state.errored && !state.ending) {\n    // This is forgiving in terms of unnecessary calls to end() and can hide\n    // logic errors. However, usually such errors are harmless and causing a\n    // hard error can be disproportionately destructive. It is not always\n    // trivial for the user to determine whether end() needs to be called\n    // or not.\n\n    state.ending = true\n    finishMaybe(this, state, true)\n    state.ended = true\n  } else if (state.finished) {\n    err = new ERR_STREAM_ALREADY_FINISHED('end')\n  } else if (state.destroyed) {\n    err = new ERR_STREAM_DESTROYED('end')\n  }\n  if (typeof cb === 'function') {\n    if (err || state.finished) {\n      process.nextTick(cb, err)\n    } else {\n      state[kOnFinished].push(cb)\n    }\n  }\n  return this\n}\nfunction needFinish(state) {\n  return (\n    state.ending &&\n    !state.destroyed &&\n    state.constructed &&\n    state.length === 0 &&\n    !state.errored &&\n    state.buffered.length === 0 &&\n    !state.finished &&\n    !state.writing &&\n    !state.errorEmitted &&\n    !state.closeEmitted\n  )\n}\nfunction callFinal(stream, state) {\n  let called = false\n  function onFinish(err) {\n    if (called) {\n      errorOrDestroy(stream, err !== null && err !== undefined ? err : ERR_MULTIPLE_CALLBACK())\n      return\n    }\n    called = true\n    state.pendingcb--\n    if (err) {\n      const onfinishCallbacks = state[kOnFinished].splice(0)\n      for (let i = 0; i < onfinishCallbacks.length; i++) {\n        onfinishCallbacks[i](err)\n      }\n      errorOrDestroy(stream, err, state.sync)\n    } else if (needFinish(state)) {\n      state.prefinished = true\n      stream.emit('prefinish')\n      // Backwards compat. Don't check state.sync here.\n      // Some streams assume 'finish' will be emitted\n      // asynchronously relative to _final callback.\n      state.pendingcb++\n      process.nextTick(finish, stream, state)\n    }\n  }\n  state.sync = true\n  state.pendingcb++\n  try {\n    stream._final(onFinish)\n  } catch (err) {\n    onFinish(err)\n  }\n  state.sync = false\n}\nfunction prefinish(stream, state) {\n  if (!state.prefinished && !state.finalCalled) {\n    if (typeof stream._final === 'function' && !state.destroyed) {\n      state.finalCalled = true\n      callFinal(stream, state)\n    } else {\n      state.prefinished = true\n      stream.emit('prefinish')\n    }\n  }\n}\nfunction finishMaybe(stream, state, sync) {\n  if (needFinish(state)) {\n    prefinish(stream, state)\n    if (state.pendingcb === 0) {\n      if (sync) {\n        state.pendingcb++\n        process.nextTick(\n          (stream, state) => {\n            if (needFinish(state)) {\n              finish(stream, state)\n            } else {\n              state.pendingcb--\n            }\n          },\n          stream,\n          state\n        )\n      } else if (needFinish(state)) {\n        state.pendingcb++\n        finish(stream, state)\n      }\n    }\n  }\n}\nfunction finish(stream, state) {\n  state.pendingcb--\n  state.finished = true\n  const onfinishCallbacks = state[kOnFinished].splice(0)\n  for (let i = 0; i < onfinishCallbacks.length; i++) {\n    onfinishCallbacks[i]()\n  }\n  stream.emit('finish')\n  if (state.autoDestroy) {\n    // In case of duplex streams we need a way to detect\n    // if the readable side is ready for autoDestroy as well.\n    const rState = stream._readableState\n    const autoDestroy =\n      !rState ||\n      (rState.autoDestroy &&\n        // We don't expect the readable to ever 'end'\n        // if readable is explicitly set to false.\n        (rState.endEmitted || rState.readable === false))\n    if (autoDestroy) {\n      stream.destroy()\n    }\n  }\n}\nObjectDefineProperties(Writable.prototype, {\n  closed: {\n    __proto__: null,\n    get() {\n      return this._writableState ? this._writableState.closed : false\n    }\n  },\n  destroyed: {\n    __proto__: null,\n    get() {\n      return this._writableState ? this._writableState.destroyed : false\n    },\n    set(value) {\n      // Backward compatibility, the user is explicitly managing destroyed.\n      if (this._writableState) {\n        this._writableState.destroyed = value\n      }\n    }\n  },\n  writable: {\n    __proto__: null,\n    get() {\n      const w = this._writableState\n      // w.writable === false means that this is part of a Duplex stream\n      // where the writable side was disabled upon construction.\n      // Compat. The user might manually disable writable side through\n      // deprecated setter.\n      return !!w && w.writable !== false && !w.destroyed && !w.errored && !w.ending && !w.ended\n    },\n    set(val) {\n      // Backwards compatible.\n      if (this._writableState) {\n        this._writableState.writable = !!val\n      }\n    }\n  },\n  writableFinished: {\n    __proto__: null,\n    get() {\n      return this._writableState ? this._writableState.finished : false\n    }\n  },\n  writableObjectMode: {\n    __proto__: null,\n    get() {\n      return this._writableState ? this._writableState.objectMode : false\n    }\n  },\n  writableBuffer: {\n    __proto__: null,\n    get() {\n      return this._writableState && this._writableState.getBuffer()\n    }\n  },\n  writableEnded: {\n    __proto__: null,\n    get() {\n      return this._writableState ? this._writableState.ending : false\n    }\n  },\n  writableNeedDrain: {\n    __proto__: null,\n    get() {\n      const wState = this._writableState\n      if (!wState) return false\n      return !wState.destroyed && !wState.ending && wState.needDrain\n    }\n  },\n  writableHighWaterMark: {\n    __proto__: null,\n    get() {\n      return this._writableState && this._writableState.highWaterMark\n    }\n  },\n  writableCorked: {\n    __proto__: null,\n    get() {\n      return this._writableState ? this._writableState.corked : 0\n    }\n  },\n  writableLength: {\n    __proto__: null,\n    get() {\n      return this._writableState && this._writableState.length\n    }\n  },\n  errored: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._writableState ? this._writableState.errored : null\n    }\n  },\n  writableAborted: {\n    __proto__: null,\n    enumerable: false,\n    get: function () {\n      return !!(\n        this._writableState.writable !== false &&\n        (this._writableState.destroyed || this._writableState.errored) &&\n        !this._writableState.finished\n      )\n    }\n  }\n})\nconst destroy = destroyImpl.destroy\nWritable.prototype.destroy = function (err, cb) {\n  const state = this._writableState\n\n  // Invoke pending callbacks.\n  if (!state.destroyed && (state.bufferedIndex < state.buffered.length || state[kOnFinished].length)) {\n    process.nextTick(errorBuffer, state)\n  }\n  destroy.call(this, err, cb)\n  return this\n}\nWritable.prototype._undestroy = destroyImpl.undestroy\nWritable.prototype._destroy = function (err, cb) {\n  cb(err)\n}\nWritable.prototype[EE.captureRejectionSymbol] = function (err) {\n  this.destroy(err)\n}\nlet webStreamsAdapters\n\n// Lazy to avoid circular references\nfunction lazyWebStreams() {\n  if (webStreamsAdapters === undefined) webStreamsAdapters = {}\n  return webStreamsAdapters\n}\nWritable.fromWeb = function (writableStream, options) {\n  return lazyWebStreams().newStreamWritableFromWritableStream(writableStream, options)\n}\nWritable.toWeb = function (streamWritable) {\n  return lazyWebStreams().newWritableStreamFromStreamWritable(streamWritable)\n}\n","/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\n;('use strict')\nconst bufferModule = require('buffer')\nconst {\n  isReadable,\n  isWritable,\n  isIterable,\n  isNodeStream,\n  isReadableNodeStream,\n  isWritableNodeStream,\n  isDuplexNodeStream,\n  isReadableStream,\n  isWritableStream\n} = require('./utils')\nconst eos = require('./end-of-stream')\nconst {\n  AbortError,\n  codes: { ERR_INVALID_ARG_TYPE, ERR_INVALID_RETURN_VALUE }\n} = require('../../ours/errors')\nconst { destroyer } = require('./destroy')\nconst Duplex = require('./duplex')\nconst Readable = require('./readable')\nconst Writable = require('./writable')\nconst { createDeferredPromise } = require('../../ours/util')\nconst from = require('./from')\nconst Blob = globalThis.Blob || bufferModule.Blob\nconst isBlob =\n  typeof Blob !== 'undefined'\n    ? function isBlob(b) {\n        return b instanceof Blob\n      }\n    : function isBlob(b) {\n        return false\n      }\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nconst { FunctionPrototypeCall } = require('../../ours/primordials')\n\n// This is needed for pre node 17.\nclass Duplexify extends Duplex {\n  constructor(options) {\n    super(options)\n\n    // https://github.com/nodejs/node/pull/34385\n\n    if ((options === null || options === undefined ? undefined : options.readable) === false) {\n      this._readableState.readable = false\n      this._readableState.ended = true\n      this._readableState.endEmitted = true\n    }\n    if ((options === null || options === undefined ? undefined : options.writable) === false) {\n      this._writableState.writable = false\n      this._writableState.ending = true\n      this._writableState.ended = true\n      this._writableState.finished = true\n    }\n  }\n}\nmodule.exports = function duplexify(body, name) {\n  if (isDuplexNodeStream(body)) {\n    return body\n  }\n  if (isReadableNodeStream(body)) {\n    return _duplexify({\n      readable: body\n    })\n  }\n  if (isWritableNodeStream(body)) {\n    return _duplexify({\n      writable: body\n    })\n  }\n  if (isNodeStream(body)) {\n    return _duplexify({\n      writable: false,\n      readable: false\n    })\n  }\n  if (isReadableStream(body)) {\n    return _duplexify({\n      readable: Readable.fromWeb(body)\n    })\n  }\n  if (isWritableStream(body)) {\n    return _duplexify({\n      writable: Writable.fromWeb(body)\n    })\n  }\n  if (typeof body === 'function') {\n    const { value, write, final, destroy } = fromAsyncGen(body)\n    if (isIterable(value)) {\n      return from(Duplexify, value, {\n        // TODO (ronag): highWaterMark?\n        objectMode: true,\n        write,\n        final,\n        destroy\n      })\n    }\n    const then = value === null || value === undefined ? undefined : value.then\n    if (typeof then === 'function') {\n      let d\n      const promise = FunctionPrototypeCall(\n        then,\n        value,\n        (val) => {\n          if (val != null) {\n            throw new ERR_INVALID_RETURN_VALUE('nully', 'body', val)\n          }\n        },\n        (err) => {\n          destroyer(d, err)\n        }\n      )\n      return (d = new Duplexify({\n        // TODO (ronag): highWaterMark?\n        objectMode: true,\n        readable: false,\n        write,\n        final(cb) {\n          final(async () => {\n            try {\n              await promise\n              process.nextTick(cb, null)\n            } catch (err) {\n              process.nextTick(cb, err)\n            }\n          })\n        },\n        destroy\n      }))\n    }\n    throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or AsyncFunction', name, value)\n  }\n  if (isBlob(body)) {\n    return duplexify(body.arrayBuffer())\n  }\n  if (isIterable(body)) {\n    return from(Duplexify, body, {\n      // TODO (ronag): highWaterMark?\n      objectMode: true,\n      writable: false\n    })\n  }\n  if (\n    isReadableStream(body === null || body === undefined ? undefined : body.readable) &&\n    isWritableStream(body === null || body === undefined ? undefined : body.writable)\n  ) {\n    return Duplexify.fromWeb(body)\n  }\n  if (\n    typeof (body === null || body === undefined ? undefined : body.writable) === 'object' ||\n    typeof (body === null || body === undefined ? undefined : body.readable) === 'object'\n  ) {\n    const readable =\n      body !== null && body !== undefined && body.readable\n        ? isReadableNodeStream(body === null || body === undefined ? undefined : body.readable)\n          ? body === null || body === undefined\n            ? undefined\n            : body.readable\n          : duplexify(body.readable)\n        : undefined\n    const writable =\n      body !== null && body !== undefined && body.writable\n        ? isWritableNodeStream(body === null || body === undefined ? undefined : body.writable)\n          ? body === null || body === undefined\n            ? undefined\n            : body.writable\n          : duplexify(body.writable)\n        : undefined\n    return _duplexify({\n      readable,\n      writable\n    })\n  }\n  const then = body === null || body === undefined ? undefined : body.then\n  if (typeof then === 'function') {\n    let d\n    FunctionPrototypeCall(\n      then,\n      body,\n      (val) => {\n        if (val != null) {\n          d.push(val)\n        }\n        d.push(null)\n      },\n      (err) => {\n        destroyer(d, err)\n      }\n    )\n    return (d = new Duplexify({\n      objectMode: true,\n      writable: false,\n      read() {}\n    }))\n  }\n  throw new ERR_INVALID_ARG_TYPE(\n    name,\n    [\n      'Blob',\n      'ReadableStream',\n      'WritableStream',\n      'Stream',\n      'Iterable',\n      'AsyncIterable',\n      'Function',\n      '{ readable, writable } pair',\n      'Promise'\n    ],\n    body\n  )\n}\nfunction fromAsyncGen(fn) {\n  let { promise, resolve } = createDeferredPromise()\n  const ac = new AbortController()\n  const signal = ac.signal\n  const value = fn(\n    (async function* () {\n      while (true) {\n        const _promise = promise\n        promise = null\n        const { chunk, done, cb } = await _promise\n        process.nextTick(cb)\n        if (done) return\n        if (signal.aborted)\n          throw new AbortError(undefined, {\n            cause: signal.reason\n          })\n        ;({ promise, resolve } = createDeferredPromise())\n        yield chunk\n      }\n    })(),\n    {\n      signal\n    }\n  )\n  return {\n    value,\n    write(chunk, encoding, cb) {\n      const _resolve = resolve\n      resolve = null\n      _resolve({\n        chunk,\n        done: false,\n        cb\n      })\n    },\n    final(cb) {\n      const _resolve = resolve\n      resolve = null\n      _resolve({\n        done: true,\n        cb\n      })\n    },\n    destroy(err, cb) {\n      ac.abort()\n      cb(err)\n    }\n  }\n}\nfunction _duplexify(pair) {\n  const r = pair.readable && typeof pair.readable.read !== 'function' ? Readable.wrap(pair.readable) : pair.readable\n  const w = pair.writable\n  let readable = !!isReadable(r)\n  let writable = !!isWritable(w)\n  let ondrain\n  let onfinish\n  let onreadable\n  let onclose\n  let d\n  function onfinished(err) {\n    const cb = onclose\n    onclose = null\n    if (cb) {\n      cb(err)\n    } else if (err) {\n      d.destroy(err)\n    }\n  }\n\n  // TODO(ronag): Avoid double buffering.\n  // Implement Writable/Readable/Duplex traits.\n  // See, https://github.com/nodejs/node/pull/33515.\n  d = new Duplexify({\n    // TODO (ronag): highWaterMark?\n    readableObjectMode: !!(r !== null && r !== undefined && r.readableObjectMode),\n    writableObjectMode: !!(w !== null && w !== undefined && w.writableObjectMode),\n    readable,\n    writable\n  })\n  if (writable) {\n    eos(w, (err) => {\n      writable = false\n      if (err) {\n        destroyer(r, err)\n      }\n      onfinished(err)\n    })\n    d._write = function (chunk, encoding, callback) {\n      if (w.write(chunk, encoding)) {\n        callback()\n      } else {\n        ondrain = callback\n      }\n    }\n    d._final = function (callback) {\n      w.end()\n      onfinish = callback\n    }\n    w.on('drain', function () {\n      if (ondrain) {\n        const cb = ondrain\n        ondrain = null\n        cb()\n      }\n    })\n    w.on('finish', function () {\n      if (onfinish) {\n        const cb = onfinish\n        onfinish = null\n        cb()\n      }\n    })\n  }\n  if (readable) {\n    eos(r, (err) => {\n      readable = false\n      if (err) {\n        destroyer(r, err)\n      }\n      onfinished(err)\n    })\n    r.on('readable', function () {\n      if (onreadable) {\n        const cb = onreadable\n        onreadable = null\n        cb()\n      }\n    })\n    r.on('end', function () {\n      d.push(null)\n    })\n    d._read = function () {\n      while (true) {\n        const buf = r.read()\n        if (buf === null) {\n          onreadable = d._read\n          return\n        }\n        if (!d.push(buf)) {\n          return\n        }\n      }\n    }\n  }\n  d._destroy = function (err, callback) {\n    if (!err && onclose !== null) {\n      err = new AbortError()\n    }\n    onreadable = null\n    ondrain = null\n    onfinish = null\n    if (onclose === null) {\n      callback(err)\n    } else {\n      onclose = callback\n      destroyer(w, err)\n      destroyer(r, err)\n    }\n  }\n  return d\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototype inheritance, this class\n// prototypically inherits from Readable, and then parasitically from\n// Writable.\n\n'use strict'\n\nconst {\n  ObjectDefineProperties,\n  ObjectGetOwnPropertyDescriptor,\n  ObjectKeys,\n  ObjectSetPrototypeOf\n} = require('../../ours/primordials')\nmodule.exports = Duplex\nconst Readable = require('./readable')\nconst Writable = require('./writable')\nObjectSetPrototypeOf(Duplex.prototype, Readable.prototype)\nObjectSetPrototypeOf(Duplex, Readable)\n{\n  const keys = ObjectKeys(Writable.prototype)\n  // Allow the keys array to be GC'ed.\n  for (let i = 0; i < keys.length; i++) {\n    const method = keys[i]\n    if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]\n  }\n}\nfunction Duplex(options) {\n  if (!(this instanceof Duplex)) return new Duplex(options)\n  Readable.call(this, options)\n  Writable.call(this, options)\n  if (options) {\n    this.allowHalfOpen = options.allowHalfOpen !== false\n    if (options.readable === false) {\n      this._readableState.readable = false\n      this._readableState.ended = true\n      this._readableState.endEmitted = true\n    }\n    if (options.writable === false) {\n      this._writableState.writable = false\n      this._writableState.ending = true\n      this._writableState.ended = true\n      this._writableState.finished = true\n    }\n  } else {\n    this.allowHalfOpen = true\n  }\n}\nObjectDefineProperties(Duplex.prototype, {\n  writable: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writable')\n  },\n  writableHighWaterMark: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableHighWaterMark')\n  },\n  writableObjectMode: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableObjectMode')\n  },\n  writableBuffer: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableBuffer')\n  },\n  writableLength: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableLength')\n  },\n  writableFinished: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableFinished')\n  },\n  writableCorked: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableCorked')\n  },\n  writableEnded: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableEnded')\n  },\n  writableNeedDrain: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableNeedDrain')\n  },\n  destroyed: {\n    __proto__: null,\n    get() {\n      if (this._readableState === undefined || this._writableState === undefined) {\n        return false\n      }\n      return this._readableState.destroyed && this._writableState.destroyed\n    },\n    set(value) {\n      // Backward compatibility, the user is explicitly\n      // managing destroyed.\n      if (this._readableState && this._writableState) {\n        this._readableState.destroyed = value\n        this._writableState.destroyed = value\n      }\n    }\n  }\n})\nlet webStreamsAdapters\n\n// Lazy to avoid circular references\nfunction lazyWebStreams() {\n  if (webStreamsAdapters === undefined) webStreamsAdapters = {}\n  return webStreamsAdapters\n}\nDuplex.fromWeb = function (pair, options) {\n  return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair, options)\n}\nDuplex.toWeb = function (duplex) {\n  return lazyWebStreams().newReadableWritablePairFromDuplex(duplex)\n}\nlet duplexify\nDuplex.from = function (body) {\n  if (!duplexify) {\n    duplexify = require('./duplexify')\n  }\n  return duplexify(body, 'body')\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data.  Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored.  (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation.  For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes.  When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up.  When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer.  When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks.  If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk.  However,\n// a pathological inflate type of transform can cause excessive buffering\n// here.  For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output.  Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output.  In this case, you could write a very small\n// amount of input, and end up with a very large amount of output.  In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform.  A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n'use strict'\n\nconst { ObjectSetPrototypeOf, Symbol } = require('../../ours/primordials')\nmodule.exports = Transform\nconst { ERR_METHOD_NOT_IMPLEMENTED } = require('../../ours/errors').codes\nconst Duplex = require('./duplex')\nconst { getHighWaterMark } = require('./state')\nObjectSetPrototypeOf(Transform.prototype, Duplex.prototype)\nObjectSetPrototypeOf(Transform, Duplex)\nconst kCallback = Symbol('kCallback')\nfunction Transform(options) {\n  if (!(this instanceof Transform)) return new Transform(options)\n\n  // TODO (ronag): This should preferably always be\n  // applied but would be semver-major. Or even better;\n  // make Transform a Readable with the Writable interface.\n  const readableHighWaterMark = options ? getHighWaterMark(this, options, 'readableHighWaterMark', true) : null\n  if (readableHighWaterMark === 0) {\n    // A Duplex will buffer both on the writable and readable side while\n    // a Transform just wants to buffer hwm number of elements. To avoid\n    // buffering twice we disable buffering on the writable side.\n    options = {\n      ...options,\n      highWaterMark: null,\n      readableHighWaterMark,\n      // TODO (ronag): 0 is not optimal since we have\n      // a \"bug\" where we check needDrain before calling _write and not after.\n      // Refs: https://github.com/nodejs/node/pull/32887\n      // Refs: https://github.com/nodejs/node/pull/35941\n      writableHighWaterMark: options.writableHighWaterMark || 0\n    }\n  }\n  Duplex.call(this, options)\n\n  // We have implemented the _read method, and done the other things\n  // that Readable wants before the first _read call, so unset the\n  // sync guard flag.\n  this._readableState.sync = false\n  this[kCallback] = null\n  if (options) {\n    if (typeof options.transform === 'function') this._transform = options.transform\n    if (typeof options.flush === 'function') this._flush = options.flush\n  }\n\n  // When the writable side finishes, then flush out anything remaining.\n  // Backwards compat. Some Transform streams incorrectly implement _final\n  // instead of or in addition to _flush. By using 'prefinish' instead of\n  // implementing _final we continue supporting this unfortunate use case.\n  this.on('prefinish', prefinish)\n}\nfunction final(cb) {\n  if (typeof this._flush === 'function' && !this.destroyed) {\n    this._flush((er, data) => {\n      if (er) {\n        if (cb) {\n          cb(er)\n        } else {\n          this.destroy(er)\n        }\n        return\n      }\n      if (data != null) {\n        this.push(data)\n      }\n      this.push(null)\n      if (cb) {\n        cb()\n      }\n    })\n  } else {\n    this.push(null)\n    if (cb) {\n      cb()\n    }\n  }\n}\nfunction prefinish() {\n  if (this._final !== final) {\n    final.call(this)\n  }\n}\nTransform.prototype._final = final\nTransform.prototype._transform = function (chunk, encoding, callback) {\n  throw new ERR_METHOD_NOT_IMPLEMENTED('_transform()')\n}\nTransform.prototype._write = function (chunk, encoding, callback) {\n  const rState = this._readableState\n  const wState = this._writableState\n  const length = rState.length\n  this._transform(chunk, encoding, (err, val) => {\n    if (err) {\n      callback(err)\n      return\n    }\n    if (val != null) {\n      this.push(val)\n    }\n    if (\n      wState.ended ||\n      // Backwards compat.\n      length === rState.length ||\n      // Backwards compat.\n      rState.length < rState.highWaterMark\n    ) {\n      callback()\n    } else {\n      this[kCallback] = callback\n    }\n  })\n}\nTransform.prototype._read = function () {\n  if (this[kCallback]) {\n    const callback = this[kCallback]\n    this[kCallback] = null\n    callback()\n  }\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n'use strict'\n\nconst { ObjectSetPrototypeOf } = require('../../ours/primordials')\nmodule.exports = PassThrough\nconst Transform = require('./transform')\nObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype)\nObjectSetPrototypeOf(PassThrough, Transform)\nfunction PassThrough(options) {\n  if (!(this instanceof PassThrough)) return new PassThrough(options)\n  Transform.call(this, options)\n}\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n  cb(null, chunk)\n}\n","/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n// Ported from https://github.com/mafintosh/pump with\n// permission from the author, Mathias Buus (@mafintosh).\n\n;('use strict')\nconst { ArrayIsArray, Promise, SymbolAsyncIterator, SymbolDispose } = require('../../ours/primordials')\nconst eos = require('./end-of-stream')\nconst { once } = require('../../ours/util')\nconst destroyImpl = require('./destroy')\nconst Duplex = require('./duplex')\nconst {\n  aggregateTwoErrors,\n  codes: {\n    ERR_INVALID_ARG_TYPE,\n    ERR_INVALID_RETURN_VALUE,\n    ERR_MISSING_ARGS,\n    ERR_STREAM_DESTROYED,\n    ERR_STREAM_PREMATURE_CLOSE\n  },\n  AbortError\n} = require('../../ours/errors')\nconst { validateFunction, validateAbortSignal } = require('../validators')\nconst {\n  isIterable,\n  isReadable,\n  isReadableNodeStream,\n  isNodeStream,\n  isTransformStream,\n  isWebStream,\n  isReadableStream,\n  isReadableFinished\n} = require('./utils')\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nlet PassThrough\nlet Readable\nlet addAbortListener\nfunction destroyer(stream, reading, writing) {\n  let finished = false\n  stream.on('close', () => {\n    finished = true\n  })\n  const cleanup = eos(\n    stream,\n    {\n      readable: reading,\n      writable: writing\n    },\n    (err) => {\n      finished = !err\n    }\n  )\n  return {\n    destroy: (err) => {\n      if (finished) return\n      finished = true\n      destroyImpl.destroyer(stream, err || new ERR_STREAM_DESTROYED('pipe'))\n    },\n    cleanup\n  }\n}\nfunction popCallback(streams) {\n  // Streams should never be an empty array. It should always contain at least\n  // a single stream. Therefore optimize for the average case instead of\n  // checking for length === 0 as well.\n  validateFunction(streams[streams.length - 1], 'streams[stream.length - 1]')\n  return streams.pop()\n}\nfunction makeAsyncIterable(val) {\n  if (isIterable(val)) {\n    return val\n  } else if (isReadableNodeStream(val)) {\n    // Legacy streams are not Iterable.\n    return fromReadable(val)\n  }\n  throw new ERR_INVALID_ARG_TYPE('val', ['Readable', 'Iterable', 'AsyncIterable'], val)\n}\nasync function* fromReadable(val) {\n  if (!Readable) {\n    Readable = require('./readable')\n  }\n  yield* Readable.prototype[SymbolAsyncIterator].call(val)\n}\nasync function pumpToNode(iterable, writable, finish, { end }) {\n  let error\n  let onresolve = null\n  const resume = (err) => {\n    if (err) {\n      error = err\n    }\n    if (onresolve) {\n      const callback = onresolve\n      onresolve = null\n      callback()\n    }\n  }\n  const wait = () =>\n    new Promise((resolve, reject) => {\n      if (error) {\n        reject(error)\n      } else {\n        onresolve = () => {\n          if (error) {\n            reject(error)\n          } else {\n            resolve()\n          }\n        }\n      }\n    })\n  writable.on('drain', resume)\n  const cleanup = eos(\n    writable,\n    {\n      readable: false\n    },\n    resume\n  )\n  try {\n    if (writable.writableNeedDrain) {\n      await wait()\n    }\n    for await (const chunk of iterable) {\n      if (!writable.write(chunk)) {\n        await wait()\n      }\n    }\n    if (end) {\n      writable.end()\n      await wait()\n    }\n    finish()\n  } catch (err) {\n    finish(error !== err ? aggregateTwoErrors(error, err) : err)\n  } finally {\n    cleanup()\n    writable.off('drain', resume)\n  }\n}\nasync function pumpToWeb(readable, writable, finish, { end }) {\n  if (isTransformStream(writable)) {\n    writable = writable.writable\n  }\n  // https://streams.spec.whatwg.org/#example-manual-write-with-backpressure\n  const writer = writable.getWriter()\n  try {\n    for await (const chunk of readable) {\n      await writer.ready\n      writer.write(chunk).catch(() => {})\n    }\n    await writer.ready\n    if (end) {\n      await writer.close()\n    }\n    finish()\n  } catch (err) {\n    try {\n      await writer.abort(err)\n      finish(err)\n    } catch (err) {\n      finish(err)\n    }\n  }\n}\nfunction pipeline(...streams) {\n  return pipelineImpl(streams, once(popCallback(streams)))\n}\nfunction pipelineImpl(streams, callback, opts) {\n  if (streams.length === 1 && ArrayIsArray(streams[0])) {\n    streams = streams[0]\n  }\n  if (streams.length < 2) {\n    throw new ERR_MISSING_ARGS('streams')\n  }\n  const ac = new AbortController()\n  const signal = ac.signal\n  const outerSignal = opts === null || opts === undefined ? undefined : opts.signal\n\n  // Need to cleanup event listeners if last stream is readable\n  // https://github.com/nodejs/node/issues/35452\n  const lastStreamCleanup = []\n  validateAbortSignal(outerSignal, 'options.signal')\n  function abort() {\n    finishImpl(new AbortError())\n  }\n  addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n  let disposable\n  if (outerSignal) {\n    disposable = addAbortListener(outerSignal, abort)\n  }\n  let error\n  let value\n  const destroys = []\n  let finishCount = 0\n  function finish(err) {\n    finishImpl(err, --finishCount === 0)\n  }\n  function finishImpl(err, final) {\n    var _disposable\n    if (err && (!error || error.code === 'ERR_STREAM_PREMATURE_CLOSE')) {\n      error = err\n    }\n    if (!error && !final) {\n      return\n    }\n    while (destroys.length) {\n      destroys.shift()(error)\n    }\n    ;(_disposable = disposable) === null || _disposable === undefined ? undefined : _disposable[SymbolDispose]()\n    ac.abort()\n    if (final) {\n      if (!error) {\n        lastStreamCleanup.forEach((fn) => fn())\n      }\n      process.nextTick(callback, error, value)\n    }\n  }\n  let ret\n  for (let i = 0; i < streams.length; i++) {\n    const stream = streams[i]\n    const reading = i < streams.length - 1\n    const writing = i > 0\n    const end = reading || (opts === null || opts === undefined ? undefined : opts.end) !== false\n    const isLastStream = i === streams.length - 1\n    if (isNodeStream(stream)) {\n      if (end) {\n        const { destroy, cleanup } = destroyer(stream, reading, writing)\n        destroys.push(destroy)\n        if (isReadable(stream) && isLastStream) {\n          lastStreamCleanup.push(cleanup)\n        }\n      }\n\n      // Catch stream errors that occur after pipe/pump has completed.\n      function onError(err) {\n        if (err && err.name !== 'AbortError' && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n          finish(err)\n        }\n      }\n      stream.on('error', onError)\n      if (isReadable(stream) && isLastStream) {\n        lastStreamCleanup.push(() => {\n          stream.removeListener('error', onError)\n        })\n      }\n    }\n    if (i === 0) {\n      if (typeof stream === 'function') {\n        ret = stream({\n          signal\n        })\n        if (!isIterable(ret)) {\n          throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or Stream', 'source', ret)\n        }\n      } else if (isIterable(stream) || isReadableNodeStream(stream) || isTransformStream(stream)) {\n        ret = stream\n      } else {\n        ret = Duplex.from(stream)\n      }\n    } else if (typeof stream === 'function') {\n      if (isTransformStream(ret)) {\n        var _ret\n        ret = makeAsyncIterable((_ret = ret) === null || _ret === undefined ? undefined : _ret.readable)\n      } else {\n        ret = makeAsyncIterable(ret)\n      }\n      ret = stream(ret, {\n        signal\n      })\n      if (reading) {\n        if (!isIterable(ret, true)) {\n          throw new ERR_INVALID_RETURN_VALUE('AsyncIterable', `transform[${i - 1}]`, ret)\n        }\n      } else {\n        var _ret2\n        if (!PassThrough) {\n          PassThrough = require('./passthrough')\n        }\n\n        // If the last argument to pipeline is not a stream\n        // we must create a proxy stream so that pipeline(...)\n        // always returns a stream which can be further\n        // composed through `.pipe(stream)`.\n\n        const pt = new PassThrough({\n          objectMode: true\n        })\n\n        // Handle Promises/A+ spec, `then` could be a getter that throws on\n        // second use.\n        const then = (_ret2 = ret) === null || _ret2 === undefined ? undefined : _ret2.then\n        if (typeof then === 'function') {\n          finishCount++\n          then.call(\n            ret,\n            (val) => {\n              value = val\n              if (val != null) {\n                pt.write(val)\n              }\n              if (end) {\n                pt.end()\n              }\n              process.nextTick(finish)\n            },\n            (err) => {\n              pt.destroy(err)\n              process.nextTick(finish, err)\n            }\n          )\n        } else if (isIterable(ret, true)) {\n          finishCount++\n          pumpToNode(ret, pt, finish, {\n            end\n          })\n        } else if (isReadableStream(ret) || isTransformStream(ret)) {\n          const toRead = ret.readable || ret\n          finishCount++\n          pumpToNode(toRead, pt, finish, {\n            end\n          })\n        } else {\n          throw new ERR_INVALID_RETURN_VALUE('AsyncIterable or Promise', 'destination', ret)\n        }\n        ret = pt\n        const { destroy, cleanup } = destroyer(ret, false, true)\n        destroys.push(destroy)\n        if (isLastStream) {\n          lastStreamCleanup.push(cleanup)\n        }\n      }\n    } else if (isNodeStream(stream)) {\n      if (isReadableNodeStream(ret)) {\n        finishCount += 2\n        const cleanup = pipe(ret, stream, finish, {\n          end\n        })\n        if (isReadable(stream) && isLastStream) {\n          lastStreamCleanup.push(cleanup)\n        }\n      } else if (isTransformStream(ret) || isReadableStream(ret)) {\n        const toRead = ret.readable || ret\n        finishCount++\n        pumpToNode(toRead, stream, finish, {\n          end\n        })\n      } else if (isIterable(ret)) {\n        finishCount++\n        pumpToNode(ret, stream, finish, {\n          end\n        })\n      } else {\n        throw new ERR_INVALID_ARG_TYPE(\n          'val',\n          ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'],\n          ret\n        )\n      }\n      ret = stream\n    } else if (isWebStream(stream)) {\n      if (isReadableNodeStream(ret)) {\n        finishCount++\n        pumpToWeb(makeAsyncIterable(ret), stream, finish, {\n          end\n        })\n      } else if (isReadableStream(ret) || isIterable(ret)) {\n        finishCount++\n        pumpToWeb(ret, stream, finish, {\n          end\n        })\n      } else if (isTransformStream(ret)) {\n        finishCount++\n        pumpToWeb(ret.readable, stream, finish, {\n          end\n        })\n      } else {\n        throw new ERR_INVALID_ARG_TYPE(\n          'val',\n          ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'],\n          ret\n        )\n      }\n      ret = stream\n    } else {\n      ret = Duplex.from(stream)\n    }\n  }\n  if (\n    (signal !== null && signal !== undefined && signal.aborted) ||\n    (outerSignal !== null && outerSignal !== undefined && outerSignal.aborted)\n  ) {\n    process.nextTick(abort)\n  }\n  return ret\n}\nfunction pipe(src, dst, finish, { end }) {\n  let ended = false\n  dst.on('close', () => {\n    if (!ended) {\n      // Finish if the destination closes before the source has completed.\n      finish(new ERR_STREAM_PREMATURE_CLOSE())\n    }\n  })\n  src.pipe(dst, {\n    end: false\n  }) // If end is true we already will have a listener to end dst.\n\n  if (end) {\n    // Compat. Before node v10.12.0 stdio used to throw an error so\n    // pipe() did/does not end() stdio destinations.\n    // Now they allow it but \"secretly\" don't close the underlying fd.\n\n    function endFn() {\n      ended = true\n      dst.end()\n    }\n    if (isReadableFinished(src)) {\n      // End the destination if the source has already ended.\n      process.nextTick(endFn)\n    } else {\n      src.once('end', endFn)\n    }\n  } else {\n    finish()\n  }\n  eos(\n    src,\n    {\n      readable: true,\n      writable: false\n    },\n    (err) => {\n      const rState = src._readableState\n      if (\n        err &&\n        err.code === 'ERR_STREAM_PREMATURE_CLOSE' &&\n        rState &&\n        rState.ended &&\n        !rState.errored &&\n        !rState.errorEmitted\n      ) {\n        // Some readable streams will emit 'close' before 'end'. However, since\n        // this is on the readable side 'end' should still be emitted if the\n        // stream has been ended and no error emitted. This should be allowed in\n        // favor of backwards compatibility. Since the stream is piped to a\n        // destination this should not result in any observable difference.\n        // We don't need to check if this is a writable premature close since\n        // eos will only fail with premature close on the reading side for\n        // duplex streams.\n        src.once('end', finish).once('error', finish)\n      } else {\n        finish(err)\n      }\n    }\n  )\n  return eos(\n    dst,\n    {\n      readable: false,\n      writable: true\n    },\n    finish\n  )\n}\nmodule.exports = {\n  pipelineImpl,\n  pipeline\n}\n","'use strict'\n\nconst { pipeline } = require('./pipeline')\nconst Duplex = require('./duplex')\nconst { destroyer } = require('./destroy')\nconst {\n  isNodeStream,\n  isReadable,\n  isWritable,\n  isWebStream,\n  isTransformStream,\n  isWritableStream,\n  isReadableStream\n} = require('./utils')\nconst {\n  AbortError,\n  codes: { ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS }\n} = require('../../ours/errors')\nconst eos = require('./end-of-stream')\nmodule.exports = function compose(...streams) {\n  if (streams.length === 0) {\n    throw new ERR_MISSING_ARGS('streams')\n  }\n  if (streams.length === 1) {\n    return Duplex.from(streams[0])\n  }\n  const orgStreams = [...streams]\n  if (typeof streams[0] === 'function') {\n    streams[0] = Duplex.from(streams[0])\n  }\n  if (typeof streams[streams.length - 1] === 'function') {\n    const idx = streams.length - 1\n    streams[idx] = Duplex.from(streams[idx])\n  }\n  for (let n = 0; n < streams.length; ++n) {\n    if (!isNodeStream(streams[n]) && !isWebStream(streams[n])) {\n      // TODO(ronag): Add checks for non streams.\n      continue\n    }\n    if (\n      n < streams.length - 1 &&\n      !(isReadable(streams[n]) || isReadableStream(streams[n]) || isTransformStream(streams[n]))\n    ) {\n      throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be readable')\n    }\n    if (n > 0 && !(isWritable(streams[n]) || isWritableStream(streams[n]) || isTransformStream(streams[n]))) {\n      throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be writable')\n    }\n  }\n  let ondrain\n  let onfinish\n  let onreadable\n  let onclose\n  let d\n  function onfinished(err) {\n    const cb = onclose\n    onclose = null\n    if (cb) {\n      cb(err)\n    } else if (err) {\n      d.destroy(err)\n    } else if (!readable && !writable) {\n      d.destroy()\n    }\n  }\n  const head = streams[0]\n  const tail = pipeline(streams, onfinished)\n  const writable = !!(isWritable(head) || isWritableStream(head) || isTransformStream(head))\n  const readable = !!(isReadable(tail) || isReadableStream(tail) || isTransformStream(tail))\n\n  // TODO(ronag): Avoid double buffering.\n  // Implement Writable/Readable/Duplex traits.\n  // See, https://github.com/nodejs/node/pull/33515.\n  d = new Duplex({\n    // TODO (ronag): highWaterMark?\n    writableObjectMode: !!(head !== null && head !== undefined && head.writableObjectMode),\n    readableObjectMode: !!(tail !== null && tail !== undefined && tail.readableObjectMode),\n    writable,\n    readable\n  })\n  if (writable) {\n    if (isNodeStream(head)) {\n      d._write = function (chunk, encoding, callback) {\n        if (head.write(chunk, encoding)) {\n          callback()\n        } else {\n          ondrain = callback\n        }\n      }\n      d._final = function (callback) {\n        head.end()\n        onfinish = callback\n      }\n      head.on('drain', function () {\n        if (ondrain) {\n          const cb = ondrain\n          ondrain = null\n          cb()\n        }\n      })\n    } else if (isWebStream(head)) {\n      const writable = isTransformStream(head) ? head.writable : head\n      const writer = writable.getWriter()\n      d._write = async function (chunk, encoding, callback) {\n        try {\n          await writer.ready\n          writer.write(chunk).catch(() => {})\n          callback()\n        } catch (err) {\n          callback(err)\n        }\n      }\n      d._final = async function (callback) {\n        try {\n          await writer.ready\n          writer.close().catch(() => {})\n          onfinish = callback\n        } catch (err) {\n          callback(err)\n        }\n      }\n    }\n    const toRead = isTransformStream(tail) ? tail.readable : tail\n    eos(toRead, () => {\n      if (onfinish) {\n        const cb = onfinish\n        onfinish = null\n        cb()\n      }\n    })\n  }\n  if (readable) {\n    if (isNodeStream(tail)) {\n      tail.on('readable', function () {\n        if (onreadable) {\n          const cb = onreadable\n          onreadable = null\n          cb()\n        }\n      })\n      tail.on('end', function () {\n        d.push(null)\n      })\n      d._read = function () {\n        while (true) {\n          const buf = tail.read()\n          if (buf === null) {\n            onreadable = d._read\n            return\n          }\n          if (!d.push(buf)) {\n            return\n          }\n        }\n      }\n    } else if (isWebStream(tail)) {\n      const readable = isTransformStream(tail) ? tail.readable : tail\n      const reader = readable.getReader()\n      d._read = async function () {\n        while (true) {\n          try {\n            const { value, done } = await reader.read()\n            if (!d.push(value)) {\n              return\n            }\n            if (done) {\n              d.push(null)\n              return\n            }\n          } catch {\n            return\n          }\n        }\n      }\n    }\n  }\n  d._destroy = function (err, callback) {\n    if (!err && onclose !== null) {\n      err = new AbortError()\n    }\n    onreadable = null\n    ondrain = null\n    onfinish = null\n    if (onclose === null) {\n      callback(err)\n    } else {\n      onclose = callback\n      if (isNodeStream(tail)) {\n        destroyer(tail, err)\n      }\n    }\n  }\n  return d\n}\n","'use strict'\n\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nconst {\n  codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE },\n  AbortError\n} = require('../../ours/errors')\nconst { validateAbortSignal, validateInteger, validateObject } = require('../validators')\nconst kWeakHandler = require('../../ours/primordials').Symbol('kWeak')\nconst kResistStopPropagation = require('../../ours/primordials').Symbol('kResistStopPropagation')\nconst { finished } = require('./end-of-stream')\nconst staticCompose = require('./compose')\nconst { addAbortSignalNoValidate } = require('./add-abort-signal')\nconst { isWritable, isNodeStream } = require('./utils')\nconst { deprecate } = require('../../ours/util')\nconst {\n  ArrayPrototypePush,\n  Boolean,\n  MathFloor,\n  Number,\n  NumberIsNaN,\n  Promise,\n  PromiseReject,\n  PromiseResolve,\n  PromisePrototypeThen,\n  Symbol\n} = require('../../ours/primordials')\nconst kEmpty = Symbol('kEmpty')\nconst kEof = Symbol('kEof')\nfunction compose(stream, options) {\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  if (isNodeStream(stream) && !isWritable(stream)) {\n    throw new ERR_INVALID_ARG_VALUE('stream', stream, 'must be writable')\n  }\n  const composedStream = staticCompose(this, stream)\n  if (options !== null && options !== undefined && options.signal) {\n    // Not validating as we already validated before\n    addAbortSignalNoValidate(options.signal, composedStream)\n  }\n  return composedStream\n}\nfunction map(fn, options) {\n  if (typeof fn !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n  }\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  let concurrency = 1\n  if ((options === null || options === undefined ? undefined : options.concurrency) != null) {\n    concurrency = MathFloor(options.concurrency)\n  }\n  let highWaterMark = concurrency - 1\n  if ((options === null || options === undefined ? undefined : options.highWaterMark) != null) {\n    highWaterMark = MathFloor(options.highWaterMark)\n  }\n  validateInteger(concurrency, 'options.concurrency', 1)\n  validateInteger(highWaterMark, 'options.highWaterMark', 0)\n  highWaterMark += concurrency\n  return async function* map() {\n    const signal = require('../../ours/util').AbortSignalAny(\n      [options === null || options === undefined ? undefined : options.signal].filter(Boolean)\n    )\n    const stream = this\n    const queue = []\n    const signalOpt = {\n      signal\n    }\n    let next\n    let resume\n    let done = false\n    let cnt = 0\n    function onCatch() {\n      done = true\n      afterItemProcessed()\n    }\n    function afterItemProcessed() {\n      cnt -= 1\n      maybeResume()\n    }\n    function maybeResume() {\n      if (resume && !done && cnt < concurrency && queue.length < highWaterMark) {\n        resume()\n        resume = null\n      }\n    }\n    async function pump() {\n      try {\n        for await (let val of stream) {\n          if (done) {\n            return\n          }\n          if (signal.aborted) {\n            throw new AbortError()\n          }\n          try {\n            val = fn(val, signalOpt)\n            if (val === kEmpty) {\n              continue\n            }\n            val = PromiseResolve(val)\n          } catch (err) {\n            val = PromiseReject(err)\n          }\n          cnt += 1\n          PromisePrototypeThen(val, afterItemProcessed, onCatch)\n          queue.push(val)\n          if (next) {\n            next()\n            next = null\n          }\n          if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) {\n            await new Promise((resolve) => {\n              resume = resolve\n            })\n          }\n        }\n        queue.push(kEof)\n      } catch (err) {\n        const val = PromiseReject(err)\n        PromisePrototypeThen(val, afterItemProcessed, onCatch)\n        queue.push(val)\n      } finally {\n        done = true\n        if (next) {\n          next()\n          next = null\n        }\n      }\n    }\n    pump()\n    try {\n      while (true) {\n        while (queue.length > 0) {\n          const val = await queue[0]\n          if (val === kEof) {\n            return\n          }\n          if (signal.aborted) {\n            throw new AbortError()\n          }\n          if (val !== kEmpty) {\n            yield val\n          }\n          queue.shift()\n          maybeResume()\n        }\n        await new Promise((resolve) => {\n          next = resolve\n        })\n      }\n    } finally {\n      done = true\n      if (resume) {\n        resume()\n        resume = null\n      }\n    }\n  }.call(this)\n}\nfunction asIndexedPairs(options = undefined) {\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  return async function* asIndexedPairs() {\n    let index = 0\n    for await (const val of this) {\n      var _options$signal\n      if (\n        options !== null &&\n        options !== undefined &&\n        (_options$signal = options.signal) !== null &&\n        _options$signal !== undefined &&\n        _options$signal.aborted\n      ) {\n        throw new AbortError({\n          cause: options.signal.reason\n        })\n      }\n      yield [index++, val]\n    }\n  }.call(this)\n}\nasync function some(fn, options = undefined) {\n  for await (const unused of filter.call(this, fn, options)) {\n    return true\n  }\n  return false\n}\nasync function every(fn, options = undefined) {\n  if (typeof fn !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n  }\n  // https://en.wikipedia.org/wiki/De_Morgan%27s_laws\n  return !(await some.call(\n    this,\n    async (...args) => {\n      return !(await fn(...args))\n    },\n    options\n  ))\n}\nasync function find(fn, options) {\n  for await (const result of filter.call(this, fn, options)) {\n    return result\n  }\n  return undefined\n}\nasync function forEach(fn, options) {\n  if (typeof fn !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n  }\n  async function forEachFn(value, options) {\n    await fn(value, options)\n    return kEmpty\n  }\n  // eslint-disable-next-line no-unused-vars\n  for await (const unused of map.call(this, forEachFn, options));\n}\nfunction filter(fn, options) {\n  if (typeof fn !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n  }\n  async function filterFn(value, options) {\n    if (await fn(value, options)) {\n      return value\n    }\n    return kEmpty\n  }\n  return map.call(this, filterFn, options)\n}\n\n// Specific to provide better error to reduce since the argument is only\n// missing if the stream has no items in it - but the code is still appropriate\nclass ReduceAwareErrMissingArgs extends ERR_MISSING_ARGS {\n  constructor() {\n    super('reduce')\n    this.message = 'Reduce of an empty stream requires an initial value'\n  }\n}\nasync function reduce(reducer, initialValue, options) {\n  var _options$signal2\n  if (typeof reducer !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE('reducer', ['Function', 'AsyncFunction'], reducer)\n  }\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  let hasInitialValue = arguments.length > 1\n  if (\n    options !== null &&\n    options !== undefined &&\n    (_options$signal2 = options.signal) !== null &&\n    _options$signal2 !== undefined &&\n    _options$signal2.aborted\n  ) {\n    const err = new AbortError(undefined, {\n      cause: options.signal.reason\n    })\n    this.once('error', () => {}) // The error is already propagated\n    await finished(this.destroy(err))\n    throw err\n  }\n  const ac = new AbortController()\n  const signal = ac.signal\n  if (options !== null && options !== undefined && options.signal) {\n    const opts = {\n      once: true,\n      [kWeakHandler]: this,\n      [kResistStopPropagation]: true\n    }\n    options.signal.addEventListener('abort', () => ac.abort(), opts)\n  }\n  let gotAnyItemFromStream = false\n  try {\n    for await (const value of this) {\n      var _options$signal3\n      gotAnyItemFromStream = true\n      if (\n        options !== null &&\n        options !== undefined &&\n        (_options$signal3 = options.signal) !== null &&\n        _options$signal3 !== undefined &&\n        _options$signal3.aborted\n      ) {\n        throw new AbortError()\n      }\n      if (!hasInitialValue) {\n        initialValue = value\n        hasInitialValue = true\n      } else {\n        initialValue = await reducer(initialValue, value, {\n          signal\n        })\n      }\n    }\n    if (!gotAnyItemFromStream && !hasInitialValue) {\n      throw new ReduceAwareErrMissingArgs()\n    }\n  } finally {\n    ac.abort()\n  }\n  return initialValue\n}\nasync function toArray(options) {\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  const result = []\n  for await (const val of this) {\n    var _options$signal4\n    if (\n      options !== null &&\n      options !== undefined &&\n      (_options$signal4 = options.signal) !== null &&\n      _options$signal4 !== undefined &&\n      _options$signal4.aborted\n    ) {\n      throw new AbortError(undefined, {\n        cause: options.signal.reason\n      })\n    }\n    ArrayPrototypePush(result, val)\n  }\n  return result\n}\nfunction flatMap(fn, options) {\n  const values = map.call(this, fn, options)\n  return async function* flatMap() {\n    for await (const val of values) {\n      yield* val\n    }\n  }.call(this)\n}\nfunction toIntegerOrInfinity(number) {\n  // We coerce here to align with the spec\n  // https://github.com/tc39/proposal-iterator-helpers/issues/169\n  number = Number(number)\n  if (NumberIsNaN(number)) {\n    return 0\n  }\n  if (number < 0) {\n    throw new ERR_OUT_OF_RANGE('number', '>= 0', number)\n  }\n  return number\n}\nfunction drop(number, options = undefined) {\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  number = toIntegerOrInfinity(number)\n  return async function* drop() {\n    var _options$signal5\n    if (\n      options !== null &&\n      options !== undefined &&\n      (_options$signal5 = options.signal) !== null &&\n      _options$signal5 !== undefined &&\n      _options$signal5.aborted\n    ) {\n      throw new AbortError()\n    }\n    for await (const val of this) {\n      var _options$signal6\n      if (\n        options !== null &&\n        options !== undefined &&\n        (_options$signal6 = options.signal) !== null &&\n        _options$signal6 !== undefined &&\n        _options$signal6.aborted\n      ) {\n        throw new AbortError()\n      }\n      if (number-- <= 0) {\n        yield val\n      }\n    }\n  }.call(this)\n}\nfunction take(number, options = undefined) {\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  number = toIntegerOrInfinity(number)\n  return async function* take() {\n    var _options$signal7\n    if (\n      options !== null &&\n      options !== undefined &&\n      (_options$signal7 = options.signal) !== null &&\n      _options$signal7 !== undefined &&\n      _options$signal7.aborted\n    ) {\n      throw new AbortError()\n    }\n    for await (const val of this) {\n      var _options$signal8\n      if (\n        options !== null &&\n        options !== undefined &&\n        (_options$signal8 = options.signal) !== null &&\n        _options$signal8 !== undefined &&\n        _options$signal8.aborted\n      ) {\n        throw new AbortError()\n      }\n      if (number-- > 0) {\n        yield val\n      }\n\n      // Don't get another item from iterator in case we reached the end\n      if (number <= 0) {\n        return\n      }\n    }\n  }.call(this)\n}\nmodule.exports.streamReturningOperators = {\n  asIndexedPairs: deprecate(asIndexedPairs, 'readable.asIndexedPairs will be removed in a future version.'),\n  drop,\n  filter,\n  flatMap,\n  map,\n  take,\n  compose\n}\nmodule.exports.promiseReturningOperators = {\n  every,\n  forEach,\n  reduce,\n  toArray,\n  some,\n  find\n}\n","'use strict'\n\nconst { ArrayPrototypePop, Promise } = require('../ours/primordials')\nconst { isIterable, isNodeStream, isWebStream } = require('../internal/streams/utils')\nconst { pipelineImpl: pl } = require('../internal/streams/pipeline')\nconst { finished } = require('../internal/streams/end-of-stream')\nrequire('../../lib/stream.js')\nfunction pipeline(...streams) {\n  return new Promise((resolve, reject) => {\n    let signal\n    let end\n    const lastArg = streams[streams.length - 1]\n    if (\n      lastArg &&\n      typeof lastArg === 'object' &&\n      !isNodeStream(lastArg) &&\n      !isIterable(lastArg) &&\n      !isWebStream(lastArg)\n    ) {\n      const options = ArrayPrototypePop(streams)\n      signal = options.signal\n      end = options.end\n    }\n    pl(\n      streams,\n      (err, value) => {\n        if (err) {\n          reject(err)\n        } else {\n          resolve(value)\n        }\n      },\n      {\n        signal,\n        end\n      }\n    )\n  })\n}\nmodule.exports = {\n  finished,\n  pipeline\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict'\n\n/* replacement start */\n\nconst { Buffer } = require('buffer')\n\n/* replacement end */\n\nconst { ObjectDefineProperty, ObjectKeys, ReflectApply } = require('./ours/primordials')\nconst {\n  promisify: { custom: customPromisify }\n} = require('./ours/util')\nconst { streamReturningOperators, promiseReturningOperators } = require('./internal/streams/operators')\nconst {\n  codes: { ERR_ILLEGAL_CONSTRUCTOR }\n} = require('./ours/errors')\nconst compose = require('./internal/streams/compose')\nconst { setDefaultHighWaterMark, getDefaultHighWaterMark } = require('./internal/streams/state')\nconst { pipeline } = require('./internal/streams/pipeline')\nconst { destroyer } = require('./internal/streams/destroy')\nconst eos = require('./internal/streams/end-of-stream')\nconst internalBuffer = {}\nconst promises = require('./stream/promises')\nconst utils = require('./internal/streams/utils')\nconst Stream = (module.exports = require('./internal/streams/legacy').Stream)\nStream.isDestroyed = utils.isDestroyed\nStream.isDisturbed = utils.isDisturbed\nStream.isErrored = utils.isErrored\nStream.isReadable = utils.isReadable\nStream.isWritable = utils.isWritable\nStream.Readable = require('./internal/streams/readable')\nfor (const key of ObjectKeys(streamReturningOperators)) {\n  const op = streamReturningOperators[key]\n  function fn(...args) {\n    if (new.target) {\n      throw ERR_ILLEGAL_CONSTRUCTOR()\n    }\n    return Stream.Readable.from(ReflectApply(op, this, args))\n  }\n  ObjectDefineProperty(fn, 'name', {\n    __proto__: null,\n    value: op.name\n  })\n  ObjectDefineProperty(fn, 'length', {\n    __proto__: null,\n    value: op.length\n  })\n  ObjectDefineProperty(Stream.Readable.prototype, key, {\n    __proto__: null,\n    value: fn,\n    enumerable: false,\n    configurable: true,\n    writable: true\n  })\n}\nfor (const key of ObjectKeys(promiseReturningOperators)) {\n  const op = promiseReturningOperators[key]\n  function fn(...args) {\n    if (new.target) {\n      throw ERR_ILLEGAL_CONSTRUCTOR()\n    }\n    return ReflectApply(op, this, args)\n  }\n  ObjectDefineProperty(fn, 'name', {\n    __proto__: null,\n    value: op.name\n  })\n  ObjectDefineProperty(fn, 'length', {\n    __proto__: null,\n    value: op.length\n  })\n  ObjectDefineProperty(Stream.Readable.prototype, key, {\n    __proto__: null,\n    value: fn,\n    enumerable: false,\n    configurable: true,\n    writable: true\n  })\n}\nStream.Writable = require('./internal/streams/writable')\nStream.Duplex = require('./internal/streams/duplex')\nStream.Transform = require('./internal/streams/transform')\nStream.PassThrough = require('./internal/streams/passthrough')\nStream.pipeline = pipeline\nconst { addAbortSignal } = require('./internal/streams/add-abort-signal')\nStream.addAbortSignal = addAbortSignal\nStream.finished = eos\nStream.destroy = destroyer\nStream.compose = compose\nStream.setDefaultHighWaterMark = setDefaultHighWaterMark\nStream.getDefaultHighWaterMark = getDefaultHighWaterMark\nObjectDefineProperty(Stream, 'promises', {\n  __proto__: null,\n  configurable: true,\n  enumerable: true,\n  get() {\n    return promises\n  }\n})\nObjectDefineProperty(pipeline, customPromisify, {\n  __proto__: null,\n  enumerable: true,\n  get() {\n    return promises.pipeline\n  }\n})\nObjectDefineProperty(eos, customPromisify, {\n  __proto__: null,\n  enumerable: true,\n  get() {\n    return promises.finished\n  }\n})\n\n// Backwards-compat with node 0.4.x\nStream.Stream = Stream\nStream._isUint8Array = function isUint8Array(value) {\n  return value instanceof Uint8Array\n}\nStream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) {\n  return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)\n}\n","'use strict'\n\nconst Stream = require('stream')\nif (Stream && process.env.READABLE_STREAM === 'disable') {\n  const promises = Stream.promises\n\n  // Explicit export naming is needed for ESM\n  module.exports._uint8ArrayToBuffer = Stream._uint8ArrayToBuffer\n  module.exports._isUint8Array = Stream._isUint8Array\n  module.exports.isDisturbed = Stream.isDisturbed\n  module.exports.isErrored = Stream.isErrored\n  module.exports.isReadable = Stream.isReadable\n  module.exports.Readable = Stream.Readable\n  module.exports.Writable = Stream.Writable\n  module.exports.Duplex = Stream.Duplex\n  module.exports.Transform = Stream.Transform\n  module.exports.PassThrough = Stream.PassThrough\n  module.exports.addAbortSignal = Stream.addAbortSignal\n  module.exports.finished = Stream.finished\n  module.exports.destroy = Stream.destroy\n  module.exports.pipeline = Stream.pipeline\n  module.exports.compose = Stream.compose\n  Object.defineProperty(Stream, 'promises', {\n    configurable: true,\n    enumerable: true,\n    get() {\n      return promises\n    }\n  })\n  module.exports.Stream = Stream.Stream\n} else {\n  const CustomStream = require('../stream')\n  const promises = require('../stream/promises')\n  const originalDestroy = CustomStream.Readable.destroy\n  module.exports = CustomStream.Readable\n\n  // Explicit export naming is needed for ESM\n  module.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer\n  module.exports._isUint8Array = CustomStream._isUint8Array\n  module.exports.isDisturbed = CustomStream.isDisturbed\n  module.exports.isErrored = CustomStream.isErrored\n  module.exports.isReadable = CustomStream.isReadable\n  module.exports.Readable = CustomStream.Readable\n  module.exports.Writable = CustomStream.Writable\n  module.exports.Duplex = CustomStream.Duplex\n  module.exports.Transform = CustomStream.Transform\n  module.exports.PassThrough = CustomStream.PassThrough\n  module.exports.addAbortSignal = CustomStream.addAbortSignal\n  module.exports.finished = CustomStream.finished\n  module.exports.destroy = CustomStream.destroy\n  module.exports.destroy = originalDestroy\n  module.exports.pipeline = CustomStream.pipeline\n  module.exports.compose = CustomStream.compose\n  Object.defineProperty(CustomStream, 'promises', {\n    configurable: true,\n    enumerable: true,\n    get() {\n      return promises\n    }\n  })\n  module.exports.Stream = CustomStream.Stream\n}\n\n// Allow default importing\nmodule.exports.default = module.exports\n","/**\n * Archiver Core\n *\n * @ignore\n * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE}\n * @copyright (c) 2012-2014 Chris Talkington, contributors.\n */\nvar fs = require('fs');\nvar glob = require('readdir-glob');\nvar async = require('async');\nvar path = require('path');\nvar util = require('archiver-utils');\n\nvar inherits = require('util').inherits;\nvar ArchiverError = require('./error');\nvar Transform = require('readable-stream').Transform;\n\nvar win32 = process.platform === 'win32';\n\n/**\n * @constructor\n * @param {String} format The archive format to use.\n * @param {(CoreOptions|TransformOptions)} options See also {@link ZipOptions} and {@link TarOptions}.\n */\nvar Archiver = function(format, options) {\n  if (!(this instanceof Archiver)) {\n    return new Archiver(format, options);\n  }\n\n  if (typeof format !== 'string') {\n    options = format;\n    format = 'zip';\n  }\n\n  options = this.options = util.defaults(options, {\n    highWaterMark: 1024 * 1024,\n    statConcurrency: 4\n  });\n\n  Transform.call(this, options);\n\n  this._format = false;\n  this._module = false;\n  this._pending = 0;\n  this._pointer = 0;\n\n  this._entriesCount = 0;\n  this._entriesProcessedCount = 0;\n  this._fsEntriesTotalBytes = 0;\n  this._fsEntriesProcessedBytes = 0;\n\n  this._queue = async.queue(this._onQueueTask.bind(this), 1);\n  this._queue.drain(this._onQueueDrain.bind(this));\n\n  this._statQueue = async.queue(this._onStatQueueTask.bind(this), options.statConcurrency);\n  this._statQueue.drain(this._onQueueDrain.bind(this));\n\n  this._state = {\n    aborted: false,\n    finalize: false,\n    finalizing: false,\n    finalized: false,\n    modulePiped: false\n  };\n\n  this._streams = [];\n};\n\ninherits(Archiver, Transform);\n\n/**\n * Internal logic for `abort`.\n *\n * @private\n * @return void\n */\nArchiver.prototype._abort = function() {\n  this._state.aborted = true;\n  this._queue.kill();\n  this._statQueue.kill();\n\n  if (this._queue.idle()) {\n    this._shutdown();\n  }\n};\n\n/**\n * Internal helper for appending files.\n *\n * @private\n * @param  {String} filepath The source filepath.\n * @param  {EntryData} data The entry data.\n * @return void\n */\nArchiver.prototype._append = function(filepath, data) {\n  data = data || {};\n\n  var task = {\n    source: null,\n    filepath: filepath\n  };\n\n  if (!data.name) {\n    data.name = filepath;\n  }\n\n  data.sourcePath = filepath;\n  task.data = data;\n  this._entriesCount++;\n\n  if (data.stats && data.stats instanceof fs.Stats) {\n    task = this._updateQueueTaskWithStats(task, data.stats);\n    if (task) {\n      if (data.stats.size) {\n        this._fsEntriesTotalBytes += data.stats.size;\n      }\n\n      this._queue.push(task);\n    }\n  } else {\n    this._statQueue.push(task);\n  }\n};\n\n/**\n * Internal logic for `finalize`.\n *\n * @private\n * @return void\n */\nArchiver.prototype._finalize = function() {\n  if (this._state.finalizing || this._state.finalized || this._state.aborted) {\n    return;\n  }\n\n  this._state.finalizing = true;\n\n  this._moduleFinalize();\n\n  this._state.finalizing = false;\n  this._state.finalized = true;\n};\n\n/**\n * Checks the various state variables to determine if we can `finalize`.\n *\n * @private\n * @return {Boolean}\n */\nArchiver.prototype._maybeFinalize = function() {\n  if (this._state.finalizing || this._state.finalized || this._state.aborted) {\n    return false;\n  }\n\n  if (this._state.finalize && this._pending === 0 && this._queue.idle() && this._statQueue.idle()) {\n    this._finalize();\n    return true;\n  }\n\n  return false;\n};\n\n/**\n * Appends an entry to the module.\n *\n * @private\n * @fires  Archiver#entry\n * @param  {(Buffer|Stream)} source\n * @param  {EntryData} data\n * @param  {Function} callback\n * @return void\n */\nArchiver.prototype._moduleAppend = function(source, data, callback) {\n  if (this._state.aborted) {\n    callback();\n    return;\n  }\n\n  this._module.append(source, data, function(err) {\n    this._task = null;\n\n    if (this._state.aborted) {\n      this._shutdown();\n      return;\n    }\n\n    if (err) {\n      this.emit('error', err);\n      setImmediate(callback);\n      return;\n    }\n\n    /**\n     * Fires when the entry's input has been processed and appended to the archive.\n     *\n     * @event Archiver#entry\n     * @type {EntryData}\n     */\n    this.emit('entry', data);\n    this._entriesProcessedCount++;\n\n    if (data.stats && data.stats.size) {\n      this._fsEntriesProcessedBytes += data.stats.size;\n    }\n\n    /**\n     * @event Archiver#progress\n     * @type {ProgressData}\n     */\n    this.emit('progress', {\n      entries: {\n        total: this._entriesCount,\n        processed: this._entriesProcessedCount\n      },\n      fs: {\n        totalBytes: this._fsEntriesTotalBytes,\n        processedBytes: this._fsEntriesProcessedBytes\n      }\n    });\n\n    setImmediate(callback);\n  }.bind(this));\n};\n\n/**\n * Finalizes the module.\n *\n * @private\n * @return void\n */\nArchiver.prototype._moduleFinalize = function() {\n  if (typeof this._module.finalize === 'function') {\n    this._module.finalize();\n  } else if (typeof this._module.end === 'function') {\n    this._module.end();\n  } else {\n    this.emit('error', new ArchiverError('NOENDMETHOD'));\n  }\n};\n\n/**\n * Pipes the module to our internal stream with error bubbling.\n *\n * @private\n * @return void\n */\nArchiver.prototype._modulePipe = function() {\n  this._module.on('error', this._onModuleError.bind(this));\n  this._module.pipe(this);\n  this._state.modulePiped = true;\n};\n\n/**\n * Determines if the current module supports a defined feature.\n *\n * @private\n * @param  {String} key\n * @return {Boolean}\n */\nArchiver.prototype._moduleSupports = function(key) {\n  if (!this._module.supports || !this._module.supports[key]) {\n    return false;\n  }\n\n  return this._module.supports[key];\n};\n\n/**\n * Unpipes the module from our internal stream.\n *\n * @private\n * @return void\n */\nArchiver.prototype._moduleUnpipe = function() {\n  this._module.unpipe(this);\n  this._state.modulePiped = false;\n};\n\n/**\n * Normalizes entry data with fallbacks for key properties.\n *\n * @private\n * @param  {Object} data\n * @param  {fs.Stats} stats\n * @return {Object}\n */\nArchiver.prototype._normalizeEntryData = function(data, stats) {\n  data = util.defaults(data, {\n    type: 'file',\n    name: null,\n    date: null,\n    mode: null,\n    prefix: null,\n    sourcePath: null,\n    stats: false\n  });\n\n  if (stats && data.stats === false) {\n    data.stats = stats;\n  }\n\n  var isDir = data.type === 'directory';\n\n  if (data.name) {\n    if (typeof data.prefix === 'string' && '' !== data.prefix) {\n      data.name = data.prefix + '/' + data.name;\n      data.prefix = null;\n    }\n\n    data.name = util.sanitizePath(data.name);\n\n    if (data.type !== 'symlink' && data.name.slice(-1) === '/') {\n      isDir = true;\n      data.type = 'directory';\n    } else if (isDir) {\n      data.name += '/';\n    }\n  }\n\n  // 511 === 0777; 493 === 0755; 438 === 0666; 420 === 0644\n  if (typeof data.mode === 'number') {\n    if (win32) {\n      data.mode &= 511;\n    } else {\n      data.mode &= 4095\n    }\n  } else if (data.stats && data.mode === null) {\n    if (win32) {\n      data.mode = data.stats.mode & 511;\n    } else {\n      data.mode = data.stats.mode & 4095;\n    }\n\n    // stat isn't reliable on windows; force 0755 for dir\n    if (win32 && isDir) {\n      data.mode = 493;\n    }\n  } else if (data.mode === null) {\n    data.mode = isDir ? 493 : 420;\n  }\n\n  if (data.stats && data.date === null) {\n    data.date = data.stats.mtime;\n  } else {\n    data.date = util.dateify(data.date);\n  }\n\n  return data;\n};\n\n/**\n * Error listener that re-emits error on to our internal stream.\n *\n * @private\n * @param  {Error} err\n * @return void\n */\nArchiver.prototype._onModuleError = function(err) {\n  /**\n   * @event Archiver#error\n   * @type {ErrorData}\n   */\n  this.emit('error', err);\n};\n\n/**\n * Checks the various state variables after queue has drained to determine if\n * we need to `finalize`.\n *\n * @private\n * @return void\n */\nArchiver.prototype._onQueueDrain = function() {\n  if (this._state.finalizing || this._state.finalized || this._state.aborted) {\n    return;\n  }\n\n  if (this._state.finalize && this._pending === 0 && this._queue.idle() && this._statQueue.idle()) {\n    this._finalize();\n  }\n};\n\n/**\n * Appends each queue task to the module.\n *\n * @private\n * @param  {Object} task\n * @param  {Function} callback\n * @return void\n */\nArchiver.prototype._onQueueTask = function(task, callback) {\n  var fullCallback = () => {\n    if(task.data.callback) {\n      task.data.callback();\n    }\n    callback();\n  }\n\n  if (this._state.finalizing || this._state.finalized || this._state.aborted) {\n    fullCallback();\n    return;\n  }\n\n  this._task = task;\n  this._moduleAppend(task.source, task.data, fullCallback);\n};\n\n/**\n * Performs a file stat and reinjects the task back into the queue.\n *\n * @private\n * @param  {Object} task\n * @param  {Function} callback\n * @return void\n */\nArchiver.prototype._onStatQueueTask = function(task, callback) {\n  if (this._state.finalizing || this._state.finalized || this._state.aborted) {\n    callback();\n    return;\n  }\n\n  fs.lstat(task.filepath, function(err, stats) {\n    if (this._state.aborted) {\n      setImmediate(callback);\n      return;\n    }\n\n    if (err) {\n      this._entriesCount--;\n\n      /**\n       * @event Archiver#warning\n       * @type {ErrorData}\n       */\n      this.emit('warning', err);\n      setImmediate(callback);\n      return;\n    }\n\n    task = this._updateQueueTaskWithStats(task, stats);\n\n    if (task) {\n      if (stats.size) {\n        this._fsEntriesTotalBytes += stats.size;\n      }\n\n      this._queue.push(task);\n    }\n\n    setImmediate(callback);\n  }.bind(this));\n};\n\n/**\n * Unpipes the module and ends our internal stream.\n *\n * @private\n * @return void\n */\nArchiver.prototype._shutdown = function() {\n  this._moduleUnpipe();\n  this.end();\n};\n\n/**\n * Tracks the bytes emitted by our internal stream.\n *\n * @private\n * @param  {Buffer} chunk\n * @param  {String} encoding\n * @param  {Function} callback\n * @return void\n */\nArchiver.prototype._transform = function(chunk, encoding, callback) {\n  if (chunk) {\n    this._pointer += chunk.length;\n  }\n\n  callback(null, chunk);\n};\n\n/**\n * Updates and normalizes a queue task using stats data.\n *\n * @private\n * @param  {Object} task\n * @param  {fs.Stats} stats\n * @return {Object}\n */\nArchiver.prototype._updateQueueTaskWithStats = function(task, stats) {\n  if (stats.isFile()) {\n    task.data.type = 'file';\n    task.data.sourceType = 'stream';\n    task.source = util.lazyReadStream(task.filepath);\n  } else if (stats.isDirectory() && this._moduleSupports('directory')) {\n    task.data.name = util.trailingSlashIt(task.data.name);\n    task.data.type = 'directory';\n    task.data.sourcePath = util.trailingSlashIt(task.filepath);\n    task.data.sourceType = 'buffer';\n    task.source = Buffer.concat([]);\n  } else if (stats.isSymbolicLink() && this._moduleSupports('symlink')) {\n    var linkPath = fs.readlinkSync(task.filepath);\n    var dirName = path.dirname(task.filepath);\n    task.data.type = 'symlink';\n    task.data.linkname = path.relative(dirName, path.resolve(dirName, linkPath));\n    task.data.sourceType = 'buffer';\n    task.source = Buffer.concat([]);\n  } else {\n    if (stats.isDirectory()) {\n      this.emit('warning', new ArchiverError('DIRECTORYNOTSUPPORTED', task.data));\n    } else if (stats.isSymbolicLink()) {\n      this.emit('warning', new ArchiverError('SYMLINKNOTSUPPORTED', task.data));\n    } else {\n      this.emit('warning', new ArchiverError('ENTRYNOTSUPPORTED', task.data));\n    }\n\n    return null;\n  }\n\n  task.data = this._normalizeEntryData(task.data, stats);\n\n  return task;\n};\n\n/**\n * Aborts the archiving process, taking a best-effort approach, by:\n *\n * - removing any pending queue tasks\n * - allowing any active queue workers to finish\n * - detaching internal module pipes\n * - ending both sides of the Transform stream\n *\n * It will NOT drain any remaining sources.\n *\n * @return {this}\n */\nArchiver.prototype.abort = function() {\n  if (this._state.aborted || this._state.finalized) {\n    return this;\n  }\n\n  this._abort();\n\n  return this;\n};\n\n/**\n * Appends an input source (text string, buffer, or stream) to the instance.\n *\n * When the instance has received, processed, and emitted the input, the `entry`\n * event is fired.\n *\n * @fires  Archiver#entry\n * @param  {(Buffer|Stream|String)} source The input source.\n * @param  {EntryData} data See also {@link ZipEntryData} and {@link TarEntryData}.\n * @return {this}\n */\nArchiver.prototype.append = function(source, data) {\n  if (this._state.finalize || this._state.aborted) {\n    this.emit('error', new ArchiverError('QUEUECLOSED'));\n    return this;\n  }\n\n  data = this._normalizeEntryData(data);\n\n  if (typeof data.name !== 'string' || data.name.length === 0) {\n    this.emit('error', new ArchiverError('ENTRYNAMEREQUIRED'));\n    return this;\n  }\n\n  if (data.type === 'directory' && !this._moduleSupports('directory')) {\n    this.emit('error', new ArchiverError('DIRECTORYNOTSUPPORTED', { name: data.name }));\n    return this;\n  }\n\n  source = util.normalizeInputSource(source);\n\n  if (Buffer.isBuffer(source)) {\n    data.sourceType = 'buffer';\n  } else if (util.isStream(source)) {\n    data.sourceType = 'stream';\n  } else {\n    this.emit('error', new ArchiverError('INPUTSTEAMBUFFERREQUIRED', { name: data.name }));\n    return this;\n  }\n\n  this._entriesCount++;\n  this._queue.push({\n    data: data,\n    source: source\n  });\n\n  return this;\n};\n\n/**\n * Appends a directory and its files, recursively, given its dirpath.\n *\n * @param  {String} dirpath The source directory path.\n * @param  {String} destpath The destination path within the archive.\n * @param  {(EntryData|Function)} data See also [ZipEntryData]{@link ZipEntryData} and\n * [TarEntryData]{@link TarEntryData}.\n * @return {this}\n */\nArchiver.prototype.directory = function(dirpath, destpath, data) {\n  if (this._state.finalize || this._state.aborted) {\n    this.emit('error', new ArchiverError('QUEUECLOSED'));\n    return this;\n  }\n\n  if (typeof dirpath !== 'string' || dirpath.length === 0) {\n    this.emit('error', new ArchiverError('DIRECTORYDIRPATHREQUIRED'));\n    return this;\n  }\n\n  this._pending++;\n\n  if (destpath === false) {\n    destpath = '';\n  } else if (typeof destpath !== 'string'){\n    destpath = dirpath;\n  }\n\n  var dataFunction = false;\n  if (typeof data === 'function') {\n    dataFunction = data;\n    data = {};\n  } else if (typeof data !== 'object') {\n    data = {};\n  }\n\n  var globOptions = {\n    stat: true,\n    dot: true\n  };\n\n  function onGlobEnd() {\n    this._pending--;\n    this._maybeFinalize();\n  }\n\n  function onGlobError(err) {\n    this.emit('error', err);\n  }\n\n  function onGlobMatch(match){\n    globber.pause();\n\n    var ignoreMatch = false;\n    var entryData = Object.assign({}, data);\n    entryData.name = match.relative;\n    entryData.prefix = destpath;\n    entryData.stats = match.stat;\n    entryData.callback = globber.resume.bind(globber);\n\n    try {\n      if (dataFunction) {\n        entryData = dataFunction(entryData);\n\n        if (entryData === false) {\n          ignoreMatch = true;\n        } else if (typeof entryData !== 'object') {\n          throw new ArchiverError('DIRECTORYFUNCTIONINVALIDDATA', { dirpath: dirpath });\n        }\n      }\n    } catch(e) {\n      this.emit('error', e);\n      return;\n    }\n\n    if (ignoreMatch) {\n      globber.resume();\n      return;\n    }\n\n    this._append(match.absolute, entryData);\n  }\n\n  var globber = glob(dirpath, globOptions);\n  globber.on('error', onGlobError.bind(this));\n  globber.on('match', onGlobMatch.bind(this));\n  globber.on('end', onGlobEnd.bind(this));\n\n  return this;\n};\n\n/**\n * Appends a file given its filepath using a\n * [lazystream]{@link https://github.com/jpommerening/node-lazystream} wrapper to\n * prevent issues with open file limits.\n *\n * When the instance has received, processed, and emitted the file, the `entry`\n * event is fired.\n *\n * @param  {String} filepath The source filepath.\n * @param  {EntryData} data See also [ZipEntryData]{@link ZipEntryData} and\n * [TarEntryData]{@link TarEntryData}.\n * @return {this}\n */\nArchiver.prototype.file = function(filepath, data) {\n  if (this._state.finalize || this._state.aborted) {\n    this.emit('error', new ArchiverError('QUEUECLOSED'));\n    return this;\n  }\n\n  if (typeof filepath !== 'string' || filepath.length === 0) {\n    this.emit('error', new ArchiverError('FILEFILEPATHREQUIRED'));\n    return this;\n  }\n\n  this._append(filepath, data);\n\n  return this;\n};\n\n/**\n * Appends multiple files that match a glob pattern.\n *\n * @param  {String} pattern The [glob pattern]{@link https://github.com/isaacs/minimatch} to match.\n * @param  {Object} options See [node-readdir-glob]{@link https://github.com/yqnn/node-readdir-glob#options}.\n * @param  {EntryData} data See also [ZipEntryData]{@link ZipEntryData} and\n * [TarEntryData]{@link TarEntryData}.\n * @return {this}\n */\nArchiver.prototype.glob = function(pattern, options, data) {\n  this._pending++;\n\n  options = util.defaults(options, {\n    stat: true,\n    pattern: pattern\n  });\n\n  function onGlobEnd() {\n    this._pending--;\n    this._maybeFinalize();\n  }\n\n  function onGlobError(err) {\n    this.emit('error', err);\n  }\n\n  function onGlobMatch(match){\n    globber.pause();\n    var entryData = Object.assign({}, data);\n    entryData.callback = globber.resume.bind(globber);\n    entryData.stats = match.stat;\n    entryData.name = match.relative;\n\n    this._append(match.absolute, entryData);\n  }\n\n  var globber = glob(options.cwd || '.', options);\n  globber.on('error', onGlobError.bind(this));\n  globber.on('match', onGlobMatch.bind(this));\n  globber.on('end', onGlobEnd.bind(this));\n\n  return this;\n};\n\n/**\n * Finalizes the instance and prevents further appending to the archive\n * structure (queue will continue til drained).\n *\n * The `end`, `close` or `finish` events on the destination stream may fire\n * right after calling this method so you should set listeners beforehand to\n * properly detect stream completion.\n *\n * @return {Promise}\n */\nArchiver.prototype.finalize = function() {\n  if (this._state.aborted) {\n    var abortedError = new ArchiverError('ABORTED');\n    this.emit('error', abortedError);\n    return Promise.reject(abortedError);\n  }\n\n  if (this._state.finalize) {\n    var finalizingError = new ArchiverError('FINALIZING');\n    this.emit('error', finalizingError);\n    return Promise.reject(finalizingError);\n  }\n\n  this._state.finalize = true;\n\n  if (this._pending === 0 && this._queue.idle() && this._statQueue.idle()) {\n    this._finalize();\n  }\n\n  var self = this;\n\n  return new Promise(function(resolve, reject) {\n    var errored;\n\n    self._module.on('end', function() {\n      if (!errored) {\n        resolve();\n      }\n    })\n\n    self._module.on('error', function(err) {\n      errored = true;\n      reject(err);\n    })\n  })\n};\n\n/**\n * Sets the module format name used for archiving.\n *\n * @param {String} format The name of the format.\n * @return {this}\n */\nArchiver.prototype.setFormat = function(format) {\n  if (this._format) {\n    this.emit('error', new ArchiverError('FORMATSET'));\n    return this;\n  }\n\n  this._format = format;\n\n  return this;\n};\n\n/**\n * Sets the module used for archiving.\n *\n * @param {Function} module The function for archiver to interact with.\n * @return {this}\n */\nArchiver.prototype.setModule = function(module) {\n  if (this._state.aborted) {\n    this.emit('error', new ArchiverError('ABORTED'));\n    return this;\n  }\n\n  if (this._state.module) {\n    this.emit('error', new ArchiverError('MODULESET'));\n    return this;\n  }\n\n  this._module = module;\n  this._modulePipe();\n\n  return this;\n};\n\n/**\n * Appends a symlink to the instance.\n *\n * This does NOT interact with filesystem and is used for programmatically creating symlinks.\n *\n * @param  {String} filepath The symlink path (within archive).\n * @param  {String} target The target path (within archive).\n * @param  {Number} mode Sets the entry permissions.\n * @return {this}\n */\nArchiver.prototype.symlink = function(filepath, target, mode) {\n  if (this._state.finalize || this._state.aborted) {\n    this.emit('error', new ArchiverError('QUEUECLOSED'));\n    return this;\n  }\n\n  if (typeof filepath !== 'string' || filepath.length === 0) {\n    this.emit('error', new ArchiverError('SYMLINKFILEPATHREQUIRED'));\n    return this;\n  }\n\n  if (typeof target !== 'string' || target.length === 0) {\n    this.emit('error', new ArchiverError('SYMLINKTARGETREQUIRED', { filepath: filepath }));\n    return this;\n  }\n\n  if (!this._moduleSupports('symlink')) {\n    this.emit('error', new ArchiverError('SYMLINKNOTSUPPORTED', { filepath: filepath }));\n    return this;\n  }\n\n  var data = {};\n  data.type = 'symlink';\n  data.name = filepath.replace(/\\\\/g, '/');\n  data.linkname = target.replace(/\\\\/g, '/');\n  data.sourceType = 'buffer';\n\n  if (typeof mode === \"number\") {\n    data.mode = mode;\n  }\n\n  this._entriesCount++;\n  this._queue.push({\n    data: data,\n    source: Buffer.concat([])\n  });\n\n  return this;\n};\n\n/**\n * Returns the current length (in bytes) that has been emitted.\n *\n * @return {Number}\n */\nArchiver.prototype.pointer = function() {\n  return this._pointer;\n};\n\n/**\n * Middleware-like helper that has yet to be fully implemented.\n *\n * @private\n * @param  {Function} plugin\n * @return {this}\n */\nArchiver.prototype.use = function(plugin) {\n  this._streams.push(plugin);\n  return this;\n};\n\nmodule.exports = Archiver;\n\n/**\n * @typedef {Object} CoreOptions\n * @global\n * @property {Number} [statConcurrency=4] Sets the number of workers used to\n * process the internal fs stat queue.\n */\n\n/**\n * @typedef {Object} TransformOptions\n * @property {Boolean} [allowHalfOpen=true] If set to false, then the stream\n * will automatically end the readable side when the writable side ends and vice\n * versa.\n * @property {Boolean} [readableObjectMode=false] Sets objectMode for readable\n * side of the stream. Has no effect if objectMode is true.\n * @property {Boolean} [writableObjectMode=false] Sets objectMode for writable\n * side of the stream. Has no effect if objectMode is true.\n * @property {Boolean} [decodeStrings=true] Whether or not to decode strings\n * into Buffers before passing them to _write(). `Writable`\n * @property {String} [encoding=NULL] If specified, then buffers will be decoded\n * to strings using the specified encoding. `Readable`\n * @property {Number} [highWaterMark=16kb] The maximum number of bytes to store\n * in the internal buffer before ceasing to read from the underlying resource.\n * `Readable` `Writable`\n * @property {Boolean} [objectMode=false] Whether this stream should behave as a\n * stream of objects. Meaning that stream.read(n) returns a single value instead\n * of a Buffer of size n. `Readable` `Writable`\n */\n\n/**\n * @typedef {Object} EntryData\n * @property {String} name Sets the entry name including internal path.\n * @property {(String|Date)} [date=NOW()] Sets the entry date.\n * @property {Number} [mode=D:0755/F:0644] Sets the entry permissions.\n * @property {String} [prefix] Sets a path prefix for the entry name. Useful\n * when working with methods like `directory` or `glob`.\n * @property {fs.Stats} [stats] Sets the fs stat data for this entry allowing\n * for reduction of fs stat calls when stat data is already known.\n */\n\n/**\n * @typedef {Object} ErrorData\n * @property {String} message The message of the error.\n * @property {String} code The error code assigned to this error.\n * @property {String} data Additional data provided for reporting or debugging (where available).\n */\n\n/**\n * @typedef {Object} ProgressData\n * @property {Object} entries\n * @property {Number} entries.total Number of entries that have been appended.\n * @property {Number} entries.processed Number of entries that have been processed.\n * @property {Object} fs\n * @property {Number} fs.totalBytes Number of bytes that have been appended. Calculated asynchronously and might not be accurate: it growth while entries are added. (based on fs.Stats)\n * @property {Number} fs.processedBytes Number of bytes that have been processed. (based on fs.Stats)\n */\n","/**\n * node-compress-commons\n *\n * Copyright (c) 2014 Chris Talkington, contributors.\n * Licensed under the MIT license.\n * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT\n */\nvar ArchiveEntry = module.exports = function() {};\n\nArchiveEntry.prototype.getName = function() {};\n\nArchiveEntry.prototype.getSize = function() {};\n\nArchiveEntry.prototype.getLastModifiedDate = function() {};\n\nArchiveEntry.prototype.isDirectory = function() {};","/**\n * node-compress-commons\n *\n * Copyright (c) 2014 Chris Talkington, contributors.\n * Licensed under the MIT license.\n * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT\n */\nvar util = module.exports = {};\n\nutil.dateToDos = function(d, forceLocalTime) {\n  forceLocalTime = forceLocalTime || false;\n\n  var year = forceLocalTime ? d.getFullYear() : d.getUTCFullYear();\n\n  if (year < 1980) {\n    return 2162688; // 1980-1-1 00:00:00\n  } else if (year >= 2044) {\n    return 2141175677; // 2043-12-31 23:59:58\n  }\n\n  var val = {\n    year: year,\n    month: forceLocalTime ? d.getMonth() : d.getUTCMonth(),\n    date: forceLocalTime ? d.getDate() : d.getUTCDate(),\n    hours: forceLocalTime ? d.getHours() : d.getUTCHours(),\n    minutes: forceLocalTime ? d.getMinutes() : d.getUTCMinutes(),\n    seconds: forceLocalTime ? d.getSeconds() : d.getUTCSeconds()\n  };\n\n  return ((val.year - 1980) << 25) | ((val.month + 1) << 21) | (val.date << 16) |\n    (val.hours << 11) | (val.minutes << 5) | (val.seconds / 2);\n};\n\nutil.dosToDate = function(dos) {\n  return new Date(((dos >> 25) & 0x7f) + 1980, ((dos >> 21) & 0x0f) - 1, (dos >> 16) & 0x1f, (dos >> 11) & 0x1f, (dos >> 5) & 0x3f, (dos & 0x1f) << 1);\n};\n\nutil.fromDosTime = function(buf) {\n  return util.dosToDate(buf.readUInt32LE(0));\n};\n\nutil.getEightBytes = function(v) {\n  var buf = Buffer.alloc(8);\n  buf.writeUInt32LE(v % 0x0100000000, 0);\n  buf.writeUInt32LE((v / 0x0100000000) | 0, 4);\n\n  return buf;\n};\n\nutil.getShortBytes = function(v) {\n  var buf = Buffer.alloc(2);\n  buf.writeUInt16LE((v & 0xFFFF) >>> 0, 0);\n\n  return buf;\n};\n\nutil.getShortBytesValue = function(buf, offset) {\n  return buf.readUInt16LE(offset);\n};\n\nutil.getLongBytes = function(v) {\n  var buf = Buffer.alloc(4);\n  buf.writeUInt32LE((v & 0xFFFFFFFF) >>> 0, 0);\n\n  return buf;\n};\n\nutil.getLongBytesValue = function(buf, offset) {\n  return buf.readUInt32LE(offset);\n};\n\nutil.toDosTime = function(d) {\n  return util.getLongBytes(util.dateToDos(d));\n};","/**\n * node-compress-commons\n *\n * Copyright (c) 2014 Chris Talkington, contributors.\n * Licensed under the MIT license.\n * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT\n */\nvar zipUtil = require('./util');\n\nvar DATA_DESCRIPTOR_FLAG = 1 << 3;\nvar ENCRYPTION_FLAG = 1 << 0;\nvar NUMBER_OF_SHANNON_FANO_TREES_FLAG = 1 << 2;\nvar SLIDING_DICTIONARY_SIZE_FLAG = 1 << 1;\nvar STRONG_ENCRYPTION_FLAG = 1 << 6;\nvar UFT8_NAMES_FLAG = 1 << 11;\n\nvar GeneralPurposeBit = module.exports = function() {\n  if (!(this instanceof GeneralPurposeBit)) {\n    return new GeneralPurposeBit();\n  }\n\n  this.descriptor = false;\n  this.encryption = false;\n  this.utf8 = false;\n  this.numberOfShannonFanoTrees = 0;\n  this.strongEncryption = false;\n  this.slidingDictionarySize = 0;\n\n  return this;\n};\n\nGeneralPurposeBit.prototype.encode = function() {\n  return zipUtil.getShortBytes(\n    (this.descriptor ? DATA_DESCRIPTOR_FLAG : 0) |\n    (this.utf8 ? UFT8_NAMES_FLAG : 0) |\n    (this.encryption ? ENCRYPTION_FLAG : 0) |\n    (this.strongEncryption ? STRONG_ENCRYPTION_FLAG : 0)\n  );\n};\n\nGeneralPurposeBit.prototype.parse = function(buf, offset) {\n  var flag = zipUtil.getShortBytesValue(buf, offset);\n  var gbp = new GeneralPurposeBit();\n\n  gbp.useDataDescriptor((flag & DATA_DESCRIPTOR_FLAG) !== 0);\n  gbp.useUTF8ForNames((flag & UFT8_NAMES_FLAG) !== 0);\n  gbp.useStrongEncryption((flag & STRONG_ENCRYPTION_FLAG) !== 0);\n  gbp.useEncryption((flag & ENCRYPTION_FLAG) !== 0);\n  gbp.setSlidingDictionarySize((flag & SLIDING_DICTIONARY_SIZE_FLAG) !== 0 ? 8192 : 4096);\n  gbp.setNumberOfShannonFanoTrees((flag & NUMBER_OF_SHANNON_FANO_TREES_FLAG) !== 0 ? 3 : 2);\n\n  return gbp;\n};\n\nGeneralPurposeBit.prototype.setNumberOfShannonFanoTrees = function(n) {\n  this.numberOfShannonFanoTrees = n;\n};\n\nGeneralPurposeBit.prototype.getNumberOfShannonFanoTrees = function() {\n  return this.numberOfShannonFanoTrees;\n};\n\nGeneralPurposeBit.prototype.setSlidingDictionarySize = function(n) {\n  this.slidingDictionarySize = n;\n};\n\nGeneralPurposeBit.prototype.getSlidingDictionarySize = function() {\n  return this.slidingDictionarySize;\n};\n\nGeneralPurposeBit.prototype.useDataDescriptor = function(b) {\n  this.descriptor = b;\n};\n\nGeneralPurposeBit.prototype.usesDataDescriptor = function() {\n  return this.descriptor;\n};\n\nGeneralPurposeBit.prototype.useEncryption = function(b) {\n  this.encryption = b;\n};\n\nGeneralPurposeBit.prototype.usesEncryption = function() {\n  return this.encryption;\n};\n\nGeneralPurposeBit.prototype.useStrongEncryption = function(b) {\n  this.strongEncryption = b;\n};\n\nGeneralPurposeBit.prototype.usesStrongEncryption = function() {\n  return this.strongEncryption;\n};\n\nGeneralPurposeBit.prototype.useUTF8ForNames = function(b) {\n  this.utf8 = b;\n};\n\nGeneralPurposeBit.prototype.usesUTF8ForNames = function() {\n  return this.utf8;\n};","/**\n * node-compress-commons\n *\n * Copyright (c) 2014 Chris Talkington, contributors.\n * Licensed under the MIT license.\n * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT\n */\nmodule.exports = {\n    /**\n     * Bits used for permissions (and sticky bit)\n     */\n    PERM_MASK: 4095, // 07777\n\n    /**\n     * Bits used to indicate the filesystem object type.\n     */\n    FILE_TYPE_FLAG: 61440, // 0170000\n\n    /**\n     * Indicates symbolic links.\n     */\n    LINK_FLAG: 40960, // 0120000\n\n    /**\n     * Indicates plain files.\n     */\n    FILE_FLAG: 32768, // 0100000\n\n    /**\n     * Indicates directories.\n     */\n    DIR_FLAG: 16384, // 040000\n\n    // ----------------------------------------------------------\n    // somewhat arbitrary choices that are quite common for shared\n    // installations\n    // -----------------------------------------------------------\n\n    /**\n     * Default permissions for symbolic links.\n     */\n    DEFAULT_LINK_PERM: 511, // 0777\n\n    /**\n     * Default permissions for directories.\n     */\n    DEFAULT_DIR_PERM: 493, // 0755\n\n    /**\n     * Default permissions for plain files.\n     */\n    DEFAULT_FILE_PERM: 420 // 0644\n};","/**\n * node-compress-commons\n *\n * Copyright (c) 2014 Chris Talkington, contributors.\n * Licensed under the MIT license.\n * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT\n */\nmodule.exports = {\n  WORD: 4,\n  DWORD: 8,\n  EMPTY: Buffer.alloc(0),\n\n  SHORT: 2,\n  SHORT_MASK: 0xffff,\n  SHORT_SHIFT: 16,\n  SHORT_ZERO: Buffer.from(Array(2)),\n  LONG: 4,\n  LONG_ZERO: Buffer.from(Array(4)),\n\n  MIN_VERSION_INITIAL: 10,\n  MIN_VERSION_DATA_DESCRIPTOR: 20,\n  MIN_VERSION_ZIP64: 45,\n  VERSION_MADEBY: 45,\n\n  METHOD_STORED: 0,\n  METHOD_DEFLATED: 8,\n\n  PLATFORM_UNIX: 3,\n  PLATFORM_FAT: 0,\n\n  SIG_LFH: 0x04034b50,\n  SIG_DD: 0x08074b50,\n  SIG_CFH: 0x02014b50,\n  SIG_EOCD: 0x06054b50,\n  SIG_ZIP64_EOCD: 0x06064B50,\n  SIG_ZIP64_EOCD_LOC: 0x07064B50,\n\n  ZIP64_MAGIC_SHORT: 0xffff,\n  ZIP64_MAGIC: 0xffffffff,\n  ZIP64_EXTRA_ID: 0x0001,\n\n  ZLIB_NO_COMPRESSION: 0,\n  ZLIB_BEST_SPEED: 1,\n  ZLIB_BEST_COMPRESSION: 9,\n  ZLIB_DEFAULT_COMPRESSION: -1,\n\n  MODE_MASK: 0xFFF,\n  DEFAULT_FILE_MODE: 33188, // 010644 = -rw-r--r-- = S_IFREG | S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH\n  DEFAULT_DIR_MODE: 16877,  // 040755 = drwxr-xr-x = S_IFDIR | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH\n\n  EXT_FILE_ATTR_DIR: 1106051088,  // 010173200020 = drwxr-xr-x = (((S_IFDIR | 0755) << 16) | S_DOS_D)\n  EXT_FILE_ATTR_FILE: 2175008800, // 020151000040 = -rw-r--r-- = (((S_IFREG | 0644) << 16) | S_DOS_A) >>> 0\n\n  // Unix file types\n  S_IFMT: 61440,   // 0170000 type of file mask\n  S_IFIFO: 4096,   // 010000 named pipe (fifo)\n  S_IFCHR: 8192,   // 020000 character special\n  S_IFDIR: 16384,  // 040000 directory\n  S_IFBLK: 24576,  // 060000 block special\n  S_IFREG: 32768,  // 0100000 regular\n  S_IFLNK: 40960,  // 0120000 symbolic link\n  S_IFSOCK: 49152, // 0140000 socket\n\n  // DOS file type flags\n  S_DOS_A: 32, // 040 Archive\n  S_DOS_D: 16, // 020 Directory\n  S_DOS_V: 8,  // 010 Volume\n  S_DOS_S: 4,  // 04 System\n  S_DOS_H: 2,  // 02 Hidden\n  S_DOS_R: 1   // 01 Read Only\n};\n","/**\n * node-compress-commons\n *\n * Copyright (c) 2014 Chris Talkington, contributors.\n * Licensed under the MIT license.\n * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT\n */\nvar inherits = require('util').inherits;\nvar normalizePath = require('normalize-path');\n\nvar ArchiveEntry = require('../archive-entry');\nvar GeneralPurposeBit = require('./general-purpose-bit');\nvar UnixStat = require('./unix-stat');\n\nvar constants = require('./constants');\nvar zipUtil = require('./util');\n\nvar ZipArchiveEntry = module.exports = function(name) {\n  if (!(this instanceof ZipArchiveEntry)) {\n    return new ZipArchiveEntry(name);\n  }\n\n  ArchiveEntry.call(this);\n\n  this.platform = constants.PLATFORM_FAT;\n  this.method = -1;\n\n  this.name = null;\n  this.size = 0;\n  this.csize = 0;\n  this.gpb = new GeneralPurposeBit();\n  this.crc = 0;\n  this.time = -1;\n\n  this.minver = constants.MIN_VERSION_INITIAL;\n  this.mode = -1;\n  this.extra = null;\n  this.exattr = 0;\n  this.inattr = 0;\n  this.comment = null;\n\n  if (name) {\n    this.setName(name);\n  }\n};\n\ninherits(ZipArchiveEntry, ArchiveEntry);\n\n/**\n * Returns the extra fields related to the entry.\n *\n * @returns {Buffer}\n */\nZipArchiveEntry.prototype.getCentralDirectoryExtra = function() {\n  return this.getExtra();\n};\n\n/**\n * Returns the comment set for the entry.\n *\n * @returns {string}\n */\nZipArchiveEntry.prototype.getComment = function() {\n  return this.comment !== null ? this.comment : '';\n};\n\n/**\n * Returns the compressed size of the entry.\n *\n * @returns {number}\n */\nZipArchiveEntry.prototype.getCompressedSize = function() {\n  return this.csize;\n};\n\n/**\n * Returns the CRC32 digest for the entry.\n *\n * @returns {number}\n */\nZipArchiveEntry.prototype.getCrc = function() {\n  return this.crc;\n};\n\n/**\n * Returns the external file attributes for the entry.\n *\n * @returns {number}\n */\nZipArchiveEntry.prototype.getExternalAttributes = function() {\n  return this.exattr;\n};\n\n/**\n * Returns the extra fields related to the entry.\n *\n * @returns {Buffer}\n */\nZipArchiveEntry.prototype.getExtra = function() {\n  return this.extra !== null ? this.extra : constants.EMPTY;\n};\n\n/**\n * Returns the general purpose bits related to the entry.\n *\n * @returns {GeneralPurposeBit}\n */\nZipArchiveEntry.prototype.getGeneralPurposeBit = function() {\n  return this.gpb;\n};\n\n/**\n * Returns the internal file attributes for the entry.\n *\n * @returns {number}\n */\nZipArchiveEntry.prototype.getInternalAttributes = function() {\n  return this.inattr;\n};\n\n/**\n * Returns the last modified date of the entry.\n *\n * @returns {number}\n */\nZipArchiveEntry.prototype.getLastModifiedDate = function() {\n  return this.getTime();\n};\n\n/**\n * Returns the extra fields related to the entry.\n *\n * @returns {Buffer}\n */\nZipArchiveEntry.prototype.getLocalFileDataExtra = function() {\n  return this.getExtra();\n};\n\n/**\n * Returns the compression method used on the entry.\n *\n * @returns {number}\n */\nZipArchiveEntry.prototype.getMethod = function() {\n  return this.method;\n};\n\n/**\n * Returns the filename of the entry.\n *\n * @returns {string}\n */\nZipArchiveEntry.prototype.getName = function() {\n  return this.name;\n};\n\n/**\n * Returns the platform on which the entry was made.\n *\n * @returns {number}\n */\nZipArchiveEntry.prototype.getPlatform = function() {\n  return this.platform;\n};\n\n/**\n * Returns the size of the entry.\n *\n * @returns {number}\n */\nZipArchiveEntry.prototype.getSize = function() {\n  return this.size;\n};\n\n/**\n * Returns a date object representing the last modified date of the entry.\n *\n * @returns {number|Date}\n */\nZipArchiveEntry.prototype.getTime = function() {\n  return this.time !== -1 ? zipUtil.dosToDate(this.time) : -1;\n};\n\n/**\n * Returns the DOS timestamp for the entry.\n *\n * @returns {number}\n */\nZipArchiveEntry.prototype.getTimeDos = function() {\n  return this.time !== -1 ? this.time : 0;\n};\n\n/**\n * Returns the UNIX file permissions for the entry.\n *\n * @returns {number}\n */\nZipArchiveEntry.prototype.getUnixMode = function() {\n  return this.platform !== constants.PLATFORM_UNIX ? 0 : ((this.getExternalAttributes() >> constants.SHORT_SHIFT) & constants.SHORT_MASK);\n};\n\n/**\n * Returns the version of ZIP needed to extract the entry.\n *\n * @returns {number}\n */\nZipArchiveEntry.prototype.getVersionNeededToExtract = function() {\n  return this.minver;\n};\n\n/**\n * Sets the comment of the entry.\n *\n * @param comment\n */\nZipArchiveEntry.prototype.setComment = function(comment) {\n  if (Buffer.byteLength(comment) !== comment.length) {\n    this.getGeneralPurposeBit().useUTF8ForNames(true);\n  }\n\n  this.comment = comment;\n};\n\n/**\n * Sets the compressed size of the entry.\n *\n * @param size\n */\nZipArchiveEntry.prototype.setCompressedSize = function(size) {\n  if (size < 0) {\n    throw new Error('invalid entry compressed size');\n  }\n\n  this.csize = size;\n};\n\n/**\n * Sets the checksum of the entry.\n *\n * @param crc\n */\nZipArchiveEntry.prototype.setCrc = function(crc) {\n  if (crc < 0) {\n    throw new Error('invalid entry crc32');\n  }\n\n  this.crc = crc;\n};\n\n/**\n * Sets the external file attributes of the entry.\n *\n * @param attr\n */\nZipArchiveEntry.prototype.setExternalAttributes = function(attr) {\n  this.exattr = attr >>> 0;\n};\n\n/**\n * Sets the extra fields related to the entry.\n *\n * @param extra\n */\nZipArchiveEntry.prototype.setExtra = function(extra) {\n  this.extra = extra;\n};\n\n/**\n * Sets the general purpose bits related to the entry.\n *\n * @param gpb\n */\nZipArchiveEntry.prototype.setGeneralPurposeBit = function(gpb) {\n  if (!(gpb instanceof GeneralPurposeBit)) {\n    throw new Error('invalid entry GeneralPurposeBit');\n  }\n\n  this.gpb = gpb;\n};\n\n/**\n * Sets the internal file attributes of the entry.\n *\n * @param attr\n */\nZipArchiveEntry.prototype.setInternalAttributes = function(attr) {\n  this.inattr = attr;\n};\n\n/**\n * Sets the compression method of the entry.\n *\n * @param method\n */\nZipArchiveEntry.prototype.setMethod = function(method) {\n  if (method < 0) {\n    throw new Error('invalid entry compression method');\n  }\n\n  this.method = method;\n};\n\n/**\n * Sets the name of the entry.\n *\n * @param name\n * @param prependSlash\n */\nZipArchiveEntry.prototype.setName = function(name, prependSlash = false) {\n  name = normalizePath(name, false)\n    .replace(/^\\w+:/, '')\n    .replace(/^(\\.\\.\\/|\\/)+/, '');\n\n  if (prependSlash) {\n    name = `/${name}`;\n  }\n\n  if (Buffer.byteLength(name) !== name.length) {\n    this.getGeneralPurposeBit().useUTF8ForNames(true);\n  }\n\n  this.name = name;\n};\n\n/**\n * Sets the platform on which the entry was made.\n *\n * @param platform\n */\nZipArchiveEntry.prototype.setPlatform = function(platform) {\n  this.platform = platform;\n};\n\n/**\n * Sets the size of the entry.\n *\n * @param size\n */\nZipArchiveEntry.prototype.setSize = function(size) {\n  if (size < 0) {\n    throw new Error('invalid entry size');\n  }\n\n  this.size = size;\n};\n\n/**\n * Sets the time of the entry.\n *\n * @param time\n * @param forceLocalTime\n */\nZipArchiveEntry.prototype.setTime = function(time, forceLocalTime) {\n  if (!(time instanceof Date)) {\n    throw new Error('invalid entry time');\n  }\n\n  this.time = zipUtil.dateToDos(time, forceLocalTime);\n};\n\n/**\n * Sets the UNIX file permissions for the entry.\n *\n * @param mode\n */\nZipArchiveEntry.prototype.setUnixMode = function(mode) {\n  mode |= this.isDirectory() ? constants.S_IFDIR : constants.S_IFREG;\n\n  var extattr = 0;\n  extattr |= (mode << constants.SHORT_SHIFT) | (this.isDirectory() ? constants.S_DOS_D : constants.S_DOS_A);\n\n  this.setExternalAttributes(extattr);\n  this.mode = mode & constants.MODE_MASK;\n  this.platform = constants.PLATFORM_UNIX;\n};\n\n/**\n * Sets the version of ZIP needed to extract this entry.\n *\n * @param minver\n */\nZipArchiveEntry.prototype.setVersionNeededToExtract = function(minver) {\n  this.minver = minver;\n};\n\n/**\n * Returns true if this entry represents a directory.\n *\n * @returns {boolean}\n */\nZipArchiveEntry.prototype.isDirectory = function() {\n  return this.getName().slice(-1) === '/';\n};\n\n/**\n * Returns true if this entry represents a unix symlink,\n * in which case the entry's content contains the target path\n * for the symlink.\n *\n * @returns {boolean}\n */\nZipArchiveEntry.prototype.isUnixSymlink = function() {\n  return (this.getUnixMode() & UnixStat.FILE_TYPE_FLAG) === UnixStat.LINK_FLAG;\n};\n\n/**\n * Returns true if this entry is using the ZIP64 extension of ZIP.\n *\n * @returns {boolean}\n */\nZipArchiveEntry.prototype.isZip64 = function() {\n  return this.csize > constants.ZIP64_MAGIC || this.size > constants.ZIP64_MAGIC;\n};\n","'use strict'\n\n/*\n  This file is a reduced and adapted version of the main lib/internal/per_context/primordials.js file defined at\n\n  https://github.com/nodejs/node/blob/main/lib/internal/per_context/primordials.js\n\n  Don't try to replace with the original file and keep it up to date with the upstream file.\n*/\n\n// This is a simplified version of AggregateError\nclass AggregateError extends Error {\n  constructor(errors) {\n    if (!Array.isArray(errors)) {\n      throw new TypeError(`Expected input to be an Array, got ${typeof errors}`)\n    }\n    let message = ''\n    for (let i = 0; i < errors.length; i++) {\n      message += `    ${errors[i].stack}\\n`\n    }\n    super(message)\n    this.name = 'AggregateError'\n    this.errors = errors\n  }\n}\nmodule.exports = {\n  AggregateError,\n  ArrayIsArray(self) {\n    return Array.isArray(self)\n  },\n  ArrayPrototypeIncludes(self, el) {\n    return self.includes(el)\n  },\n  ArrayPrototypeIndexOf(self, el) {\n    return self.indexOf(el)\n  },\n  ArrayPrototypeJoin(self, sep) {\n    return self.join(sep)\n  },\n  ArrayPrototypeMap(self, fn) {\n    return self.map(fn)\n  },\n  ArrayPrototypePop(self, el) {\n    return self.pop(el)\n  },\n  ArrayPrototypePush(self, el) {\n    return self.push(el)\n  },\n  ArrayPrototypeSlice(self, start, end) {\n    return self.slice(start, end)\n  },\n  Error,\n  FunctionPrototypeCall(fn, thisArgs, ...args) {\n    return fn.call(thisArgs, ...args)\n  },\n  FunctionPrototypeSymbolHasInstance(self, instance) {\n    return Function.prototype[Symbol.hasInstance].call(self, instance)\n  },\n  MathFloor: Math.floor,\n  Number,\n  NumberIsInteger: Number.isInteger,\n  NumberIsNaN: Number.isNaN,\n  NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER,\n  NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER,\n  NumberParseInt: Number.parseInt,\n  ObjectDefineProperties(self, props) {\n    return Object.defineProperties(self, props)\n  },\n  ObjectDefineProperty(self, name, prop) {\n    return Object.defineProperty(self, name, prop)\n  },\n  ObjectGetOwnPropertyDescriptor(self, name) {\n    return Object.getOwnPropertyDescriptor(self, name)\n  },\n  ObjectKeys(obj) {\n    return Object.keys(obj)\n  },\n  ObjectSetPrototypeOf(target, proto) {\n    return Object.setPrototypeOf(target, proto)\n  },\n  Promise,\n  PromisePrototypeCatch(self, fn) {\n    return self.catch(fn)\n  },\n  PromisePrototypeThen(self, thenFn, catchFn) {\n    return self.then(thenFn, catchFn)\n  },\n  PromiseReject(err) {\n    return Promise.reject(err)\n  },\n  PromiseResolve(val) {\n    return Promise.resolve(val)\n  },\n  ReflectApply: Reflect.apply,\n  RegExpPrototypeTest(self, value) {\n    return self.test(value)\n  },\n  SafeSet: Set,\n  String,\n  StringPrototypeSlice(self, start, end) {\n    return self.slice(start, end)\n  },\n  StringPrototypeToLowerCase(self) {\n    return self.toLowerCase()\n  },\n  StringPrototypeToUpperCase(self) {\n    return self.toUpperCase()\n  },\n  StringPrototypeTrim(self) {\n    return self.trim()\n  },\n  Symbol,\n  SymbolFor: Symbol.for,\n  SymbolAsyncIterator: Symbol.asyncIterator,\n  SymbolHasInstance: Symbol.hasInstance,\n  SymbolIterator: Symbol.iterator,\n  SymbolDispose: Symbol.dispose || Symbol('Symbol.dispose'),\n  SymbolAsyncDispose: Symbol.asyncDispose || Symbol('Symbol.asyncDispose'),\n  TypedArrayPrototypeSet(self, buf, len) {\n    return self.set(buf, len)\n  },\n  Boolean,\n  Uint8Array\n}\n","'use strict'\n\n/*\n  This file is a reduced and adapted version of the main lib/internal/util/inspect.js file defined at\n\n  https://github.com/nodejs/node/blob/main/lib/internal/util/inspect.js\n\n  Don't try to replace with the original file and keep it up to date with the upstream file.\n*/\nmodule.exports = {\n  format(format, ...args) {\n    // Simplified version of https://nodejs.org/api/util.html#utilformatformat-args\n    return format.replace(/%([sdifj])/g, function (...[_unused, type]) {\n      const replacement = args.shift()\n      if (type === 'f') {\n        return replacement.toFixed(6)\n      } else if (type === 'j') {\n        return JSON.stringify(replacement)\n      } else if (type === 's' && typeof replacement === 'object') {\n        const ctor = replacement.constructor !== Object ? replacement.constructor.name : ''\n        return `${ctor} {}`.trim()\n      } else {\n        return replacement.toString()\n      }\n    })\n  },\n  inspect(value) {\n    // Vastly simplified version of https://nodejs.org/api/util.html#utilinspectobject-options\n    switch (typeof value) {\n      case 'string':\n        if (value.includes(\"'\")) {\n          if (!value.includes('\"')) {\n            return `\"${value}\"`\n          } else if (!value.includes('`') && !value.includes('${')) {\n            return `\\`${value}\\``\n          }\n        }\n        return `'${value}'`\n      case 'number':\n        if (isNaN(value)) {\n          return 'NaN'\n        } else if (Object.is(value, -0)) {\n          return String(value)\n        }\n        return value\n      case 'bigint':\n        return `${String(value)}n`\n      case 'boolean':\n      case 'undefined':\n        return String(value)\n      case 'object':\n        return '{}'\n    }\n  }\n}\n","'use strict'\n\nconst { format, inspect } = require('./util/inspect')\nconst { AggregateError: CustomAggregateError } = require('./primordials')\n\n/*\n  This file is a reduced and adapted version of the main lib/internal/errors.js file defined at\n\n  https://github.com/nodejs/node/blob/main/lib/internal/errors.js\n\n  Don't try to replace with the original file and keep it up to date (starting from E(...) definitions)\n  with the upstream file.\n*/\n\nconst AggregateError = globalThis.AggregateError || CustomAggregateError\nconst kIsNodeError = Symbol('kIsNodeError')\nconst kTypes = [\n  'string',\n  'function',\n  'number',\n  'object',\n  // Accept 'Function' and 'Object' as alternative to the lower cased version.\n  'Function',\n  'Object',\n  'boolean',\n  'bigint',\n  'symbol'\n]\nconst classRegExp = /^([A-Z][a-z0-9]*)+$/\nconst nodeInternalPrefix = '__node_internal_'\nconst codes = {}\nfunction assert(value, message) {\n  if (!value) {\n    throw new codes.ERR_INTERNAL_ASSERTION(message)\n  }\n}\n\n// Only use this for integers! Decimal numbers do not work with this function.\nfunction addNumericalSeparator(val) {\n  let res = ''\n  let i = val.length\n  const start = val[0] === '-' ? 1 : 0\n  for (; i >= start + 4; i -= 3) {\n    res = `_${val.slice(i - 3, i)}${res}`\n  }\n  return `${val.slice(0, i)}${res}`\n}\nfunction getMessage(key, msg, args) {\n  if (typeof msg === 'function') {\n    assert(\n      msg.length <= args.length,\n      // Default options do not count.\n      `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).`\n    )\n    return msg(...args)\n  }\n  const expectedLength = (msg.match(/%[dfijoOs]/g) || []).length\n  assert(\n    expectedLength === args.length,\n    `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).`\n  )\n  if (args.length === 0) {\n    return msg\n  }\n  return format(msg, ...args)\n}\nfunction E(code, message, Base) {\n  if (!Base) {\n    Base = Error\n  }\n  class NodeError extends Base {\n    constructor(...args) {\n      super(getMessage(code, message, args))\n    }\n    toString() {\n      return `${this.name} [${code}]: ${this.message}`\n    }\n  }\n  Object.defineProperties(NodeError.prototype, {\n    name: {\n      value: Base.name,\n      writable: true,\n      enumerable: false,\n      configurable: true\n    },\n    toString: {\n      value() {\n        return `${this.name} [${code}]: ${this.message}`\n      },\n      writable: true,\n      enumerable: false,\n      configurable: true\n    }\n  })\n  NodeError.prototype.code = code\n  NodeError.prototype[kIsNodeError] = true\n  codes[code] = NodeError\n}\nfunction hideStackFrames(fn) {\n  // We rename the functions that will be hidden to cut off the stacktrace\n  // at the outermost one\n  const hidden = nodeInternalPrefix + fn.name\n  Object.defineProperty(fn, 'name', {\n    value: hidden\n  })\n  return fn\n}\nfunction aggregateTwoErrors(innerError, outerError) {\n  if (innerError && outerError && innerError !== outerError) {\n    if (Array.isArray(outerError.errors)) {\n      // If `outerError` is already an `AggregateError`.\n      outerError.errors.push(innerError)\n      return outerError\n    }\n    const err = new AggregateError([outerError, innerError], outerError.message)\n    err.code = outerError.code\n    return err\n  }\n  return innerError || outerError\n}\nclass AbortError extends Error {\n  constructor(message = 'The operation was aborted', options = undefined) {\n    if (options !== undefined && typeof options !== 'object') {\n      throw new codes.ERR_INVALID_ARG_TYPE('options', 'Object', options)\n    }\n    super(message, options)\n    this.code = 'ABORT_ERR'\n    this.name = 'AbortError'\n  }\n}\nE('ERR_ASSERTION', '%s', Error)\nE(\n  'ERR_INVALID_ARG_TYPE',\n  (name, expected, actual) => {\n    assert(typeof name === 'string', \"'name' must be a string\")\n    if (!Array.isArray(expected)) {\n      expected = [expected]\n    }\n    let msg = 'The '\n    if (name.endsWith(' argument')) {\n      // For cases like 'first argument'\n      msg += `${name} `\n    } else {\n      msg += `\"${name}\" ${name.includes('.') ? 'property' : 'argument'} `\n    }\n    msg += 'must be '\n    const types = []\n    const instances = []\n    const other = []\n    for (const value of expected) {\n      assert(typeof value === 'string', 'All expected entries have to be of type string')\n      if (kTypes.includes(value)) {\n        types.push(value.toLowerCase())\n      } else if (classRegExp.test(value)) {\n        instances.push(value)\n      } else {\n        assert(value !== 'object', 'The value \"object\" should be written as \"Object\"')\n        other.push(value)\n      }\n    }\n\n    // Special handle `object` in case other instances are allowed to outline\n    // the differences between each other.\n    if (instances.length > 0) {\n      const pos = types.indexOf('object')\n      if (pos !== -1) {\n        types.splice(types, pos, 1)\n        instances.push('Object')\n      }\n    }\n    if (types.length > 0) {\n      switch (types.length) {\n        case 1:\n          msg += `of type ${types[0]}`\n          break\n        case 2:\n          msg += `one of type ${types[0]} or ${types[1]}`\n          break\n        default: {\n          const last = types.pop()\n          msg += `one of type ${types.join(', ')}, or ${last}`\n        }\n      }\n      if (instances.length > 0 || other.length > 0) {\n        msg += ' or '\n      }\n    }\n    if (instances.length > 0) {\n      switch (instances.length) {\n        case 1:\n          msg += `an instance of ${instances[0]}`\n          break\n        case 2:\n          msg += `an instance of ${instances[0]} or ${instances[1]}`\n          break\n        default: {\n          const last = instances.pop()\n          msg += `an instance of ${instances.join(', ')}, or ${last}`\n        }\n      }\n      if (other.length > 0) {\n        msg += ' or '\n      }\n    }\n    switch (other.length) {\n      case 0:\n        break\n      case 1:\n        if (other[0].toLowerCase() !== other[0]) {\n          msg += 'an '\n        }\n        msg += `${other[0]}`\n        break\n      case 2:\n        msg += `one of ${other[0]} or ${other[1]}`\n        break\n      default: {\n        const last = other.pop()\n        msg += `one of ${other.join(', ')}, or ${last}`\n      }\n    }\n    if (actual == null) {\n      msg += `. Received ${actual}`\n    } else if (typeof actual === 'function' && actual.name) {\n      msg += `. Received function ${actual.name}`\n    } else if (typeof actual === 'object') {\n      var _actual$constructor\n      if (\n        (_actual$constructor = actual.constructor) !== null &&\n        _actual$constructor !== undefined &&\n        _actual$constructor.name\n      ) {\n        msg += `. Received an instance of ${actual.constructor.name}`\n      } else {\n        const inspected = inspect(actual, {\n          depth: -1\n        })\n        msg += `. Received ${inspected}`\n      }\n    } else {\n      let inspected = inspect(actual, {\n        colors: false\n      })\n      if (inspected.length > 25) {\n        inspected = `${inspected.slice(0, 25)}...`\n      }\n      msg += `. Received type ${typeof actual} (${inspected})`\n    }\n    return msg\n  },\n  TypeError\n)\nE(\n  'ERR_INVALID_ARG_VALUE',\n  (name, value, reason = 'is invalid') => {\n    let inspected = inspect(value)\n    if (inspected.length > 128) {\n      inspected = inspected.slice(0, 128) + '...'\n    }\n    const type = name.includes('.') ? 'property' : 'argument'\n    return `The ${type} '${name}' ${reason}. Received ${inspected}`\n  },\n  TypeError\n)\nE(\n  'ERR_INVALID_RETURN_VALUE',\n  (input, name, value) => {\n    var _value$constructor\n    const type =\n      value !== null &&\n      value !== undefined &&\n      (_value$constructor = value.constructor) !== null &&\n      _value$constructor !== undefined &&\n      _value$constructor.name\n        ? `instance of ${value.constructor.name}`\n        : `type ${typeof value}`\n    return `Expected ${input} to be returned from the \"${name}\"` + ` function but got ${type}.`\n  },\n  TypeError\n)\nE(\n  'ERR_MISSING_ARGS',\n  (...args) => {\n    assert(args.length > 0, 'At least one arg needs to be specified')\n    let msg\n    const len = args.length\n    args = (Array.isArray(args) ? args : [args]).map((a) => `\"${a}\"`).join(' or ')\n    switch (len) {\n      case 1:\n        msg += `The ${args[0]} argument`\n        break\n      case 2:\n        msg += `The ${args[0]} and ${args[1]} arguments`\n        break\n      default:\n        {\n          const last = args.pop()\n          msg += `The ${args.join(', ')}, and ${last} arguments`\n        }\n        break\n    }\n    return `${msg} must be specified`\n  },\n  TypeError\n)\nE(\n  'ERR_OUT_OF_RANGE',\n  (str, range, input) => {\n    assert(range, 'Missing \"range\" argument')\n    let received\n    if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n      received = addNumericalSeparator(String(input))\n    } else if (typeof input === 'bigint') {\n      received = String(input)\n      const limit = BigInt(2) ** BigInt(32)\n      if (input > limit || input < -limit) {\n        received = addNumericalSeparator(received)\n      }\n      received += 'n'\n    } else {\n      received = inspect(input)\n    }\n    return `The value of \"${str}\" is out of range. It must be ${range}. Received ${received}`\n  },\n  RangeError\n)\nE('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times', Error)\nE('ERR_METHOD_NOT_IMPLEMENTED', 'The %s method is not implemented', Error)\nE('ERR_STREAM_ALREADY_FINISHED', 'Cannot call %s after a stream was finished', Error)\nE('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable', Error)\nE('ERR_STREAM_DESTROYED', 'Cannot call %s after a stream was destroyed', Error)\nE('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError)\nE('ERR_STREAM_PREMATURE_CLOSE', 'Premature close', Error)\nE('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF', Error)\nE('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event', Error)\nE('ERR_STREAM_WRITE_AFTER_END', 'write after end', Error)\nE('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s', TypeError)\nmodule.exports = {\n  AbortError,\n  aggregateTwoErrors: hideStackFrames(aggregateTwoErrors),\n  hideStackFrames,\n  codes\n}\n","'use strict'\n\nconst bufferModule = require('buffer')\nconst { format, inspect } = require('./util/inspect')\nconst {\n  codes: { ERR_INVALID_ARG_TYPE }\n} = require('./errors')\nconst { kResistStopPropagation, AggregateError, SymbolDispose } = require('./primordials')\nconst AbortSignal = globalThis.AbortSignal || require('abort-controller').AbortSignal\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nconst AsyncFunction = Object.getPrototypeOf(async function () {}).constructor\nconst Blob = globalThis.Blob || bufferModule.Blob\n/* eslint-disable indent */\nconst isBlob =\n  typeof Blob !== 'undefined'\n    ? function isBlob(b) {\n        // eslint-disable-next-line indent\n        return b instanceof Blob\n      }\n    : function isBlob(b) {\n        return false\n      }\n/* eslint-enable indent */\n\nconst validateAbortSignal = (signal, name) => {\n  if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) {\n    throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal)\n  }\n}\nconst validateFunction = (value, name) => {\n  if (typeof value !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE(name, 'Function', value)\n  }\n}\nmodule.exports = {\n  AggregateError,\n  kEmptyObject: Object.freeze({}),\n  once(callback) {\n    let called = false\n    return function (...args) {\n      if (called) {\n        return\n      }\n      called = true\n      callback.apply(this, args)\n    }\n  },\n  createDeferredPromise: function () {\n    let resolve\n    let reject\n\n    // eslint-disable-next-line promise/param-names\n    const promise = new Promise((res, rej) => {\n      resolve = res\n      reject = rej\n    })\n    return {\n      promise,\n      resolve,\n      reject\n    }\n  },\n  promisify(fn) {\n    return new Promise((resolve, reject) => {\n      fn((err, ...args) => {\n        if (err) {\n          return reject(err)\n        }\n        return resolve(...args)\n      })\n    })\n  },\n  debuglog() {\n    return function () {}\n  },\n  format,\n  inspect,\n  types: {\n    isAsyncFunction(fn) {\n      return fn instanceof AsyncFunction\n    },\n    isArrayBufferView(arr) {\n      return ArrayBuffer.isView(arr)\n    }\n  },\n  isBlob,\n  deprecate(fn, message) {\n    return fn\n  },\n  addAbortListener:\n    require('events').addAbortListener ||\n    function addAbortListener(signal, listener) {\n      if (signal === undefined) {\n        throw new ERR_INVALID_ARG_TYPE('signal', 'AbortSignal', signal)\n      }\n      validateAbortSignal(signal, 'signal')\n      validateFunction(listener, 'listener')\n      let removeEventListener\n      if (signal.aborted) {\n        queueMicrotask(() => listener())\n      } else {\n        signal.addEventListener('abort', listener, {\n          __proto__: null,\n          once: true,\n          [kResistStopPropagation]: true\n        })\n        removeEventListener = () => {\n          signal.removeEventListener('abort', listener)\n        }\n      }\n      return {\n        __proto__: null,\n        [SymbolDispose]() {\n          var _removeEventListener\n          ;(_removeEventListener = removeEventListener) === null || _removeEventListener === undefined\n            ? undefined\n            : _removeEventListener()\n        }\n      }\n    },\n  AbortSignalAny:\n    AbortSignal.any ||\n    function AbortSignalAny(signals) {\n      // Fast path if there is only one signal.\n      if (signals.length === 1) {\n        return signals[0]\n      }\n      const ac = new AbortController()\n      const abort = () => ac.abort()\n      signals.forEach((signal) => {\n        validateAbortSignal(signal, 'signals')\n        signal.addEventListener('abort', abort, {\n          once: true\n        })\n      })\n      ac.signal.addEventListener(\n        'abort',\n        () => {\n          signals.forEach((signal) => signal.removeEventListener('abort', abort))\n        },\n        {\n          once: true\n        }\n      )\n      return ac.signal\n    }\n}\nmodule.exports.promisify.custom = Symbol.for('nodejs.util.promisify.custom')\n","/* eslint jsdoc/require-jsdoc: \"error\" */\n\n'use strict'\n\nconst {\n  ArrayIsArray,\n  ArrayPrototypeIncludes,\n  ArrayPrototypeJoin,\n  ArrayPrototypeMap,\n  NumberIsInteger,\n  NumberIsNaN,\n  NumberMAX_SAFE_INTEGER,\n  NumberMIN_SAFE_INTEGER,\n  NumberParseInt,\n  ObjectPrototypeHasOwnProperty,\n  RegExpPrototypeExec,\n  String,\n  StringPrototypeToUpperCase,\n  StringPrototypeTrim\n} = require('../ours/primordials')\nconst {\n  hideStackFrames,\n  codes: { ERR_SOCKET_BAD_PORT, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_OUT_OF_RANGE, ERR_UNKNOWN_SIGNAL }\n} = require('../ours/errors')\nconst { normalizeEncoding } = require('../ours/util')\nconst { isAsyncFunction, isArrayBufferView } = require('../ours/util').types\nconst signals = {}\n\n/**\n * @param {*} value\n * @returns {boolean}\n */\nfunction isInt32(value) {\n  return value === (value | 0)\n}\n\n/**\n * @param {*} value\n * @returns {boolean}\n */\nfunction isUint32(value) {\n  return value === value >>> 0\n}\nconst octalReg = /^[0-7]+$/\nconst modeDesc = 'must be a 32-bit unsigned integer or an octal string'\n\n/**\n * Parse and validate values that will be converted into mode_t (the S_*\n * constants). Only valid numbers and octal strings are allowed. They could be\n * converted to 32-bit unsigned integers or non-negative signed integers in the\n * C++ land, but any value higher than 0o777 will result in platform-specific\n * behaviors.\n * @param {*} value Values to be validated\n * @param {string} name Name of the argument\n * @param {number} [def] If specified, will be returned for invalid values\n * @returns {number}\n */\nfunction parseFileMode(value, name, def) {\n  if (typeof value === 'undefined') {\n    value = def\n  }\n  if (typeof value === 'string') {\n    if (RegExpPrototypeExec(octalReg, value) === null) {\n      throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc)\n    }\n    value = NumberParseInt(value, 8)\n  }\n  validateUint32(value, name)\n  return value\n}\n\n/**\n * @callback validateInteger\n * @param {*} value\n * @param {string} name\n * @param {number} [min]\n * @param {number} [max]\n * @returns {asserts value is number}\n */\n\n/** @type {validateInteger} */\nconst validateInteger = hideStackFrames((value, name, min = NumberMIN_SAFE_INTEGER, max = NumberMAX_SAFE_INTEGER) => {\n  if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n  if (!NumberIsInteger(value)) throw new ERR_OUT_OF_RANGE(name, 'an integer', value)\n  if (value < min || value > max) throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value)\n})\n\n/**\n * @callback validateInt32\n * @param {*} value\n * @param {string} name\n * @param {number} [min]\n * @param {number} [max]\n * @returns {asserts value is number}\n */\n\n/** @type {validateInt32} */\nconst validateInt32 = hideStackFrames((value, name, min = -2147483648, max = 2147483647) => {\n  // The defaults for min and max correspond to the limits of 32-bit integers.\n  if (typeof value !== 'number') {\n    throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n  }\n  if (!NumberIsInteger(value)) {\n    throw new ERR_OUT_OF_RANGE(name, 'an integer', value)\n  }\n  if (value < min || value > max) {\n    throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value)\n  }\n})\n\n/**\n * @callback validateUint32\n * @param {*} value\n * @param {string} name\n * @param {number|boolean} [positive=false]\n * @returns {asserts value is number}\n */\n\n/** @type {validateUint32} */\nconst validateUint32 = hideStackFrames((value, name, positive = false) => {\n  if (typeof value !== 'number') {\n    throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n  }\n  if (!NumberIsInteger(value)) {\n    throw new ERR_OUT_OF_RANGE(name, 'an integer', value)\n  }\n  const min = positive ? 1 : 0\n  // 2 ** 32 === 4294967296\n  const max = 4294967295\n  if (value < min || value > max) {\n    throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value)\n  }\n})\n\n/**\n * @callback validateString\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is string}\n */\n\n/** @type {validateString} */\nfunction validateString(value, name) {\n  if (typeof value !== 'string') throw new ERR_INVALID_ARG_TYPE(name, 'string', value)\n}\n\n/**\n * @callback validateNumber\n * @param {*} value\n * @param {string} name\n * @param {number} [min]\n * @param {number} [max]\n * @returns {asserts value is number}\n */\n\n/** @type {validateNumber} */\nfunction validateNumber(value, name, min = undefined, max) {\n  if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n  if (\n    (min != null && value < min) ||\n    (max != null && value > max) ||\n    ((min != null || max != null) && NumberIsNaN(value))\n  ) {\n    throw new ERR_OUT_OF_RANGE(\n      name,\n      `${min != null ? `>= ${min}` : ''}${min != null && max != null ? ' && ' : ''}${max != null ? `<= ${max}` : ''}`,\n      value\n    )\n  }\n}\n\n/**\n * @callback validateOneOf\n * @template T\n * @param {T} value\n * @param {string} name\n * @param {T[]} oneOf\n */\n\n/** @type {validateOneOf} */\nconst validateOneOf = hideStackFrames((value, name, oneOf) => {\n  if (!ArrayPrototypeIncludes(oneOf, value)) {\n    const allowed = ArrayPrototypeJoin(\n      ArrayPrototypeMap(oneOf, (v) => (typeof v === 'string' ? `'${v}'` : String(v))),\n      ', '\n    )\n    const reason = 'must be one of: ' + allowed\n    throw new ERR_INVALID_ARG_VALUE(name, value, reason)\n  }\n})\n\n/**\n * @callback validateBoolean\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is boolean}\n */\n\n/** @type {validateBoolean} */\nfunction validateBoolean(value, name) {\n  if (typeof value !== 'boolean') throw new ERR_INVALID_ARG_TYPE(name, 'boolean', value)\n}\n\n/**\n * @param {any} options\n * @param {string} key\n * @param {boolean} defaultValue\n * @returns {boolean}\n */\nfunction getOwnPropertyValueOrDefault(options, key, defaultValue) {\n  return options == null || !ObjectPrototypeHasOwnProperty(options, key) ? defaultValue : options[key]\n}\n\n/**\n * @callback validateObject\n * @param {*} value\n * @param {string} name\n * @param {{\n *   allowArray?: boolean,\n *   allowFunction?: boolean,\n *   nullable?: boolean\n * }} [options]\n */\n\n/** @type {validateObject} */\nconst validateObject = hideStackFrames((value, name, options = null) => {\n  const allowArray = getOwnPropertyValueOrDefault(options, 'allowArray', false)\n  const allowFunction = getOwnPropertyValueOrDefault(options, 'allowFunction', false)\n  const nullable = getOwnPropertyValueOrDefault(options, 'nullable', false)\n  if (\n    (!nullable && value === null) ||\n    (!allowArray && ArrayIsArray(value)) ||\n    (typeof value !== 'object' && (!allowFunction || typeof value !== 'function'))\n  ) {\n    throw new ERR_INVALID_ARG_TYPE(name, 'Object', value)\n  }\n})\n\n/**\n * @callback validateDictionary - We are using the Web IDL Standard definition\n *                                of \"dictionary\" here, which means any value\n *                                whose Type is either Undefined, Null, or\n *                                Object (which includes functions).\n * @param {*} value\n * @param {string} name\n * @see https://webidl.spec.whatwg.org/#es-dictionary\n * @see https://tc39.es/ecma262/#table-typeof-operator-results\n */\n\n/** @type {validateDictionary} */\nconst validateDictionary = hideStackFrames((value, name) => {\n  if (value != null && typeof value !== 'object' && typeof value !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE(name, 'a dictionary', value)\n  }\n})\n\n/**\n * @callback validateArray\n * @param {*} value\n * @param {string} name\n * @param {number} [minLength]\n * @returns {asserts value is any[]}\n */\n\n/** @type {validateArray} */\nconst validateArray = hideStackFrames((value, name, minLength = 0) => {\n  if (!ArrayIsArray(value)) {\n    throw new ERR_INVALID_ARG_TYPE(name, 'Array', value)\n  }\n  if (value.length < minLength) {\n    const reason = `must be longer than ${minLength}`\n    throw new ERR_INVALID_ARG_VALUE(name, value, reason)\n  }\n})\n\n/**\n * @callback validateStringArray\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is string[]}\n */\n\n/** @type {validateStringArray} */\nfunction validateStringArray(value, name) {\n  validateArray(value, name)\n  for (let i = 0; i < value.length; i++) {\n    validateString(value[i], `${name}[${i}]`)\n  }\n}\n\n/**\n * @callback validateBooleanArray\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is boolean[]}\n */\n\n/** @type {validateBooleanArray} */\nfunction validateBooleanArray(value, name) {\n  validateArray(value, name)\n  for (let i = 0; i < value.length; i++) {\n    validateBoolean(value[i], `${name}[${i}]`)\n  }\n}\n\n/**\n * @callback validateAbortSignalArray\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is AbortSignal[]}\n */\n\n/** @type {validateAbortSignalArray} */\nfunction validateAbortSignalArray(value, name) {\n  validateArray(value, name)\n  for (let i = 0; i < value.length; i++) {\n    const signal = value[i]\n    const indexedName = `${name}[${i}]`\n    if (signal == null) {\n      throw new ERR_INVALID_ARG_TYPE(indexedName, 'AbortSignal', signal)\n    }\n    validateAbortSignal(signal, indexedName)\n  }\n}\n\n/**\n * @param {*} signal\n * @param {string} [name='signal']\n * @returns {asserts signal is keyof signals}\n */\nfunction validateSignalName(signal, name = 'signal') {\n  validateString(signal, name)\n  if (signals[signal] === undefined) {\n    if (signals[StringPrototypeToUpperCase(signal)] !== undefined) {\n      throw new ERR_UNKNOWN_SIGNAL(signal + ' (signals must use all capital letters)')\n    }\n    throw new ERR_UNKNOWN_SIGNAL(signal)\n  }\n}\n\n/**\n * @callback validateBuffer\n * @param {*} buffer\n * @param {string} [name='buffer']\n * @returns {asserts buffer is ArrayBufferView}\n */\n\n/** @type {validateBuffer} */\nconst validateBuffer = hideStackFrames((buffer, name = 'buffer') => {\n  if (!isArrayBufferView(buffer)) {\n    throw new ERR_INVALID_ARG_TYPE(name, ['Buffer', 'TypedArray', 'DataView'], buffer)\n  }\n})\n\n/**\n * @param {string} data\n * @param {string} encoding\n */\nfunction validateEncoding(data, encoding) {\n  const normalizedEncoding = normalizeEncoding(encoding)\n  const length = data.length\n  if (normalizedEncoding === 'hex' && length % 2 !== 0) {\n    throw new ERR_INVALID_ARG_VALUE('encoding', encoding, `is invalid for data of length ${length}`)\n  }\n}\n\n/**\n * Check that the port number is not NaN when coerced to a number,\n * is an integer and that it falls within the legal range of port numbers.\n * @param {*} port\n * @param {string} [name='Port']\n * @param {boolean} [allowZero=true]\n * @returns {number}\n */\nfunction validatePort(port, name = 'Port', allowZero = true) {\n  if (\n    (typeof port !== 'number' && typeof port !== 'string') ||\n    (typeof port === 'string' && StringPrototypeTrim(port).length === 0) ||\n    +port !== +port >>> 0 ||\n    port > 0xffff ||\n    (port === 0 && !allowZero)\n  ) {\n    throw new ERR_SOCKET_BAD_PORT(name, port, allowZero)\n  }\n  return port | 0\n}\n\n/**\n * @callback validateAbortSignal\n * @param {*} signal\n * @param {string} name\n */\n\n/** @type {validateAbortSignal} */\nconst validateAbortSignal = hideStackFrames((signal, name) => {\n  if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) {\n    throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal)\n  }\n})\n\n/**\n * @callback validateFunction\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is Function}\n */\n\n/** @type {validateFunction} */\nconst validateFunction = hideStackFrames((value, name) => {\n  if (typeof value !== 'function') throw new ERR_INVALID_ARG_TYPE(name, 'Function', value)\n})\n\n/**\n * @callback validatePlainFunction\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is Function}\n */\n\n/** @type {validatePlainFunction} */\nconst validatePlainFunction = hideStackFrames((value, name) => {\n  if (typeof value !== 'function' || isAsyncFunction(value)) throw new ERR_INVALID_ARG_TYPE(name, 'Function', value)\n})\n\n/**\n * @callback validateUndefined\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is undefined}\n */\n\n/** @type {validateUndefined} */\nconst validateUndefined = hideStackFrames((value, name) => {\n  if (value !== undefined) throw new ERR_INVALID_ARG_TYPE(name, 'undefined', value)\n})\n\n/**\n * @template T\n * @param {T} value\n * @param {string} name\n * @param {T[]} union\n */\nfunction validateUnion(value, name, union) {\n  if (!ArrayPrototypeIncludes(union, value)) {\n    throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value)\n  }\n}\n\n/*\n  The rules for the Link header field are described here:\n  https://www.rfc-editor.org/rfc/rfc8288.html#section-3\n\n  This regex validates any string surrounded by angle brackets\n  (not necessarily a valid URI reference) followed by zero or more\n  link-params separated by semicolons.\n*/\nconst linkValueRegExp = /^(?:<[^>]*>)(?:\\s*;\\s*[^;\"\\s]+(?:=(\")?[^;\"\\s]*\\1)?)*$/\n\n/**\n * @param {any} value\n * @param {string} name\n */\nfunction validateLinkHeaderFormat(value, name) {\n  if (typeof value === 'undefined' || !RegExpPrototypeExec(linkValueRegExp, value)) {\n    throw new ERR_INVALID_ARG_VALUE(\n      name,\n      value,\n      'must be an array or string of format \"; rel=preload; as=style\"'\n    )\n  }\n}\n\n/**\n * @param {any} hints\n * @return {string}\n */\nfunction validateLinkHeaderValue(hints) {\n  if (typeof hints === 'string') {\n    validateLinkHeaderFormat(hints, 'hints')\n    return hints\n  } else if (ArrayIsArray(hints)) {\n    const hintsLength = hints.length\n    let result = ''\n    if (hintsLength === 0) {\n      return result\n    }\n    for (let i = 0; i < hintsLength; i++) {\n      const link = hints[i]\n      validateLinkHeaderFormat(link, 'hints')\n      result += link\n      if (i !== hintsLength - 1) {\n        result += ', '\n      }\n    }\n    return result\n  }\n  throw new ERR_INVALID_ARG_VALUE(\n    'hints',\n    hints,\n    'must be an array or string of format \"; rel=preload; as=style\"'\n  )\n}\nmodule.exports = {\n  isInt32,\n  isUint32,\n  parseFileMode,\n  validateArray,\n  validateStringArray,\n  validateBooleanArray,\n  validateAbortSignalArray,\n  validateBoolean,\n  validateBuffer,\n  validateDictionary,\n  validateEncoding,\n  validateFunction,\n  validateInt32,\n  validateInteger,\n  validateNumber,\n  validateObject,\n  validateOneOf,\n  validatePlainFunction,\n  validatePort,\n  validateSignalName,\n  validateString,\n  validateUint32,\n  validateUndefined,\n  validateUnion,\n  validateAbortSignal,\n  validateLinkHeaderValue\n}\n","'use strict'\n\nconst { SymbolAsyncIterator, SymbolIterator, SymbolFor } = require('../../ours/primordials')\n\n// We need to use SymbolFor to make these globally available\n// for interopt with readable-stream, i.e. readable-stream\n// and node core needs to be able to read/write private state\n// from each other for proper interoperability.\nconst kIsDestroyed = SymbolFor('nodejs.stream.destroyed')\nconst kIsErrored = SymbolFor('nodejs.stream.errored')\nconst kIsReadable = SymbolFor('nodejs.stream.readable')\nconst kIsWritable = SymbolFor('nodejs.stream.writable')\nconst kIsDisturbed = SymbolFor('nodejs.stream.disturbed')\nconst kIsClosedPromise = SymbolFor('nodejs.webstream.isClosedPromise')\nconst kControllerErrorFunction = SymbolFor('nodejs.webstream.controllerErrorFunction')\nfunction isReadableNodeStream(obj, strict = false) {\n  var _obj$_readableState\n  return !!(\n    (\n      obj &&\n      typeof obj.pipe === 'function' &&\n      typeof obj.on === 'function' &&\n      (!strict || (typeof obj.pause === 'function' && typeof obj.resume === 'function')) &&\n      (!obj._writableState ||\n        ((_obj$_readableState = obj._readableState) === null || _obj$_readableState === undefined\n          ? undefined\n          : _obj$_readableState.readable) !== false) &&\n      // Duplex\n      (!obj._writableState || obj._readableState)\n    ) // Writable has .pipe.\n  )\n}\nfunction isWritableNodeStream(obj) {\n  var _obj$_writableState\n  return !!(\n    (\n      obj &&\n      typeof obj.write === 'function' &&\n      typeof obj.on === 'function' &&\n      (!obj._readableState ||\n        ((_obj$_writableState = obj._writableState) === null || _obj$_writableState === undefined\n          ? undefined\n          : _obj$_writableState.writable) !== false)\n    ) // Duplex\n  )\n}\nfunction isDuplexNodeStream(obj) {\n  return !!(\n    obj &&\n    typeof obj.pipe === 'function' &&\n    obj._readableState &&\n    typeof obj.on === 'function' &&\n    typeof obj.write === 'function'\n  )\n}\nfunction isNodeStream(obj) {\n  return (\n    obj &&\n    (obj._readableState ||\n      obj._writableState ||\n      (typeof obj.write === 'function' && typeof obj.on === 'function') ||\n      (typeof obj.pipe === 'function' && typeof obj.on === 'function'))\n  )\n}\nfunction isReadableStream(obj) {\n  return !!(\n    obj &&\n    !isNodeStream(obj) &&\n    typeof obj.pipeThrough === 'function' &&\n    typeof obj.getReader === 'function' &&\n    typeof obj.cancel === 'function'\n  )\n}\nfunction isWritableStream(obj) {\n  return !!(obj && !isNodeStream(obj) && typeof obj.getWriter === 'function' && typeof obj.abort === 'function')\n}\nfunction isTransformStream(obj) {\n  return !!(obj && !isNodeStream(obj) && typeof obj.readable === 'object' && typeof obj.writable === 'object')\n}\nfunction isWebStream(obj) {\n  return isReadableStream(obj) || isWritableStream(obj) || isTransformStream(obj)\n}\nfunction isIterable(obj, isAsync) {\n  if (obj == null) return false\n  if (isAsync === true) return typeof obj[SymbolAsyncIterator] === 'function'\n  if (isAsync === false) return typeof obj[SymbolIterator] === 'function'\n  return typeof obj[SymbolAsyncIterator] === 'function' || typeof obj[SymbolIterator] === 'function'\n}\nfunction isDestroyed(stream) {\n  if (!isNodeStream(stream)) return null\n  const wState = stream._writableState\n  const rState = stream._readableState\n  const state = wState || rState\n  return !!(stream.destroyed || stream[kIsDestroyed] || (state !== null && state !== undefined && state.destroyed))\n}\n\n// Have been end():d.\nfunction isWritableEnded(stream) {\n  if (!isWritableNodeStream(stream)) return null\n  if (stream.writableEnded === true) return true\n  const wState = stream._writableState\n  if (wState !== null && wState !== undefined && wState.errored) return false\n  if (typeof (wState === null || wState === undefined ? undefined : wState.ended) !== 'boolean') return null\n  return wState.ended\n}\n\n// Have emitted 'finish'.\nfunction isWritableFinished(stream, strict) {\n  if (!isWritableNodeStream(stream)) return null\n  if (stream.writableFinished === true) return true\n  const wState = stream._writableState\n  if (wState !== null && wState !== undefined && wState.errored) return false\n  if (typeof (wState === null || wState === undefined ? undefined : wState.finished) !== 'boolean') return null\n  return !!(wState.finished || (strict === false && wState.ended === true && wState.length === 0))\n}\n\n// Have been push(null):d.\nfunction isReadableEnded(stream) {\n  if (!isReadableNodeStream(stream)) return null\n  if (stream.readableEnded === true) return true\n  const rState = stream._readableState\n  if (!rState || rState.errored) return false\n  if (typeof (rState === null || rState === undefined ? undefined : rState.ended) !== 'boolean') return null\n  return rState.ended\n}\n\n// Have emitted 'end'.\nfunction isReadableFinished(stream, strict) {\n  if (!isReadableNodeStream(stream)) return null\n  const rState = stream._readableState\n  if (rState !== null && rState !== undefined && rState.errored) return false\n  if (typeof (rState === null || rState === undefined ? undefined : rState.endEmitted) !== 'boolean') return null\n  return !!(rState.endEmitted || (strict === false && rState.ended === true && rState.length === 0))\n}\nfunction isReadable(stream) {\n  if (stream && stream[kIsReadable] != null) return stream[kIsReadable]\n  if (typeof (stream === null || stream === undefined ? undefined : stream.readable) !== 'boolean') return null\n  if (isDestroyed(stream)) return false\n  return isReadableNodeStream(stream) && stream.readable && !isReadableFinished(stream)\n}\nfunction isWritable(stream) {\n  if (stream && stream[kIsWritable] != null) return stream[kIsWritable]\n  if (typeof (stream === null || stream === undefined ? undefined : stream.writable) !== 'boolean') return null\n  if (isDestroyed(stream)) return false\n  return isWritableNodeStream(stream) && stream.writable && !isWritableEnded(stream)\n}\nfunction isFinished(stream, opts) {\n  if (!isNodeStream(stream)) {\n    return null\n  }\n  if (isDestroyed(stream)) {\n    return true\n  }\n  if ((opts === null || opts === undefined ? undefined : opts.readable) !== false && isReadable(stream)) {\n    return false\n  }\n  if ((opts === null || opts === undefined ? undefined : opts.writable) !== false && isWritable(stream)) {\n    return false\n  }\n  return true\n}\nfunction isWritableErrored(stream) {\n  var _stream$_writableStat, _stream$_writableStat2\n  if (!isNodeStream(stream)) {\n    return null\n  }\n  if (stream.writableErrored) {\n    return stream.writableErrored\n  }\n  return (_stream$_writableStat =\n    (_stream$_writableStat2 = stream._writableState) === null || _stream$_writableStat2 === undefined\n      ? undefined\n      : _stream$_writableStat2.errored) !== null && _stream$_writableStat !== undefined\n    ? _stream$_writableStat\n    : null\n}\nfunction isReadableErrored(stream) {\n  var _stream$_readableStat, _stream$_readableStat2\n  if (!isNodeStream(stream)) {\n    return null\n  }\n  if (stream.readableErrored) {\n    return stream.readableErrored\n  }\n  return (_stream$_readableStat =\n    (_stream$_readableStat2 = stream._readableState) === null || _stream$_readableStat2 === undefined\n      ? undefined\n      : _stream$_readableStat2.errored) !== null && _stream$_readableStat !== undefined\n    ? _stream$_readableStat\n    : null\n}\nfunction isClosed(stream) {\n  if (!isNodeStream(stream)) {\n    return null\n  }\n  if (typeof stream.closed === 'boolean') {\n    return stream.closed\n  }\n  const wState = stream._writableState\n  const rState = stream._readableState\n  if (\n    typeof (wState === null || wState === undefined ? undefined : wState.closed) === 'boolean' ||\n    typeof (rState === null || rState === undefined ? undefined : rState.closed) === 'boolean'\n  ) {\n    return (\n      (wState === null || wState === undefined ? undefined : wState.closed) ||\n      (rState === null || rState === undefined ? undefined : rState.closed)\n    )\n  }\n  if (typeof stream._closed === 'boolean' && isOutgoingMessage(stream)) {\n    return stream._closed\n  }\n  return null\n}\nfunction isOutgoingMessage(stream) {\n  return (\n    typeof stream._closed === 'boolean' &&\n    typeof stream._defaultKeepAlive === 'boolean' &&\n    typeof stream._removedConnection === 'boolean' &&\n    typeof stream._removedContLen === 'boolean'\n  )\n}\nfunction isServerResponse(stream) {\n  return typeof stream._sent100 === 'boolean' && isOutgoingMessage(stream)\n}\nfunction isServerRequest(stream) {\n  var _stream$req\n  return (\n    typeof stream._consuming === 'boolean' &&\n    typeof stream._dumped === 'boolean' &&\n    ((_stream$req = stream.req) === null || _stream$req === undefined ? undefined : _stream$req.upgradeOrConnect) ===\n      undefined\n  )\n}\nfunction willEmitClose(stream) {\n  if (!isNodeStream(stream)) return null\n  const wState = stream._writableState\n  const rState = stream._readableState\n  const state = wState || rState\n  return (\n    (!state && isServerResponse(stream)) || !!(state && state.autoDestroy && state.emitClose && state.closed === false)\n  )\n}\nfunction isDisturbed(stream) {\n  var _stream$kIsDisturbed\n  return !!(\n    stream &&\n    ((_stream$kIsDisturbed = stream[kIsDisturbed]) !== null && _stream$kIsDisturbed !== undefined\n      ? _stream$kIsDisturbed\n      : stream.readableDidRead || stream.readableAborted)\n  )\n}\nfunction isErrored(stream) {\n  var _ref,\n    _ref2,\n    _ref3,\n    _ref4,\n    _ref5,\n    _stream$kIsErrored,\n    _stream$_readableStat3,\n    _stream$_writableStat3,\n    _stream$_readableStat4,\n    _stream$_writableStat4\n  return !!(\n    stream &&\n    ((_ref =\n      (_ref2 =\n        (_ref3 =\n          (_ref4 =\n            (_ref5 =\n              (_stream$kIsErrored = stream[kIsErrored]) !== null && _stream$kIsErrored !== undefined\n                ? _stream$kIsErrored\n                : stream.readableErrored) !== null && _ref5 !== undefined\n              ? _ref5\n              : stream.writableErrored) !== null && _ref4 !== undefined\n            ? _ref4\n            : (_stream$_readableStat3 = stream._readableState) === null || _stream$_readableStat3 === undefined\n            ? undefined\n            : _stream$_readableStat3.errorEmitted) !== null && _ref3 !== undefined\n          ? _ref3\n          : (_stream$_writableStat3 = stream._writableState) === null || _stream$_writableStat3 === undefined\n          ? undefined\n          : _stream$_writableStat3.errorEmitted) !== null && _ref2 !== undefined\n        ? _ref2\n        : (_stream$_readableStat4 = stream._readableState) === null || _stream$_readableStat4 === undefined\n        ? undefined\n        : _stream$_readableStat4.errored) !== null && _ref !== undefined\n      ? _ref\n      : (_stream$_writableStat4 = stream._writableState) === null || _stream$_writableStat4 === undefined\n      ? undefined\n      : _stream$_writableStat4.errored)\n  )\n}\nmodule.exports = {\n  isDestroyed,\n  kIsDestroyed,\n  isDisturbed,\n  kIsDisturbed,\n  isErrored,\n  kIsErrored,\n  isReadable,\n  kIsReadable,\n  kIsClosedPromise,\n  kControllerErrorFunction,\n  kIsWritable,\n  isClosed,\n  isDuplexNodeStream,\n  isFinished,\n  isIterable,\n  isReadableNodeStream,\n  isReadableStream,\n  isReadableEnded,\n  isReadableFinished,\n  isReadableErrored,\n  isNodeStream,\n  isWebStream,\n  isWritable,\n  isWritableNodeStream,\n  isWritableStream,\n  isWritableEnded,\n  isWritableFinished,\n  isWritableErrored,\n  isServerRequest,\n  isServerResponse,\n  willEmitClose,\n  isTransformStream\n}\n","// Ported from https://github.com/mafintosh/end-of-stream with\n// permission from the author, Mathias Buus (@mafintosh).\n\n'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst { AbortError, codes } = require('../../ours/errors')\nconst { ERR_INVALID_ARG_TYPE, ERR_STREAM_PREMATURE_CLOSE } = codes\nconst { kEmptyObject, once } = require('../../ours/util')\nconst { validateAbortSignal, validateFunction, validateObject, validateBoolean } = require('../validators')\nconst { Promise, PromisePrototypeThen, SymbolDispose } = require('../../ours/primordials')\nconst {\n  isClosed,\n  isReadable,\n  isReadableNodeStream,\n  isReadableStream,\n  isReadableFinished,\n  isReadableErrored,\n  isWritable,\n  isWritableNodeStream,\n  isWritableStream,\n  isWritableFinished,\n  isWritableErrored,\n  isNodeStream,\n  willEmitClose: _willEmitClose,\n  kIsClosedPromise\n} = require('./utils')\nlet addAbortListener\nfunction isRequest(stream) {\n  return stream.setHeader && typeof stream.abort === 'function'\n}\nconst nop = () => {}\nfunction eos(stream, options, callback) {\n  var _options$readable, _options$writable\n  if (arguments.length === 2) {\n    callback = options\n    options = kEmptyObject\n  } else if (options == null) {\n    options = kEmptyObject\n  } else {\n    validateObject(options, 'options')\n  }\n  validateFunction(callback, 'callback')\n  validateAbortSignal(options.signal, 'options.signal')\n  callback = once(callback)\n  if (isReadableStream(stream) || isWritableStream(stream)) {\n    return eosWeb(stream, options, callback)\n  }\n  if (!isNodeStream(stream)) {\n    throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream)\n  }\n  const readable =\n    (_options$readable = options.readable) !== null && _options$readable !== undefined\n      ? _options$readable\n      : isReadableNodeStream(stream)\n  const writable =\n    (_options$writable = options.writable) !== null && _options$writable !== undefined\n      ? _options$writable\n      : isWritableNodeStream(stream)\n  const wState = stream._writableState\n  const rState = stream._readableState\n  const onlegacyfinish = () => {\n    if (!stream.writable) {\n      onfinish()\n    }\n  }\n\n  // TODO (ronag): Improve soft detection to include core modules and\n  // common ecosystem modules that do properly emit 'close' but fail\n  // this generic check.\n  let willEmitClose =\n    _willEmitClose(stream) && isReadableNodeStream(stream) === readable && isWritableNodeStream(stream) === writable\n  let writableFinished = isWritableFinished(stream, false)\n  const onfinish = () => {\n    writableFinished = true\n    // Stream should not be destroyed here. If it is that\n    // means that user space is doing something differently and\n    // we cannot trust willEmitClose.\n    if (stream.destroyed) {\n      willEmitClose = false\n    }\n    if (willEmitClose && (!stream.readable || readable)) {\n      return\n    }\n    if (!readable || readableFinished) {\n      callback.call(stream)\n    }\n  }\n  let readableFinished = isReadableFinished(stream, false)\n  const onend = () => {\n    readableFinished = true\n    // Stream should not be destroyed here. If it is that\n    // means that user space is doing something differently and\n    // we cannot trust willEmitClose.\n    if (stream.destroyed) {\n      willEmitClose = false\n    }\n    if (willEmitClose && (!stream.writable || writable)) {\n      return\n    }\n    if (!writable || writableFinished) {\n      callback.call(stream)\n    }\n  }\n  const onerror = (err) => {\n    callback.call(stream, err)\n  }\n  let closed = isClosed(stream)\n  const onclose = () => {\n    closed = true\n    const errored = isWritableErrored(stream) || isReadableErrored(stream)\n    if (errored && typeof errored !== 'boolean') {\n      return callback.call(stream, errored)\n    }\n    if (readable && !readableFinished && isReadableNodeStream(stream, true)) {\n      if (!isReadableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE())\n    }\n    if (writable && !writableFinished) {\n      if (!isWritableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE())\n    }\n    callback.call(stream)\n  }\n  const onclosed = () => {\n    closed = true\n    const errored = isWritableErrored(stream) || isReadableErrored(stream)\n    if (errored && typeof errored !== 'boolean') {\n      return callback.call(stream, errored)\n    }\n    callback.call(stream)\n  }\n  const onrequest = () => {\n    stream.req.on('finish', onfinish)\n  }\n  if (isRequest(stream)) {\n    stream.on('complete', onfinish)\n    if (!willEmitClose) {\n      stream.on('abort', onclose)\n    }\n    if (stream.req) {\n      onrequest()\n    } else {\n      stream.on('request', onrequest)\n    }\n  } else if (writable && !wState) {\n    // legacy streams\n    stream.on('end', onlegacyfinish)\n    stream.on('close', onlegacyfinish)\n  }\n\n  // Not all streams will emit 'close' after 'aborted'.\n  if (!willEmitClose && typeof stream.aborted === 'boolean') {\n    stream.on('aborted', onclose)\n  }\n  stream.on('end', onend)\n  stream.on('finish', onfinish)\n  if (options.error !== false) {\n    stream.on('error', onerror)\n  }\n  stream.on('close', onclose)\n  if (closed) {\n    process.nextTick(onclose)\n  } else if (\n    (wState !== null && wState !== undefined && wState.errorEmitted) ||\n    (rState !== null && rState !== undefined && rState.errorEmitted)\n  ) {\n    if (!willEmitClose) {\n      process.nextTick(onclosed)\n    }\n  } else if (\n    !readable &&\n    (!willEmitClose || isReadable(stream)) &&\n    (writableFinished || isWritable(stream) === false)\n  ) {\n    process.nextTick(onclosed)\n  } else if (\n    !writable &&\n    (!willEmitClose || isWritable(stream)) &&\n    (readableFinished || isReadable(stream) === false)\n  ) {\n    process.nextTick(onclosed)\n  } else if (rState && stream.req && stream.aborted) {\n    process.nextTick(onclosed)\n  }\n  const cleanup = () => {\n    callback = nop\n    stream.removeListener('aborted', onclose)\n    stream.removeListener('complete', onfinish)\n    stream.removeListener('abort', onclose)\n    stream.removeListener('request', onrequest)\n    if (stream.req) stream.req.removeListener('finish', onfinish)\n    stream.removeListener('end', onlegacyfinish)\n    stream.removeListener('close', onlegacyfinish)\n    stream.removeListener('finish', onfinish)\n    stream.removeListener('end', onend)\n    stream.removeListener('error', onerror)\n    stream.removeListener('close', onclose)\n  }\n  if (options.signal && !closed) {\n    const abort = () => {\n      // Keep it because cleanup removes it.\n      const endCallback = callback\n      cleanup()\n      endCallback.call(\n        stream,\n        new AbortError(undefined, {\n          cause: options.signal.reason\n        })\n      )\n    }\n    if (options.signal.aborted) {\n      process.nextTick(abort)\n    } else {\n      addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n      const disposable = addAbortListener(options.signal, abort)\n      const originalCallback = callback\n      callback = once((...args) => {\n        disposable[SymbolDispose]()\n        originalCallback.apply(stream, args)\n      })\n    }\n  }\n  return cleanup\n}\nfunction eosWeb(stream, options, callback) {\n  let isAborted = false\n  let abort = nop\n  if (options.signal) {\n    abort = () => {\n      isAborted = true\n      callback.call(\n        stream,\n        new AbortError(undefined, {\n          cause: options.signal.reason\n        })\n      )\n    }\n    if (options.signal.aborted) {\n      process.nextTick(abort)\n    } else {\n      addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n      const disposable = addAbortListener(options.signal, abort)\n      const originalCallback = callback\n      callback = once((...args) => {\n        disposable[SymbolDispose]()\n        originalCallback.apply(stream, args)\n      })\n    }\n  }\n  const resolverFn = (...args) => {\n    if (!isAborted) {\n      process.nextTick(() => callback.apply(stream, args))\n    }\n  }\n  PromisePrototypeThen(stream[kIsClosedPromise].promise, resolverFn, resolverFn)\n  return nop\n}\nfunction finished(stream, opts) {\n  var _opts\n  let autoCleanup = false\n  if (opts === null) {\n    opts = kEmptyObject\n  }\n  if ((_opts = opts) !== null && _opts !== undefined && _opts.cleanup) {\n    validateBoolean(opts.cleanup, 'cleanup')\n    autoCleanup = opts.cleanup\n  }\n  return new Promise((resolve, reject) => {\n    const cleanup = eos(stream, opts, (err) => {\n      if (autoCleanup) {\n        cleanup()\n      }\n      if (err) {\n        reject(err)\n      } else {\n        resolve()\n      }\n    })\n  })\n}\nmodule.exports = eos\nmodule.exports.finished = finished\n","'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst {\n  aggregateTwoErrors,\n  codes: { ERR_MULTIPLE_CALLBACK },\n  AbortError\n} = require('../../ours/errors')\nconst { Symbol } = require('../../ours/primordials')\nconst { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = require('./utils')\nconst kDestroy = Symbol('kDestroy')\nconst kConstruct = Symbol('kConstruct')\nfunction checkError(err, w, r) {\n  if (err) {\n    // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364\n    err.stack // eslint-disable-line no-unused-expressions\n\n    if (w && !w.errored) {\n      w.errored = err\n    }\n    if (r && !r.errored) {\n      r.errored = err\n    }\n  }\n}\n\n// Backwards compat. cb() is undocumented and unused in core but\n// unfortunately might be used by modules.\nfunction destroy(err, cb) {\n  const r = this._readableState\n  const w = this._writableState\n  // With duplex streams we use the writable side for state.\n  const s = w || r\n  if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) {\n    if (typeof cb === 'function') {\n      cb()\n    }\n    return this\n  }\n\n  // We set destroyed to true before firing error callbacks in order\n  // to make it re-entrance safe in case destroy() is called within callbacks\n  checkError(err, w, r)\n  if (w) {\n    w.destroyed = true\n  }\n  if (r) {\n    r.destroyed = true\n  }\n\n  // If still constructing then defer calling _destroy.\n  if (!s.constructed) {\n    this.once(kDestroy, function (er) {\n      _destroy(this, aggregateTwoErrors(er, err), cb)\n    })\n  } else {\n    _destroy(this, err, cb)\n  }\n  return this\n}\nfunction _destroy(self, err, cb) {\n  let called = false\n  function onDestroy(err) {\n    if (called) {\n      return\n    }\n    called = true\n    const r = self._readableState\n    const w = self._writableState\n    checkError(err, w, r)\n    if (w) {\n      w.closed = true\n    }\n    if (r) {\n      r.closed = true\n    }\n    if (typeof cb === 'function') {\n      cb(err)\n    }\n    if (err) {\n      process.nextTick(emitErrorCloseNT, self, err)\n    } else {\n      process.nextTick(emitCloseNT, self)\n    }\n  }\n  try {\n    self._destroy(err || null, onDestroy)\n  } catch (err) {\n    onDestroy(err)\n  }\n}\nfunction emitErrorCloseNT(self, err) {\n  emitErrorNT(self, err)\n  emitCloseNT(self)\n}\nfunction emitCloseNT(self) {\n  const r = self._readableState\n  const w = self._writableState\n  if (w) {\n    w.closeEmitted = true\n  }\n  if (r) {\n    r.closeEmitted = true\n  }\n  if ((w !== null && w !== undefined && w.emitClose) || (r !== null && r !== undefined && r.emitClose)) {\n    self.emit('close')\n  }\n}\nfunction emitErrorNT(self, err) {\n  const r = self._readableState\n  const w = self._writableState\n  if ((w !== null && w !== undefined && w.errorEmitted) || (r !== null && r !== undefined && r.errorEmitted)) {\n    return\n  }\n  if (w) {\n    w.errorEmitted = true\n  }\n  if (r) {\n    r.errorEmitted = true\n  }\n  self.emit('error', err)\n}\nfunction undestroy() {\n  const r = this._readableState\n  const w = this._writableState\n  if (r) {\n    r.constructed = true\n    r.closed = false\n    r.closeEmitted = false\n    r.destroyed = false\n    r.errored = null\n    r.errorEmitted = false\n    r.reading = false\n    r.ended = r.readable === false\n    r.endEmitted = r.readable === false\n  }\n  if (w) {\n    w.constructed = true\n    w.destroyed = false\n    w.closed = false\n    w.closeEmitted = false\n    w.errored = null\n    w.errorEmitted = false\n    w.finalCalled = false\n    w.prefinished = false\n    w.ended = w.writable === false\n    w.ending = w.writable === false\n    w.finished = w.writable === false\n  }\n}\nfunction errorOrDestroy(stream, err, sync) {\n  // We have tests that rely on errors being emitted\n  // in the same tick, so changing this is semver major.\n  // For now when you opt-in to autoDestroy we allow\n  // the error to be emitted nextTick. In a future\n  // semver major update we should change the default to this.\n\n  const r = stream._readableState\n  const w = stream._writableState\n  if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) {\n    return this\n  }\n  if ((r !== null && r !== undefined && r.autoDestroy) || (w !== null && w !== undefined && w.autoDestroy))\n    stream.destroy(err)\n  else if (err) {\n    // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364\n    err.stack // eslint-disable-line no-unused-expressions\n\n    if (w && !w.errored) {\n      w.errored = err\n    }\n    if (r && !r.errored) {\n      r.errored = err\n    }\n    if (sync) {\n      process.nextTick(emitErrorNT, stream, err)\n    } else {\n      emitErrorNT(stream, err)\n    }\n  }\n}\nfunction construct(stream, cb) {\n  if (typeof stream._construct !== 'function') {\n    return\n  }\n  const r = stream._readableState\n  const w = stream._writableState\n  if (r) {\n    r.constructed = false\n  }\n  if (w) {\n    w.constructed = false\n  }\n  stream.once(kConstruct, cb)\n  if (stream.listenerCount(kConstruct) > 1) {\n    // Duplex\n    return\n  }\n  process.nextTick(constructNT, stream)\n}\nfunction constructNT(stream) {\n  let called = false\n  function onConstruct(err) {\n    if (called) {\n      errorOrDestroy(stream, err !== null && err !== undefined ? err : new ERR_MULTIPLE_CALLBACK())\n      return\n    }\n    called = true\n    const r = stream._readableState\n    const w = stream._writableState\n    const s = w || r\n    if (r) {\n      r.constructed = true\n    }\n    if (w) {\n      w.constructed = true\n    }\n    if (s.destroyed) {\n      stream.emit(kDestroy, err)\n    } else if (err) {\n      errorOrDestroy(stream, err, true)\n    } else {\n      process.nextTick(emitConstructNT, stream)\n    }\n  }\n  try {\n    stream._construct((err) => {\n      process.nextTick(onConstruct, err)\n    })\n  } catch (err) {\n    process.nextTick(onConstruct, err)\n  }\n}\nfunction emitConstructNT(stream) {\n  stream.emit(kConstruct)\n}\nfunction isRequest(stream) {\n  return (stream === null || stream === undefined ? undefined : stream.setHeader) && typeof stream.abort === 'function'\n}\nfunction emitCloseLegacy(stream) {\n  stream.emit('close')\n}\nfunction emitErrorCloseLegacy(stream, err) {\n  stream.emit('error', err)\n  process.nextTick(emitCloseLegacy, stream)\n}\n\n// Normalize destroy for legacy.\nfunction destroyer(stream, err) {\n  if (!stream || isDestroyed(stream)) {\n    return\n  }\n  if (!err && !isFinished(stream)) {\n    err = new AbortError()\n  }\n\n  // TODO: Remove isRequest branches.\n  if (isServerRequest(stream)) {\n    stream.socket = null\n    stream.destroy(err)\n  } else if (isRequest(stream)) {\n    stream.abort()\n  } else if (isRequest(stream.req)) {\n    stream.req.abort()\n  } else if (typeof stream.destroy === 'function') {\n    stream.destroy(err)\n  } else if (typeof stream.close === 'function') {\n    // TODO: Don't lose err?\n    stream.close()\n  } else if (err) {\n    process.nextTick(emitErrorCloseLegacy, stream, err)\n  } else {\n    process.nextTick(emitCloseLegacy, stream)\n  }\n  if (!stream.destroyed) {\n    stream[kIsDestroyed] = true\n  }\n}\nmodule.exports = {\n  construct,\n  destroyer,\n  destroy,\n  undestroy,\n  errorOrDestroy\n}\n","'use strict'\n\nconst { ArrayIsArray, ObjectSetPrototypeOf } = require('../../ours/primordials')\nconst { EventEmitter: EE } = require('events')\nfunction Stream(opts) {\n  EE.call(this, opts)\n}\nObjectSetPrototypeOf(Stream.prototype, EE.prototype)\nObjectSetPrototypeOf(Stream, EE)\nStream.prototype.pipe = function (dest, options) {\n  const source = this\n  function ondata(chunk) {\n    if (dest.writable && dest.write(chunk) === false && source.pause) {\n      source.pause()\n    }\n  }\n  source.on('data', ondata)\n  function ondrain() {\n    if (source.readable && source.resume) {\n      source.resume()\n    }\n  }\n  dest.on('drain', ondrain)\n\n  // If the 'end' option is not supplied, dest.end() will be called when\n  // source gets the 'end' or 'close' events.  Only dest.end() once.\n  if (!dest._isStdio && (!options || options.end !== false)) {\n    source.on('end', onend)\n    source.on('close', onclose)\n  }\n  let didOnEnd = false\n  function onend() {\n    if (didOnEnd) return\n    didOnEnd = true\n    dest.end()\n  }\n  function onclose() {\n    if (didOnEnd) return\n    didOnEnd = true\n    if (typeof dest.destroy === 'function') dest.destroy()\n  }\n\n  // Don't leave dangling pipes when there are errors.\n  function onerror(er) {\n    cleanup()\n    if (EE.listenerCount(this, 'error') === 0) {\n      this.emit('error', er)\n    }\n  }\n  prependListener(source, 'error', onerror)\n  prependListener(dest, 'error', onerror)\n\n  // Remove all the event listeners that were added.\n  function cleanup() {\n    source.removeListener('data', ondata)\n    dest.removeListener('drain', ondrain)\n    source.removeListener('end', onend)\n    source.removeListener('close', onclose)\n    source.removeListener('error', onerror)\n    dest.removeListener('error', onerror)\n    source.removeListener('end', cleanup)\n    source.removeListener('close', cleanup)\n    dest.removeListener('close', cleanup)\n  }\n  source.on('end', cleanup)\n  source.on('close', cleanup)\n  dest.on('close', cleanup)\n  dest.emit('pipe', source)\n\n  // Allow for unix-like usage: A.pipe(B).pipe(C)\n  return dest\n}\nfunction prependListener(emitter, event, fn) {\n  // Sadly this is not cacheable as some libraries bundle their own\n  // event emitter implementation with them.\n  if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn)\n\n  // This is a hack to make sure that our error handler is attached before any\n  // userland ones.  NEVER DO THIS. This is here only because this code needs\n  // to continue to work with older versions of Node.js that do not include\n  // the prependListener() method. The goal is to eventually remove this hack.\n  if (!emitter._events || !emitter._events[event]) emitter.on(event, fn)\n  else if (ArrayIsArray(emitter._events[event])) emitter._events[event].unshift(fn)\n  else emitter._events[event] = [fn, emitter._events[event]]\n}\nmodule.exports = {\n  Stream,\n  prependListener\n}\n","'use strict'\n\nconst { SymbolDispose } = require('../../ours/primordials')\nconst { AbortError, codes } = require('../../ours/errors')\nconst { isNodeStream, isWebStream, kControllerErrorFunction } = require('./utils')\nconst eos = require('./end-of-stream')\nconst { ERR_INVALID_ARG_TYPE } = codes\nlet addAbortListener\n\n// This method is inlined here for readable-stream\n// It also does not allow for signal to not exist on the stream\n// https://github.com/nodejs/node/pull/36061#discussion_r533718029\nconst validateAbortSignal = (signal, name) => {\n  if (typeof signal !== 'object' || !('aborted' in signal)) {\n    throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal)\n  }\n}\nmodule.exports.addAbortSignal = function addAbortSignal(signal, stream) {\n  validateAbortSignal(signal, 'signal')\n  if (!isNodeStream(stream) && !isWebStream(stream)) {\n    throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream)\n  }\n  return module.exports.addAbortSignalNoValidate(signal, stream)\n}\nmodule.exports.addAbortSignalNoValidate = function (signal, stream) {\n  if (typeof signal !== 'object' || !('aborted' in signal)) {\n    return stream\n  }\n  const onAbort = isNodeStream(stream)\n    ? () => {\n        stream.destroy(\n          new AbortError(undefined, {\n            cause: signal.reason\n          })\n        )\n      }\n    : () => {\n        stream[kControllerErrorFunction](\n          new AbortError(undefined, {\n            cause: signal.reason\n          })\n        )\n      }\n  if (signal.aborted) {\n    onAbort()\n  } else {\n    addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n    const disposable = addAbortListener(signal, onAbort)\n    eos(stream, disposable[SymbolDispose])\n  }\n  return stream\n}\n","'use strict'\n\nconst { StringPrototypeSlice, SymbolIterator, TypedArrayPrototypeSet, Uint8Array } = require('../../ours/primordials')\nconst { Buffer } = require('buffer')\nconst { inspect } = require('../../ours/util')\nmodule.exports = class BufferList {\n  constructor() {\n    this.head = null\n    this.tail = null\n    this.length = 0\n  }\n  push(v) {\n    const entry = {\n      data: v,\n      next: null\n    }\n    if (this.length > 0) this.tail.next = entry\n    else this.head = entry\n    this.tail = entry\n    ++this.length\n  }\n  unshift(v) {\n    const entry = {\n      data: v,\n      next: this.head\n    }\n    if (this.length === 0) this.tail = entry\n    this.head = entry\n    ++this.length\n  }\n  shift() {\n    if (this.length === 0) return\n    const ret = this.head.data\n    if (this.length === 1) this.head = this.tail = null\n    else this.head = this.head.next\n    --this.length\n    return ret\n  }\n  clear() {\n    this.head = this.tail = null\n    this.length = 0\n  }\n  join(s) {\n    if (this.length === 0) return ''\n    let p = this.head\n    let ret = '' + p.data\n    while ((p = p.next) !== null) ret += s + p.data\n    return ret\n  }\n  concat(n) {\n    if (this.length === 0) return Buffer.alloc(0)\n    const ret = Buffer.allocUnsafe(n >>> 0)\n    let p = this.head\n    let i = 0\n    while (p) {\n      TypedArrayPrototypeSet(ret, p.data, i)\n      i += p.data.length\n      p = p.next\n    }\n    return ret\n  }\n\n  // Consumes a specified amount of bytes or characters from the buffered data.\n  consume(n, hasStrings) {\n    const data = this.head.data\n    if (n < data.length) {\n      // `slice` is the same for buffers and strings.\n      const slice = data.slice(0, n)\n      this.head.data = data.slice(n)\n      return slice\n    }\n    if (n === data.length) {\n      // First chunk is a perfect match.\n      return this.shift()\n    }\n    // Result spans more than one buffer.\n    return hasStrings ? this._getString(n) : this._getBuffer(n)\n  }\n  first() {\n    return this.head.data\n  }\n  *[SymbolIterator]() {\n    for (let p = this.head; p; p = p.next) {\n      yield p.data\n    }\n  }\n\n  // Consumes a specified amount of characters from the buffered data.\n  _getString(n) {\n    let ret = ''\n    let p = this.head\n    let c = 0\n    do {\n      const str = p.data\n      if (n > str.length) {\n        ret += str\n        n -= str.length\n      } else {\n        if (n === str.length) {\n          ret += str\n          ++c\n          if (p.next) this.head = p.next\n          else this.head = this.tail = null\n        } else {\n          ret += StringPrototypeSlice(str, 0, n)\n          this.head = p\n          p.data = StringPrototypeSlice(str, n)\n        }\n        break\n      }\n      ++c\n    } while ((p = p.next) !== null)\n    this.length -= c\n    return ret\n  }\n\n  // Consumes a specified amount of bytes from the buffered data.\n  _getBuffer(n) {\n    const ret = Buffer.allocUnsafe(n)\n    const retLen = n\n    let p = this.head\n    let c = 0\n    do {\n      const buf = p.data\n      if (n > buf.length) {\n        TypedArrayPrototypeSet(ret, buf, retLen - n)\n        n -= buf.length\n      } else {\n        if (n === buf.length) {\n          TypedArrayPrototypeSet(ret, buf, retLen - n)\n          ++c\n          if (p.next) this.head = p.next\n          else this.head = this.tail = null\n        } else {\n          TypedArrayPrototypeSet(ret, new Uint8Array(buf.buffer, buf.byteOffset, n), retLen - n)\n          this.head = p\n          p.data = buf.slice(n)\n        }\n        break\n      }\n      ++c\n    } while ((p = p.next) !== null)\n    this.length -= c\n    return ret\n  }\n\n  // Make sure the linked list only shows the minimal necessary information.\n  [Symbol.for('nodejs.util.inspect.custom')](_, options) {\n    return inspect(this, {\n      ...options,\n      // Only inspect one level.\n      depth: 0,\n      // It should not recurse.\n      customInspect: false\n    })\n  }\n}\n","'use strict'\n\nconst { MathFloor, NumberIsInteger } = require('../../ours/primordials')\nconst { validateInteger } = require('../validators')\nconst { ERR_INVALID_ARG_VALUE } = require('../../ours/errors').codes\nlet defaultHighWaterMarkBytes = 16 * 1024\nlet defaultHighWaterMarkObjectMode = 16\nfunction highWaterMarkFrom(options, isDuplex, duplexKey) {\n  return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null\n}\nfunction getDefaultHighWaterMark(objectMode) {\n  return objectMode ? defaultHighWaterMarkObjectMode : defaultHighWaterMarkBytes\n}\nfunction setDefaultHighWaterMark(objectMode, value) {\n  validateInteger(value, 'value', 0)\n  if (objectMode) {\n    defaultHighWaterMarkObjectMode = value\n  } else {\n    defaultHighWaterMarkBytes = value\n  }\n}\nfunction getHighWaterMark(state, options, duplexKey, isDuplex) {\n  const hwm = highWaterMarkFrom(options, isDuplex, duplexKey)\n  if (hwm != null) {\n    if (!NumberIsInteger(hwm) || hwm < 0) {\n      const name = isDuplex ? `options.${duplexKey}` : 'options.highWaterMark'\n      throw new ERR_INVALID_ARG_VALUE(name, hwm)\n    }\n    return MathFloor(hwm)\n  }\n\n  // Default value\n  return getDefaultHighWaterMark(state.objectMode)\n}\nmodule.exports = {\n  getHighWaterMark,\n  getDefaultHighWaterMark,\n  setDefaultHighWaterMark\n}\n","/*! safe-buffer. MIT License. Feross Aboukhadijeh  */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n  for (var key in src) {\n    dst[key] = src[key]\n  }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n  module.exports = buffer\n} else {\n  // Copy properties from require('buffer')\n  copyProps(buffer, exports)\n  exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n  return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n  if (typeof arg === 'number') {\n    throw new TypeError('Argument must not be a number')\n  }\n  return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n  if (typeof size !== 'number') {\n    throw new TypeError('Argument must be a number')\n  }\n  var buf = Buffer(size)\n  if (fill !== undefined) {\n    if (typeof encoding === 'string') {\n      buf.fill(fill, encoding)\n    } else {\n      buf.fill(fill)\n    }\n  } else {\n    buf.fill(0)\n  }\n  return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n  if (typeof size !== 'number') {\n    throw new TypeError('Argument must be a number')\n  }\n  return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n  if (typeof size !== 'number') {\n    throw new TypeError('Argument must be a number')\n  }\n  return buffer.SlowBuffer(size)\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n  encoding = '' + encoding;\n  switch (encoding && encoding.toLowerCase()) {\n    case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n      return true;\n    default:\n      return false;\n  }\n};\n\nfunction _normalizeEncoding(enc) {\n  if (!enc) return 'utf8';\n  var retried;\n  while (true) {\n    switch (enc) {\n      case 'utf8':\n      case 'utf-8':\n        return 'utf8';\n      case 'ucs2':\n      case 'ucs-2':\n      case 'utf16le':\n      case 'utf-16le':\n        return 'utf16le';\n      case 'latin1':\n      case 'binary':\n        return 'latin1';\n      case 'base64':\n      case 'ascii':\n      case 'hex':\n        return enc;\n      default:\n        if (retried) return; // undefined\n        enc = ('' + enc).toLowerCase();\n        retried = true;\n    }\n  }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n  var nenc = _normalizeEncoding(enc);\n  if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n  return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n  this.encoding = normalizeEncoding(encoding);\n  var nb;\n  switch (this.encoding) {\n    case 'utf16le':\n      this.text = utf16Text;\n      this.end = utf16End;\n      nb = 4;\n      break;\n    case 'utf8':\n      this.fillLast = utf8FillLast;\n      nb = 4;\n      break;\n    case 'base64':\n      this.text = base64Text;\n      this.end = base64End;\n      nb = 3;\n      break;\n    default:\n      this.write = simpleWrite;\n      this.end = simpleEnd;\n      return;\n  }\n  this.lastNeed = 0;\n  this.lastTotal = 0;\n  this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n  if (buf.length === 0) return '';\n  var r;\n  var i;\n  if (this.lastNeed) {\n    r = this.fillLast(buf);\n    if (r === undefined) return '';\n    i = this.lastNeed;\n    this.lastNeed = 0;\n  } else {\n    i = 0;\n  }\n  if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n  return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n  if (this.lastNeed <= buf.length) {\n    buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n    return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n  }\n  buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n  this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n  if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n  return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n  var j = buf.length - 1;\n  if (j < i) return 0;\n  var nb = utf8CheckByte(buf[j]);\n  if (nb >= 0) {\n    if (nb > 0) self.lastNeed = nb - 1;\n    return nb;\n  }\n  if (--j < i || nb === -2) return 0;\n  nb = utf8CheckByte(buf[j]);\n  if (nb >= 0) {\n    if (nb > 0) self.lastNeed = nb - 2;\n    return nb;\n  }\n  if (--j < i || nb === -2) return 0;\n  nb = utf8CheckByte(buf[j]);\n  if (nb >= 0) {\n    if (nb > 0) {\n      if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n    }\n    return nb;\n  }\n  return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n  if ((buf[0] & 0xC0) !== 0x80) {\n    self.lastNeed = 0;\n    return '\\ufffd';\n  }\n  if (self.lastNeed > 1 && buf.length > 1) {\n    if ((buf[1] & 0xC0) !== 0x80) {\n      self.lastNeed = 1;\n      return '\\ufffd';\n    }\n    if (self.lastNeed > 2 && buf.length > 2) {\n      if ((buf[2] & 0xC0) !== 0x80) {\n        self.lastNeed = 2;\n        return '\\ufffd';\n      }\n    }\n  }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n  var p = this.lastTotal - this.lastNeed;\n  var r = utf8CheckExtraBytes(this, buf, p);\n  if (r !== undefined) return r;\n  if (this.lastNeed <= buf.length) {\n    buf.copy(this.lastChar, p, 0, this.lastNeed);\n    return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n  }\n  buf.copy(this.lastChar, p, 0, buf.length);\n  this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n  var total = utf8CheckIncomplete(this, buf, i);\n  if (!this.lastNeed) return buf.toString('utf8', i);\n  this.lastTotal = total;\n  var end = buf.length - (total - this.lastNeed);\n  buf.copy(this.lastChar, 0, end);\n  return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n  var r = buf && buf.length ? this.write(buf) : '';\n  if (this.lastNeed) return r + '\\ufffd';\n  return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n  if ((buf.length - i) % 2 === 0) {\n    var r = buf.toString('utf16le', i);\n    if (r) {\n      var c = r.charCodeAt(r.length - 1);\n      if (c >= 0xD800 && c <= 0xDBFF) {\n        this.lastNeed = 2;\n        this.lastTotal = 4;\n        this.lastChar[0] = buf[buf.length - 2];\n        this.lastChar[1] = buf[buf.length - 1];\n        return r.slice(0, -1);\n      }\n    }\n    return r;\n  }\n  this.lastNeed = 1;\n  this.lastTotal = 2;\n  this.lastChar[0] = buf[buf.length - 1];\n  return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n  var r = buf && buf.length ? this.write(buf) : '';\n  if (this.lastNeed) {\n    var end = this.lastTotal - this.lastNeed;\n    return r + this.lastChar.toString('utf16le', 0, end);\n  }\n  return r;\n}\n\nfunction base64Text(buf, i) {\n  var n = (buf.length - i) % 3;\n  if (n === 0) return buf.toString('base64', i);\n  this.lastNeed = 3 - n;\n  this.lastTotal = 3;\n  if (n === 1) {\n    this.lastChar[0] = buf[buf.length - 1];\n  } else {\n    this.lastChar[0] = buf[buf.length - 2];\n    this.lastChar[1] = buf[buf.length - 1];\n  }\n  return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n  var r = buf && buf.length ? this.write(buf) : '';\n  if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n  return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n  return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n  return buf && buf.length ? this.write(buf) : '';\n}","'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } = require('../../ours/primordials')\nconst { Buffer } = require('buffer')\nconst { ERR_INVALID_ARG_TYPE, ERR_STREAM_NULL_VALUES } = require('../../ours/errors').codes\nfunction from(Readable, iterable, opts) {\n  let iterator\n  if (typeof iterable === 'string' || iterable instanceof Buffer) {\n    return new Readable({\n      objectMode: true,\n      ...opts,\n      read() {\n        this.push(iterable)\n        this.push(null)\n      }\n    })\n  }\n  let isAsync\n  if (iterable && iterable[SymbolAsyncIterator]) {\n    isAsync = true\n    iterator = iterable[SymbolAsyncIterator]()\n  } else if (iterable && iterable[SymbolIterator]) {\n    isAsync = false\n    iterator = iterable[SymbolIterator]()\n  } else {\n    throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable)\n  }\n  const readable = new Readable({\n    objectMode: true,\n    highWaterMark: 1,\n    // TODO(ronag): What options should be allowed?\n    ...opts\n  })\n\n  // Flag to protect against _read\n  // being called before last iteration completion.\n  let reading = false\n  readable._read = function () {\n    if (!reading) {\n      reading = true\n      next()\n    }\n  }\n  readable._destroy = function (error, cb) {\n    PromisePrototypeThen(\n      close(error),\n      () => process.nextTick(cb, error),\n      // nextTick is here in case cb throws\n      (e) => process.nextTick(cb, e || error)\n    )\n  }\n  async function close(error) {\n    const hadError = error !== undefined && error !== null\n    const hasThrow = typeof iterator.throw === 'function'\n    if (hadError && hasThrow) {\n      const { value, done } = await iterator.throw(error)\n      await value\n      if (done) {\n        return\n      }\n    }\n    if (typeof iterator.return === 'function') {\n      const { value } = await iterator.return()\n      await value\n    }\n  }\n  async function next() {\n    for (;;) {\n      try {\n        const { value, done } = isAsync ? await iterator.next() : iterator.next()\n        if (done) {\n          readable.push(null)\n        } else {\n          const res = value && typeof value.then === 'function' ? await value : value\n          if (res === null) {\n            reading = false\n            throw new ERR_STREAM_NULL_VALUES()\n          } else if (readable.push(res)) {\n            continue\n          } else {\n            reading = false\n          }\n        }\n      } catch (err) {\n        readable.destroy(err)\n      }\n      break\n    }\n  }\n  return readable\n}\nmodule.exports = from\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst {\n  ArrayPrototypeIndexOf,\n  NumberIsInteger,\n  NumberIsNaN,\n  NumberParseInt,\n  ObjectDefineProperties,\n  ObjectKeys,\n  ObjectSetPrototypeOf,\n  Promise,\n  SafeSet,\n  SymbolAsyncDispose,\n  SymbolAsyncIterator,\n  Symbol\n} = require('../../ours/primordials')\nmodule.exports = Readable\nReadable.ReadableState = ReadableState\nconst { EventEmitter: EE } = require('events')\nconst { Stream, prependListener } = require('./legacy')\nconst { Buffer } = require('buffer')\nconst { addAbortSignal } = require('./add-abort-signal')\nconst eos = require('./end-of-stream')\nlet debug = require('../../ours/util').debuglog('stream', (fn) => {\n  debug = fn\n})\nconst BufferList = require('./buffer_list')\nconst destroyImpl = require('./destroy')\nconst { getHighWaterMark, getDefaultHighWaterMark } = require('./state')\nconst {\n  aggregateTwoErrors,\n  codes: {\n    ERR_INVALID_ARG_TYPE,\n    ERR_METHOD_NOT_IMPLEMENTED,\n    ERR_OUT_OF_RANGE,\n    ERR_STREAM_PUSH_AFTER_EOF,\n    ERR_STREAM_UNSHIFT_AFTER_END_EVENT\n  },\n  AbortError\n} = require('../../ours/errors')\nconst { validateObject } = require('../validators')\nconst kPaused = Symbol('kPaused')\nconst { StringDecoder } = require('string_decoder/')\nconst from = require('./from')\nObjectSetPrototypeOf(Readable.prototype, Stream.prototype)\nObjectSetPrototypeOf(Readable, Stream)\nconst nop = () => {}\nconst { errorOrDestroy } = destroyImpl\nconst kObjectMode = 1 << 0\nconst kEnded = 1 << 1\nconst kEndEmitted = 1 << 2\nconst kReading = 1 << 3\nconst kConstructed = 1 << 4\nconst kSync = 1 << 5\nconst kNeedReadable = 1 << 6\nconst kEmittedReadable = 1 << 7\nconst kReadableListening = 1 << 8\nconst kResumeScheduled = 1 << 9\nconst kErrorEmitted = 1 << 10\nconst kEmitClose = 1 << 11\nconst kAutoDestroy = 1 << 12\nconst kDestroyed = 1 << 13\nconst kClosed = 1 << 14\nconst kCloseEmitted = 1 << 15\nconst kMultiAwaitDrain = 1 << 16\nconst kReadingMore = 1 << 17\nconst kDataEmitted = 1 << 18\n\n// TODO(benjamingr) it is likely slower to do it this way than with free functions\nfunction makeBitMapDescriptor(bit) {\n  return {\n    enumerable: false,\n    get() {\n      return (this.state & bit) !== 0\n    },\n    set(value) {\n      if (value) this.state |= bit\n      else this.state &= ~bit\n    }\n  }\n}\nObjectDefineProperties(ReadableState.prototype, {\n  objectMode: makeBitMapDescriptor(kObjectMode),\n  ended: makeBitMapDescriptor(kEnded),\n  endEmitted: makeBitMapDescriptor(kEndEmitted),\n  reading: makeBitMapDescriptor(kReading),\n  // Stream is still being constructed and cannot be\n  // destroyed until construction finished or failed.\n  // Async construction is opt in, therefore we start as\n  // constructed.\n  constructed: makeBitMapDescriptor(kConstructed),\n  // A flag to be able to tell if the event 'readable'/'data' is emitted\n  // immediately, or on a later tick.  We set this to true at first, because\n  // any actions that shouldn't happen until \"later\" should generally also\n  // not happen before the first read call.\n  sync: makeBitMapDescriptor(kSync),\n  // Whenever we return null, then we set a flag to say\n  // that we're awaiting a 'readable' event emission.\n  needReadable: makeBitMapDescriptor(kNeedReadable),\n  emittedReadable: makeBitMapDescriptor(kEmittedReadable),\n  readableListening: makeBitMapDescriptor(kReadableListening),\n  resumeScheduled: makeBitMapDescriptor(kResumeScheduled),\n  // True if the error was already emitted and should not be thrown again.\n  errorEmitted: makeBitMapDescriptor(kErrorEmitted),\n  emitClose: makeBitMapDescriptor(kEmitClose),\n  autoDestroy: makeBitMapDescriptor(kAutoDestroy),\n  // Has it been destroyed.\n  destroyed: makeBitMapDescriptor(kDestroyed),\n  // Indicates whether the stream has finished destroying.\n  closed: makeBitMapDescriptor(kClosed),\n  // True if close has been emitted or would have been emitted\n  // depending on emitClose.\n  closeEmitted: makeBitMapDescriptor(kCloseEmitted),\n  multiAwaitDrain: makeBitMapDescriptor(kMultiAwaitDrain),\n  // If true, a maybeReadMore has been scheduled.\n  readingMore: makeBitMapDescriptor(kReadingMore),\n  dataEmitted: makeBitMapDescriptor(kDataEmitted)\n})\nfunction ReadableState(options, stream, isDuplex) {\n  // Duplex streams are both readable and writable, but share\n  // the same options object.\n  // However, some cases require setting options to different\n  // values for the readable and the writable sides of the duplex stream.\n  // These options can be provided separately as readableXXX and writableXXX.\n  if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof require('./duplex')\n\n  // Bit map field to store ReadableState more effciently with 1 bit per field\n  // instead of a V8 slot per field.\n  this.state = kEmitClose | kAutoDestroy | kConstructed | kSync\n  // Object stream flag. Used to make read(n) ignore n and to\n  // make all the buffer merging and length checks go away.\n  if (options && options.objectMode) this.state |= kObjectMode\n  if (isDuplex && options && options.readableObjectMode) this.state |= kObjectMode\n\n  // The point at which it stops calling _read() to fill the buffer\n  // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n  this.highWaterMark = options\n    ? getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex)\n    : getDefaultHighWaterMark(false)\n\n  // A linked list is used to store data chunks instead of an array because the\n  // linked list can remove elements from the beginning faster than\n  // array.shift().\n  this.buffer = new BufferList()\n  this.length = 0\n  this.pipes = []\n  this.flowing = null\n  this[kPaused] = null\n\n  // Should close be emitted on destroy. Defaults to true.\n  if (options && options.emitClose === false) this.state &= ~kEmitClose\n\n  // Should .destroy() be called after 'end' (and potentially 'finish').\n  if (options && options.autoDestroy === false) this.state &= ~kAutoDestroy\n\n  // Indicates whether the stream has errored. When true no further\n  // _read calls, 'data' or 'readable' events should occur. This is needed\n  // since when autoDestroy is disabled we need a way to tell whether the\n  // stream has failed.\n  this.errored = null\n\n  // Crypto is kind of old and crusty.  Historically, its default string\n  // encoding is 'binary' so we have to make this configurable.\n  // Everything else in the universe uses 'utf8', though.\n  this.defaultEncoding = (options && options.defaultEncoding) || 'utf8'\n\n  // Ref the piped dest which we need a drain event on it\n  // type: null | Writable | Set.\n  this.awaitDrainWriters = null\n  this.decoder = null\n  this.encoding = null\n  if (options && options.encoding) {\n    this.decoder = new StringDecoder(options.encoding)\n    this.encoding = options.encoding\n  }\n}\nfunction Readable(options) {\n  if (!(this instanceof Readable)) return new Readable(options)\n\n  // Checking for a Stream.Duplex instance is faster here instead of inside\n  // the ReadableState constructor, at least with V8 6.5.\n  const isDuplex = this instanceof require('./duplex')\n  this._readableState = new ReadableState(options, this, isDuplex)\n  if (options) {\n    if (typeof options.read === 'function') this._read = options.read\n    if (typeof options.destroy === 'function') this._destroy = options.destroy\n    if (typeof options.construct === 'function') this._construct = options.construct\n    if (options.signal && !isDuplex) addAbortSignal(options.signal, this)\n  }\n  Stream.call(this, options)\n  destroyImpl.construct(this, () => {\n    if (this._readableState.needReadable) {\n      maybeReadMore(this, this._readableState)\n    }\n  })\n}\nReadable.prototype.destroy = destroyImpl.destroy\nReadable.prototype._undestroy = destroyImpl.undestroy\nReadable.prototype._destroy = function (err, cb) {\n  cb(err)\n}\nReadable.prototype[EE.captureRejectionSymbol] = function (err) {\n  this.destroy(err)\n}\nReadable.prototype[SymbolAsyncDispose] = function () {\n  let error\n  if (!this.destroyed) {\n    error = this.readableEnded ? null : new AbortError()\n    this.destroy(error)\n  }\n  return new Promise((resolve, reject) => eos(this, (err) => (err && err !== error ? reject(err) : resolve(null))))\n}\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n  return readableAddChunk(this, chunk, encoding, false)\n}\n\n// Unshift should *always* be something directly out of read().\nReadable.prototype.unshift = function (chunk, encoding) {\n  return readableAddChunk(this, chunk, encoding, true)\n}\nfunction readableAddChunk(stream, chunk, encoding, addToFront) {\n  debug('readableAddChunk', chunk)\n  const state = stream._readableState\n  let err\n  if ((state.state & kObjectMode) === 0) {\n    if (typeof chunk === 'string') {\n      encoding = encoding || state.defaultEncoding\n      if (state.encoding !== encoding) {\n        if (addToFront && state.encoding) {\n          // When unshifting, if state.encoding is set, we have to save\n          // the string in the BufferList with the state encoding.\n          chunk = Buffer.from(chunk, encoding).toString(state.encoding)\n        } else {\n          chunk = Buffer.from(chunk, encoding)\n          encoding = ''\n        }\n      }\n    } else if (chunk instanceof Buffer) {\n      encoding = ''\n    } else if (Stream._isUint8Array(chunk)) {\n      chunk = Stream._uint8ArrayToBuffer(chunk)\n      encoding = ''\n    } else if (chunk != null) {\n      err = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk)\n    }\n  }\n  if (err) {\n    errorOrDestroy(stream, err)\n  } else if (chunk === null) {\n    state.state &= ~kReading\n    onEofChunk(stream, state)\n  } else if ((state.state & kObjectMode) !== 0 || (chunk && chunk.length > 0)) {\n    if (addToFront) {\n      if ((state.state & kEndEmitted) !== 0) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT())\n      else if (state.destroyed || state.errored) return false\n      else addChunk(stream, state, chunk, true)\n    } else if (state.ended) {\n      errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF())\n    } else if (state.destroyed || state.errored) {\n      return false\n    } else {\n      state.state &= ~kReading\n      if (state.decoder && !encoding) {\n        chunk = state.decoder.write(chunk)\n        if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false)\n        else maybeReadMore(stream, state)\n      } else {\n        addChunk(stream, state, chunk, false)\n      }\n    }\n  } else if (!addToFront) {\n    state.state &= ~kReading\n    maybeReadMore(stream, state)\n  }\n\n  // We can push more data if we are below the highWaterMark.\n  // Also, if we have no data yet, we can stand some more bytes.\n  // This is to work around cases where hwm=0, such as the repl.\n  return !state.ended && (state.length < state.highWaterMark || state.length === 0)\n}\nfunction addChunk(stream, state, chunk, addToFront) {\n  if (state.flowing && state.length === 0 && !state.sync && stream.listenerCount('data') > 0) {\n    // Use the guard to avoid creating `Set()` repeatedly\n    // when we have multiple pipes.\n    if ((state.state & kMultiAwaitDrain) !== 0) {\n      state.awaitDrainWriters.clear()\n    } else {\n      state.awaitDrainWriters = null\n    }\n    state.dataEmitted = true\n    stream.emit('data', chunk)\n  } else {\n    // Update the buffer info.\n    state.length += state.objectMode ? 1 : chunk.length\n    if (addToFront) state.buffer.unshift(chunk)\n    else state.buffer.push(chunk)\n    if ((state.state & kNeedReadable) !== 0) emitReadable(stream)\n  }\n  maybeReadMore(stream, state)\n}\nReadable.prototype.isPaused = function () {\n  const state = this._readableState\n  return state[kPaused] === true || state.flowing === false\n}\n\n// Backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n  const decoder = new StringDecoder(enc)\n  this._readableState.decoder = decoder\n  // If setEncoding(null), decoder.encoding equals utf8.\n  this._readableState.encoding = this._readableState.decoder.encoding\n  const buffer = this._readableState.buffer\n  // Iterate over current buffer to convert already stored Buffers:\n  let content = ''\n  for (const data of buffer) {\n    content += decoder.write(data)\n  }\n  buffer.clear()\n  if (content !== '') buffer.push(content)\n  this._readableState.length = content.length\n  return this\n}\n\n// Don't raise the hwm > 1GB.\nconst MAX_HWM = 0x40000000\nfunction computeNewHighWaterMark(n) {\n  if (n > MAX_HWM) {\n    throw new ERR_OUT_OF_RANGE('size', '<= 1GiB', n)\n  } else {\n    // Get the next highest power of 2 to prevent increasing hwm excessively in\n    // tiny amounts.\n    n--\n    n |= n >>> 1\n    n |= n >>> 2\n    n |= n >>> 4\n    n |= n >>> 8\n    n |= n >>> 16\n    n++\n  }\n  return n\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n  if (n <= 0 || (state.length === 0 && state.ended)) return 0\n  if ((state.state & kObjectMode) !== 0) return 1\n  if (NumberIsNaN(n)) {\n    // Only flow one buffer at a time.\n    if (state.flowing && state.length) return state.buffer.first().length\n    return state.length\n  }\n  if (n <= state.length) return n\n  return state.ended ? state.length : 0\n}\n\n// You can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n  debug('read', n)\n  // Same as parseInt(undefined, 10), however V8 7.3 performance regressed\n  // in this scenario, so we are doing it manually.\n  if (n === undefined) {\n    n = NaN\n  } else if (!NumberIsInteger(n)) {\n    n = NumberParseInt(n, 10)\n  }\n  const state = this._readableState\n  const nOrig = n\n\n  // If we're asking for more than the current hwm, then raise the hwm.\n  if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n)\n  if (n !== 0) state.state &= ~kEmittedReadable\n\n  // If we're doing read(0) to trigger a readable event, but we\n  // already have a bunch of data in the buffer, then just trigger\n  // the 'readable' event and move on.\n  if (\n    n === 0 &&\n    state.needReadable &&\n    ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)\n  ) {\n    debug('read: emitReadable', state.length, state.ended)\n    if (state.length === 0 && state.ended) endReadable(this)\n    else emitReadable(this)\n    return null\n  }\n  n = howMuchToRead(n, state)\n\n  // If we've ended, and we're now clear, then finish it up.\n  if (n === 0 && state.ended) {\n    if (state.length === 0) endReadable(this)\n    return null\n  }\n\n  // All the actual chunk generation logic needs to be\n  // *below* the call to _read.  The reason is that in certain\n  // synthetic stream cases, such as passthrough streams, _read\n  // may be a completely synchronous operation which may change\n  // the state of the read buffer, providing enough data when\n  // before there was *not* enough.\n  //\n  // So, the steps are:\n  // 1. Figure out what the state of things will be after we do\n  // a read from the buffer.\n  //\n  // 2. If that resulting state will trigger a _read, then call _read.\n  // Note that this may be asynchronous, or synchronous.  Yes, it is\n  // deeply ugly to write APIs this way, but that still doesn't mean\n  // that the Readable class should behave improperly, as streams are\n  // designed to be sync/async agnostic.\n  // Take note if the _read call is sync or async (ie, if the read call\n  // has returned yet), so that we know whether or not it's safe to emit\n  // 'readable' etc.\n  //\n  // 3. Actually pull the requested chunks out of the buffer and return.\n\n  // if we need a readable event, then we need to do some reading.\n  let doRead = (state.state & kNeedReadable) !== 0\n  debug('need readable', doRead)\n\n  // If we currently have less than the highWaterMark, then also read some.\n  if (state.length === 0 || state.length - n < state.highWaterMark) {\n    doRead = true\n    debug('length less than watermark', doRead)\n  }\n\n  // However, if we've ended, then there's no point, if we're already\n  // reading, then it's unnecessary, if we're constructing we have to wait,\n  // and if we're destroyed or errored, then it's not allowed,\n  if (state.ended || state.reading || state.destroyed || state.errored || !state.constructed) {\n    doRead = false\n    debug('reading, ended or constructing', doRead)\n  } else if (doRead) {\n    debug('do read')\n    state.state |= kReading | kSync\n    // If the length is currently zero, then we *need* a readable event.\n    if (state.length === 0) state.state |= kNeedReadable\n\n    // Call internal read method\n    try {\n      this._read(state.highWaterMark)\n    } catch (err) {\n      errorOrDestroy(this, err)\n    }\n    state.state &= ~kSync\n\n    // If _read pushed data synchronously, then `reading` will be false,\n    // and we need to re-evaluate how much data we can return to the user.\n    if (!state.reading) n = howMuchToRead(nOrig, state)\n  }\n  let ret\n  if (n > 0) ret = fromList(n, state)\n  else ret = null\n  if (ret === null) {\n    state.needReadable = state.length <= state.highWaterMark\n    n = 0\n  } else {\n    state.length -= n\n    if (state.multiAwaitDrain) {\n      state.awaitDrainWriters.clear()\n    } else {\n      state.awaitDrainWriters = null\n    }\n  }\n  if (state.length === 0) {\n    // If we have nothing in the buffer, then we want to know\n    // as soon as we *do* get something into the buffer.\n    if (!state.ended) state.needReadable = true\n\n    // If we tried to read() past the EOF, then emit end on the next tick.\n    if (nOrig !== n && state.ended) endReadable(this)\n  }\n  if (ret !== null && !state.errorEmitted && !state.closeEmitted) {\n    state.dataEmitted = true\n    this.emit('data', ret)\n  }\n  return ret\n}\nfunction onEofChunk(stream, state) {\n  debug('onEofChunk')\n  if (state.ended) return\n  if (state.decoder) {\n    const chunk = state.decoder.end()\n    if (chunk && chunk.length) {\n      state.buffer.push(chunk)\n      state.length += state.objectMode ? 1 : chunk.length\n    }\n  }\n  state.ended = true\n  if (state.sync) {\n    // If we are sync, wait until next tick to emit the data.\n    // Otherwise we risk emitting data in the flow()\n    // the readable code triggers during a read() call.\n    emitReadable(stream)\n  } else {\n    // Emit 'readable' now to make sure it gets picked up.\n    state.needReadable = false\n    state.emittedReadable = true\n    // We have to emit readable now that we are EOF. Modules\n    // in the ecosystem (e.g. dicer) rely on this event being sync.\n    emitReadable_(stream)\n  }\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow.  This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n  const state = stream._readableState\n  debug('emitReadable', state.needReadable, state.emittedReadable)\n  state.needReadable = false\n  if (!state.emittedReadable) {\n    debug('emitReadable', state.flowing)\n    state.emittedReadable = true\n    process.nextTick(emitReadable_, stream)\n  }\n}\nfunction emitReadable_(stream) {\n  const state = stream._readableState\n  debug('emitReadable_', state.destroyed, state.length, state.ended)\n  if (!state.destroyed && !state.errored && (state.length || state.ended)) {\n    stream.emit('readable')\n    state.emittedReadable = false\n  }\n\n  // The stream needs another readable event if:\n  // 1. It is not flowing, as the flow mechanism will take\n  //    care of it.\n  // 2. It is not ended.\n  // 3. It is below the highWaterMark, so we can schedule\n  //    another readable later.\n  state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark\n  flow(stream)\n}\n\n// At this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data.  that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n  if (!state.readingMore && state.constructed) {\n    state.readingMore = true\n    process.nextTick(maybeReadMore_, stream, state)\n  }\n}\nfunction maybeReadMore_(stream, state) {\n  // Attempt to read more data if we should.\n  //\n  // The conditions for reading more data are (one of):\n  // - Not enough data buffered (state.length < state.highWaterMark). The loop\n  //   is responsible for filling the buffer with enough data if such data\n  //   is available. If highWaterMark is 0 and we are not in the flowing mode\n  //   we should _not_ attempt to buffer any extra data. We'll get more data\n  //   when the stream consumer calls read() instead.\n  // - No data in the buffer, and the stream is in flowing mode. In this mode\n  //   the loop below is responsible for ensuring read() is called. Failing to\n  //   call read here would abort the flow and there's no other mechanism for\n  //   continuing the flow if the stream consumer has just subscribed to the\n  //   'data' event.\n  //\n  // In addition to the above conditions to keep reading data, the following\n  // conditions prevent the data from being read:\n  // - The stream has ended (state.ended).\n  // - There is already a pending 'read' operation (state.reading). This is a\n  //   case where the stream has called the implementation defined _read()\n  //   method, but they are processing the call asynchronously and have _not_\n  //   called push() with new data. In this case we skip performing more\n  //   read()s. The execution ends in this method again after the _read() ends\n  //   up calling push() with more data.\n  while (\n    !state.reading &&\n    !state.ended &&\n    (state.length < state.highWaterMark || (state.flowing && state.length === 0))\n  ) {\n    const len = state.length\n    debug('maybeReadMore read 0')\n    stream.read(0)\n    if (len === state.length)\n      // Didn't get any data, stop spinning.\n      break\n  }\n  state.readingMore = false\n}\n\n// Abstract method.  to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n  throw new ERR_METHOD_NOT_IMPLEMENTED('_read()')\n}\nReadable.prototype.pipe = function (dest, pipeOpts) {\n  const src = this\n  const state = this._readableState\n  if (state.pipes.length === 1) {\n    if (!state.multiAwaitDrain) {\n      state.multiAwaitDrain = true\n      state.awaitDrainWriters = new SafeSet(state.awaitDrainWriters ? [state.awaitDrainWriters] : [])\n    }\n  }\n  state.pipes.push(dest)\n  debug('pipe count=%d opts=%j', state.pipes.length, pipeOpts)\n  const doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr\n  const endFn = doEnd ? onend : unpipe\n  if (state.endEmitted) process.nextTick(endFn)\n  else src.once('end', endFn)\n  dest.on('unpipe', onunpipe)\n  function onunpipe(readable, unpipeInfo) {\n    debug('onunpipe')\n    if (readable === src) {\n      if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n        unpipeInfo.hasUnpiped = true\n        cleanup()\n      }\n    }\n  }\n  function onend() {\n    debug('onend')\n    dest.end()\n  }\n  let ondrain\n  let cleanedUp = false\n  function cleanup() {\n    debug('cleanup')\n    // Cleanup event handlers once the pipe is broken.\n    dest.removeListener('close', onclose)\n    dest.removeListener('finish', onfinish)\n    if (ondrain) {\n      dest.removeListener('drain', ondrain)\n    }\n    dest.removeListener('error', onerror)\n    dest.removeListener('unpipe', onunpipe)\n    src.removeListener('end', onend)\n    src.removeListener('end', unpipe)\n    src.removeListener('data', ondata)\n    cleanedUp = true\n\n    // If the reader is waiting for a drain event from this\n    // specific writer, then it would cause it to never start\n    // flowing again.\n    // So, if this is awaiting a drain, then we just call it now.\n    // If we don't know, then assume that we are waiting for one.\n    if (ondrain && state.awaitDrainWriters && (!dest._writableState || dest._writableState.needDrain)) ondrain()\n  }\n  function pause() {\n    // If the user unpiped during `dest.write()`, it is possible\n    // to get stuck in a permanently paused state if that write\n    // also returned false.\n    // => Check whether `dest` is still a piping destination.\n    if (!cleanedUp) {\n      if (state.pipes.length === 1 && state.pipes[0] === dest) {\n        debug('false write response, pause', 0)\n        state.awaitDrainWriters = dest\n        state.multiAwaitDrain = false\n      } else if (state.pipes.length > 1 && state.pipes.includes(dest)) {\n        debug('false write response, pause', state.awaitDrainWriters.size)\n        state.awaitDrainWriters.add(dest)\n      }\n      src.pause()\n    }\n    if (!ondrain) {\n      // When the dest drains, it reduces the awaitDrain counter\n      // on the source.  This would be more elegant with a .once()\n      // handler in flow(), but adding and removing repeatedly is\n      // too slow.\n      ondrain = pipeOnDrain(src, dest)\n      dest.on('drain', ondrain)\n    }\n  }\n  src.on('data', ondata)\n  function ondata(chunk) {\n    debug('ondata')\n    const ret = dest.write(chunk)\n    debug('dest.write', ret)\n    if (ret === false) {\n      pause()\n    }\n  }\n\n  // If the dest has an error, then stop piping into it.\n  // However, don't suppress the throwing behavior for this.\n  function onerror(er) {\n    debug('onerror', er)\n    unpipe()\n    dest.removeListener('error', onerror)\n    if (dest.listenerCount('error') === 0) {\n      const s = dest._writableState || dest._readableState\n      if (s && !s.errorEmitted) {\n        // User incorrectly emitted 'error' directly on the stream.\n        errorOrDestroy(dest, er)\n      } else {\n        dest.emit('error', er)\n      }\n    }\n  }\n\n  // Make sure our error handler is attached before userland ones.\n  prependListener(dest, 'error', onerror)\n\n  // Both close and finish should trigger unpipe, but only once.\n  function onclose() {\n    dest.removeListener('finish', onfinish)\n    unpipe()\n  }\n  dest.once('close', onclose)\n  function onfinish() {\n    debug('onfinish')\n    dest.removeListener('close', onclose)\n    unpipe()\n  }\n  dest.once('finish', onfinish)\n  function unpipe() {\n    debug('unpipe')\n    src.unpipe(dest)\n  }\n\n  // Tell the dest that it's being piped to.\n  dest.emit('pipe', src)\n\n  // Start the flow if it hasn't been started already.\n\n  if (dest.writableNeedDrain === true) {\n    pause()\n  } else if (!state.flowing) {\n    debug('pipe resume')\n    src.resume()\n  }\n  return dest\n}\nfunction pipeOnDrain(src, dest) {\n  return function pipeOnDrainFunctionResult() {\n    const state = src._readableState\n\n    // `ondrain` will call directly,\n    // `this` maybe not a reference to dest,\n    // so we use the real dest here.\n    if (state.awaitDrainWriters === dest) {\n      debug('pipeOnDrain', 1)\n      state.awaitDrainWriters = null\n    } else if (state.multiAwaitDrain) {\n      debug('pipeOnDrain', state.awaitDrainWriters.size)\n      state.awaitDrainWriters.delete(dest)\n    }\n    if ((!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) && src.listenerCount('data')) {\n      src.resume()\n    }\n  }\n}\nReadable.prototype.unpipe = function (dest) {\n  const state = this._readableState\n  const unpipeInfo = {\n    hasUnpiped: false\n  }\n\n  // If we're not piping anywhere, then do nothing.\n  if (state.pipes.length === 0) return this\n  if (!dest) {\n    // remove all.\n    const dests = state.pipes\n    state.pipes = []\n    this.pause()\n    for (let i = 0; i < dests.length; i++)\n      dests[i].emit('unpipe', this, {\n        hasUnpiped: false\n      })\n    return this\n  }\n\n  // Try to find the right one.\n  const index = ArrayPrototypeIndexOf(state.pipes, dest)\n  if (index === -1) return this\n  state.pipes.splice(index, 1)\n  if (state.pipes.length === 0) this.pause()\n  dest.emit('unpipe', this, unpipeInfo)\n  return this\n}\n\n// Set up data events if they are asked for\n// Ensure readable listeners eventually get something.\nReadable.prototype.on = function (ev, fn) {\n  const res = Stream.prototype.on.call(this, ev, fn)\n  const state = this._readableState\n  if (ev === 'data') {\n    // Update readableListening so that resume() may be a no-op\n    // a few lines down. This is needed to support once('readable').\n    state.readableListening = this.listenerCount('readable') > 0\n\n    // Try start flowing on next tick if stream isn't explicitly paused.\n    if (state.flowing !== false) this.resume()\n  } else if (ev === 'readable') {\n    if (!state.endEmitted && !state.readableListening) {\n      state.readableListening = state.needReadable = true\n      state.flowing = false\n      state.emittedReadable = false\n      debug('on readable', state.length, state.reading)\n      if (state.length) {\n        emitReadable(this)\n      } else if (!state.reading) {\n        process.nextTick(nReadingNextTick, this)\n      }\n    }\n  }\n  return res\n}\nReadable.prototype.addListener = Readable.prototype.on\nReadable.prototype.removeListener = function (ev, fn) {\n  const res = Stream.prototype.removeListener.call(this, ev, fn)\n  if (ev === 'readable') {\n    // We need to check if there is someone still listening to\n    // readable and reset the state. However this needs to happen\n    // after readable has been emitted but before I/O (nextTick) to\n    // support once('readable', fn) cycles. This means that calling\n    // resume within the same tick will have no\n    // effect.\n    process.nextTick(updateReadableListening, this)\n  }\n  return res\n}\nReadable.prototype.off = Readable.prototype.removeListener\nReadable.prototype.removeAllListeners = function (ev) {\n  const res = Stream.prototype.removeAllListeners.apply(this, arguments)\n  if (ev === 'readable' || ev === undefined) {\n    // We need to check if there is someone still listening to\n    // readable and reset the state. However this needs to happen\n    // after readable has been emitted but before I/O (nextTick) to\n    // support once('readable', fn) cycles. This means that calling\n    // resume within the same tick will have no\n    // effect.\n    process.nextTick(updateReadableListening, this)\n  }\n  return res\n}\nfunction updateReadableListening(self) {\n  const state = self._readableState\n  state.readableListening = self.listenerCount('readable') > 0\n  if (state.resumeScheduled && state[kPaused] === false) {\n    // Flowing needs to be set to true now, otherwise\n    // the upcoming resume will not flow.\n    state.flowing = true\n\n    // Crude way to check if we should resume.\n  } else if (self.listenerCount('data') > 0) {\n    self.resume()\n  } else if (!state.readableListening) {\n    state.flowing = null\n  }\n}\nfunction nReadingNextTick(self) {\n  debug('readable nexttick read 0')\n  self.read(0)\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n  const state = this._readableState\n  if (!state.flowing) {\n    debug('resume')\n    // We flow only if there is no one listening\n    // for readable, but we still have to call\n    // resume().\n    state.flowing = !state.readableListening\n    resume(this, state)\n  }\n  state[kPaused] = false\n  return this\n}\nfunction resume(stream, state) {\n  if (!state.resumeScheduled) {\n    state.resumeScheduled = true\n    process.nextTick(resume_, stream, state)\n  }\n}\nfunction resume_(stream, state) {\n  debug('resume', state.reading)\n  if (!state.reading) {\n    stream.read(0)\n  }\n  state.resumeScheduled = false\n  stream.emit('resume')\n  flow(stream)\n  if (state.flowing && !state.reading) stream.read(0)\n}\nReadable.prototype.pause = function () {\n  debug('call pause flowing=%j', this._readableState.flowing)\n  if (this._readableState.flowing !== false) {\n    debug('pause')\n    this._readableState.flowing = false\n    this.emit('pause')\n  }\n  this._readableState[kPaused] = true\n  return this\n}\nfunction flow(stream) {\n  const state = stream._readableState\n  debug('flow', state.flowing)\n  while (state.flowing && stream.read() !== null);\n}\n\n// Wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n  let paused = false\n\n  // TODO (ronag): Should this.destroy(err) emit\n  // 'error' on the wrapped stream? Would require\n  // a static factory method, e.g. Readable.wrap(stream).\n\n  stream.on('data', (chunk) => {\n    if (!this.push(chunk) && stream.pause) {\n      paused = true\n      stream.pause()\n    }\n  })\n  stream.on('end', () => {\n    this.push(null)\n  })\n  stream.on('error', (err) => {\n    errorOrDestroy(this, err)\n  })\n  stream.on('close', () => {\n    this.destroy()\n  })\n  stream.on('destroy', () => {\n    this.destroy()\n  })\n  this._read = () => {\n    if (paused && stream.resume) {\n      paused = false\n      stream.resume()\n    }\n  }\n\n  // Proxy all the other methods. Important when wrapping filters and duplexes.\n  const streamKeys = ObjectKeys(stream)\n  for (let j = 1; j < streamKeys.length; j++) {\n    const i = streamKeys[j]\n    if (this[i] === undefined && typeof stream[i] === 'function') {\n      this[i] = stream[i].bind(stream)\n    }\n  }\n  return this\n}\nReadable.prototype[SymbolAsyncIterator] = function () {\n  return streamToAsyncIterator(this)\n}\nReadable.prototype.iterator = function (options) {\n  if (options !== undefined) {\n    validateObject(options, 'options')\n  }\n  return streamToAsyncIterator(this, options)\n}\nfunction streamToAsyncIterator(stream, options) {\n  if (typeof stream.read !== 'function') {\n    stream = Readable.wrap(stream, {\n      objectMode: true\n    })\n  }\n  const iter = createAsyncIterator(stream, options)\n  iter.stream = stream\n  return iter\n}\nasync function* createAsyncIterator(stream, options) {\n  let callback = nop\n  function next(resolve) {\n    if (this === stream) {\n      callback()\n      callback = nop\n    } else {\n      callback = resolve\n    }\n  }\n  stream.on('readable', next)\n  let error\n  const cleanup = eos(\n    stream,\n    {\n      writable: false\n    },\n    (err) => {\n      error = err ? aggregateTwoErrors(error, err) : null\n      callback()\n      callback = nop\n    }\n  )\n  try {\n    while (true) {\n      const chunk = stream.destroyed ? null : stream.read()\n      if (chunk !== null) {\n        yield chunk\n      } else if (error) {\n        throw error\n      } else if (error === null) {\n        return\n      } else {\n        await new Promise(next)\n      }\n    }\n  } catch (err) {\n    error = aggregateTwoErrors(error, err)\n    throw error\n  } finally {\n    if (\n      (error || (options === null || options === undefined ? undefined : options.destroyOnReturn) !== false) &&\n      (error === undefined || stream._readableState.autoDestroy)\n    ) {\n      destroyImpl.destroyer(stream, null)\n    } else {\n      stream.off('readable', next)\n      cleanup()\n    }\n  }\n}\n\n// Making it explicit these properties are not enumerable\n// because otherwise some prototype manipulation in\n// userland will fail.\nObjectDefineProperties(Readable.prototype, {\n  readable: {\n    __proto__: null,\n    get() {\n      const r = this._readableState\n      // r.readable === false means that this is part of a Duplex stream\n      // where the readable side was disabled upon construction.\n      // Compat. The user might manually disable readable side through\n      // deprecated setter.\n      return !!r && r.readable !== false && !r.destroyed && !r.errorEmitted && !r.endEmitted\n    },\n    set(val) {\n      // Backwards compat.\n      if (this._readableState) {\n        this._readableState.readable = !!val\n      }\n    }\n  },\n  readableDidRead: {\n    __proto__: null,\n    enumerable: false,\n    get: function () {\n      return this._readableState.dataEmitted\n    }\n  },\n  readableAborted: {\n    __proto__: null,\n    enumerable: false,\n    get: function () {\n      return !!(\n        this._readableState.readable !== false &&\n        (this._readableState.destroyed || this._readableState.errored) &&\n        !this._readableState.endEmitted\n      )\n    }\n  },\n  readableHighWaterMark: {\n    __proto__: null,\n    enumerable: false,\n    get: function () {\n      return this._readableState.highWaterMark\n    }\n  },\n  readableBuffer: {\n    __proto__: null,\n    enumerable: false,\n    get: function () {\n      return this._readableState && this._readableState.buffer\n    }\n  },\n  readableFlowing: {\n    __proto__: null,\n    enumerable: false,\n    get: function () {\n      return this._readableState.flowing\n    },\n    set: function (state) {\n      if (this._readableState) {\n        this._readableState.flowing = state\n      }\n    }\n  },\n  readableLength: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._readableState.length\n    }\n  },\n  readableObjectMode: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._readableState ? this._readableState.objectMode : false\n    }\n  },\n  readableEncoding: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._readableState ? this._readableState.encoding : null\n    }\n  },\n  errored: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._readableState ? this._readableState.errored : null\n    }\n  },\n  closed: {\n    __proto__: null,\n    get() {\n      return this._readableState ? this._readableState.closed : false\n    }\n  },\n  destroyed: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._readableState ? this._readableState.destroyed : false\n    },\n    set(value) {\n      // We ignore the value if the stream\n      // has not been initialized yet.\n      if (!this._readableState) {\n        return\n      }\n\n      // Backward compatibility, the user is explicitly\n      // managing destroyed.\n      this._readableState.destroyed = value\n    }\n  },\n  readableEnded: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._readableState ? this._readableState.endEmitted : false\n    }\n  }\n})\nObjectDefineProperties(ReadableState.prototype, {\n  // Legacy getter for `pipesCount`.\n  pipesCount: {\n    __proto__: null,\n    get() {\n      return this.pipes.length\n    }\n  },\n  // Legacy property for `paused`.\n  paused: {\n    __proto__: null,\n    get() {\n      return this[kPaused] !== false\n    },\n    set(value) {\n      this[kPaused] = !!value\n    }\n  }\n})\n\n// Exposed for testing purposes only.\nReadable._fromList = fromList\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n  // nothing buffered.\n  if (state.length === 0) return null\n  let ret\n  if (state.objectMode) ret = state.buffer.shift()\n  else if (!n || n >= state.length) {\n    // Read it all, truncate the list.\n    if (state.decoder) ret = state.buffer.join('')\n    else if (state.buffer.length === 1) ret = state.buffer.first()\n    else ret = state.buffer.concat(state.length)\n    state.buffer.clear()\n  } else {\n    // read part of list.\n    ret = state.buffer.consume(n, state.decoder)\n  }\n  return ret\n}\nfunction endReadable(stream) {\n  const state = stream._readableState\n  debug('endReadable', state.endEmitted)\n  if (!state.endEmitted) {\n    state.ended = true\n    process.nextTick(endReadableNT, state, stream)\n  }\n}\nfunction endReadableNT(state, stream) {\n  debug('endReadableNT', state.endEmitted, state.length)\n\n  // Check that we didn't get one last unshift.\n  if (!state.errored && !state.closeEmitted && !state.endEmitted && state.length === 0) {\n    state.endEmitted = true\n    stream.emit('end')\n    if (stream.writable && stream.allowHalfOpen === false) {\n      process.nextTick(endWritableNT, stream)\n    } else if (state.autoDestroy) {\n      // In case of duplex streams we need a way to detect\n      // if the writable side is ready for autoDestroy as well.\n      const wState = stream._writableState\n      const autoDestroy =\n        !wState ||\n        (wState.autoDestroy &&\n          // We don't expect the writable to ever 'finish'\n          // if writable is explicitly set to false.\n          (wState.finished || wState.writable === false))\n      if (autoDestroy) {\n        stream.destroy()\n      }\n    }\n  }\n}\nfunction endWritableNT(stream) {\n  const writable = stream.writable && !stream.writableEnded && !stream.destroyed\n  if (writable) {\n    stream.end()\n  }\n}\nReadable.from = function (iterable, opts) {\n  return from(Readable, iterable, opts)\n}\nlet webStreamsAdapters\n\n// Lazy to avoid circular references\nfunction lazyWebStreams() {\n  if (webStreamsAdapters === undefined) webStreamsAdapters = {}\n  return webStreamsAdapters\n}\nReadable.fromWeb = function (readableStream, options) {\n  return lazyWebStreams().newStreamReadableFromReadableStream(readableStream, options)\n}\nReadable.toWeb = function (streamReadable, options) {\n  return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable, options)\n}\nReadable.wrap = function (src, options) {\n  var _ref, _src$readableObjectMo\n  return new Readable({\n    objectMode:\n      (_ref =\n        (_src$readableObjectMo = src.readableObjectMode) !== null && _src$readableObjectMo !== undefined\n          ? _src$readableObjectMo\n          : src.objectMode) !== null && _ref !== undefined\n        ? _ref\n        : true,\n    ...options,\n    destroy(err, callback) {\n      destroyImpl.destroyer(src, err)\n      callback(err)\n    }\n  }).wrap(src)\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst {\n  ArrayPrototypeSlice,\n  Error,\n  FunctionPrototypeSymbolHasInstance,\n  ObjectDefineProperty,\n  ObjectDefineProperties,\n  ObjectSetPrototypeOf,\n  StringPrototypeToLowerCase,\n  Symbol,\n  SymbolHasInstance\n} = require('../../ours/primordials')\nmodule.exports = Writable\nWritable.WritableState = WritableState\nconst { EventEmitter: EE } = require('events')\nconst Stream = require('./legacy').Stream\nconst { Buffer } = require('buffer')\nconst destroyImpl = require('./destroy')\nconst { addAbortSignal } = require('./add-abort-signal')\nconst { getHighWaterMark, getDefaultHighWaterMark } = require('./state')\nconst {\n  ERR_INVALID_ARG_TYPE,\n  ERR_METHOD_NOT_IMPLEMENTED,\n  ERR_MULTIPLE_CALLBACK,\n  ERR_STREAM_CANNOT_PIPE,\n  ERR_STREAM_DESTROYED,\n  ERR_STREAM_ALREADY_FINISHED,\n  ERR_STREAM_NULL_VALUES,\n  ERR_STREAM_WRITE_AFTER_END,\n  ERR_UNKNOWN_ENCODING\n} = require('../../ours/errors').codes\nconst { errorOrDestroy } = destroyImpl\nObjectSetPrototypeOf(Writable.prototype, Stream.prototype)\nObjectSetPrototypeOf(Writable, Stream)\nfunction nop() {}\nconst kOnFinished = Symbol('kOnFinished')\nfunction WritableState(options, stream, isDuplex) {\n  // Duplex streams are both readable and writable, but share\n  // the same options object.\n  // However, some cases require setting options to different\n  // values for the readable and the writable sides of the duplex stream,\n  // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n  if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof require('./duplex')\n\n  // Object stream flag to indicate whether or not this stream\n  // contains buffers or objects.\n  this.objectMode = !!(options && options.objectMode)\n  if (isDuplex) this.objectMode = this.objectMode || !!(options && options.writableObjectMode)\n\n  // The point at which write() starts returning false\n  // Note: 0 is a valid value, means that we always return false if\n  // the entire buffer is not flushed immediately on write().\n  this.highWaterMark = options\n    ? getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex)\n    : getDefaultHighWaterMark(false)\n\n  // if _final has been called.\n  this.finalCalled = false\n\n  // drain event flag.\n  this.needDrain = false\n  // At the start of calling end()\n  this.ending = false\n  // When end() has been called, and returned.\n  this.ended = false\n  // When 'finish' is emitted.\n  this.finished = false\n\n  // Has it been destroyed\n  this.destroyed = false\n\n  // Should we decode strings into buffers before passing to _write?\n  // this is here so that some node-core streams can optimize string\n  // handling at a lower level.\n  const noDecode = !!(options && options.decodeStrings === false)\n  this.decodeStrings = !noDecode\n\n  // Crypto is kind of old and crusty.  Historically, its default string\n  // encoding is 'binary' so we have to make this configurable.\n  // Everything else in the universe uses 'utf8', though.\n  this.defaultEncoding = (options && options.defaultEncoding) || 'utf8'\n\n  // Not an actual buffer we keep track of, but a measurement\n  // of how much we're waiting to get pushed to some underlying\n  // socket or file.\n  this.length = 0\n\n  // A flag to see when we're in the middle of a write.\n  this.writing = false\n\n  // When true all writes will be buffered until .uncork() call.\n  this.corked = 0\n\n  // A flag to be able to tell if the onwrite cb is called immediately,\n  // or on a later tick.  We set this to true at first, because any\n  // actions that shouldn't happen until \"later\" should generally also\n  // not happen before the first write call.\n  this.sync = true\n\n  // A flag to know if we're processing previously buffered items, which\n  // may call the _write() callback in the same tick, so that we don't\n  // end up in an overlapped onwrite situation.\n  this.bufferProcessing = false\n\n  // The callback that's passed to _write(chunk, cb).\n  this.onwrite = onwrite.bind(undefined, stream)\n\n  // The callback that the user supplies to write(chunk, encoding, cb).\n  this.writecb = null\n\n  // The amount that is being written when _write is called.\n  this.writelen = 0\n\n  // Storage for data passed to the afterWrite() callback in case of\n  // synchronous _write() completion.\n  this.afterWriteTickInfo = null\n  resetBuffer(this)\n\n  // Number of pending user-supplied write callbacks\n  // this must be 0 before 'finish' can be emitted.\n  this.pendingcb = 0\n\n  // Stream is still being constructed and cannot be\n  // destroyed until construction finished or failed.\n  // Async construction is opt in, therefore we start as\n  // constructed.\n  this.constructed = true\n\n  // Emit prefinish if the only thing we're waiting for is _write cbs\n  // This is relevant for synchronous Transform streams.\n  this.prefinished = false\n\n  // True if the error was already emitted and should not be thrown again.\n  this.errorEmitted = false\n\n  // Should close be emitted on destroy. Defaults to true.\n  this.emitClose = !options || options.emitClose !== false\n\n  // Should .destroy() be called after 'finish' (and potentially 'end').\n  this.autoDestroy = !options || options.autoDestroy !== false\n\n  // Indicates whether the stream has errored. When true all write() calls\n  // should return false. This is needed since when autoDestroy\n  // is disabled we need a way to tell whether the stream has failed.\n  this.errored = null\n\n  // Indicates whether the stream has finished destroying.\n  this.closed = false\n\n  // True if close has been emitted or would have been emitted\n  // depending on emitClose.\n  this.closeEmitted = false\n  this[kOnFinished] = []\n}\nfunction resetBuffer(state) {\n  state.buffered = []\n  state.bufferedIndex = 0\n  state.allBuffers = true\n  state.allNoop = true\n}\nWritableState.prototype.getBuffer = function getBuffer() {\n  return ArrayPrototypeSlice(this.buffered, this.bufferedIndex)\n}\nObjectDefineProperty(WritableState.prototype, 'bufferedRequestCount', {\n  __proto__: null,\n  get() {\n    return this.buffered.length - this.bufferedIndex\n  }\n})\nfunction Writable(options) {\n  // Writable ctor is applied to Duplexes, too.\n  // `realHasInstance` is necessary because using plain `instanceof`\n  // would return false, as no `_writableState` property is attached.\n\n  // Trying to use the custom `instanceof` for Writable here will also break the\n  // Node.js LazyTransform implementation, which has a non-trivial getter for\n  // `_writableState` that would lead to infinite recursion.\n\n  // Checking for a Stream.Duplex instance is faster here instead of inside\n  // the WritableState constructor, at least with V8 6.5.\n  const isDuplex = this instanceof require('./duplex')\n  if (!isDuplex && !FunctionPrototypeSymbolHasInstance(Writable, this)) return new Writable(options)\n  this._writableState = new WritableState(options, this, isDuplex)\n  if (options) {\n    if (typeof options.write === 'function') this._write = options.write\n    if (typeof options.writev === 'function') this._writev = options.writev\n    if (typeof options.destroy === 'function') this._destroy = options.destroy\n    if (typeof options.final === 'function') this._final = options.final\n    if (typeof options.construct === 'function') this._construct = options.construct\n    if (options.signal) addAbortSignal(options.signal, this)\n  }\n  Stream.call(this, options)\n  destroyImpl.construct(this, () => {\n    const state = this._writableState\n    if (!state.writing) {\n      clearBuffer(this, state)\n    }\n    finishMaybe(this, state)\n  })\n}\nObjectDefineProperty(Writable, SymbolHasInstance, {\n  __proto__: null,\n  value: function (object) {\n    if (FunctionPrototypeSymbolHasInstance(this, object)) return true\n    if (this !== Writable) return false\n    return object && object._writableState instanceof WritableState\n  }\n})\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n  errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE())\n}\nfunction _write(stream, chunk, encoding, cb) {\n  const state = stream._writableState\n  if (typeof encoding === 'function') {\n    cb = encoding\n    encoding = state.defaultEncoding\n  } else {\n    if (!encoding) encoding = state.defaultEncoding\n    else if (encoding !== 'buffer' && !Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding)\n    if (typeof cb !== 'function') cb = nop\n  }\n  if (chunk === null) {\n    throw new ERR_STREAM_NULL_VALUES()\n  } else if (!state.objectMode) {\n    if (typeof chunk === 'string') {\n      if (state.decodeStrings !== false) {\n        chunk = Buffer.from(chunk, encoding)\n        encoding = 'buffer'\n      }\n    } else if (chunk instanceof Buffer) {\n      encoding = 'buffer'\n    } else if (Stream._isUint8Array(chunk)) {\n      chunk = Stream._uint8ArrayToBuffer(chunk)\n      encoding = 'buffer'\n    } else {\n      throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk)\n    }\n  }\n  let err\n  if (state.ending) {\n    err = new ERR_STREAM_WRITE_AFTER_END()\n  } else if (state.destroyed) {\n    err = new ERR_STREAM_DESTROYED('write')\n  }\n  if (err) {\n    process.nextTick(cb, err)\n    errorOrDestroy(stream, err, true)\n    return err\n  }\n  state.pendingcb++\n  return writeOrBuffer(stream, state, chunk, encoding, cb)\n}\nWritable.prototype.write = function (chunk, encoding, cb) {\n  return _write(this, chunk, encoding, cb) === true\n}\nWritable.prototype.cork = function () {\n  this._writableState.corked++\n}\nWritable.prototype.uncork = function () {\n  const state = this._writableState\n  if (state.corked) {\n    state.corked--\n    if (!state.writing) clearBuffer(this, state)\n  }\n}\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n  // node::ParseEncoding() requires lower case.\n  if (typeof encoding === 'string') encoding = StringPrototypeToLowerCase(encoding)\n  if (!Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding)\n  this._writableState.defaultEncoding = encoding\n  return this\n}\n\n// If we're already writing something, then just put this\n// in the queue, and wait our turn.  Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, chunk, encoding, callback) {\n  const len = state.objectMode ? 1 : chunk.length\n  state.length += len\n\n  // stream._write resets state.length\n  const ret = state.length < state.highWaterMark\n  // We must ensure that previous needDrain will not be reset to false.\n  if (!ret) state.needDrain = true\n  if (state.writing || state.corked || state.errored || !state.constructed) {\n    state.buffered.push({\n      chunk,\n      encoding,\n      callback\n    })\n    if (state.allBuffers && encoding !== 'buffer') {\n      state.allBuffers = false\n    }\n    if (state.allNoop && callback !== nop) {\n      state.allNoop = false\n    }\n  } else {\n    state.writelen = len\n    state.writecb = callback\n    state.writing = true\n    state.sync = true\n    stream._write(chunk, encoding, state.onwrite)\n    state.sync = false\n  }\n\n  // Return false if errored or destroyed in order to break\n  // any synchronous while(stream.write(data)) loops.\n  return ret && !state.errored && !state.destroyed\n}\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n  state.writelen = len\n  state.writecb = cb\n  state.writing = true\n  state.sync = true\n  if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'))\n  else if (writev) stream._writev(chunk, state.onwrite)\n  else stream._write(chunk, encoding, state.onwrite)\n  state.sync = false\n}\nfunction onwriteError(stream, state, er, cb) {\n  --state.pendingcb\n  cb(er)\n  // Ensure callbacks are invoked even when autoDestroy is\n  // not enabled. Passing `er` here doesn't make sense since\n  // it's related to one specific write, not to the buffered\n  // writes.\n  errorBuffer(state)\n  // This can emit error, but error must always follow cb.\n  errorOrDestroy(stream, er)\n}\nfunction onwrite(stream, er) {\n  const state = stream._writableState\n  const sync = state.sync\n  const cb = state.writecb\n  if (typeof cb !== 'function') {\n    errorOrDestroy(stream, new ERR_MULTIPLE_CALLBACK())\n    return\n  }\n  state.writing = false\n  state.writecb = null\n  state.length -= state.writelen\n  state.writelen = 0\n  if (er) {\n    // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364\n    er.stack // eslint-disable-line no-unused-expressions\n\n    if (!state.errored) {\n      state.errored = er\n    }\n\n    // In case of duplex streams we need to notify the readable side of the\n    // error.\n    if (stream._readableState && !stream._readableState.errored) {\n      stream._readableState.errored = er\n    }\n    if (sync) {\n      process.nextTick(onwriteError, stream, state, er, cb)\n    } else {\n      onwriteError(stream, state, er, cb)\n    }\n  } else {\n    if (state.buffered.length > state.bufferedIndex) {\n      clearBuffer(stream, state)\n    }\n    if (sync) {\n      // It is a common case that the callback passed to .write() is always\n      // the same. In that case, we do not schedule a new nextTick(), but\n      // rather just increase a counter, to improve performance and avoid\n      // memory allocations.\n      if (state.afterWriteTickInfo !== null && state.afterWriteTickInfo.cb === cb) {\n        state.afterWriteTickInfo.count++\n      } else {\n        state.afterWriteTickInfo = {\n          count: 1,\n          cb,\n          stream,\n          state\n        }\n        process.nextTick(afterWriteTick, state.afterWriteTickInfo)\n      }\n    } else {\n      afterWrite(stream, state, 1, cb)\n    }\n  }\n}\nfunction afterWriteTick({ stream, state, count, cb }) {\n  state.afterWriteTickInfo = null\n  return afterWrite(stream, state, count, cb)\n}\nfunction afterWrite(stream, state, count, cb) {\n  const needDrain = !state.ending && !stream.destroyed && state.length === 0 && state.needDrain\n  if (needDrain) {\n    state.needDrain = false\n    stream.emit('drain')\n  }\n  while (count-- > 0) {\n    state.pendingcb--\n    cb()\n  }\n  if (state.destroyed) {\n    errorBuffer(state)\n  }\n  finishMaybe(stream, state)\n}\n\n// If there's something in the buffer waiting, then invoke callbacks.\nfunction errorBuffer(state) {\n  if (state.writing) {\n    return\n  }\n  for (let n = state.bufferedIndex; n < state.buffered.length; ++n) {\n    var _state$errored\n    const { chunk, callback } = state.buffered[n]\n    const len = state.objectMode ? 1 : chunk.length\n    state.length -= len\n    callback(\n      (_state$errored = state.errored) !== null && _state$errored !== undefined\n        ? _state$errored\n        : new ERR_STREAM_DESTROYED('write')\n    )\n  }\n  const onfinishCallbacks = state[kOnFinished].splice(0)\n  for (let i = 0; i < onfinishCallbacks.length; i++) {\n    var _state$errored2\n    onfinishCallbacks[i](\n      (_state$errored2 = state.errored) !== null && _state$errored2 !== undefined\n        ? _state$errored2\n        : new ERR_STREAM_DESTROYED('end')\n    )\n  }\n  resetBuffer(state)\n}\n\n// If there's something in the buffer waiting, then process it.\nfunction clearBuffer(stream, state) {\n  if (state.corked || state.bufferProcessing || state.destroyed || !state.constructed) {\n    return\n  }\n  const { buffered, bufferedIndex, objectMode } = state\n  const bufferedLength = buffered.length - bufferedIndex\n  if (!bufferedLength) {\n    return\n  }\n  let i = bufferedIndex\n  state.bufferProcessing = true\n  if (bufferedLength > 1 && stream._writev) {\n    state.pendingcb -= bufferedLength - 1\n    const callback = state.allNoop\n      ? nop\n      : (err) => {\n          for (let n = i; n < buffered.length; ++n) {\n            buffered[n].callback(err)\n          }\n        }\n    // Make a copy of `buffered` if it's going to be used by `callback` above,\n    // since `doWrite` will mutate the array.\n    const chunks = state.allNoop && i === 0 ? buffered : ArrayPrototypeSlice(buffered, i)\n    chunks.allBuffers = state.allBuffers\n    doWrite(stream, state, true, state.length, chunks, '', callback)\n    resetBuffer(state)\n  } else {\n    do {\n      const { chunk, encoding, callback } = buffered[i]\n      buffered[i++] = null\n      const len = objectMode ? 1 : chunk.length\n      doWrite(stream, state, false, len, chunk, encoding, callback)\n    } while (i < buffered.length && !state.writing)\n    if (i === buffered.length) {\n      resetBuffer(state)\n    } else if (i > 256) {\n      buffered.splice(0, i)\n      state.bufferedIndex = 0\n    } else {\n      state.bufferedIndex = i\n    }\n  }\n  state.bufferProcessing = false\n}\nWritable.prototype._write = function (chunk, encoding, cb) {\n  if (this._writev) {\n    this._writev(\n      [\n        {\n          chunk,\n          encoding\n        }\n      ],\n      cb\n    )\n  } else {\n    throw new ERR_METHOD_NOT_IMPLEMENTED('_write()')\n  }\n}\nWritable.prototype._writev = null\nWritable.prototype.end = function (chunk, encoding, cb) {\n  const state = this._writableState\n  if (typeof chunk === 'function') {\n    cb = chunk\n    chunk = null\n    encoding = null\n  } else if (typeof encoding === 'function') {\n    cb = encoding\n    encoding = null\n  }\n  let err\n  if (chunk !== null && chunk !== undefined) {\n    const ret = _write(this, chunk, encoding)\n    if (ret instanceof Error) {\n      err = ret\n    }\n  }\n\n  // .end() fully uncorks.\n  if (state.corked) {\n    state.corked = 1\n    this.uncork()\n  }\n  if (err) {\n    // Do nothing...\n  } else if (!state.errored && !state.ending) {\n    // This is forgiving in terms of unnecessary calls to end() and can hide\n    // logic errors. However, usually such errors are harmless and causing a\n    // hard error can be disproportionately destructive. It is not always\n    // trivial for the user to determine whether end() needs to be called\n    // or not.\n\n    state.ending = true\n    finishMaybe(this, state, true)\n    state.ended = true\n  } else if (state.finished) {\n    err = new ERR_STREAM_ALREADY_FINISHED('end')\n  } else if (state.destroyed) {\n    err = new ERR_STREAM_DESTROYED('end')\n  }\n  if (typeof cb === 'function') {\n    if (err || state.finished) {\n      process.nextTick(cb, err)\n    } else {\n      state[kOnFinished].push(cb)\n    }\n  }\n  return this\n}\nfunction needFinish(state) {\n  return (\n    state.ending &&\n    !state.destroyed &&\n    state.constructed &&\n    state.length === 0 &&\n    !state.errored &&\n    state.buffered.length === 0 &&\n    !state.finished &&\n    !state.writing &&\n    !state.errorEmitted &&\n    !state.closeEmitted\n  )\n}\nfunction callFinal(stream, state) {\n  let called = false\n  function onFinish(err) {\n    if (called) {\n      errorOrDestroy(stream, err !== null && err !== undefined ? err : ERR_MULTIPLE_CALLBACK())\n      return\n    }\n    called = true\n    state.pendingcb--\n    if (err) {\n      const onfinishCallbacks = state[kOnFinished].splice(0)\n      for (let i = 0; i < onfinishCallbacks.length; i++) {\n        onfinishCallbacks[i](err)\n      }\n      errorOrDestroy(stream, err, state.sync)\n    } else if (needFinish(state)) {\n      state.prefinished = true\n      stream.emit('prefinish')\n      // Backwards compat. Don't check state.sync here.\n      // Some streams assume 'finish' will be emitted\n      // asynchronously relative to _final callback.\n      state.pendingcb++\n      process.nextTick(finish, stream, state)\n    }\n  }\n  state.sync = true\n  state.pendingcb++\n  try {\n    stream._final(onFinish)\n  } catch (err) {\n    onFinish(err)\n  }\n  state.sync = false\n}\nfunction prefinish(stream, state) {\n  if (!state.prefinished && !state.finalCalled) {\n    if (typeof stream._final === 'function' && !state.destroyed) {\n      state.finalCalled = true\n      callFinal(stream, state)\n    } else {\n      state.prefinished = true\n      stream.emit('prefinish')\n    }\n  }\n}\nfunction finishMaybe(stream, state, sync) {\n  if (needFinish(state)) {\n    prefinish(stream, state)\n    if (state.pendingcb === 0) {\n      if (sync) {\n        state.pendingcb++\n        process.nextTick(\n          (stream, state) => {\n            if (needFinish(state)) {\n              finish(stream, state)\n            } else {\n              state.pendingcb--\n            }\n          },\n          stream,\n          state\n        )\n      } else if (needFinish(state)) {\n        state.pendingcb++\n        finish(stream, state)\n      }\n    }\n  }\n}\nfunction finish(stream, state) {\n  state.pendingcb--\n  state.finished = true\n  const onfinishCallbacks = state[kOnFinished].splice(0)\n  for (let i = 0; i < onfinishCallbacks.length; i++) {\n    onfinishCallbacks[i]()\n  }\n  stream.emit('finish')\n  if (state.autoDestroy) {\n    // In case of duplex streams we need a way to detect\n    // if the readable side is ready for autoDestroy as well.\n    const rState = stream._readableState\n    const autoDestroy =\n      !rState ||\n      (rState.autoDestroy &&\n        // We don't expect the readable to ever 'end'\n        // if readable is explicitly set to false.\n        (rState.endEmitted || rState.readable === false))\n    if (autoDestroy) {\n      stream.destroy()\n    }\n  }\n}\nObjectDefineProperties(Writable.prototype, {\n  closed: {\n    __proto__: null,\n    get() {\n      return this._writableState ? this._writableState.closed : false\n    }\n  },\n  destroyed: {\n    __proto__: null,\n    get() {\n      return this._writableState ? this._writableState.destroyed : false\n    },\n    set(value) {\n      // Backward compatibility, the user is explicitly managing destroyed.\n      if (this._writableState) {\n        this._writableState.destroyed = value\n      }\n    }\n  },\n  writable: {\n    __proto__: null,\n    get() {\n      const w = this._writableState\n      // w.writable === false means that this is part of a Duplex stream\n      // where the writable side was disabled upon construction.\n      // Compat. The user might manually disable writable side through\n      // deprecated setter.\n      return !!w && w.writable !== false && !w.destroyed && !w.errored && !w.ending && !w.ended\n    },\n    set(val) {\n      // Backwards compatible.\n      if (this._writableState) {\n        this._writableState.writable = !!val\n      }\n    }\n  },\n  writableFinished: {\n    __proto__: null,\n    get() {\n      return this._writableState ? this._writableState.finished : false\n    }\n  },\n  writableObjectMode: {\n    __proto__: null,\n    get() {\n      return this._writableState ? this._writableState.objectMode : false\n    }\n  },\n  writableBuffer: {\n    __proto__: null,\n    get() {\n      return this._writableState && this._writableState.getBuffer()\n    }\n  },\n  writableEnded: {\n    __proto__: null,\n    get() {\n      return this._writableState ? this._writableState.ending : false\n    }\n  },\n  writableNeedDrain: {\n    __proto__: null,\n    get() {\n      const wState = this._writableState\n      if (!wState) return false\n      return !wState.destroyed && !wState.ending && wState.needDrain\n    }\n  },\n  writableHighWaterMark: {\n    __proto__: null,\n    get() {\n      return this._writableState && this._writableState.highWaterMark\n    }\n  },\n  writableCorked: {\n    __proto__: null,\n    get() {\n      return this._writableState ? this._writableState.corked : 0\n    }\n  },\n  writableLength: {\n    __proto__: null,\n    get() {\n      return this._writableState && this._writableState.length\n    }\n  },\n  errored: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._writableState ? this._writableState.errored : null\n    }\n  },\n  writableAborted: {\n    __proto__: null,\n    enumerable: false,\n    get: function () {\n      return !!(\n        this._writableState.writable !== false &&\n        (this._writableState.destroyed || this._writableState.errored) &&\n        !this._writableState.finished\n      )\n    }\n  }\n})\nconst destroy = destroyImpl.destroy\nWritable.prototype.destroy = function (err, cb) {\n  const state = this._writableState\n\n  // Invoke pending callbacks.\n  if (!state.destroyed && (state.bufferedIndex < state.buffered.length || state[kOnFinished].length)) {\n    process.nextTick(errorBuffer, state)\n  }\n  destroy.call(this, err, cb)\n  return this\n}\nWritable.prototype._undestroy = destroyImpl.undestroy\nWritable.prototype._destroy = function (err, cb) {\n  cb(err)\n}\nWritable.prototype[EE.captureRejectionSymbol] = function (err) {\n  this.destroy(err)\n}\nlet webStreamsAdapters\n\n// Lazy to avoid circular references\nfunction lazyWebStreams() {\n  if (webStreamsAdapters === undefined) webStreamsAdapters = {}\n  return webStreamsAdapters\n}\nWritable.fromWeb = function (writableStream, options) {\n  return lazyWebStreams().newStreamWritableFromWritableStream(writableStream, options)\n}\nWritable.toWeb = function (streamWritable) {\n  return lazyWebStreams().newWritableStreamFromStreamWritable(streamWritable)\n}\n","/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\n;('use strict')\nconst bufferModule = require('buffer')\nconst {\n  isReadable,\n  isWritable,\n  isIterable,\n  isNodeStream,\n  isReadableNodeStream,\n  isWritableNodeStream,\n  isDuplexNodeStream,\n  isReadableStream,\n  isWritableStream\n} = require('./utils')\nconst eos = require('./end-of-stream')\nconst {\n  AbortError,\n  codes: { ERR_INVALID_ARG_TYPE, ERR_INVALID_RETURN_VALUE }\n} = require('../../ours/errors')\nconst { destroyer } = require('./destroy')\nconst Duplex = require('./duplex')\nconst Readable = require('./readable')\nconst Writable = require('./writable')\nconst { createDeferredPromise } = require('../../ours/util')\nconst from = require('./from')\nconst Blob = globalThis.Blob || bufferModule.Blob\nconst isBlob =\n  typeof Blob !== 'undefined'\n    ? function isBlob(b) {\n        return b instanceof Blob\n      }\n    : function isBlob(b) {\n        return false\n      }\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nconst { FunctionPrototypeCall } = require('../../ours/primordials')\n\n// This is needed for pre node 17.\nclass Duplexify extends Duplex {\n  constructor(options) {\n    super(options)\n\n    // https://github.com/nodejs/node/pull/34385\n\n    if ((options === null || options === undefined ? undefined : options.readable) === false) {\n      this._readableState.readable = false\n      this._readableState.ended = true\n      this._readableState.endEmitted = true\n    }\n    if ((options === null || options === undefined ? undefined : options.writable) === false) {\n      this._writableState.writable = false\n      this._writableState.ending = true\n      this._writableState.ended = true\n      this._writableState.finished = true\n    }\n  }\n}\nmodule.exports = function duplexify(body, name) {\n  if (isDuplexNodeStream(body)) {\n    return body\n  }\n  if (isReadableNodeStream(body)) {\n    return _duplexify({\n      readable: body\n    })\n  }\n  if (isWritableNodeStream(body)) {\n    return _duplexify({\n      writable: body\n    })\n  }\n  if (isNodeStream(body)) {\n    return _duplexify({\n      writable: false,\n      readable: false\n    })\n  }\n  if (isReadableStream(body)) {\n    return _duplexify({\n      readable: Readable.fromWeb(body)\n    })\n  }\n  if (isWritableStream(body)) {\n    return _duplexify({\n      writable: Writable.fromWeb(body)\n    })\n  }\n  if (typeof body === 'function') {\n    const { value, write, final, destroy } = fromAsyncGen(body)\n    if (isIterable(value)) {\n      return from(Duplexify, value, {\n        // TODO (ronag): highWaterMark?\n        objectMode: true,\n        write,\n        final,\n        destroy\n      })\n    }\n    const then = value === null || value === undefined ? undefined : value.then\n    if (typeof then === 'function') {\n      let d\n      const promise = FunctionPrototypeCall(\n        then,\n        value,\n        (val) => {\n          if (val != null) {\n            throw new ERR_INVALID_RETURN_VALUE('nully', 'body', val)\n          }\n        },\n        (err) => {\n          destroyer(d, err)\n        }\n      )\n      return (d = new Duplexify({\n        // TODO (ronag): highWaterMark?\n        objectMode: true,\n        readable: false,\n        write,\n        final(cb) {\n          final(async () => {\n            try {\n              await promise\n              process.nextTick(cb, null)\n            } catch (err) {\n              process.nextTick(cb, err)\n            }\n          })\n        },\n        destroy\n      }))\n    }\n    throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or AsyncFunction', name, value)\n  }\n  if (isBlob(body)) {\n    return duplexify(body.arrayBuffer())\n  }\n  if (isIterable(body)) {\n    return from(Duplexify, body, {\n      // TODO (ronag): highWaterMark?\n      objectMode: true,\n      writable: false\n    })\n  }\n  if (\n    isReadableStream(body === null || body === undefined ? undefined : body.readable) &&\n    isWritableStream(body === null || body === undefined ? undefined : body.writable)\n  ) {\n    return Duplexify.fromWeb(body)\n  }\n  if (\n    typeof (body === null || body === undefined ? undefined : body.writable) === 'object' ||\n    typeof (body === null || body === undefined ? undefined : body.readable) === 'object'\n  ) {\n    const readable =\n      body !== null && body !== undefined && body.readable\n        ? isReadableNodeStream(body === null || body === undefined ? undefined : body.readable)\n          ? body === null || body === undefined\n            ? undefined\n            : body.readable\n          : duplexify(body.readable)\n        : undefined\n    const writable =\n      body !== null && body !== undefined && body.writable\n        ? isWritableNodeStream(body === null || body === undefined ? undefined : body.writable)\n          ? body === null || body === undefined\n            ? undefined\n            : body.writable\n          : duplexify(body.writable)\n        : undefined\n    return _duplexify({\n      readable,\n      writable\n    })\n  }\n  const then = body === null || body === undefined ? undefined : body.then\n  if (typeof then === 'function') {\n    let d\n    FunctionPrototypeCall(\n      then,\n      body,\n      (val) => {\n        if (val != null) {\n          d.push(val)\n        }\n        d.push(null)\n      },\n      (err) => {\n        destroyer(d, err)\n      }\n    )\n    return (d = new Duplexify({\n      objectMode: true,\n      writable: false,\n      read() {}\n    }))\n  }\n  throw new ERR_INVALID_ARG_TYPE(\n    name,\n    [\n      'Blob',\n      'ReadableStream',\n      'WritableStream',\n      'Stream',\n      'Iterable',\n      'AsyncIterable',\n      'Function',\n      '{ readable, writable } pair',\n      'Promise'\n    ],\n    body\n  )\n}\nfunction fromAsyncGen(fn) {\n  let { promise, resolve } = createDeferredPromise()\n  const ac = new AbortController()\n  const signal = ac.signal\n  const value = fn(\n    (async function* () {\n      while (true) {\n        const _promise = promise\n        promise = null\n        const { chunk, done, cb } = await _promise\n        process.nextTick(cb)\n        if (done) return\n        if (signal.aborted)\n          throw new AbortError(undefined, {\n            cause: signal.reason\n          })\n        ;({ promise, resolve } = createDeferredPromise())\n        yield chunk\n      }\n    })(),\n    {\n      signal\n    }\n  )\n  return {\n    value,\n    write(chunk, encoding, cb) {\n      const _resolve = resolve\n      resolve = null\n      _resolve({\n        chunk,\n        done: false,\n        cb\n      })\n    },\n    final(cb) {\n      const _resolve = resolve\n      resolve = null\n      _resolve({\n        done: true,\n        cb\n      })\n    },\n    destroy(err, cb) {\n      ac.abort()\n      cb(err)\n    }\n  }\n}\nfunction _duplexify(pair) {\n  const r = pair.readable && typeof pair.readable.read !== 'function' ? Readable.wrap(pair.readable) : pair.readable\n  const w = pair.writable\n  let readable = !!isReadable(r)\n  let writable = !!isWritable(w)\n  let ondrain\n  let onfinish\n  let onreadable\n  let onclose\n  let d\n  function onfinished(err) {\n    const cb = onclose\n    onclose = null\n    if (cb) {\n      cb(err)\n    } else if (err) {\n      d.destroy(err)\n    }\n  }\n\n  // TODO(ronag): Avoid double buffering.\n  // Implement Writable/Readable/Duplex traits.\n  // See, https://github.com/nodejs/node/pull/33515.\n  d = new Duplexify({\n    // TODO (ronag): highWaterMark?\n    readableObjectMode: !!(r !== null && r !== undefined && r.readableObjectMode),\n    writableObjectMode: !!(w !== null && w !== undefined && w.writableObjectMode),\n    readable,\n    writable\n  })\n  if (writable) {\n    eos(w, (err) => {\n      writable = false\n      if (err) {\n        destroyer(r, err)\n      }\n      onfinished(err)\n    })\n    d._write = function (chunk, encoding, callback) {\n      if (w.write(chunk, encoding)) {\n        callback()\n      } else {\n        ondrain = callback\n      }\n    }\n    d._final = function (callback) {\n      w.end()\n      onfinish = callback\n    }\n    w.on('drain', function () {\n      if (ondrain) {\n        const cb = ondrain\n        ondrain = null\n        cb()\n      }\n    })\n    w.on('finish', function () {\n      if (onfinish) {\n        const cb = onfinish\n        onfinish = null\n        cb()\n      }\n    })\n  }\n  if (readable) {\n    eos(r, (err) => {\n      readable = false\n      if (err) {\n        destroyer(r, err)\n      }\n      onfinished(err)\n    })\n    r.on('readable', function () {\n      if (onreadable) {\n        const cb = onreadable\n        onreadable = null\n        cb()\n      }\n    })\n    r.on('end', function () {\n      d.push(null)\n    })\n    d._read = function () {\n      while (true) {\n        const buf = r.read()\n        if (buf === null) {\n          onreadable = d._read\n          return\n        }\n        if (!d.push(buf)) {\n          return\n        }\n      }\n    }\n  }\n  d._destroy = function (err, callback) {\n    if (!err && onclose !== null) {\n      err = new AbortError()\n    }\n    onreadable = null\n    ondrain = null\n    onfinish = null\n    if (onclose === null) {\n      callback(err)\n    } else {\n      onclose = callback\n      destroyer(w, err)\n      destroyer(r, err)\n    }\n  }\n  return d\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototype inheritance, this class\n// prototypically inherits from Readable, and then parasitically from\n// Writable.\n\n'use strict'\n\nconst {\n  ObjectDefineProperties,\n  ObjectGetOwnPropertyDescriptor,\n  ObjectKeys,\n  ObjectSetPrototypeOf\n} = require('../../ours/primordials')\nmodule.exports = Duplex\nconst Readable = require('./readable')\nconst Writable = require('./writable')\nObjectSetPrototypeOf(Duplex.prototype, Readable.prototype)\nObjectSetPrototypeOf(Duplex, Readable)\n{\n  const keys = ObjectKeys(Writable.prototype)\n  // Allow the keys array to be GC'ed.\n  for (let i = 0; i < keys.length; i++) {\n    const method = keys[i]\n    if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]\n  }\n}\nfunction Duplex(options) {\n  if (!(this instanceof Duplex)) return new Duplex(options)\n  Readable.call(this, options)\n  Writable.call(this, options)\n  if (options) {\n    this.allowHalfOpen = options.allowHalfOpen !== false\n    if (options.readable === false) {\n      this._readableState.readable = false\n      this._readableState.ended = true\n      this._readableState.endEmitted = true\n    }\n    if (options.writable === false) {\n      this._writableState.writable = false\n      this._writableState.ending = true\n      this._writableState.ended = true\n      this._writableState.finished = true\n    }\n  } else {\n    this.allowHalfOpen = true\n  }\n}\nObjectDefineProperties(Duplex.prototype, {\n  writable: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writable')\n  },\n  writableHighWaterMark: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableHighWaterMark')\n  },\n  writableObjectMode: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableObjectMode')\n  },\n  writableBuffer: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableBuffer')\n  },\n  writableLength: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableLength')\n  },\n  writableFinished: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableFinished')\n  },\n  writableCorked: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableCorked')\n  },\n  writableEnded: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableEnded')\n  },\n  writableNeedDrain: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableNeedDrain')\n  },\n  destroyed: {\n    __proto__: null,\n    get() {\n      if (this._readableState === undefined || this._writableState === undefined) {\n        return false\n      }\n      return this._readableState.destroyed && this._writableState.destroyed\n    },\n    set(value) {\n      // Backward compatibility, the user is explicitly\n      // managing destroyed.\n      if (this._readableState && this._writableState) {\n        this._readableState.destroyed = value\n        this._writableState.destroyed = value\n      }\n    }\n  }\n})\nlet webStreamsAdapters\n\n// Lazy to avoid circular references\nfunction lazyWebStreams() {\n  if (webStreamsAdapters === undefined) webStreamsAdapters = {}\n  return webStreamsAdapters\n}\nDuplex.fromWeb = function (pair, options) {\n  return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair, options)\n}\nDuplex.toWeb = function (duplex) {\n  return lazyWebStreams().newReadableWritablePairFromDuplex(duplex)\n}\nlet duplexify\nDuplex.from = function (body) {\n  if (!duplexify) {\n    duplexify = require('./duplexify')\n  }\n  return duplexify(body, 'body')\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data.  Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored.  (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation.  For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes.  When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up.  When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer.  When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks.  If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk.  However,\n// a pathological inflate type of transform can cause excessive buffering\n// here.  For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output.  Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output.  In this case, you could write a very small\n// amount of input, and end up with a very large amount of output.  In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform.  A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n'use strict'\n\nconst { ObjectSetPrototypeOf, Symbol } = require('../../ours/primordials')\nmodule.exports = Transform\nconst { ERR_METHOD_NOT_IMPLEMENTED } = require('../../ours/errors').codes\nconst Duplex = require('./duplex')\nconst { getHighWaterMark } = require('./state')\nObjectSetPrototypeOf(Transform.prototype, Duplex.prototype)\nObjectSetPrototypeOf(Transform, Duplex)\nconst kCallback = Symbol('kCallback')\nfunction Transform(options) {\n  if (!(this instanceof Transform)) return new Transform(options)\n\n  // TODO (ronag): This should preferably always be\n  // applied but would be semver-major. Or even better;\n  // make Transform a Readable with the Writable interface.\n  const readableHighWaterMark = options ? getHighWaterMark(this, options, 'readableHighWaterMark', true) : null\n  if (readableHighWaterMark === 0) {\n    // A Duplex will buffer both on the writable and readable side while\n    // a Transform just wants to buffer hwm number of elements. To avoid\n    // buffering twice we disable buffering on the writable side.\n    options = {\n      ...options,\n      highWaterMark: null,\n      readableHighWaterMark,\n      // TODO (ronag): 0 is not optimal since we have\n      // a \"bug\" where we check needDrain before calling _write and not after.\n      // Refs: https://github.com/nodejs/node/pull/32887\n      // Refs: https://github.com/nodejs/node/pull/35941\n      writableHighWaterMark: options.writableHighWaterMark || 0\n    }\n  }\n  Duplex.call(this, options)\n\n  // We have implemented the _read method, and done the other things\n  // that Readable wants before the first _read call, so unset the\n  // sync guard flag.\n  this._readableState.sync = false\n  this[kCallback] = null\n  if (options) {\n    if (typeof options.transform === 'function') this._transform = options.transform\n    if (typeof options.flush === 'function') this._flush = options.flush\n  }\n\n  // When the writable side finishes, then flush out anything remaining.\n  // Backwards compat. Some Transform streams incorrectly implement _final\n  // instead of or in addition to _flush. By using 'prefinish' instead of\n  // implementing _final we continue supporting this unfortunate use case.\n  this.on('prefinish', prefinish)\n}\nfunction final(cb) {\n  if (typeof this._flush === 'function' && !this.destroyed) {\n    this._flush((er, data) => {\n      if (er) {\n        if (cb) {\n          cb(er)\n        } else {\n          this.destroy(er)\n        }\n        return\n      }\n      if (data != null) {\n        this.push(data)\n      }\n      this.push(null)\n      if (cb) {\n        cb()\n      }\n    })\n  } else {\n    this.push(null)\n    if (cb) {\n      cb()\n    }\n  }\n}\nfunction prefinish() {\n  if (this._final !== final) {\n    final.call(this)\n  }\n}\nTransform.prototype._final = final\nTransform.prototype._transform = function (chunk, encoding, callback) {\n  throw new ERR_METHOD_NOT_IMPLEMENTED('_transform()')\n}\nTransform.prototype._write = function (chunk, encoding, callback) {\n  const rState = this._readableState\n  const wState = this._writableState\n  const length = rState.length\n  this._transform(chunk, encoding, (err, val) => {\n    if (err) {\n      callback(err)\n      return\n    }\n    if (val != null) {\n      this.push(val)\n    }\n    if (\n      wState.ended ||\n      // Backwards compat.\n      length === rState.length ||\n      // Backwards compat.\n      rState.length < rState.highWaterMark\n    ) {\n      callback()\n    } else {\n      this[kCallback] = callback\n    }\n  })\n}\nTransform.prototype._read = function () {\n  if (this[kCallback]) {\n    const callback = this[kCallback]\n    this[kCallback] = null\n    callback()\n  }\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n'use strict'\n\nconst { ObjectSetPrototypeOf } = require('../../ours/primordials')\nmodule.exports = PassThrough\nconst Transform = require('./transform')\nObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype)\nObjectSetPrototypeOf(PassThrough, Transform)\nfunction PassThrough(options) {\n  if (!(this instanceof PassThrough)) return new PassThrough(options)\n  Transform.call(this, options)\n}\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n  cb(null, chunk)\n}\n","/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n// Ported from https://github.com/mafintosh/pump with\n// permission from the author, Mathias Buus (@mafintosh).\n\n;('use strict')\nconst { ArrayIsArray, Promise, SymbolAsyncIterator, SymbolDispose } = require('../../ours/primordials')\nconst eos = require('./end-of-stream')\nconst { once } = require('../../ours/util')\nconst destroyImpl = require('./destroy')\nconst Duplex = require('./duplex')\nconst {\n  aggregateTwoErrors,\n  codes: {\n    ERR_INVALID_ARG_TYPE,\n    ERR_INVALID_RETURN_VALUE,\n    ERR_MISSING_ARGS,\n    ERR_STREAM_DESTROYED,\n    ERR_STREAM_PREMATURE_CLOSE\n  },\n  AbortError\n} = require('../../ours/errors')\nconst { validateFunction, validateAbortSignal } = require('../validators')\nconst {\n  isIterable,\n  isReadable,\n  isReadableNodeStream,\n  isNodeStream,\n  isTransformStream,\n  isWebStream,\n  isReadableStream,\n  isReadableFinished\n} = require('./utils')\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nlet PassThrough\nlet Readable\nlet addAbortListener\nfunction destroyer(stream, reading, writing) {\n  let finished = false\n  stream.on('close', () => {\n    finished = true\n  })\n  const cleanup = eos(\n    stream,\n    {\n      readable: reading,\n      writable: writing\n    },\n    (err) => {\n      finished = !err\n    }\n  )\n  return {\n    destroy: (err) => {\n      if (finished) return\n      finished = true\n      destroyImpl.destroyer(stream, err || new ERR_STREAM_DESTROYED('pipe'))\n    },\n    cleanup\n  }\n}\nfunction popCallback(streams) {\n  // Streams should never be an empty array. It should always contain at least\n  // a single stream. Therefore optimize for the average case instead of\n  // checking for length === 0 as well.\n  validateFunction(streams[streams.length - 1], 'streams[stream.length - 1]')\n  return streams.pop()\n}\nfunction makeAsyncIterable(val) {\n  if (isIterable(val)) {\n    return val\n  } else if (isReadableNodeStream(val)) {\n    // Legacy streams are not Iterable.\n    return fromReadable(val)\n  }\n  throw new ERR_INVALID_ARG_TYPE('val', ['Readable', 'Iterable', 'AsyncIterable'], val)\n}\nasync function* fromReadable(val) {\n  if (!Readable) {\n    Readable = require('./readable')\n  }\n  yield* Readable.prototype[SymbolAsyncIterator].call(val)\n}\nasync function pumpToNode(iterable, writable, finish, { end }) {\n  let error\n  let onresolve = null\n  const resume = (err) => {\n    if (err) {\n      error = err\n    }\n    if (onresolve) {\n      const callback = onresolve\n      onresolve = null\n      callback()\n    }\n  }\n  const wait = () =>\n    new Promise((resolve, reject) => {\n      if (error) {\n        reject(error)\n      } else {\n        onresolve = () => {\n          if (error) {\n            reject(error)\n          } else {\n            resolve()\n          }\n        }\n      }\n    })\n  writable.on('drain', resume)\n  const cleanup = eos(\n    writable,\n    {\n      readable: false\n    },\n    resume\n  )\n  try {\n    if (writable.writableNeedDrain) {\n      await wait()\n    }\n    for await (const chunk of iterable) {\n      if (!writable.write(chunk)) {\n        await wait()\n      }\n    }\n    if (end) {\n      writable.end()\n      await wait()\n    }\n    finish()\n  } catch (err) {\n    finish(error !== err ? aggregateTwoErrors(error, err) : err)\n  } finally {\n    cleanup()\n    writable.off('drain', resume)\n  }\n}\nasync function pumpToWeb(readable, writable, finish, { end }) {\n  if (isTransformStream(writable)) {\n    writable = writable.writable\n  }\n  // https://streams.spec.whatwg.org/#example-manual-write-with-backpressure\n  const writer = writable.getWriter()\n  try {\n    for await (const chunk of readable) {\n      await writer.ready\n      writer.write(chunk).catch(() => {})\n    }\n    await writer.ready\n    if (end) {\n      await writer.close()\n    }\n    finish()\n  } catch (err) {\n    try {\n      await writer.abort(err)\n      finish(err)\n    } catch (err) {\n      finish(err)\n    }\n  }\n}\nfunction pipeline(...streams) {\n  return pipelineImpl(streams, once(popCallback(streams)))\n}\nfunction pipelineImpl(streams, callback, opts) {\n  if (streams.length === 1 && ArrayIsArray(streams[0])) {\n    streams = streams[0]\n  }\n  if (streams.length < 2) {\n    throw new ERR_MISSING_ARGS('streams')\n  }\n  const ac = new AbortController()\n  const signal = ac.signal\n  const outerSignal = opts === null || opts === undefined ? undefined : opts.signal\n\n  // Need to cleanup event listeners if last stream is readable\n  // https://github.com/nodejs/node/issues/35452\n  const lastStreamCleanup = []\n  validateAbortSignal(outerSignal, 'options.signal')\n  function abort() {\n    finishImpl(new AbortError())\n  }\n  addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n  let disposable\n  if (outerSignal) {\n    disposable = addAbortListener(outerSignal, abort)\n  }\n  let error\n  let value\n  const destroys = []\n  let finishCount = 0\n  function finish(err) {\n    finishImpl(err, --finishCount === 0)\n  }\n  function finishImpl(err, final) {\n    var _disposable\n    if (err && (!error || error.code === 'ERR_STREAM_PREMATURE_CLOSE')) {\n      error = err\n    }\n    if (!error && !final) {\n      return\n    }\n    while (destroys.length) {\n      destroys.shift()(error)\n    }\n    ;(_disposable = disposable) === null || _disposable === undefined ? undefined : _disposable[SymbolDispose]()\n    ac.abort()\n    if (final) {\n      if (!error) {\n        lastStreamCleanup.forEach((fn) => fn())\n      }\n      process.nextTick(callback, error, value)\n    }\n  }\n  let ret\n  for (let i = 0; i < streams.length; i++) {\n    const stream = streams[i]\n    const reading = i < streams.length - 1\n    const writing = i > 0\n    const end = reading || (opts === null || opts === undefined ? undefined : opts.end) !== false\n    const isLastStream = i === streams.length - 1\n    if (isNodeStream(stream)) {\n      if (end) {\n        const { destroy, cleanup } = destroyer(stream, reading, writing)\n        destroys.push(destroy)\n        if (isReadable(stream) && isLastStream) {\n          lastStreamCleanup.push(cleanup)\n        }\n      }\n\n      // Catch stream errors that occur after pipe/pump has completed.\n      function onError(err) {\n        if (err && err.name !== 'AbortError' && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n          finish(err)\n        }\n      }\n      stream.on('error', onError)\n      if (isReadable(stream) && isLastStream) {\n        lastStreamCleanup.push(() => {\n          stream.removeListener('error', onError)\n        })\n      }\n    }\n    if (i === 0) {\n      if (typeof stream === 'function') {\n        ret = stream({\n          signal\n        })\n        if (!isIterable(ret)) {\n          throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or Stream', 'source', ret)\n        }\n      } else if (isIterable(stream) || isReadableNodeStream(stream) || isTransformStream(stream)) {\n        ret = stream\n      } else {\n        ret = Duplex.from(stream)\n      }\n    } else if (typeof stream === 'function') {\n      if (isTransformStream(ret)) {\n        var _ret\n        ret = makeAsyncIterable((_ret = ret) === null || _ret === undefined ? undefined : _ret.readable)\n      } else {\n        ret = makeAsyncIterable(ret)\n      }\n      ret = stream(ret, {\n        signal\n      })\n      if (reading) {\n        if (!isIterable(ret, true)) {\n          throw new ERR_INVALID_RETURN_VALUE('AsyncIterable', `transform[${i - 1}]`, ret)\n        }\n      } else {\n        var _ret2\n        if (!PassThrough) {\n          PassThrough = require('./passthrough')\n        }\n\n        // If the last argument to pipeline is not a stream\n        // we must create a proxy stream so that pipeline(...)\n        // always returns a stream which can be further\n        // composed through `.pipe(stream)`.\n\n        const pt = new PassThrough({\n          objectMode: true\n        })\n\n        // Handle Promises/A+ spec, `then` could be a getter that throws on\n        // second use.\n        const then = (_ret2 = ret) === null || _ret2 === undefined ? undefined : _ret2.then\n        if (typeof then === 'function') {\n          finishCount++\n          then.call(\n            ret,\n            (val) => {\n              value = val\n              if (val != null) {\n                pt.write(val)\n              }\n              if (end) {\n                pt.end()\n              }\n              process.nextTick(finish)\n            },\n            (err) => {\n              pt.destroy(err)\n              process.nextTick(finish, err)\n            }\n          )\n        } else if (isIterable(ret, true)) {\n          finishCount++\n          pumpToNode(ret, pt, finish, {\n            end\n          })\n        } else if (isReadableStream(ret) || isTransformStream(ret)) {\n          const toRead = ret.readable || ret\n          finishCount++\n          pumpToNode(toRead, pt, finish, {\n            end\n          })\n        } else {\n          throw new ERR_INVALID_RETURN_VALUE('AsyncIterable or Promise', 'destination', ret)\n        }\n        ret = pt\n        const { destroy, cleanup } = destroyer(ret, false, true)\n        destroys.push(destroy)\n        if (isLastStream) {\n          lastStreamCleanup.push(cleanup)\n        }\n      }\n    } else if (isNodeStream(stream)) {\n      if (isReadableNodeStream(ret)) {\n        finishCount += 2\n        const cleanup = pipe(ret, stream, finish, {\n          end\n        })\n        if (isReadable(stream) && isLastStream) {\n          lastStreamCleanup.push(cleanup)\n        }\n      } else if (isTransformStream(ret) || isReadableStream(ret)) {\n        const toRead = ret.readable || ret\n        finishCount++\n        pumpToNode(toRead, stream, finish, {\n          end\n        })\n      } else if (isIterable(ret)) {\n        finishCount++\n        pumpToNode(ret, stream, finish, {\n          end\n        })\n      } else {\n        throw new ERR_INVALID_ARG_TYPE(\n          'val',\n          ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'],\n          ret\n        )\n      }\n      ret = stream\n    } else if (isWebStream(stream)) {\n      if (isReadableNodeStream(ret)) {\n        finishCount++\n        pumpToWeb(makeAsyncIterable(ret), stream, finish, {\n          end\n        })\n      } else if (isReadableStream(ret) || isIterable(ret)) {\n        finishCount++\n        pumpToWeb(ret, stream, finish, {\n          end\n        })\n      } else if (isTransformStream(ret)) {\n        finishCount++\n        pumpToWeb(ret.readable, stream, finish, {\n          end\n        })\n      } else {\n        throw new ERR_INVALID_ARG_TYPE(\n          'val',\n          ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'],\n          ret\n        )\n      }\n      ret = stream\n    } else {\n      ret = Duplex.from(stream)\n    }\n  }\n  if (\n    (signal !== null && signal !== undefined && signal.aborted) ||\n    (outerSignal !== null && outerSignal !== undefined && outerSignal.aborted)\n  ) {\n    process.nextTick(abort)\n  }\n  return ret\n}\nfunction pipe(src, dst, finish, { end }) {\n  let ended = false\n  dst.on('close', () => {\n    if (!ended) {\n      // Finish if the destination closes before the source has completed.\n      finish(new ERR_STREAM_PREMATURE_CLOSE())\n    }\n  })\n  src.pipe(dst, {\n    end: false\n  }) // If end is true we already will have a listener to end dst.\n\n  if (end) {\n    // Compat. Before node v10.12.0 stdio used to throw an error so\n    // pipe() did/does not end() stdio destinations.\n    // Now they allow it but \"secretly\" don't close the underlying fd.\n\n    function endFn() {\n      ended = true\n      dst.end()\n    }\n    if (isReadableFinished(src)) {\n      // End the destination if the source has already ended.\n      process.nextTick(endFn)\n    } else {\n      src.once('end', endFn)\n    }\n  } else {\n    finish()\n  }\n  eos(\n    src,\n    {\n      readable: true,\n      writable: false\n    },\n    (err) => {\n      const rState = src._readableState\n      if (\n        err &&\n        err.code === 'ERR_STREAM_PREMATURE_CLOSE' &&\n        rState &&\n        rState.ended &&\n        !rState.errored &&\n        !rState.errorEmitted\n      ) {\n        // Some readable streams will emit 'close' before 'end'. However, since\n        // this is on the readable side 'end' should still be emitted if the\n        // stream has been ended and no error emitted. This should be allowed in\n        // favor of backwards compatibility. Since the stream is piped to a\n        // destination this should not result in any observable difference.\n        // We don't need to check if this is a writable premature close since\n        // eos will only fail with premature close on the reading side for\n        // duplex streams.\n        src.once('end', finish).once('error', finish)\n      } else {\n        finish(err)\n      }\n    }\n  )\n  return eos(\n    dst,\n    {\n      readable: false,\n      writable: true\n    },\n    finish\n  )\n}\nmodule.exports = {\n  pipelineImpl,\n  pipeline\n}\n","'use strict'\n\nconst { pipeline } = require('./pipeline')\nconst Duplex = require('./duplex')\nconst { destroyer } = require('./destroy')\nconst {\n  isNodeStream,\n  isReadable,\n  isWritable,\n  isWebStream,\n  isTransformStream,\n  isWritableStream,\n  isReadableStream\n} = require('./utils')\nconst {\n  AbortError,\n  codes: { ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS }\n} = require('../../ours/errors')\nconst eos = require('./end-of-stream')\nmodule.exports = function compose(...streams) {\n  if (streams.length === 0) {\n    throw new ERR_MISSING_ARGS('streams')\n  }\n  if (streams.length === 1) {\n    return Duplex.from(streams[0])\n  }\n  const orgStreams = [...streams]\n  if (typeof streams[0] === 'function') {\n    streams[0] = Duplex.from(streams[0])\n  }\n  if (typeof streams[streams.length - 1] === 'function') {\n    const idx = streams.length - 1\n    streams[idx] = Duplex.from(streams[idx])\n  }\n  for (let n = 0; n < streams.length; ++n) {\n    if (!isNodeStream(streams[n]) && !isWebStream(streams[n])) {\n      // TODO(ronag): Add checks for non streams.\n      continue\n    }\n    if (\n      n < streams.length - 1 &&\n      !(isReadable(streams[n]) || isReadableStream(streams[n]) || isTransformStream(streams[n]))\n    ) {\n      throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be readable')\n    }\n    if (n > 0 && !(isWritable(streams[n]) || isWritableStream(streams[n]) || isTransformStream(streams[n]))) {\n      throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be writable')\n    }\n  }\n  let ondrain\n  let onfinish\n  let onreadable\n  let onclose\n  let d\n  function onfinished(err) {\n    const cb = onclose\n    onclose = null\n    if (cb) {\n      cb(err)\n    } else if (err) {\n      d.destroy(err)\n    } else if (!readable && !writable) {\n      d.destroy()\n    }\n  }\n  const head = streams[0]\n  const tail = pipeline(streams, onfinished)\n  const writable = !!(isWritable(head) || isWritableStream(head) || isTransformStream(head))\n  const readable = !!(isReadable(tail) || isReadableStream(tail) || isTransformStream(tail))\n\n  // TODO(ronag): Avoid double buffering.\n  // Implement Writable/Readable/Duplex traits.\n  // See, https://github.com/nodejs/node/pull/33515.\n  d = new Duplex({\n    // TODO (ronag): highWaterMark?\n    writableObjectMode: !!(head !== null && head !== undefined && head.writableObjectMode),\n    readableObjectMode: !!(tail !== null && tail !== undefined && tail.readableObjectMode),\n    writable,\n    readable\n  })\n  if (writable) {\n    if (isNodeStream(head)) {\n      d._write = function (chunk, encoding, callback) {\n        if (head.write(chunk, encoding)) {\n          callback()\n        } else {\n          ondrain = callback\n        }\n      }\n      d._final = function (callback) {\n        head.end()\n        onfinish = callback\n      }\n      head.on('drain', function () {\n        if (ondrain) {\n          const cb = ondrain\n          ondrain = null\n          cb()\n        }\n      })\n    } else if (isWebStream(head)) {\n      const writable = isTransformStream(head) ? head.writable : head\n      const writer = writable.getWriter()\n      d._write = async function (chunk, encoding, callback) {\n        try {\n          await writer.ready\n          writer.write(chunk).catch(() => {})\n          callback()\n        } catch (err) {\n          callback(err)\n        }\n      }\n      d._final = async function (callback) {\n        try {\n          await writer.ready\n          writer.close().catch(() => {})\n          onfinish = callback\n        } catch (err) {\n          callback(err)\n        }\n      }\n    }\n    const toRead = isTransformStream(tail) ? tail.readable : tail\n    eos(toRead, () => {\n      if (onfinish) {\n        const cb = onfinish\n        onfinish = null\n        cb()\n      }\n    })\n  }\n  if (readable) {\n    if (isNodeStream(tail)) {\n      tail.on('readable', function () {\n        if (onreadable) {\n          const cb = onreadable\n          onreadable = null\n          cb()\n        }\n      })\n      tail.on('end', function () {\n        d.push(null)\n      })\n      d._read = function () {\n        while (true) {\n          const buf = tail.read()\n          if (buf === null) {\n            onreadable = d._read\n            return\n          }\n          if (!d.push(buf)) {\n            return\n          }\n        }\n      }\n    } else if (isWebStream(tail)) {\n      const readable = isTransformStream(tail) ? tail.readable : tail\n      const reader = readable.getReader()\n      d._read = async function () {\n        while (true) {\n          try {\n            const { value, done } = await reader.read()\n            if (!d.push(value)) {\n              return\n            }\n            if (done) {\n              d.push(null)\n              return\n            }\n          } catch {\n            return\n          }\n        }\n      }\n    }\n  }\n  d._destroy = function (err, callback) {\n    if (!err && onclose !== null) {\n      err = new AbortError()\n    }\n    onreadable = null\n    ondrain = null\n    onfinish = null\n    if (onclose === null) {\n      callback(err)\n    } else {\n      onclose = callback\n      if (isNodeStream(tail)) {\n        destroyer(tail, err)\n      }\n    }\n  }\n  return d\n}\n","'use strict'\n\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nconst {\n  codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE },\n  AbortError\n} = require('../../ours/errors')\nconst { validateAbortSignal, validateInteger, validateObject } = require('../validators')\nconst kWeakHandler = require('../../ours/primordials').Symbol('kWeak')\nconst kResistStopPropagation = require('../../ours/primordials').Symbol('kResistStopPropagation')\nconst { finished } = require('./end-of-stream')\nconst staticCompose = require('./compose')\nconst { addAbortSignalNoValidate } = require('./add-abort-signal')\nconst { isWritable, isNodeStream } = require('./utils')\nconst { deprecate } = require('../../ours/util')\nconst {\n  ArrayPrototypePush,\n  Boolean,\n  MathFloor,\n  Number,\n  NumberIsNaN,\n  Promise,\n  PromiseReject,\n  PromiseResolve,\n  PromisePrototypeThen,\n  Symbol\n} = require('../../ours/primordials')\nconst kEmpty = Symbol('kEmpty')\nconst kEof = Symbol('kEof')\nfunction compose(stream, options) {\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  if (isNodeStream(stream) && !isWritable(stream)) {\n    throw new ERR_INVALID_ARG_VALUE('stream', stream, 'must be writable')\n  }\n  const composedStream = staticCompose(this, stream)\n  if (options !== null && options !== undefined && options.signal) {\n    // Not validating as we already validated before\n    addAbortSignalNoValidate(options.signal, composedStream)\n  }\n  return composedStream\n}\nfunction map(fn, options) {\n  if (typeof fn !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n  }\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  let concurrency = 1\n  if ((options === null || options === undefined ? undefined : options.concurrency) != null) {\n    concurrency = MathFloor(options.concurrency)\n  }\n  let highWaterMark = concurrency - 1\n  if ((options === null || options === undefined ? undefined : options.highWaterMark) != null) {\n    highWaterMark = MathFloor(options.highWaterMark)\n  }\n  validateInteger(concurrency, 'options.concurrency', 1)\n  validateInteger(highWaterMark, 'options.highWaterMark', 0)\n  highWaterMark += concurrency\n  return async function* map() {\n    const signal = require('../../ours/util').AbortSignalAny(\n      [options === null || options === undefined ? undefined : options.signal].filter(Boolean)\n    )\n    const stream = this\n    const queue = []\n    const signalOpt = {\n      signal\n    }\n    let next\n    let resume\n    let done = false\n    let cnt = 0\n    function onCatch() {\n      done = true\n      afterItemProcessed()\n    }\n    function afterItemProcessed() {\n      cnt -= 1\n      maybeResume()\n    }\n    function maybeResume() {\n      if (resume && !done && cnt < concurrency && queue.length < highWaterMark) {\n        resume()\n        resume = null\n      }\n    }\n    async function pump() {\n      try {\n        for await (let val of stream) {\n          if (done) {\n            return\n          }\n          if (signal.aborted) {\n            throw new AbortError()\n          }\n          try {\n            val = fn(val, signalOpt)\n            if (val === kEmpty) {\n              continue\n            }\n            val = PromiseResolve(val)\n          } catch (err) {\n            val = PromiseReject(err)\n          }\n          cnt += 1\n          PromisePrototypeThen(val, afterItemProcessed, onCatch)\n          queue.push(val)\n          if (next) {\n            next()\n            next = null\n          }\n          if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) {\n            await new Promise((resolve) => {\n              resume = resolve\n            })\n          }\n        }\n        queue.push(kEof)\n      } catch (err) {\n        const val = PromiseReject(err)\n        PromisePrototypeThen(val, afterItemProcessed, onCatch)\n        queue.push(val)\n      } finally {\n        done = true\n        if (next) {\n          next()\n          next = null\n        }\n      }\n    }\n    pump()\n    try {\n      while (true) {\n        while (queue.length > 0) {\n          const val = await queue[0]\n          if (val === kEof) {\n            return\n          }\n          if (signal.aborted) {\n            throw new AbortError()\n          }\n          if (val !== kEmpty) {\n            yield val\n          }\n          queue.shift()\n          maybeResume()\n        }\n        await new Promise((resolve) => {\n          next = resolve\n        })\n      }\n    } finally {\n      done = true\n      if (resume) {\n        resume()\n        resume = null\n      }\n    }\n  }.call(this)\n}\nfunction asIndexedPairs(options = undefined) {\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  return async function* asIndexedPairs() {\n    let index = 0\n    for await (const val of this) {\n      var _options$signal\n      if (\n        options !== null &&\n        options !== undefined &&\n        (_options$signal = options.signal) !== null &&\n        _options$signal !== undefined &&\n        _options$signal.aborted\n      ) {\n        throw new AbortError({\n          cause: options.signal.reason\n        })\n      }\n      yield [index++, val]\n    }\n  }.call(this)\n}\nasync function some(fn, options = undefined) {\n  for await (const unused of filter.call(this, fn, options)) {\n    return true\n  }\n  return false\n}\nasync function every(fn, options = undefined) {\n  if (typeof fn !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n  }\n  // https://en.wikipedia.org/wiki/De_Morgan%27s_laws\n  return !(await some.call(\n    this,\n    async (...args) => {\n      return !(await fn(...args))\n    },\n    options\n  ))\n}\nasync function find(fn, options) {\n  for await (const result of filter.call(this, fn, options)) {\n    return result\n  }\n  return undefined\n}\nasync function forEach(fn, options) {\n  if (typeof fn !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n  }\n  async function forEachFn(value, options) {\n    await fn(value, options)\n    return kEmpty\n  }\n  // eslint-disable-next-line no-unused-vars\n  for await (const unused of map.call(this, forEachFn, options));\n}\nfunction filter(fn, options) {\n  if (typeof fn !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n  }\n  async function filterFn(value, options) {\n    if (await fn(value, options)) {\n      return value\n    }\n    return kEmpty\n  }\n  return map.call(this, filterFn, options)\n}\n\n// Specific to provide better error to reduce since the argument is only\n// missing if the stream has no items in it - but the code is still appropriate\nclass ReduceAwareErrMissingArgs extends ERR_MISSING_ARGS {\n  constructor() {\n    super('reduce')\n    this.message = 'Reduce of an empty stream requires an initial value'\n  }\n}\nasync function reduce(reducer, initialValue, options) {\n  var _options$signal2\n  if (typeof reducer !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE('reducer', ['Function', 'AsyncFunction'], reducer)\n  }\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  let hasInitialValue = arguments.length > 1\n  if (\n    options !== null &&\n    options !== undefined &&\n    (_options$signal2 = options.signal) !== null &&\n    _options$signal2 !== undefined &&\n    _options$signal2.aborted\n  ) {\n    const err = new AbortError(undefined, {\n      cause: options.signal.reason\n    })\n    this.once('error', () => {}) // The error is already propagated\n    await finished(this.destroy(err))\n    throw err\n  }\n  const ac = new AbortController()\n  const signal = ac.signal\n  if (options !== null && options !== undefined && options.signal) {\n    const opts = {\n      once: true,\n      [kWeakHandler]: this,\n      [kResistStopPropagation]: true\n    }\n    options.signal.addEventListener('abort', () => ac.abort(), opts)\n  }\n  let gotAnyItemFromStream = false\n  try {\n    for await (const value of this) {\n      var _options$signal3\n      gotAnyItemFromStream = true\n      if (\n        options !== null &&\n        options !== undefined &&\n        (_options$signal3 = options.signal) !== null &&\n        _options$signal3 !== undefined &&\n        _options$signal3.aborted\n      ) {\n        throw new AbortError()\n      }\n      if (!hasInitialValue) {\n        initialValue = value\n        hasInitialValue = true\n      } else {\n        initialValue = await reducer(initialValue, value, {\n          signal\n        })\n      }\n    }\n    if (!gotAnyItemFromStream && !hasInitialValue) {\n      throw new ReduceAwareErrMissingArgs()\n    }\n  } finally {\n    ac.abort()\n  }\n  return initialValue\n}\nasync function toArray(options) {\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  const result = []\n  for await (const val of this) {\n    var _options$signal4\n    if (\n      options !== null &&\n      options !== undefined &&\n      (_options$signal4 = options.signal) !== null &&\n      _options$signal4 !== undefined &&\n      _options$signal4.aborted\n    ) {\n      throw new AbortError(undefined, {\n        cause: options.signal.reason\n      })\n    }\n    ArrayPrototypePush(result, val)\n  }\n  return result\n}\nfunction flatMap(fn, options) {\n  const values = map.call(this, fn, options)\n  return async function* flatMap() {\n    for await (const val of values) {\n      yield* val\n    }\n  }.call(this)\n}\nfunction toIntegerOrInfinity(number) {\n  // We coerce here to align with the spec\n  // https://github.com/tc39/proposal-iterator-helpers/issues/169\n  number = Number(number)\n  if (NumberIsNaN(number)) {\n    return 0\n  }\n  if (number < 0) {\n    throw new ERR_OUT_OF_RANGE('number', '>= 0', number)\n  }\n  return number\n}\nfunction drop(number, options = undefined) {\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  number = toIntegerOrInfinity(number)\n  return async function* drop() {\n    var _options$signal5\n    if (\n      options !== null &&\n      options !== undefined &&\n      (_options$signal5 = options.signal) !== null &&\n      _options$signal5 !== undefined &&\n      _options$signal5.aborted\n    ) {\n      throw new AbortError()\n    }\n    for await (const val of this) {\n      var _options$signal6\n      if (\n        options !== null &&\n        options !== undefined &&\n        (_options$signal6 = options.signal) !== null &&\n        _options$signal6 !== undefined &&\n        _options$signal6.aborted\n      ) {\n        throw new AbortError()\n      }\n      if (number-- <= 0) {\n        yield val\n      }\n    }\n  }.call(this)\n}\nfunction take(number, options = undefined) {\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  number = toIntegerOrInfinity(number)\n  return async function* take() {\n    var _options$signal7\n    if (\n      options !== null &&\n      options !== undefined &&\n      (_options$signal7 = options.signal) !== null &&\n      _options$signal7 !== undefined &&\n      _options$signal7.aborted\n    ) {\n      throw new AbortError()\n    }\n    for await (const val of this) {\n      var _options$signal8\n      if (\n        options !== null &&\n        options !== undefined &&\n        (_options$signal8 = options.signal) !== null &&\n        _options$signal8 !== undefined &&\n        _options$signal8.aborted\n      ) {\n        throw new AbortError()\n      }\n      if (number-- > 0) {\n        yield val\n      }\n\n      // Don't get another item from iterator in case we reached the end\n      if (number <= 0) {\n        return\n      }\n    }\n  }.call(this)\n}\nmodule.exports.streamReturningOperators = {\n  asIndexedPairs: deprecate(asIndexedPairs, 'readable.asIndexedPairs will be removed in a future version.'),\n  drop,\n  filter,\n  flatMap,\n  map,\n  take,\n  compose\n}\nmodule.exports.promiseReturningOperators = {\n  every,\n  forEach,\n  reduce,\n  toArray,\n  some,\n  find\n}\n","'use strict'\n\nconst { ArrayPrototypePop, Promise } = require('../ours/primordials')\nconst { isIterable, isNodeStream, isWebStream } = require('../internal/streams/utils')\nconst { pipelineImpl: pl } = require('../internal/streams/pipeline')\nconst { finished } = require('../internal/streams/end-of-stream')\nrequire('../../lib/stream.js')\nfunction pipeline(...streams) {\n  return new Promise((resolve, reject) => {\n    let signal\n    let end\n    const lastArg = streams[streams.length - 1]\n    if (\n      lastArg &&\n      typeof lastArg === 'object' &&\n      !isNodeStream(lastArg) &&\n      !isIterable(lastArg) &&\n      !isWebStream(lastArg)\n    ) {\n      const options = ArrayPrototypePop(streams)\n      signal = options.signal\n      end = options.end\n    }\n    pl(\n      streams,\n      (err, value) => {\n        if (err) {\n          reject(err)\n        } else {\n          resolve(value)\n        }\n      },\n      {\n        signal,\n        end\n      }\n    )\n  })\n}\nmodule.exports = {\n  finished,\n  pipeline\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict'\n\n/* replacement start */\n\nconst { Buffer } = require('buffer')\n\n/* replacement end */\n\nconst { ObjectDefineProperty, ObjectKeys, ReflectApply } = require('./ours/primordials')\nconst {\n  promisify: { custom: customPromisify }\n} = require('./ours/util')\nconst { streamReturningOperators, promiseReturningOperators } = require('./internal/streams/operators')\nconst {\n  codes: { ERR_ILLEGAL_CONSTRUCTOR }\n} = require('./ours/errors')\nconst compose = require('./internal/streams/compose')\nconst { setDefaultHighWaterMark, getDefaultHighWaterMark } = require('./internal/streams/state')\nconst { pipeline } = require('./internal/streams/pipeline')\nconst { destroyer } = require('./internal/streams/destroy')\nconst eos = require('./internal/streams/end-of-stream')\nconst internalBuffer = {}\nconst promises = require('./stream/promises')\nconst utils = require('./internal/streams/utils')\nconst Stream = (module.exports = require('./internal/streams/legacy').Stream)\nStream.isDestroyed = utils.isDestroyed\nStream.isDisturbed = utils.isDisturbed\nStream.isErrored = utils.isErrored\nStream.isReadable = utils.isReadable\nStream.isWritable = utils.isWritable\nStream.Readable = require('./internal/streams/readable')\nfor (const key of ObjectKeys(streamReturningOperators)) {\n  const op = streamReturningOperators[key]\n  function fn(...args) {\n    if (new.target) {\n      throw ERR_ILLEGAL_CONSTRUCTOR()\n    }\n    return Stream.Readable.from(ReflectApply(op, this, args))\n  }\n  ObjectDefineProperty(fn, 'name', {\n    __proto__: null,\n    value: op.name\n  })\n  ObjectDefineProperty(fn, 'length', {\n    __proto__: null,\n    value: op.length\n  })\n  ObjectDefineProperty(Stream.Readable.prototype, key, {\n    __proto__: null,\n    value: fn,\n    enumerable: false,\n    configurable: true,\n    writable: true\n  })\n}\nfor (const key of ObjectKeys(promiseReturningOperators)) {\n  const op = promiseReturningOperators[key]\n  function fn(...args) {\n    if (new.target) {\n      throw ERR_ILLEGAL_CONSTRUCTOR()\n    }\n    return ReflectApply(op, this, args)\n  }\n  ObjectDefineProperty(fn, 'name', {\n    __proto__: null,\n    value: op.name\n  })\n  ObjectDefineProperty(fn, 'length', {\n    __proto__: null,\n    value: op.length\n  })\n  ObjectDefineProperty(Stream.Readable.prototype, key, {\n    __proto__: null,\n    value: fn,\n    enumerable: false,\n    configurable: true,\n    writable: true\n  })\n}\nStream.Writable = require('./internal/streams/writable')\nStream.Duplex = require('./internal/streams/duplex')\nStream.Transform = require('./internal/streams/transform')\nStream.PassThrough = require('./internal/streams/passthrough')\nStream.pipeline = pipeline\nconst { addAbortSignal } = require('./internal/streams/add-abort-signal')\nStream.addAbortSignal = addAbortSignal\nStream.finished = eos\nStream.destroy = destroyer\nStream.compose = compose\nStream.setDefaultHighWaterMark = setDefaultHighWaterMark\nStream.getDefaultHighWaterMark = getDefaultHighWaterMark\nObjectDefineProperty(Stream, 'promises', {\n  __proto__: null,\n  configurable: true,\n  enumerable: true,\n  get() {\n    return promises\n  }\n})\nObjectDefineProperty(pipeline, customPromisify, {\n  __proto__: null,\n  enumerable: true,\n  get() {\n    return promises.pipeline\n  }\n})\nObjectDefineProperty(eos, customPromisify, {\n  __proto__: null,\n  enumerable: true,\n  get() {\n    return promises.finished\n  }\n})\n\n// Backwards-compat with node 0.4.x\nStream.Stream = Stream\nStream._isUint8Array = function isUint8Array(value) {\n  return value instanceof Uint8Array\n}\nStream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) {\n  return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)\n}\n","'use strict'\n\nconst Stream = require('stream')\nif (Stream && process.env.READABLE_STREAM === 'disable') {\n  const promises = Stream.promises\n\n  // Explicit export naming is needed for ESM\n  module.exports._uint8ArrayToBuffer = Stream._uint8ArrayToBuffer\n  module.exports._isUint8Array = Stream._isUint8Array\n  module.exports.isDisturbed = Stream.isDisturbed\n  module.exports.isErrored = Stream.isErrored\n  module.exports.isReadable = Stream.isReadable\n  module.exports.Readable = Stream.Readable\n  module.exports.Writable = Stream.Writable\n  module.exports.Duplex = Stream.Duplex\n  module.exports.Transform = Stream.Transform\n  module.exports.PassThrough = Stream.PassThrough\n  module.exports.addAbortSignal = Stream.addAbortSignal\n  module.exports.finished = Stream.finished\n  module.exports.destroy = Stream.destroy\n  module.exports.pipeline = Stream.pipeline\n  module.exports.compose = Stream.compose\n  Object.defineProperty(Stream, 'promises', {\n    configurable: true,\n    enumerable: true,\n    get() {\n      return promises\n    }\n  })\n  module.exports.Stream = Stream.Stream\n} else {\n  const CustomStream = require('../stream')\n  const promises = require('../stream/promises')\n  const originalDestroy = CustomStream.Readable.destroy\n  module.exports = CustomStream.Readable\n\n  // Explicit export naming is needed for ESM\n  module.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer\n  module.exports._isUint8Array = CustomStream._isUint8Array\n  module.exports.isDisturbed = CustomStream.isDisturbed\n  module.exports.isErrored = CustomStream.isErrored\n  module.exports.isReadable = CustomStream.isReadable\n  module.exports.Readable = CustomStream.Readable\n  module.exports.Writable = CustomStream.Writable\n  module.exports.Duplex = CustomStream.Duplex\n  module.exports.Transform = CustomStream.Transform\n  module.exports.PassThrough = CustomStream.PassThrough\n  module.exports.addAbortSignal = CustomStream.addAbortSignal\n  module.exports.finished = CustomStream.finished\n  module.exports.destroy = CustomStream.destroy\n  module.exports.destroy = originalDestroy\n  module.exports.pipeline = CustomStream.pipeline\n  module.exports.compose = CustomStream.compose\n  Object.defineProperty(CustomStream, 'promises', {\n    configurable: true,\n    enumerable: true,\n    get() {\n      return promises\n    }\n  })\n  module.exports.Stream = CustomStream.Stream\n}\n\n// Allow default importing\nmodule.exports.default = module.exports\n","/**\n * node-compress-commons\n *\n * Copyright (c) 2014 Chris Talkington, contributors.\n * Licensed under the MIT license.\n * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT\n */\nvar Stream = require('stream').Stream;\nvar PassThrough = require('readable-stream').PassThrough;\nvar isStream = require('is-stream');\n\nvar util = module.exports = {};\n\nutil.normalizeInputSource = function(source) {\n  if (source === null) {\n    return Buffer.alloc(0);\n  } else if (typeof source === 'string') {\n    return Buffer.from(source);\n  } else if (isStream(source) && !source._readableState) {\n    var normalized = new PassThrough();\n    source.pipe(normalized);\n\n    return normalized;\n  }\n\n  return source;\n};","/**\n * node-compress-commons\n *\n * Copyright (c) 2014 Chris Talkington, contributors.\n * Licensed under the MIT license.\n * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT\n */\nvar inherits = require('util').inherits;\nvar isStream = require('is-stream');\nvar Transform = require('readable-stream').Transform;\n\nvar ArchiveEntry = require('./archive-entry');\nvar util = require('../util');\n\nvar ArchiveOutputStream = module.exports = function(options) {\n  if (!(this instanceof ArchiveOutputStream)) {\n    return new ArchiveOutputStream(options);\n  }\n\n  Transform.call(this, options);\n\n  this.offset = 0;\n  this._archive = {\n    finish: false,\n    finished: false,\n    processing: false\n  };\n};\n\ninherits(ArchiveOutputStream, Transform);\n\nArchiveOutputStream.prototype._appendBuffer = function(zae, source, callback) {\n  // scaffold only\n};\n\nArchiveOutputStream.prototype._appendStream = function(zae, source, callback) {\n  // scaffold only\n};\n\nArchiveOutputStream.prototype._emitErrorCallback = function(err) {\n  if (err) {\n    this.emit('error', err);\n  }\n};\n\nArchiveOutputStream.prototype._finish = function(ae) {\n  // scaffold only\n};\n\nArchiveOutputStream.prototype._normalizeEntry = function(ae) {\n  // scaffold only\n};\n\nArchiveOutputStream.prototype._transform = function(chunk, encoding, callback) {\n  callback(null, chunk);\n};\n\nArchiveOutputStream.prototype.entry = function(ae, source, callback) {\n  source = source || null;\n\n  if (typeof callback !== 'function') {\n    callback = this._emitErrorCallback.bind(this);\n  }\n\n  if (!(ae instanceof ArchiveEntry)) {\n    callback(new Error('not a valid instance of ArchiveEntry'));\n    return;\n  }\n\n  if (this._archive.finish || this._archive.finished) {\n    callback(new Error('unacceptable entry after finish'));\n    return;\n  }\n\n  if (this._archive.processing) {\n    callback(new Error('already processing an entry'));\n    return;\n  }\n\n  this._archive.processing = true;\n  this._normalizeEntry(ae);\n  this._entry = ae;\n\n  source = util.normalizeInputSource(source);\n\n  if (Buffer.isBuffer(source)) {\n    this._appendBuffer(ae, source, callback);\n  } else if (isStream(source)) {\n    this._appendStream(ae, source, callback);\n  } else {\n    this._archive.processing = false;\n    callback(new Error('input source must be valid Stream or Buffer instance'));\n    return;\n  }\n\n  return this;\n};\n\nArchiveOutputStream.prototype.finish = function() {\n  if (this._archive.processing) {\n    this._archive.finish = true;\n    return;\n  }\n\n  this._finish();\n};\n\nArchiveOutputStream.prototype.getBytesWritten = function() {\n  return this.offset;\n};\n\nArchiveOutputStream.prototype.write = function(chunk, cb) {\n  if (chunk) {\n    this.offset += chunk.length;\n  }\n\n  return Transform.prototype.write.call(this, chunk, cb);\n};","/*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */\n/* vim: set ts=2: */\n/*exported CRC32 */\nvar CRC32;\n(function (factory) {\n\t/*jshint ignore:start */\n\t/*eslint-disable */\n\tif(typeof DO_NOT_EXPORT_CRC === 'undefined') {\n\t\tif('object' === typeof exports) {\n\t\t\tfactory(exports);\n\t\t} else if ('function' === typeof define && define.amd) {\n\t\t\tdefine(function () {\n\t\t\t\tvar module = {};\n\t\t\t\tfactory(module);\n\t\t\t\treturn module;\n\t\t\t});\n\t\t} else {\n\t\t\tfactory(CRC32 = {});\n\t\t}\n\t} else {\n\t\tfactory(CRC32 = {});\n\t}\n\t/*eslint-enable */\n\t/*jshint ignore:end */\n}(function(CRC32) {\nCRC32.version = '1.2.2';\n/*global Int32Array */\nfunction signed_crc_table() {\n\tvar c = 0, table = new Array(256);\n\n\tfor(var n =0; n != 256; ++n){\n\t\tc = n;\n\t\tc = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));\n\t\tc = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));\n\t\tc = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));\n\t\tc = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));\n\t\tc = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));\n\t\tc = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));\n\t\tc = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));\n\t\tc = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1));\n\t\ttable[n] = c;\n\t}\n\n\treturn typeof Int32Array !== 'undefined' ? new Int32Array(table) : table;\n}\n\nvar T0 = signed_crc_table();\nfunction slice_by_16_tables(T) {\n\tvar c = 0, v = 0, n = 0, table = typeof Int32Array !== 'undefined' ? new Int32Array(4096) : new Array(4096) ;\n\n\tfor(n = 0; n != 256; ++n) table[n] = T[n];\n\tfor(n = 0; n != 256; ++n) {\n\t\tv = T[n];\n\t\tfor(c = 256 + n; c < 4096; c += 256) v = table[c] = (v >>> 8) ^ T[v & 0xFF];\n\t}\n\tvar out = [];\n\tfor(n = 1; n != 16; ++n) out[n - 1] = typeof Int32Array !== 'undefined' ? table.subarray(n * 256, n * 256 + 256) : table.slice(n * 256, n * 256 + 256);\n\treturn out;\n}\nvar TT = slice_by_16_tables(T0);\nvar T1 = TT[0],  T2 = TT[1],  T3 = TT[2],  T4 = TT[3],  T5 = TT[4];\nvar T6 = TT[5],  T7 = TT[6],  T8 = TT[7],  T9 = TT[8],  Ta = TT[9];\nvar Tb = TT[10], Tc = TT[11], Td = TT[12], Te = TT[13], Tf = TT[14];\nfunction crc32_bstr(bstr, seed) {\n\tvar C = seed ^ -1;\n\tfor(var i = 0, L = bstr.length; i < L;) C = (C>>>8) ^ T0[(C^bstr.charCodeAt(i++))&0xFF];\n\treturn ~C;\n}\n\nfunction crc32_buf(B, seed) {\n\tvar C = seed ^ -1, L = B.length - 15, i = 0;\n\tfor(; i < L;) C =\n\t\tTf[B[i++] ^ (C & 255)] ^\n\t\tTe[B[i++] ^ ((C >> 8) & 255)] ^\n\t\tTd[B[i++] ^ ((C >> 16) & 255)] ^\n\t\tTc[B[i++] ^ (C >>> 24)] ^\n\t\tTb[B[i++]] ^ Ta[B[i++]] ^ T9[B[i++]] ^ T8[B[i++]] ^\n\t\tT7[B[i++]] ^ T6[B[i++]] ^ T5[B[i++]] ^ T4[B[i++]] ^\n\t\tT3[B[i++]] ^ T2[B[i++]] ^ T1[B[i++]] ^ T0[B[i++]];\n\tL += 15;\n\twhile(i < L) C = (C>>>8) ^ T0[(C^B[i++])&0xFF];\n\treturn ~C;\n}\n\nfunction crc32_str(str, seed) {\n\tvar C = seed ^ -1;\n\tfor(var i = 0, L = str.length, c = 0, d = 0; i < L;) {\n\t\tc = str.charCodeAt(i++);\n\t\tif(c < 0x80) {\n\t\t\tC = (C>>>8) ^ T0[(C^c)&0xFF];\n\t\t} else if(c < 0x800) {\n\t\t\tC = (C>>>8) ^ T0[(C ^ (192|((c>>6)&31)))&0xFF];\n\t\t\tC = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF];\n\t\t} else if(c >= 0xD800 && c < 0xE000) {\n\t\t\tc = (c&1023)+64; d = str.charCodeAt(i++)&1023;\n\t\t\tC = (C>>>8) ^ T0[(C ^ (240|((c>>8)&7)))&0xFF];\n\t\t\tC = (C>>>8) ^ T0[(C ^ (128|((c>>2)&63)))&0xFF];\n\t\t\tC = (C>>>8) ^ T0[(C ^ (128|((d>>6)&15)|((c&3)<<4)))&0xFF];\n\t\t\tC = (C>>>8) ^ T0[(C ^ (128|(d&63)))&0xFF];\n\t\t} else {\n\t\t\tC = (C>>>8) ^ T0[(C ^ (224|((c>>12)&15)))&0xFF];\n\t\t\tC = (C>>>8) ^ T0[(C ^ (128|((c>>6)&63)))&0xFF];\n\t\t\tC = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF];\n\t\t}\n\t}\n\treturn ~C;\n}\nCRC32.table = T0;\n// $FlowIgnore\nCRC32.bstr = crc32_bstr;\n// $FlowIgnore\nCRC32.buf = crc32_buf;\n// $FlowIgnore\nCRC32.str = crc32_str;\n}));\n","'use strict'\n\n/*\n  This file is a reduced and adapted version of the main lib/internal/per_context/primordials.js file defined at\n\n  https://github.com/nodejs/node/blob/main/lib/internal/per_context/primordials.js\n\n  Don't try to replace with the original file and keep it up to date with the upstream file.\n*/\n\n// This is a simplified version of AggregateError\nclass AggregateError extends Error {\n  constructor(errors) {\n    if (!Array.isArray(errors)) {\n      throw new TypeError(`Expected input to be an Array, got ${typeof errors}`)\n    }\n    let message = ''\n    for (let i = 0; i < errors.length; i++) {\n      message += `    ${errors[i].stack}\\n`\n    }\n    super(message)\n    this.name = 'AggregateError'\n    this.errors = errors\n  }\n}\nmodule.exports = {\n  AggregateError,\n  ArrayIsArray(self) {\n    return Array.isArray(self)\n  },\n  ArrayPrototypeIncludes(self, el) {\n    return self.includes(el)\n  },\n  ArrayPrototypeIndexOf(self, el) {\n    return self.indexOf(el)\n  },\n  ArrayPrototypeJoin(self, sep) {\n    return self.join(sep)\n  },\n  ArrayPrototypeMap(self, fn) {\n    return self.map(fn)\n  },\n  ArrayPrototypePop(self, el) {\n    return self.pop(el)\n  },\n  ArrayPrototypePush(self, el) {\n    return self.push(el)\n  },\n  ArrayPrototypeSlice(self, start, end) {\n    return self.slice(start, end)\n  },\n  Error,\n  FunctionPrototypeCall(fn, thisArgs, ...args) {\n    return fn.call(thisArgs, ...args)\n  },\n  FunctionPrototypeSymbolHasInstance(self, instance) {\n    return Function.prototype[Symbol.hasInstance].call(self, instance)\n  },\n  MathFloor: Math.floor,\n  Number,\n  NumberIsInteger: Number.isInteger,\n  NumberIsNaN: Number.isNaN,\n  NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER,\n  NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER,\n  NumberParseInt: Number.parseInt,\n  ObjectDefineProperties(self, props) {\n    return Object.defineProperties(self, props)\n  },\n  ObjectDefineProperty(self, name, prop) {\n    return Object.defineProperty(self, name, prop)\n  },\n  ObjectGetOwnPropertyDescriptor(self, name) {\n    return Object.getOwnPropertyDescriptor(self, name)\n  },\n  ObjectKeys(obj) {\n    return Object.keys(obj)\n  },\n  ObjectSetPrototypeOf(target, proto) {\n    return Object.setPrototypeOf(target, proto)\n  },\n  Promise,\n  PromisePrototypeCatch(self, fn) {\n    return self.catch(fn)\n  },\n  PromisePrototypeThen(self, thenFn, catchFn) {\n    return self.then(thenFn, catchFn)\n  },\n  PromiseReject(err) {\n    return Promise.reject(err)\n  },\n  PromiseResolve(val) {\n    return Promise.resolve(val)\n  },\n  ReflectApply: Reflect.apply,\n  RegExpPrototypeTest(self, value) {\n    return self.test(value)\n  },\n  SafeSet: Set,\n  String,\n  StringPrototypeSlice(self, start, end) {\n    return self.slice(start, end)\n  },\n  StringPrototypeToLowerCase(self) {\n    return self.toLowerCase()\n  },\n  StringPrototypeToUpperCase(self) {\n    return self.toUpperCase()\n  },\n  StringPrototypeTrim(self) {\n    return self.trim()\n  },\n  Symbol,\n  SymbolFor: Symbol.for,\n  SymbolAsyncIterator: Symbol.asyncIterator,\n  SymbolHasInstance: Symbol.hasInstance,\n  SymbolIterator: Symbol.iterator,\n  SymbolDispose: Symbol.dispose || Symbol('Symbol.dispose'),\n  SymbolAsyncDispose: Symbol.asyncDispose || Symbol('Symbol.asyncDispose'),\n  TypedArrayPrototypeSet(self, buf, len) {\n    return self.set(buf, len)\n  },\n  Boolean,\n  Uint8Array\n}\n","'use strict'\n\n/*\n  This file is a reduced and adapted version of the main lib/internal/util/inspect.js file defined at\n\n  https://github.com/nodejs/node/blob/main/lib/internal/util/inspect.js\n\n  Don't try to replace with the original file and keep it up to date with the upstream file.\n*/\nmodule.exports = {\n  format(format, ...args) {\n    // Simplified version of https://nodejs.org/api/util.html#utilformatformat-args\n    return format.replace(/%([sdifj])/g, function (...[_unused, type]) {\n      const replacement = args.shift()\n      if (type === 'f') {\n        return replacement.toFixed(6)\n      } else if (type === 'j') {\n        return JSON.stringify(replacement)\n      } else if (type === 's' && typeof replacement === 'object') {\n        const ctor = replacement.constructor !== Object ? replacement.constructor.name : ''\n        return `${ctor} {}`.trim()\n      } else {\n        return replacement.toString()\n      }\n    })\n  },\n  inspect(value) {\n    // Vastly simplified version of https://nodejs.org/api/util.html#utilinspectobject-options\n    switch (typeof value) {\n      case 'string':\n        if (value.includes(\"'\")) {\n          if (!value.includes('\"')) {\n            return `\"${value}\"`\n          } else if (!value.includes('`') && !value.includes('${')) {\n            return `\\`${value}\\``\n          }\n        }\n        return `'${value}'`\n      case 'number':\n        if (isNaN(value)) {\n          return 'NaN'\n        } else if (Object.is(value, -0)) {\n          return String(value)\n        }\n        return value\n      case 'bigint':\n        return `${String(value)}n`\n      case 'boolean':\n      case 'undefined':\n        return String(value)\n      case 'object':\n        return '{}'\n    }\n  }\n}\n","'use strict'\n\nconst { format, inspect } = require('./util/inspect')\nconst { AggregateError: CustomAggregateError } = require('./primordials')\n\n/*\n  This file is a reduced and adapted version of the main lib/internal/errors.js file defined at\n\n  https://github.com/nodejs/node/blob/main/lib/internal/errors.js\n\n  Don't try to replace with the original file and keep it up to date (starting from E(...) definitions)\n  with the upstream file.\n*/\n\nconst AggregateError = globalThis.AggregateError || CustomAggregateError\nconst kIsNodeError = Symbol('kIsNodeError')\nconst kTypes = [\n  'string',\n  'function',\n  'number',\n  'object',\n  // Accept 'Function' and 'Object' as alternative to the lower cased version.\n  'Function',\n  'Object',\n  'boolean',\n  'bigint',\n  'symbol'\n]\nconst classRegExp = /^([A-Z][a-z0-9]*)+$/\nconst nodeInternalPrefix = '__node_internal_'\nconst codes = {}\nfunction assert(value, message) {\n  if (!value) {\n    throw new codes.ERR_INTERNAL_ASSERTION(message)\n  }\n}\n\n// Only use this for integers! Decimal numbers do not work with this function.\nfunction addNumericalSeparator(val) {\n  let res = ''\n  let i = val.length\n  const start = val[0] === '-' ? 1 : 0\n  for (; i >= start + 4; i -= 3) {\n    res = `_${val.slice(i - 3, i)}${res}`\n  }\n  return `${val.slice(0, i)}${res}`\n}\nfunction getMessage(key, msg, args) {\n  if (typeof msg === 'function') {\n    assert(\n      msg.length <= args.length,\n      // Default options do not count.\n      `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).`\n    )\n    return msg(...args)\n  }\n  const expectedLength = (msg.match(/%[dfijoOs]/g) || []).length\n  assert(\n    expectedLength === args.length,\n    `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).`\n  )\n  if (args.length === 0) {\n    return msg\n  }\n  return format(msg, ...args)\n}\nfunction E(code, message, Base) {\n  if (!Base) {\n    Base = Error\n  }\n  class NodeError extends Base {\n    constructor(...args) {\n      super(getMessage(code, message, args))\n    }\n    toString() {\n      return `${this.name} [${code}]: ${this.message}`\n    }\n  }\n  Object.defineProperties(NodeError.prototype, {\n    name: {\n      value: Base.name,\n      writable: true,\n      enumerable: false,\n      configurable: true\n    },\n    toString: {\n      value() {\n        return `${this.name} [${code}]: ${this.message}`\n      },\n      writable: true,\n      enumerable: false,\n      configurable: true\n    }\n  })\n  NodeError.prototype.code = code\n  NodeError.prototype[kIsNodeError] = true\n  codes[code] = NodeError\n}\nfunction hideStackFrames(fn) {\n  // We rename the functions that will be hidden to cut off the stacktrace\n  // at the outermost one\n  const hidden = nodeInternalPrefix + fn.name\n  Object.defineProperty(fn, 'name', {\n    value: hidden\n  })\n  return fn\n}\nfunction aggregateTwoErrors(innerError, outerError) {\n  if (innerError && outerError && innerError !== outerError) {\n    if (Array.isArray(outerError.errors)) {\n      // If `outerError` is already an `AggregateError`.\n      outerError.errors.push(innerError)\n      return outerError\n    }\n    const err = new AggregateError([outerError, innerError], outerError.message)\n    err.code = outerError.code\n    return err\n  }\n  return innerError || outerError\n}\nclass AbortError extends Error {\n  constructor(message = 'The operation was aborted', options = undefined) {\n    if (options !== undefined && typeof options !== 'object') {\n      throw new codes.ERR_INVALID_ARG_TYPE('options', 'Object', options)\n    }\n    super(message, options)\n    this.code = 'ABORT_ERR'\n    this.name = 'AbortError'\n  }\n}\nE('ERR_ASSERTION', '%s', Error)\nE(\n  'ERR_INVALID_ARG_TYPE',\n  (name, expected, actual) => {\n    assert(typeof name === 'string', \"'name' must be a string\")\n    if (!Array.isArray(expected)) {\n      expected = [expected]\n    }\n    let msg = 'The '\n    if (name.endsWith(' argument')) {\n      // For cases like 'first argument'\n      msg += `${name} `\n    } else {\n      msg += `\"${name}\" ${name.includes('.') ? 'property' : 'argument'} `\n    }\n    msg += 'must be '\n    const types = []\n    const instances = []\n    const other = []\n    for (const value of expected) {\n      assert(typeof value === 'string', 'All expected entries have to be of type string')\n      if (kTypes.includes(value)) {\n        types.push(value.toLowerCase())\n      } else if (classRegExp.test(value)) {\n        instances.push(value)\n      } else {\n        assert(value !== 'object', 'The value \"object\" should be written as \"Object\"')\n        other.push(value)\n      }\n    }\n\n    // Special handle `object` in case other instances are allowed to outline\n    // the differences between each other.\n    if (instances.length > 0) {\n      const pos = types.indexOf('object')\n      if (pos !== -1) {\n        types.splice(types, pos, 1)\n        instances.push('Object')\n      }\n    }\n    if (types.length > 0) {\n      switch (types.length) {\n        case 1:\n          msg += `of type ${types[0]}`\n          break\n        case 2:\n          msg += `one of type ${types[0]} or ${types[1]}`\n          break\n        default: {\n          const last = types.pop()\n          msg += `one of type ${types.join(', ')}, or ${last}`\n        }\n      }\n      if (instances.length > 0 || other.length > 0) {\n        msg += ' or '\n      }\n    }\n    if (instances.length > 0) {\n      switch (instances.length) {\n        case 1:\n          msg += `an instance of ${instances[0]}`\n          break\n        case 2:\n          msg += `an instance of ${instances[0]} or ${instances[1]}`\n          break\n        default: {\n          const last = instances.pop()\n          msg += `an instance of ${instances.join(', ')}, or ${last}`\n        }\n      }\n      if (other.length > 0) {\n        msg += ' or '\n      }\n    }\n    switch (other.length) {\n      case 0:\n        break\n      case 1:\n        if (other[0].toLowerCase() !== other[0]) {\n          msg += 'an '\n        }\n        msg += `${other[0]}`\n        break\n      case 2:\n        msg += `one of ${other[0]} or ${other[1]}`\n        break\n      default: {\n        const last = other.pop()\n        msg += `one of ${other.join(', ')}, or ${last}`\n      }\n    }\n    if (actual == null) {\n      msg += `. Received ${actual}`\n    } else if (typeof actual === 'function' && actual.name) {\n      msg += `. Received function ${actual.name}`\n    } else if (typeof actual === 'object') {\n      var _actual$constructor\n      if (\n        (_actual$constructor = actual.constructor) !== null &&\n        _actual$constructor !== undefined &&\n        _actual$constructor.name\n      ) {\n        msg += `. Received an instance of ${actual.constructor.name}`\n      } else {\n        const inspected = inspect(actual, {\n          depth: -1\n        })\n        msg += `. Received ${inspected}`\n      }\n    } else {\n      let inspected = inspect(actual, {\n        colors: false\n      })\n      if (inspected.length > 25) {\n        inspected = `${inspected.slice(0, 25)}...`\n      }\n      msg += `. Received type ${typeof actual} (${inspected})`\n    }\n    return msg\n  },\n  TypeError\n)\nE(\n  'ERR_INVALID_ARG_VALUE',\n  (name, value, reason = 'is invalid') => {\n    let inspected = inspect(value)\n    if (inspected.length > 128) {\n      inspected = inspected.slice(0, 128) + '...'\n    }\n    const type = name.includes('.') ? 'property' : 'argument'\n    return `The ${type} '${name}' ${reason}. Received ${inspected}`\n  },\n  TypeError\n)\nE(\n  'ERR_INVALID_RETURN_VALUE',\n  (input, name, value) => {\n    var _value$constructor\n    const type =\n      value !== null &&\n      value !== undefined &&\n      (_value$constructor = value.constructor) !== null &&\n      _value$constructor !== undefined &&\n      _value$constructor.name\n        ? `instance of ${value.constructor.name}`\n        : `type ${typeof value}`\n    return `Expected ${input} to be returned from the \"${name}\"` + ` function but got ${type}.`\n  },\n  TypeError\n)\nE(\n  'ERR_MISSING_ARGS',\n  (...args) => {\n    assert(args.length > 0, 'At least one arg needs to be specified')\n    let msg\n    const len = args.length\n    args = (Array.isArray(args) ? args : [args]).map((a) => `\"${a}\"`).join(' or ')\n    switch (len) {\n      case 1:\n        msg += `The ${args[0]} argument`\n        break\n      case 2:\n        msg += `The ${args[0]} and ${args[1]} arguments`\n        break\n      default:\n        {\n          const last = args.pop()\n          msg += `The ${args.join(', ')}, and ${last} arguments`\n        }\n        break\n    }\n    return `${msg} must be specified`\n  },\n  TypeError\n)\nE(\n  'ERR_OUT_OF_RANGE',\n  (str, range, input) => {\n    assert(range, 'Missing \"range\" argument')\n    let received\n    if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n      received = addNumericalSeparator(String(input))\n    } else if (typeof input === 'bigint') {\n      received = String(input)\n      const limit = BigInt(2) ** BigInt(32)\n      if (input > limit || input < -limit) {\n        received = addNumericalSeparator(received)\n      }\n      received += 'n'\n    } else {\n      received = inspect(input)\n    }\n    return `The value of \"${str}\" is out of range. It must be ${range}. Received ${received}`\n  },\n  RangeError\n)\nE('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times', Error)\nE('ERR_METHOD_NOT_IMPLEMENTED', 'The %s method is not implemented', Error)\nE('ERR_STREAM_ALREADY_FINISHED', 'Cannot call %s after a stream was finished', Error)\nE('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable', Error)\nE('ERR_STREAM_DESTROYED', 'Cannot call %s after a stream was destroyed', Error)\nE('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError)\nE('ERR_STREAM_PREMATURE_CLOSE', 'Premature close', Error)\nE('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF', Error)\nE('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event', Error)\nE('ERR_STREAM_WRITE_AFTER_END', 'write after end', Error)\nE('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s', TypeError)\nmodule.exports = {\n  AbortError,\n  aggregateTwoErrors: hideStackFrames(aggregateTwoErrors),\n  hideStackFrames,\n  codes\n}\n","'use strict'\n\nconst bufferModule = require('buffer')\nconst { format, inspect } = require('./util/inspect')\nconst {\n  codes: { ERR_INVALID_ARG_TYPE }\n} = require('./errors')\nconst { kResistStopPropagation, AggregateError, SymbolDispose } = require('./primordials')\nconst AbortSignal = globalThis.AbortSignal || require('abort-controller').AbortSignal\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nconst AsyncFunction = Object.getPrototypeOf(async function () {}).constructor\nconst Blob = globalThis.Blob || bufferModule.Blob\n/* eslint-disable indent */\nconst isBlob =\n  typeof Blob !== 'undefined'\n    ? function isBlob(b) {\n        // eslint-disable-next-line indent\n        return b instanceof Blob\n      }\n    : function isBlob(b) {\n        return false\n      }\n/* eslint-enable indent */\n\nconst validateAbortSignal = (signal, name) => {\n  if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) {\n    throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal)\n  }\n}\nconst validateFunction = (value, name) => {\n  if (typeof value !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE(name, 'Function', value)\n  }\n}\nmodule.exports = {\n  AggregateError,\n  kEmptyObject: Object.freeze({}),\n  once(callback) {\n    let called = false\n    return function (...args) {\n      if (called) {\n        return\n      }\n      called = true\n      callback.apply(this, args)\n    }\n  },\n  createDeferredPromise: function () {\n    let resolve\n    let reject\n\n    // eslint-disable-next-line promise/param-names\n    const promise = new Promise((res, rej) => {\n      resolve = res\n      reject = rej\n    })\n    return {\n      promise,\n      resolve,\n      reject\n    }\n  },\n  promisify(fn) {\n    return new Promise((resolve, reject) => {\n      fn((err, ...args) => {\n        if (err) {\n          return reject(err)\n        }\n        return resolve(...args)\n      })\n    })\n  },\n  debuglog() {\n    return function () {}\n  },\n  format,\n  inspect,\n  types: {\n    isAsyncFunction(fn) {\n      return fn instanceof AsyncFunction\n    },\n    isArrayBufferView(arr) {\n      return ArrayBuffer.isView(arr)\n    }\n  },\n  isBlob,\n  deprecate(fn, message) {\n    return fn\n  },\n  addAbortListener:\n    require('events').addAbortListener ||\n    function addAbortListener(signal, listener) {\n      if (signal === undefined) {\n        throw new ERR_INVALID_ARG_TYPE('signal', 'AbortSignal', signal)\n      }\n      validateAbortSignal(signal, 'signal')\n      validateFunction(listener, 'listener')\n      let removeEventListener\n      if (signal.aborted) {\n        queueMicrotask(() => listener())\n      } else {\n        signal.addEventListener('abort', listener, {\n          __proto__: null,\n          once: true,\n          [kResistStopPropagation]: true\n        })\n        removeEventListener = () => {\n          signal.removeEventListener('abort', listener)\n        }\n      }\n      return {\n        __proto__: null,\n        [SymbolDispose]() {\n          var _removeEventListener\n          ;(_removeEventListener = removeEventListener) === null || _removeEventListener === undefined\n            ? undefined\n            : _removeEventListener()\n        }\n      }\n    },\n  AbortSignalAny:\n    AbortSignal.any ||\n    function AbortSignalAny(signals) {\n      // Fast path if there is only one signal.\n      if (signals.length === 1) {\n        return signals[0]\n      }\n      const ac = new AbortController()\n      const abort = () => ac.abort()\n      signals.forEach((signal) => {\n        validateAbortSignal(signal, 'signals')\n        signal.addEventListener('abort', abort, {\n          once: true\n        })\n      })\n      ac.signal.addEventListener(\n        'abort',\n        () => {\n          signals.forEach((signal) => signal.removeEventListener('abort', abort))\n        },\n        {\n          once: true\n        }\n      )\n      return ac.signal\n    }\n}\nmodule.exports.promisify.custom = Symbol.for('nodejs.util.promisify.custom')\n","/* eslint jsdoc/require-jsdoc: \"error\" */\n\n'use strict'\n\nconst {\n  ArrayIsArray,\n  ArrayPrototypeIncludes,\n  ArrayPrototypeJoin,\n  ArrayPrototypeMap,\n  NumberIsInteger,\n  NumberIsNaN,\n  NumberMAX_SAFE_INTEGER,\n  NumberMIN_SAFE_INTEGER,\n  NumberParseInt,\n  ObjectPrototypeHasOwnProperty,\n  RegExpPrototypeExec,\n  String,\n  StringPrototypeToUpperCase,\n  StringPrototypeTrim\n} = require('../ours/primordials')\nconst {\n  hideStackFrames,\n  codes: { ERR_SOCKET_BAD_PORT, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_OUT_OF_RANGE, ERR_UNKNOWN_SIGNAL }\n} = require('../ours/errors')\nconst { normalizeEncoding } = require('../ours/util')\nconst { isAsyncFunction, isArrayBufferView } = require('../ours/util').types\nconst signals = {}\n\n/**\n * @param {*} value\n * @returns {boolean}\n */\nfunction isInt32(value) {\n  return value === (value | 0)\n}\n\n/**\n * @param {*} value\n * @returns {boolean}\n */\nfunction isUint32(value) {\n  return value === value >>> 0\n}\nconst octalReg = /^[0-7]+$/\nconst modeDesc = 'must be a 32-bit unsigned integer or an octal string'\n\n/**\n * Parse and validate values that will be converted into mode_t (the S_*\n * constants). Only valid numbers and octal strings are allowed. They could be\n * converted to 32-bit unsigned integers or non-negative signed integers in the\n * C++ land, but any value higher than 0o777 will result in platform-specific\n * behaviors.\n * @param {*} value Values to be validated\n * @param {string} name Name of the argument\n * @param {number} [def] If specified, will be returned for invalid values\n * @returns {number}\n */\nfunction parseFileMode(value, name, def) {\n  if (typeof value === 'undefined') {\n    value = def\n  }\n  if (typeof value === 'string') {\n    if (RegExpPrototypeExec(octalReg, value) === null) {\n      throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc)\n    }\n    value = NumberParseInt(value, 8)\n  }\n  validateUint32(value, name)\n  return value\n}\n\n/**\n * @callback validateInteger\n * @param {*} value\n * @param {string} name\n * @param {number} [min]\n * @param {number} [max]\n * @returns {asserts value is number}\n */\n\n/** @type {validateInteger} */\nconst validateInteger = hideStackFrames((value, name, min = NumberMIN_SAFE_INTEGER, max = NumberMAX_SAFE_INTEGER) => {\n  if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n  if (!NumberIsInteger(value)) throw new ERR_OUT_OF_RANGE(name, 'an integer', value)\n  if (value < min || value > max) throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value)\n})\n\n/**\n * @callback validateInt32\n * @param {*} value\n * @param {string} name\n * @param {number} [min]\n * @param {number} [max]\n * @returns {asserts value is number}\n */\n\n/** @type {validateInt32} */\nconst validateInt32 = hideStackFrames((value, name, min = -2147483648, max = 2147483647) => {\n  // The defaults for min and max correspond to the limits of 32-bit integers.\n  if (typeof value !== 'number') {\n    throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n  }\n  if (!NumberIsInteger(value)) {\n    throw new ERR_OUT_OF_RANGE(name, 'an integer', value)\n  }\n  if (value < min || value > max) {\n    throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value)\n  }\n})\n\n/**\n * @callback validateUint32\n * @param {*} value\n * @param {string} name\n * @param {number|boolean} [positive=false]\n * @returns {asserts value is number}\n */\n\n/** @type {validateUint32} */\nconst validateUint32 = hideStackFrames((value, name, positive = false) => {\n  if (typeof value !== 'number') {\n    throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n  }\n  if (!NumberIsInteger(value)) {\n    throw new ERR_OUT_OF_RANGE(name, 'an integer', value)\n  }\n  const min = positive ? 1 : 0\n  // 2 ** 32 === 4294967296\n  const max = 4294967295\n  if (value < min || value > max) {\n    throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value)\n  }\n})\n\n/**\n * @callback validateString\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is string}\n */\n\n/** @type {validateString} */\nfunction validateString(value, name) {\n  if (typeof value !== 'string') throw new ERR_INVALID_ARG_TYPE(name, 'string', value)\n}\n\n/**\n * @callback validateNumber\n * @param {*} value\n * @param {string} name\n * @param {number} [min]\n * @param {number} [max]\n * @returns {asserts value is number}\n */\n\n/** @type {validateNumber} */\nfunction validateNumber(value, name, min = undefined, max) {\n  if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value)\n  if (\n    (min != null && value < min) ||\n    (max != null && value > max) ||\n    ((min != null || max != null) && NumberIsNaN(value))\n  ) {\n    throw new ERR_OUT_OF_RANGE(\n      name,\n      `${min != null ? `>= ${min}` : ''}${min != null && max != null ? ' && ' : ''}${max != null ? `<= ${max}` : ''}`,\n      value\n    )\n  }\n}\n\n/**\n * @callback validateOneOf\n * @template T\n * @param {T} value\n * @param {string} name\n * @param {T[]} oneOf\n */\n\n/** @type {validateOneOf} */\nconst validateOneOf = hideStackFrames((value, name, oneOf) => {\n  if (!ArrayPrototypeIncludes(oneOf, value)) {\n    const allowed = ArrayPrototypeJoin(\n      ArrayPrototypeMap(oneOf, (v) => (typeof v === 'string' ? `'${v}'` : String(v))),\n      ', '\n    )\n    const reason = 'must be one of: ' + allowed\n    throw new ERR_INVALID_ARG_VALUE(name, value, reason)\n  }\n})\n\n/**\n * @callback validateBoolean\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is boolean}\n */\n\n/** @type {validateBoolean} */\nfunction validateBoolean(value, name) {\n  if (typeof value !== 'boolean') throw new ERR_INVALID_ARG_TYPE(name, 'boolean', value)\n}\n\n/**\n * @param {any} options\n * @param {string} key\n * @param {boolean} defaultValue\n * @returns {boolean}\n */\nfunction getOwnPropertyValueOrDefault(options, key, defaultValue) {\n  return options == null || !ObjectPrototypeHasOwnProperty(options, key) ? defaultValue : options[key]\n}\n\n/**\n * @callback validateObject\n * @param {*} value\n * @param {string} name\n * @param {{\n *   allowArray?: boolean,\n *   allowFunction?: boolean,\n *   nullable?: boolean\n * }} [options]\n */\n\n/** @type {validateObject} */\nconst validateObject = hideStackFrames((value, name, options = null) => {\n  const allowArray = getOwnPropertyValueOrDefault(options, 'allowArray', false)\n  const allowFunction = getOwnPropertyValueOrDefault(options, 'allowFunction', false)\n  const nullable = getOwnPropertyValueOrDefault(options, 'nullable', false)\n  if (\n    (!nullable && value === null) ||\n    (!allowArray && ArrayIsArray(value)) ||\n    (typeof value !== 'object' && (!allowFunction || typeof value !== 'function'))\n  ) {\n    throw new ERR_INVALID_ARG_TYPE(name, 'Object', value)\n  }\n})\n\n/**\n * @callback validateDictionary - We are using the Web IDL Standard definition\n *                                of \"dictionary\" here, which means any value\n *                                whose Type is either Undefined, Null, or\n *                                Object (which includes functions).\n * @param {*} value\n * @param {string} name\n * @see https://webidl.spec.whatwg.org/#es-dictionary\n * @see https://tc39.es/ecma262/#table-typeof-operator-results\n */\n\n/** @type {validateDictionary} */\nconst validateDictionary = hideStackFrames((value, name) => {\n  if (value != null && typeof value !== 'object' && typeof value !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE(name, 'a dictionary', value)\n  }\n})\n\n/**\n * @callback validateArray\n * @param {*} value\n * @param {string} name\n * @param {number} [minLength]\n * @returns {asserts value is any[]}\n */\n\n/** @type {validateArray} */\nconst validateArray = hideStackFrames((value, name, minLength = 0) => {\n  if (!ArrayIsArray(value)) {\n    throw new ERR_INVALID_ARG_TYPE(name, 'Array', value)\n  }\n  if (value.length < minLength) {\n    const reason = `must be longer than ${minLength}`\n    throw new ERR_INVALID_ARG_VALUE(name, value, reason)\n  }\n})\n\n/**\n * @callback validateStringArray\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is string[]}\n */\n\n/** @type {validateStringArray} */\nfunction validateStringArray(value, name) {\n  validateArray(value, name)\n  for (let i = 0; i < value.length; i++) {\n    validateString(value[i], `${name}[${i}]`)\n  }\n}\n\n/**\n * @callback validateBooleanArray\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is boolean[]}\n */\n\n/** @type {validateBooleanArray} */\nfunction validateBooleanArray(value, name) {\n  validateArray(value, name)\n  for (let i = 0; i < value.length; i++) {\n    validateBoolean(value[i], `${name}[${i}]`)\n  }\n}\n\n/**\n * @callback validateAbortSignalArray\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is AbortSignal[]}\n */\n\n/** @type {validateAbortSignalArray} */\nfunction validateAbortSignalArray(value, name) {\n  validateArray(value, name)\n  for (let i = 0; i < value.length; i++) {\n    const signal = value[i]\n    const indexedName = `${name}[${i}]`\n    if (signal == null) {\n      throw new ERR_INVALID_ARG_TYPE(indexedName, 'AbortSignal', signal)\n    }\n    validateAbortSignal(signal, indexedName)\n  }\n}\n\n/**\n * @param {*} signal\n * @param {string} [name='signal']\n * @returns {asserts signal is keyof signals}\n */\nfunction validateSignalName(signal, name = 'signal') {\n  validateString(signal, name)\n  if (signals[signal] === undefined) {\n    if (signals[StringPrototypeToUpperCase(signal)] !== undefined) {\n      throw new ERR_UNKNOWN_SIGNAL(signal + ' (signals must use all capital letters)')\n    }\n    throw new ERR_UNKNOWN_SIGNAL(signal)\n  }\n}\n\n/**\n * @callback validateBuffer\n * @param {*} buffer\n * @param {string} [name='buffer']\n * @returns {asserts buffer is ArrayBufferView}\n */\n\n/** @type {validateBuffer} */\nconst validateBuffer = hideStackFrames((buffer, name = 'buffer') => {\n  if (!isArrayBufferView(buffer)) {\n    throw new ERR_INVALID_ARG_TYPE(name, ['Buffer', 'TypedArray', 'DataView'], buffer)\n  }\n})\n\n/**\n * @param {string} data\n * @param {string} encoding\n */\nfunction validateEncoding(data, encoding) {\n  const normalizedEncoding = normalizeEncoding(encoding)\n  const length = data.length\n  if (normalizedEncoding === 'hex' && length % 2 !== 0) {\n    throw new ERR_INVALID_ARG_VALUE('encoding', encoding, `is invalid for data of length ${length}`)\n  }\n}\n\n/**\n * Check that the port number is not NaN when coerced to a number,\n * is an integer and that it falls within the legal range of port numbers.\n * @param {*} port\n * @param {string} [name='Port']\n * @param {boolean} [allowZero=true]\n * @returns {number}\n */\nfunction validatePort(port, name = 'Port', allowZero = true) {\n  if (\n    (typeof port !== 'number' && typeof port !== 'string') ||\n    (typeof port === 'string' && StringPrototypeTrim(port).length === 0) ||\n    +port !== +port >>> 0 ||\n    port > 0xffff ||\n    (port === 0 && !allowZero)\n  ) {\n    throw new ERR_SOCKET_BAD_PORT(name, port, allowZero)\n  }\n  return port | 0\n}\n\n/**\n * @callback validateAbortSignal\n * @param {*} signal\n * @param {string} name\n */\n\n/** @type {validateAbortSignal} */\nconst validateAbortSignal = hideStackFrames((signal, name) => {\n  if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) {\n    throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal)\n  }\n})\n\n/**\n * @callback validateFunction\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is Function}\n */\n\n/** @type {validateFunction} */\nconst validateFunction = hideStackFrames((value, name) => {\n  if (typeof value !== 'function') throw new ERR_INVALID_ARG_TYPE(name, 'Function', value)\n})\n\n/**\n * @callback validatePlainFunction\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is Function}\n */\n\n/** @type {validatePlainFunction} */\nconst validatePlainFunction = hideStackFrames((value, name) => {\n  if (typeof value !== 'function' || isAsyncFunction(value)) throw new ERR_INVALID_ARG_TYPE(name, 'Function', value)\n})\n\n/**\n * @callback validateUndefined\n * @param {*} value\n * @param {string} name\n * @returns {asserts value is undefined}\n */\n\n/** @type {validateUndefined} */\nconst validateUndefined = hideStackFrames((value, name) => {\n  if (value !== undefined) throw new ERR_INVALID_ARG_TYPE(name, 'undefined', value)\n})\n\n/**\n * @template T\n * @param {T} value\n * @param {string} name\n * @param {T[]} union\n */\nfunction validateUnion(value, name, union) {\n  if (!ArrayPrototypeIncludes(union, value)) {\n    throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value)\n  }\n}\n\n/*\n  The rules for the Link header field are described here:\n  https://www.rfc-editor.org/rfc/rfc8288.html#section-3\n\n  This regex validates any string surrounded by angle brackets\n  (not necessarily a valid URI reference) followed by zero or more\n  link-params separated by semicolons.\n*/\nconst linkValueRegExp = /^(?:<[^>]*>)(?:\\s*;\\s*[^;\"\\s]+(?:=(\")?[^;\"\\s]*\\1)?)*$/\n\n/**\n * @param {any} value\n * @param {string} name\n */\nfunction validateLinkHeaderFormat(value, name) {\n  if (typeof value === 'undefined' || !RegExpPrototypeExec(linkValueRegExp, value)) {\n    throw new ERR_INVALID_ARG_VALUE(\n      name,\n      value,\n      'must be an array or string of format \"; rel=preload; as=style\"'\n    )\n  }\n}\n\n/**\n * @param {any} hints\n * @return {string}\n */\nfunction validateLinkHeaderValue(hints) {\n  if (typeof hints === 'string') {\n    validateLinkHeaderFormat(hints, 'hints')\n    return hints\n  } else if (ArrayIsArray(hints)) {\n    const hintsLength = hints.length\n    let result = ''\n    if (hintsLength === 0) {\n      return result\n    }\n    for (let i = 0; i < hintsLength; i++) {\n      const link = hints[i]\n      validateLinkHeaderFormat(link, 'hints')\n      result += link\n      if (i !== hintsLength - 1) {\n        result += ', '\n      }\n    }\n    return result\n  }\n  throw new ERR_INVALID_ARG_VALUE(\n    'hints',\n    hints,\n    'must be an array or string of format \"; rel=preload; as=style\"'\n  )\n}\nmodule.exports = {\n  isInt32,\n  isUint32,\n  parseFileMode,\n  validateArray,\n  validateStringArray,\n  validateBooleanArray,\n  validateAbortSignalArray,\n  validateBoolean,\n  validateBuffer,\n  validateDictionary,\n  validateEncoding,\n  validateFunction,\n  validateInt32,\n  validateInteger,\n  validateNumber,\n  validateObject,\n  validateOneOf,\n  validatePlainFunction,\n  validatePort,\n  validateSignalName,\n  validateString,\n  validateUint32,\n  validateUndefined,\n  validateUnion,\n  validateAbortSignal,\n  validateLinkHeaderValue\n}\n","'use strict'\n\nconst { SymbolAsyncIterator, SymbolIterator, SymbolFor } = require('../../ours/primordials')\n\n// We need to use SymbolFor to make these globally available\n// for interopt with readable-stream, i.e. readable-stream\n// and node core needs to be able to read/write private state\n// from each other for proper interoperability.\nconst kIsDestroyed = SymbolFor('nodejs.stream.destroyed')\nconst kIsErrored = SymbolFor('nodejs.stream.errored')\nconst kIsReadable = SymbolFor('nodejs.stream.readable')\nconst kIsWritable = SymbolFor('nodejs.stream.writable')\nconst kIsDisturbed = SymbolFor('nodejs.stream.disturbed')\nconst kIsClosedPromise = SymbolFor('nodejs.webstream.isClosedPromise')\nconst kControllerErrorFunction = SymbolFor('nodejs.webstream.controllerErrorFunction')\nfunction isReadableNodeStream(obj, strict = false) {\n  var _obj$_readableState\n  return !!(\n    (\n      obj &&\n      typeof obj.pipe === 'function' &&\n      typeof obj.on === 'function' &&\n      (!strict || (typeof obj.pause === 'function' && typeof obj.resume === 'function')) &&\n      (!obj._writableState ||\n        ((_obj$_readableState = obj._readableState) === null || _obj$_readableState === undefined\n          ? undefined\n          : _obj$_readableState.readable) !== false) &&\n      // Duplex\n      (!obj._writableState || obj._readableState)\n    ) // Writable has .pipe.\n  )\n}\nfunction isWritableNodeStream(obj) {\n  var _obj$_writableState\n  return !!(\n    (\n      obj &&\n      typeof obj.write === 'function' &&\n      typeof obj.on === 'function' &&\n      (!obj._readableState ||\n        ((_obj$_writableState = obj._writableState) === null || _obj$_writableState === undefined\n          ? undefined\n          : _obj$_writableState.writable) !== false)\n    ) // Duplex\n  )\n}\nfunction isDuplexNodeStream(obj) {\n  return !!(\n    obj &&\n    typeof obj.pipe === 'function' &&\n    obj._readableState &&\n    typeof obj.on === 'function' &&\n    typeof obj.write === 'function'\n  )\n}\nfunction isNodeStream(obj) {\n  return (\n    obj &&\n    (obj._readableState ||\n      obj._writableState ||\n      (typeof obj.write === 'function' && typeof obj.on === 'function') ||\n      (typeof obj.pipe === 'function' && typeof obj.on === 'function'))\n  )\n}\nfunction isReadableStream(obj) {\n  return !!(\n    obj &&\n    !isNodeStream(obj) &&\n    typeof obj.pipeThrough === 'function' &&\n    typeof obj.getReader === 'function' &&\n    typeof obj.cancel === 'function'\n  )\n}\nfunction isWritableStream(obj) {\n  return !!(obj && !isNodeStream(obj) && typeof obj.getWriter === 'function' && typeof obj.abort === 'function')\n}\nfunction isTransformStream(obj) {\n  return !!(obj && !isNodeStream(obj) && typeof obj.readable === 'object' && typeof obj.writable === 'object')\n}\nfunction isWebStream(obj) {\n  return isReadableStream(obj) || isWritableStream(obj) || isTransformStream(obj)\n}\nfunction isIterable(obj, isAsync) {\n  if (obj == null) return false\n  if (isAsync === true) return typeof obj[SymbolAsyncIterator] === 'function'\n  if (isAsync === false) return typeof obj[SymbolIterator] === 'function'\n  return typeof obj[SymbolAsyncIterator] === 'function' || typeof obj[SymbolIterator] === 'function'\n}\nfunction isDestroyed(stream) {\n  if (!isNodeStream(stream)) return null\n  const wState = stream._writableState\n  const rState = stream._readableState\n  const state = wState || rState\n  return !!(stream.destroyed || stream[kIsDestroyed] || (state !== null && state !== undefined && state.destroyed))\n}\n\n// Have been end():d.\nfunction isWritableEnded(stream) {\n  if (!isWritableNodeStream(stream)) return null\n  if (stream.writableEnded === true) return true\n  const wState = stream._writableState\n  if (wState !== null && wState !== undefined && wState.errored) return false\n  if (typeof (wState === null || wState === undefined ? undefined : wState.ended) !== 'boolean') return null\n  return wState.ended\n}\n\n// Have emitted 'finish'.\nfunction isWritableFinished(stream, strict) {\n  if (!isWritableNodeStream(stream)) return null\n  if (stream.writableFinished === true) return true\n  const wState = stream._writableState\n  if (wState !== null && wState !== undefined && wState.errored) return false\n  if (typeof (wState === null || wState === undefined ? undefined : wState.finished) !== 'boolean') return null\n  return !!(wState.finished || (strict === false && wState.ended === true && wState.length === 0))\n}\n\n// Have been push(null):d.\nfunction isReadableEnded(stream) {\n  if (!isReadableNodeStream(stream)) return null\n  if (stream.readableEnded === true) return true\n  const rState = stream._readableState\n  if (!rState || rState.errored) return false\n  if (typeof (rState === null || rState === undefined ? undefined : rState.ended) !== 'boolean') return null\n  return rState.ended\n}\n\n// Have emitted 'end'.\nfunction isReadableFinished(stream, strict) {\n  if (!isReadableNodeStream(stream)) return null\n  const rState = stream._readableState\n  if (rState !== null && rState !== undefined && rState.errored) return false\n  if (typeof (rState === null || rState === undefined ? undefined : rState.endEmitted) !== 'boolean') return null\n  return !!(rState.endEmitted || (strict === false && rState.ended === true && rState.length === 0))\n}\nfunction isReadable(stream) {\n  if (stream && stream[kIsReadable] != null) return stream[kIsReadable]\n  if (typeof (stream === null || stream === undefined ? undefined : stream.readable) !== 'boolean') return null\n  if (isDestroyed(stream)) return false\n  return isReadableNodeStream(stream) && stream.readable && !isReadableFinished(stream)\n}\nfunction isWritable(stream) {\n  if (stream && stream[kIsWritable] != null) return stream[kIsWritable]\n  if (typeof (stream === null || stream === undefined ? undefined : stream.writable) !== 'boolean') return null\n  if (isDestroyed(stream)) return false\n  return isWritableNodeStream(stream) && stream.writable && !isWritableEnded(stream)\n}\nfunction isFinished(stream, opts) {\n  if (!isNodeStream(stream)) {\n    return null\n  }\n  if (isDestroyed(stream)) {\n    return true\n  }\n  if ((opts === null || opts === undefined ? undefined : opts.readable) !== false && isReadable(stream)) {\n    return false\n  }\n  if ((opts === null || opts === undefined ? undefined : opts.writable) !== false && isWritable(stream)) {\n    return false\n  }\n  return true\n}\nfunction isWritableErrored(stream) {\n  var _stream$_writableStat, _stream$_writableStat2\n  if (!isNodeStream(stream)) {\n    return null\n  }\n  if (stream.writableErrored) {\n    return stream.writableErrored\n  }\n  return (_stream$_writableStat =\n    (_stream$_writableStat2 = stream._writableState) === null || _stream$_writableStat2 === undefined\n      ? undefined\n      : _stream$_writableStat2.errored) !== null && _stream$_writableStat !== undefined\n    ? _stream$_writableStat\n    : null\n}\nfunction isReadableErrored(stream) {\n  var _stream$_readableStat, _stream$_readableStat2\n  if (!isNodeStream(stream)) {\n    return null\n  }\n  if (stream.readableErrored) {\n    return stream.readableErrored\n  }\n  return (_stream$_readableStat =\n    (_stream$_readableStat2 = stream._readableState) === null || _stream$_readableStat2 === undefined\n      ? undefined\n      : _stream$_readableStat2.errored) !== null && _stream$_readableStat !== undefined\n    ? _stream$_readableStat\n    : null\n}\nfunction isClosed(stream) {\n  if (!isNodeStream(stream)) {\n    return null\n  }\n  if (typeof stream.closed === 'boolean') {\n    return stream.closed\n  }\n  const wState = stream._writableState\n  const rState = stream._readableState\n  if (\n    typeof (wState === null || wState === undefined ? undefined : wState.closed) === 'boolean' ||\n    typeof (rState === null || rState === undefined ? undefined : rState.closed) === 'boolean'\n  ) {\n    return (\n      (wState === null || wState === undefined ? undefined : wState.closed) ||\n      (rState === null || rState === undefined ? undefined : rState.closed)\n    )\n  }\n  if (typeof stream._closed === 'boolean' && isOutgoingMessage(stream)) {\n    return stream._closed\n  }\n  return null\n}\nfunction isOutgoingMessage(stream) {\n  return (\n    typeof stream._closed === 'boolean' &&\n    typeof stream._defaultKeepAlive === 'boolean' &&\n    typeof stream._removedConnection === 'boolean' &&\n    typeof stream._removedContLen === 'boolean'\n  )\n}\nfunction isServerResponse(stream) {\n  return typeof stream._sent100 === 'boolean' && isOutgoingMessage(stream)\n}\nfunction isServerRequest(stream) {\n  var _stream$req\n  return (\n    typeof stream._consuming === 'boolean' &&\n    typeof stream._dumped === 'boolean' &&\n    ((_stream$req = stream.req) === null || _stream$req === undefined ? undefined : _stream$req.upgradeOrConnect) ===\n      undefined\n  )\n}\nfunction willEmitClose(stream) {\n  if (!isNodeStream(stream)) return null\n  const wState = stream._writableState\n  const rState = stream._readableState\n  const state = wState || rState\n  return (\n    (!state && isServerResponse(stream)) || !!(state && state.autoDestroy && state.emitClose && state.closed === false)\n  )\n}\nfunction isDisturbed(stream) {\n  var _stream$kIsDisturbed\n  return !!(\n    stream &&\n    ((_stream$kIsDisturbed = stream[kIsDisturbed]) !== null && _stream$kIsDisturbed !== undefined\n      ? _stream$kIsDisturbed\n      : stream.readableDidRead || stream.readableAborted)\n  )\n}\nfunction isErrored(stream) {\n  var _ref,\n    _ref2,\n    _ref3,\n    _ref4,\n    _ref5,\n    _stream$kIsErrored,\n    _stream$_readableStat3,\n    _stream$_writableStat3,\n    _stream$_readableStat4,\n    _stream$_writableStat4\n  return !!(\n    stream &&\n    ((_ref =\n      (_ref2 =\n        (_ref3 =\n          (_ref4 =\n            (_ref5 =\n              (_stream$kIsErrored = stream[kIsErrored]) !== null && _stream$kIsErrored !== undefined\n                ? _stream$kIsErrored\n                : stream.readableErrored) !== null && _ref5 !== undefined\n              ? _ref5\n              : stream.writableErrored) !== null && _ref4 !== undefined\n            ? _ref4\n            : (_stream$_readableStat3 = stream._readableState) === null || _stream$_readableStat3 === undefined\n            ? undefined\n            : _stream$_readableStat3.errorEmitted) !== null && _ref3 !== undefined\n          ? _ref3\n          : (_stream$_writableStat3 = stream._writableState) === null || _stream$_writableStat3 === undefined\n          ? undefined\n          : _stream$_writableStat3.errorEmitted) !== null && _ref2 !== undefined\n        ? _ref2\n        : (_stream$_readableStat4 = stream._readableState) === null || _stream$_readableStat4 === undefined\n        ? undefined\n        : _stream$_readableStat4.errored) !== null && _ref !== undefined\n      ? _ref\n      : (_stream$_writableStat4 = stream._writableState) === null || _stream$_writableStat4 === undefined\n      ? undefined\n      : _stream$_writableStat4.errored)\n  )\n}\nmodule.exports = {\n  isDestroyed,\n  kIsDestroyed,\n  isDisturbed,\n  kIsDisturbed,\n  isErrored,\n  kIsErrored,\n  isReadable,\n  kIsReadable,\n  kIsClosedPromise,\n  kControllerErrorFunction,\n  kIsWritable,\n  isClosed,\n  isDuplexNodeStream,\n  isFinished,\n  isIterable,\n  isReadableNodeStream,\n  isReadableStream,\n  isReadableEnded,\n  isReadableFinished,\n  isReadableErrored,\n  isNodeStream,\n  isWebStream,\n  isWritable,\n  isWritableNodeStream,\n  isWritableStream,\n  isWritableEnded,\n  isWritableFinished,\n  isWritableErrored,\n  isServerRequest,\n  isServerResponse,\n  willEmitClose,\n  isTransformStream\n}\n","// Ported from https://github.com/mafintosh/end-of-stream with\n// permission from the author, Mathias Buus (@mafintosh).\n\n'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst { AbortError, codes } = require('../../ours/errors')\nconst { ERR_INVALID_ARG_TYPE, ERR_STREAM_PREMATURE_CLOSE } = codes\nconst { kEmptyObject, once } = require('../../ours/util')\nconst { validateAbortSignal, validateFunction, validateObject, validateBoolean } = require('../validators')\nconst { Promise, PromisePrototypeThen, SymbolDispose } = require('../../ours/primordials')\nconst {\n  isClosed,\n  isReadable,\n  isReadableNodeStream,\n  isReadableStream,\n  isReadableFinished,\n  isReadableErrored,\n  isWritable,\n  isWritableNodeStream,\n  isWritableStream,\n  isWritableFinished,\n  isWritableErrored,\n  isNodeStream,\n  willEmitClose: _willEmitClose,\n  kIsClosedPromise\n} = require('./utils')\nlet addAbortListener\nfunction isRequest(stream) {\n  return stream.setHeader && typeof stream.abort === 'function'\n}\nconst nop = () => {}\nfunction eos(stream, options, callback) {\n  var _options$readable, _options$writable\n  if (arguments.length === 2) {\n    callback = options\n    options = kEmptyObject\n  } else if (options == null) {\n    options = kEmptyObject\n  } else {\n    validateObject(options, 'options')\n  }\n  validateFunction(callback, 'callback')\n  validateAbortSignal(options.signal, 'options.signal')\n  callback = once(callback)\n  if (isReadableStream(stream) || isWritableStream(stream)) {\n    return eosWeb(stream, options, callback)\n  }\n  if (!isNodeStream(stream)) {\n    throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream)\n  }\n  const readable =\n    (_options$readable = options.readable) !== null && _options$readable !== undefined\n      ? _options$readable\n      : isReadableNodeStream(stream)\n  const writable =\n    (_options$writable = options.writable) !== null && _options$writable !== undefined\n      ? _options$writable\n      : isWritableNodeStream(stream)\n  const wState = stream._writableState\n  const rState = stream._readableState\n  const onlegacyfinish = () => {\n    if (!stream.writable) {\n      onfinish()\n    }\n  }\n\n  // TODO (ronag): Improve soft detection to include core modules and\n  // common ecosystem modules that do properly emit 'close' but fail\n  // this generic check.\n  let willEmitClose =\n    _willEmitClose(stream) && isReadableNodeStream(stream) === readable && isWritableNodeStream(stream) === writable\n  let writableFinished = isWritableFinished(stream, false)\n  const onfinish = () => {\n    writableFinished = true\n    // Stream should not be destroyed here. If it is that\n    // means that user space is doing something differently and\n    // we cannot trust willEmitClose.\n    if (stream.destroyed) {\n      willEmitClose = false\n    }\n    if (willEmitClose && (!stream.readable || readable)) {\n      return\n    }\n    if (!readable || readableFinished) {\n      callback.call(stream)\n    }\n  }\n  let readableFinished = isReadableFinished(stream, false)\n  const onend = () => {\n    readableFinished = true\n    // Stream should not be destroyed here. If it is that\n    // means that user space is doing something differently and\n    // we cannot trust willEmitClose.\n    if (stream.destroyed) {\n      willEmitClose = false\n    }\n    if (willEmitClose && (!stream.writable || writable)) {\n      return\n    }\n    if (!writable || writableFinished) {\n      callback.call(stream)\n    }\n  }\n  const onerror = (err) => {\n    callback.call(stream, err)\n  }\n  let closed = isClosed(stream)\n  const onclose = () => {\n    closed = true\n    const errored = isWritableErrored(stream) || isReadableErrored(stream)\n    if (errored && typeof errored !== 'boolean') {\n      return callback.call(stream, errored)\n    }\n    if (readable && !readableFinished && isReadableNodeStream(stream, true)) {\n      if (!isReadableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE())\n    }\n    if (writable && !writableFinished) {\n      if (!isWritableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE())\n    }\n    callback.call(stream)\n  }\n  const onclosed = () => {\n    closed = true\n    const errored = isWritableErrored(stream) || isReadableErrored(stream)\n    if (errored && typeof errored !== 'boolean') {\n      return callback.call(stream, errored)\n    }\n    callback.call(stream)\n  }\n  const onrequest = () => {\n    stream.req.on('finish', onfinish)\n  }\n  if (isRequest(stream)) {\n    stream.on('complete', onfinish)\n    if (!willEmitClose) {\n      stream.on('abort', onclose)\n    }\n    if (stream.req) {\n      onrequest()\n    } else {\n      stream.on('request', onrequest)\n    }\n  } else if (writable && !wState) {\n    // legacy streams\n    stream.on('end', onlegacyfinish)\n    stream.on('close', onlegacyfinish)\n  }\n\n  // Not all streams will emit 'close' after 'aborted'.\n  if (!willEmitClose && typeof stream.aborted === 'boolean') {\n    stream.on('aborted', onclose)\n  }\n  stream.on('end', onend)\n  stream.on('finish', onfinish)\n  if (options.error !== false) {\n    stream.on('error', onerror)\n  }\n  stream.on('close', onclose)\n  if (closed) {\n    process.nextTick(onclose)\n  } else if (\n    (wState !== null && wState !== undefined && wState.errorEmitted) ||\n    (rState !== null && rState !== undefined && rState.errorEmitted)\n  ) {\n    if (!willEmitClose) {\n      process.nextTick(onclosed)\n    }\n  } else if (\n    !readable &&\n    (!willEmitClose || isReadable(stream)) &&\n    (writableFinished || isWritable(stream) === false)\n  ) {\n    process.nextTick(onclosed)\n  } else if (\n    !writable &&\n    (!willEmitClose || isWritable(stream)) &&\n    (readableFinished || isReadable(stream) === false)\n  ) {\n    process.nextTick(onclosed)\n  } else if (rState && stream.req && stream.aborted) {\n    process.nextTick(onclosed)\n  }\n  const cleanup = () => {\n    callback = nop\n    stream.removeListener('aborted', onclose)\n    stream.removeListener('complete', onfinish)\n    stream.removeListener('abort', onclose)\n    stream.removeListener('request', onrequest)\n    if (stream.req) stream.req.removeListener('finish', onfinish)\n    stream.removeListener('end', onlegacyfinish)\n    stream.removeListener('close', onlegacyfinish)\n    stream.removeListener('finish', onfinish)\n    stream.removeListener('end', onend)\n    stream.removeListener('error', onerror)\n    stream.removeListener('close', onclose)\n  }\n  if (options.signal && !closed) {\n    const abort = () => {\n      // Keep it because cleanup removes it.\n      const endCallback = callback\n      cleanup()\n      endCallback.call(\n        stream,\n        new AbortError(undefined, {\n          cause: options.signal.reason\n        })\n      )\n    }\n    if (options.signal.aborted) {\n      process.nextTick(abort)\n    } else {\n      addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n      const disposable = addAbortListener(options.signal, abort)\n      const originalCallback = callback\n      callback = once((...args) => {\n        disposable[SymbolDispose]()\n        originalCallback.apply(stream, args)\n      })\n    }\n  }\n  return cleanup\n}\nfunction eosWeb(stream, options, callback) {\n  let isAborted = false\n  let abort = nop\n  if (options.signal) {\n    abort = () => {\n      isAborted = true\n      callback.call(\n        stream,\n        new AbortError(undefined, {\n          cause: options.signal.reason\n        })\n      )\n    }\n    if (options.signal.aborted) {\n      process.nextTick(abort)\n    } else {\n      addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n      const disposable = addAbortListener(options.signal, abort)\n      const originalCallback = callback\n      callback = once((...args) => {\n        disposable[SymbolDispose]()\n        originalCallback.apply(stream, args)\n      })\n    }\n  }\n  const resolverFn = (...args) => {\n    if (!isAborted) {\n      process.nextTick(() => callback.apply(stream, args))\n    }\n  }\n  PromisePrototypeThen(stream[kIsClosedPromise].promise, resolverFn, resolverFn)\n  return nop\n}\nfunction finished(stream, opts) {\n  var _opts\n  let autoCleanup = false\n  if (opts === null) {\n    opts = kEmptyObject\n  }\n  if ((_opts = opts) !== null && _opts !== undefined && _opts.cleanup) {\n    validateBoolean(opts.cleanup, 'cleanup')\n    autoCleanup = opts.cleanup\n  }\n  return new Promise((resolve, reject) => {\n    const cleanup = eos(stream, opts, (err) => {\n      if (autoCleanup) {\n        cleanup()\n      }\n      if (err) {\n        reject(err)\n      } else {\n        resolve()\n      }\n    })\n  })\n}\nmodule.exports = eos\nmodule.exports.finished = finished\n","'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst {\n  aggregateTwoErrors,\n  codes: { ERR_MULTIPLE_CALLBACK },\n  AbortError\n} = require('../../ours/errors')\nconst { Symbol } = require('../../ours/primordials')\nconst { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = require('./utils')\nconst kDestroy = Symbol('kDestroy')\nconst kConstruct = Symbol('kConstruct')\nfunction checkError(err, w, r) {\n  if (err) {\n    // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364\n    err.stack // eslint-disable-line no-unused-expressions\n\n    if (w && !w.errored) {\n      w.errored = err\n    }\n    if (r && !r.errored) {\n      r.errored = err\n    }\n  }\n}\n\n// Backwards compat. cb() is undocumented and unused in core but\n// unfortunately might be used by modules.\nfunction destroy(err, cb) {\n  const r = this._readableState\n  const w = this._writableState\n  // With duplex streams we use the writable side for state.\n  const s = w || r\n  if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) {\n    if (typeof cb === 'function') {\n      cb()\n    }\n    return this\n  }\n\n  // We set destroyed to true before firing error callbacks in order\n  // to make it re-entrance safe in case destroy() is called within callbacks\n  checkError(err, w, r)\n  if (w) {\n    w.destroyed = true\n  }\n  if (r) {\n    r.destroyed = true\n  }\n\n  // If still constructing then defer calling _destroy.\n  if (!s.constructed) {\n    this.once(kDestroy, function (er) {\n      _destroy(this, aggregateTwoErrors(er, err), cb)\n    })\n  } else {\n    _destroy(this, err, cb)\n  }\n  return this\n}\nfunction _destroy(self, err, cb) {\n  let called = false\n  function onDestroy(err) {\n    if (called) {\n      return\n    }\n    called = true\n    const r = self._readableState\n    const w = self._writableState\n    checkError(err, w, r)\n    if (w) {\n      w.closed = true\n    }\n    if (r) {\n      r.closed = true\n    }\n    if (typeof cb === 'function') {\n      cb(err)\n    }\n    if (err) {\n      process.nextTick(emitErrorCloseNT, self, err)\n    } else {\n      process.nextTick(emitCloseNT, self)\n    }\n  }\n  try {\n    self._destroy(err || null, onDestroy)\n  } catch (err) {\n    onDestroy(err)\n  }\n}\nfunction emitErrorCloseNT(self, err) {\n  emitErrorNT(self, err)\n  emitCloseNT(self)\n}\nfunction emitCloseNT(self) {\n  const r = self._readableState\n  const w = self._writableState\n  if (w) {\n    w.closeEmitted = true\n  }\n  if (r) {\n    r.closeEmitted = true\n  }\n  if ((w !== null && w !== undefined && w.emitClose) || (r !== null && r !== undefined && r.emitClose)) {\n    self.emit('close')\n  }\n}\nfunction emitErrorNT(self, err) {\n  const r = self._readableState\n  const w = self._writableState\n  if ((w !== null && w !== undefined && w.errorEmitted) || (r !== null && r !== undefined && r.errorEmitted)) {\n    return\n  }\n  if (w) {\n    w.errorEmitted = true\n  }\n  if (r) {\n    r.errorEmitted = true\n  }\n  self.emit('error', err)\n}\nfunction undestroy() {\n  const r = this._readableState\n  const w = this._writableState\n  if (r) {\n    r.constructed = true\n    r.closed = false\n    r.closeEmitted = false\n    r.destroyed = false\n    r.errored = null\n    r.errorEmitted = false\n    r.reading = false\n    r.ended = r.readable === false\n    r.endEmitted = r.readable === false\n  }\n  if (w) {\n    w.constructed = true\n    w.destroyed = false\n    w.closed = false\n    w.closeEmitted = false\n    w.errored = null\n    w.errorEmitted = false\n    w.finalCalled = false\n    w.prefinished = false\n    w.ended = w.writable === false\n    w.ending = w.writable === false\n    w.finished = w.writable === false\n  }\n}\nfunction errorOrDestroy(stream, err, sync) {\n  // We have tests that rely on errors being emitted\n  // in the same tick, so changing this is semver major.\n  // For now when you opt-in to autoDestroy we allow\n  // the error to be emitted nextTick. In a future\n  // semver major update we should change the default to this.\n\n  const r = stream._readableState\n  const w = stream._writableState\n  if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) {\n    return this\n  }\n  if ((r !== null && r !== undefined && r.autoDestroy) || (w !== null && w !== undefined && w.autoDestroy))\n    stream.destroy(err)\n  else if (err) {\n    // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364\n    err.stack // eslint-disable-line no-unused-expressions\n\n    if (w && !w.errored) {\n      w.errored = err\n    }\n    if (r && !r.errored) {\n      r.errored = err\n    }\n    if (sync) {\n      process.nextTick(emitErrorNT, stream, err)\n    } else {\n      emitErrorNT(stream, err)\n    }\n  }\n}\nfunction construct(stream, cb) {\n  if (typeof stream._construct !== 'function') {\n    return\n  }\n  const r = stream._readableState\n  const w = stream._writableState\n  if (r) {\n    r.constructed = false\n  }\n  if (w) {\n    w.constructed = false\n  }\n  stream.once(kConstruct, cb)\n  if (stream.listenerCount(kConstruct) > 1) {\n    // Duplex\n    return\n  }\n  process.nextTick(constructNT, stream)\n}\nfunction constructNT(stream) {\n  let called = false\n  function onConstruct(err) {\n    if (called) {\n      errorOrDestroy(stream, err !== null && err !== undefined ? err : new ERR_MULTIPLE_CALLBACK())\n      return\n    }\n    called = true\n    const r = stream._readableState\n    const w = stream._writableState\n    const s = w || r\n    if (r) {\n      r.constructed = true\n    }\n    if (w) {\n      w.constructed = true\n    }\n    if (s.destroyed) {\n      stream.emit(kDestroy, err)\n    } else if (err) {\n      errorOrDestroy(stream, err, true)\n    } else {\n      process.nextTick(emitConstructNT, stream)\n    }\n  }\n  try {\n    stream._construct((err) => {\n      process.nextTick(onConstruct, err)\n    })\n  } catch (err) {\n    process.nextTick(onConstruct, err)\n  }\n}\nfunction emitConstructNT(stream) {\n  stream.emit(kConstruct)\n}\nfunction isRequest(stream) {\n  return (stream === null || stream === undefined ? undefined : stream.setHeader) && typeof stream.abort === 'function'\n}\nfunction emitCloseLegacy(stream) {\n  stream.emit('close')\n}\nfunction emitErrorCloseLegacy(stream, err) {\n  stream.emit('error', err)\n  process.nextTick(emitCloseLegacy, stream)\n}\n\n// Normalize destroy for legacy.\nfunction destroyer(stream, err) {\n  if (!stream || isDestroyed(stream)) {\n    return\n  }\n  if (!err && !isFinished(stream)) {\n    err = new AbortError()\n  }\n\n  // TODO: Remove isRequest branches.\n  if (isServerRequest(stream)) {\n    stream.socket = null\n    stream.destroy(err)\n  } else if (isRequest(stream)) {\n    stream.abort()\n  } else if (isRequest(stream.req)) {\n    stream.req.abort()\n  } else if (typeof stream.destroy === 'function') {\n    stream.destroy(err)\n  } else if (typeof stream.close === 'function') {\n    // TODO: Don't lose err?\n    stream.close()\n  } else if (err) {\n    process.nextTick(emitErrorCloseLegacy, stream, err)\n  } else {\n    process.nextTick(emitCloseLegacy, stream)\n  }\n  if (!stream.destroyed) {\n    stream[kIsDestroyed] = true\n  }\n}\nmodule.exports = {\n  construct,\n  destroyer,\n  destroy,\n  undestroy,\n  errorOrDestroy\n}\n","'use strict'\n\nconst { ArrayIsArray, ObjectSetPrototypeOf } = require('../../ours/primordials')\nconst { EventEmitter: EE } = require('events')\nfunction Stream(opts) {\n  EE.call(this, opts)\n}\nObjectSetPrototypeOf(Stream.prototype, EE.prototype)\nObjectSetPrototypeOf(Stream, EE)\nStream.prototype.pipe = function (dest, options) {\n  const source = this\n  function ondata(chunk) {\n    if (dest.writable && dest.write(chunk) === false && source.pause) {\n      source.pause()\n    }\n  }\n  source.on('data', ondata)\n  function ondrain() {\n    if (source.readable && source.resume) {\n      source.resume()\n    }\n  }\n  dest.on('drain', ondrain)\n\n  // If the 'end' option is not supplied, dest.end() will be called when\n  // source gets the 'end' or 'close' events.  Only dest.end() once.\n  if (!dest._isStdio && (!options || options.end !== false)) {\n    source.on('end', onend)\n    source.on('close', onclose)\n  }\n  let didOnEnd = false\n  function onend() {\n    if (didOnEnd) return\n    didOnEnd = true\n    dest.end()\n  }\n  function onclose() {\n    if (didOnEnd) return\n    didOnEnd = true\n    if (typeof dest.destroy === 'function') dest.destroy()\n  }\n\n  // Don't leave dangling pipes when there are errors.\n  function onerror(er) {\n    cleanup()\n    if (EE.listenerCount(this, 'error') === 0) {\n      this.emit('error', er)\n    }\n  }\n  prependListener(source, 'error', onerror)\n  prependListener(dest, 'error', onerror)\n\n  // Remove all the event listeners that were added.\n  function cleanup() {\n    source.removeListener('data', ondata)\n    dest.removeListener('drain', ondrain)\n    source.removeListener('end', onend)\n    source.removeListener('close', onclose)\n    source.removeListener('error', onerror)\n    dest.removeListener('error', onerror)\n    source.removeListener('end', cleanup)\n    source.removeListener('close', cleanup)\n    dest.removeListener('close', cleanup)\n  }\n  source.on('end', cleanup)\n  source.on('close', cleanup)\n  dest.on('close', cleanup)\n  dest.emit('pipe', source)\n\n  // Allow for unix-like usage: A.pipe(B).pipe(C)\n  return dest\n}\nfunction prependListener(emitter, event, fn) {\n  // Sadly this is not cacheable as some libraries bundle their own\n  // event emitter implementation with them.\n  if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn)\n\n  // This is a hack to make sure that our error handler is attached before any\n  // userland ones.  NEVER DO THIS. This is here only because this code needs\n  // to continue to work with older versions of Node.js that do not include\n  // the prependListener() method. The goal is to eventually remove this hack.\n  if (!emitter._events || !emitter._events[event]) emitter.on(event, fn)\n  else if (ArrayIsArray(emitter._events[event])) emitter._events[event].unshift(fn)\n  else emitter._events[event] = [fn, emitter._events[event]]\n}\nmodule.exports = {\n  Stream,\n  prependListener\n}\n","'use strict'\n\nconst { SymbolDispose } = require('../../ours/primordials')\nconst { AbortError, codes } = require('../../ours/errors')\nconst { isNodeStream, isWebStream, kControllerErrorFunction } = require('./utils')\nconst eos = require('./end-of-stream')\nconst { ERR_INVALID_ARG_TYPE } = codes\nlet addAbortListener\n\n// This method is inlined here for readable-stream\n// It also does not allow for signal to not exist on the stream\n// https://github.com/nodejs/node/pull/36061#discussion_r533718029\nconst validateAbortSignal = (signal, name) => {\n  if (typeof signal !== 'object' || !('aborted' in signal)) {\n    throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal)\n  }\n}\nmodule.exports.addAbortSignal = function addAbortSignal(signal, stream) {\n  validateAbortSignal(signal, 'signal')\n  if (!isNodeStream(stream) && !isWebStream(stream)) {\n    throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream)\n  }\n  return module.exports.addAbortSignalNoValidate(signal, stream)\n}\nmodule.exports.addAbortSignalNoValidate = function (signal, stream) {\n  if (typeof signal !== 'object' || !('aborted' in signal)) {\n    return stream\n  }\n  const onAbort = isNodeStream(stream)\n    ? () => {\n        stream.destroy(\n          new AbortError(undefined, {\n            cause: signal.reason\n          })\n        )\n      }\n    : () => {\n        stream[kControllerErrorFunction](\n          new AbortError(undefined, {\n            cause: signal.reason\n          })\n        )\n      }\n  if (signal.aborted) {\n    onAbort()\n  } else {\n    addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n    const disposable = addAbortListener(signal, onAbort)\n    eos(stream, disposable[SymbolDispose])\n  }\n  return stream\n}\n","'use strict'\n\nconst { StringPrototypeSlice, SymbolIterator, TypedArrayPrototypeSet, Uint8Array } = require('../../ours/primordials')\nconst { Buffer } = require('buffer')\nconst { inspect } = require('../../ours/util')\nmodule.exports = class BufferList {\n  constructor() {\n    this.head = null\n    this.tail = null\n    this.length = 0\n  }\n  push(v) {\n    const entry = {\n      data: v,\n      next: null\n    }\n    if (this.length > 0) this.tail.next = entry\n    else this.head = entry\n    this.tail = entry\n    ++this.length\n  }\n  unshift(v) {\n    const entry = {\n      data: v,\n      next: this.head\n    }\n    if (this.length === 0) this.tail = entry\n    this.head = entry\n    ++this.length\n  }\n  shift() {\n    if (this.length === 0) return\n    const ret = this.head.data\n    if (this.length === 1) this.head = this.tail = null\n    else this.head = this.head.next\n    --this.length\n    return ret\n  }\n  clear() {\n    this.head = this.tail = null\n    this.length = 0\n  }\n  join(s) {\n    if (this.length === 0) return ''\n    let p = this.head\n    let ret = '' + p.data\n    while ((p = p.next) !== null) ret += s + p.data\n    return ret\n  }\n  concat(n) {\n    if (this.length === 0) return Buffer.alloc(0)\n    const ret = Buffer.allocUnsafe(n >>> 0)\n    let p = this.head\n    let i = 0\n    while (p) {\n      TypedArrayPrototypeSet(ret, p.data, i)\n      i += p.data.length\n      p = p.next\n    }\n    return ret\n  }\n\n  // Consumes a specified amount of bytes or characters from the buffered data.\n  consume(n, hasStrings) {\n    const data = this.head.data\n    if (n < data.length) {\n      // `slice` is the same for buffers and strings.\n      const slice = data.slice(0, n)\n      this.head.data = data.slice(n)\n      return slice\n    }\n    if (n === data.length) {\n      // First chunk is a perfect match.\n      return this.shift()\n    }\n    // Result spans more than one buffer.\n    return hasStrings ? this._getString(n) : this._getBuffer(n)\n  }\n  first() {\n    return this.head.data\n  }\n  *[SymbolIterator]() {\n    for (let p = this.head; p; p = p.next) {\n      yield p.data\n    }\n  }\n\n  // Consumes a specified amount of characters from the buffered data.\n  _getString(n) {\n    let ret = ''\n    let p = this.head\n    let c = 0\n    do {\n      const str = p.data\n      if (n > str.length) {\n        ret += str\n        n -= str.length\n      } else {\n        if (n === str.length) {\n          ret += str\n          ++c\n          if (p.next) this.head = p.next\n          else this.head = this.tail = null\n        } else {\n          ret += StringPrototypeSlice(str, 0, n)\n          this.head = p\n          p.data = StringPrototypeSlice(str, n)\n        }\n        break\n      }\n      ++c\n    } while ((p = p.next) !== null)\n    this.length -= c\n    return ret\n  }\n\n  // Consumes a specified amount of bytes from the buffered data.\n  _getBuffer(n) {\n    const ret = Buffer.allocUnsafe(n)\n    const retLen = n\n    let p = this.head\n    let c = 0\n    do {\n      const buf = p.data\n      if (n > buf.length) {\n        TypedArrayPrototypeSet(ret, buf, retLen - n)\n        n -= buf.length\n      } else {\n        if (n === buf.length) {\n          TypedArrayPrototypeSet(ret, buf, retLen - n)\n          ++c\n          if (p.next) this.head = p.next\n          else this.head = this.tail = null\n        } else {\n          TypedArrayPrototypeSet(ret, new Uint8Array(buf.buffer, buf.byteOffset, n), retLen - n)\n          this.head = p\n          p.data = buf.slice(n)\n        }\n        break\n      }\n      ++c\n    } while ((p = p.next) !== null)\n    this.length -= c\n    return ret\n  }\n\n  // Make sure the linked list only shows the minimal necessary information.\n  [Symbol.for('nodejs.util.inspect.custom')](_, options) {\n    return inspect(this, {\n      ...options,\n      // Only inspect one level.\n      depth: 0,\n      // It should not recurse.\n      customInspect: false\n    })\n  }\n}\n","'use strict'\n\nconst { MathFloor, NumberIsInteger } = require('../../ours/primordials')\nconst { validateInteger } = require('../validators')\nconst { ERR_INVALID_ARG_VALUE } = require('../../ours/errors').codes\nlet defaultHighWaterMarkBytes = 16 * 1024\nlet defaultHighWaterMarkObjectMode = 16\nfunction highWaterMarkFrom(options, isDuplex, duplexKey) {\n  return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null\n}\nfunction getDefaultHighWaterMark(objectMode) {\n  return objectMode ? defaultHighWaterMarkObjectMode : defaultHighWaterMarkBytes\n}\nfunction setDefaultHighWaterMark(objectMode, value) {\n  validateInteger(value, 'value', 0)\n  if (objectMode) {\n    defaultHighWaterMarkObjectMode = value\n  } else {\n    defaultHighWaterMarkBytes = value\n  }\n}\nfunction getHighWaterMark(state, options, duplexKey, isDuplex) {\n  const hwm = highWaterMarkFrom(options, isDuplex, duplexKey)\n  if (hwm != null) {\n    if (!NumberIsInteger(hwm) || hwm < 0) {\n      const name = isDuplex ? `options.${duplexKey}` : 'options.highWaterMark'\n      throw new ERR_INVALID_ARG_VALUE(name, hwm)\n    }\n    return MathFloor(hwm)\n  }\n\n  // Default value\n  return getDefaultHighWaterMark(state.objectMode)\n}\nmodule.exports = {\n  getHighWaterMark,\n  getDefaultHighWaterMark,\n  setDefaultHighWaterMark\n}\n","/*! safe-buffer. MIT License. Feross Aboukhadijeh  */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n  for (var key in src) {\n    dst[key] = src[key]\n  }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n  module.exports = buffer\n} else {\n  // Copy properties from require('buffer')\n  copyProps(buffer, exports)\n  exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n  return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n  if (typeof arg === 'number') {\n    throw new TypeError('Argument must not be a number')\n  }\n  return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n  if (typeof size !== 'number') {\n    throw new TypeError('Argument must be a number')\n  }\n  var buf = Buffer(size)\n  if (fill !== undefined) {\n    if (typeof encoding === 'string') {\n      buf.fill(fill, encoding)\n    } else {\n      buf.fill(fill)\n    }\n  } else {\n    buf.fill(0)\n  }\n  return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n  if (typeof size !== 'number') {\n    throw new TypeError('Argument must be a number')\n  }\n  return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n  if (typeof size !== 'number') {\n    throw new TypeError('Argument must be a number')\n  }\n  return buffer.SlowBuffer(size)\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n  encoding = '' + encoding;\n  switch (encoding && encoding.toLowerCase()) {\n    case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':\n      return true;\n    default:\n      return false;\n  }\n};\n\nfunction _normalizeEncoding(enc) {\n  if (!enc) return 'utf8';\n  var retried;\n  while (true) {\n    switch (enc) {\n      case 'utf8':\n      case 'utf-8':\n        return 'utf8';\n      case 'ucs2':\n      case 'ucs-2':\n      case 'utf16le':\n      case 'utf-16le':\n        return 'utf16le';\n      case 'latin1':\n      case 'binary':\n        return 'latin1';\n      case 'base64':\n      case 'ascii':\n      case 'hex':\n        return enc;\n      default:\n        if (retried) return; // undefined\n        enc = ('' + enc).toLowerCase();\n        retried = true;\n    }\n  }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n  var nenc = _normalizeEncoding(enc);\n  if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n  return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n  this.encoding = normalizeEncoding(encoding);\n  var nb;\n  switch (this.encoding) {\n    case 'utf16le':\n      this.text = utf16Text;\n      this.end = utf16End;\n      nb = 4;\n      break;\n    case 'utf8':\n      this.fillLast = utf8FillLast;\n      nb = 4;\n      break;\n    case 'base64':\n      this.text = base64Text;\n      this.end = base64End;\n      nb = 3;\n      break;\n    default:\n      this.write = simpleWrite;\n      this.end = simpleEnd;\n      return;\n  }\n  this.lastNeed = 0;\n  this.lastTotal = 0;\n  this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n  if (buf.length === 0) return '';\n  var r;\n  var i;\n  if (this.lastNeed) {\n    r = this.fillLast(buf);\n    if (r === undefined) return '';\n    i = this.lastNeed;\n    this.lastNeed = 0;\n  } else {\n    i = 0;\n  }\n  if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n  return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n  if (this.lastNeed <= buf.length) {\n    buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n    return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n  }\n  buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n  this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n  if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;\n  return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n  var j = buf.length - 1;\n  if (j < i) return 0;\n  var nb = utf8CheckByte(buf[j]);\n  if (nb >= 0) {\n    if (nb > 0) self.lastNeed = nb - 1;\n    return nb;\n  }\n  if (--j < i || nb === -2) return 0;\n  nb = utf8CheckByte(buf[j]);\n  if (nb >= 0) {\n    if (nb > 0) self.lastNeed = nb - 2;\n    return nb;\n  }\n  if (--j < i || nb === -2) return 0;\n  nb = utf8CheckByte(buf[j]);\n  if (nb >= 0) {\n    if (nb > 0) {\n      if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n    }\n    return nb;\n  }\n  return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n  if ((buf[0] & 0xC0) !== 0x80) {\n    self.lastNeed = 0;\n    return '\\ufffd';\n  }\n  if (self.lastNeed > 1 && buf.length > 1) {\n    if ((buf[1] & 0xC0) !== 0x80) {\n      self.lastNeed = 1;\n      return '\\ufffd';\n    }\n    if (self.lastNeed > 2 && buf.length > 2) {\n      if ((buf[2] & 0xC0) !== 0x80) {\n        self.lastNeed = 2;\n        return '\\ufffd';\n      }\n    }\n  }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n  var p = this.lastTotal - this.lastNeed;\n  var r = utf8CheckExtraBytes(this, buf, p);\n  if (r !== undefined) return r;\n  if (this.lastNeed <= buf.length) {\n    buf.copy(this.lastChar, p, 0, this.lastNeed);\n    return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n  }\n  buf.copy(this.lastChar, p, 0, buf.length);\n  this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n  var total = utf8CheckIncomplete(this, buf, i);\n  if (!this.lastNeed) return buf.toString('utf8', i);\n  this.lastTotal = total;\n  var end = buf.length - (total - this.lastNeed);\n  buf.copy(this.lastChar, 0, end);\n  return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n  var r = buf && buf.length ? this.write(buf) : '';\n  if (this.lastNeed) return r + '\\ufffd';\n  return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n  if ((buf.length - i) % 2 === 0) {\n    var r = buf.toString('utf16le', i);\n    if (r) {\n      var c = r.charCodeAt(r.length - 1);\n      if (c >= 0xD800 && c <= 0xDBFF) {\n        this.lastNeed = 2;\n        this.lastTotal = 4;\n        this.lastChar[0] = buf[buf.length - 2];\n        this.lastChar[1] = buf[buf.length - 1];\n        return r.slice(0, -1);\n      }\n    }\n    return r;\n  }\n  this.lastNeed = 1;\n  this.lastTotal = 2;\n  this.lastChar[0] = buf[buf.length - 1];\n  return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n  var r = buf && buf.length ? this.write(buf) : '';\n  if (this.lastNeed) {\n    var end = this.lastTotal - this.lastNeed;\n    return r + this.lastChar.toString('utf16le', 0, end);\n  }\n  return r;\n}\n\nfunction base64Text(buf, i) {\n  var n = (buf.length - i) % 3;\n  if (n === 0) return buf.toString('base64', i);\n  this.lastNeed = 3 - n;\n  this.lastTotal = 3;\n  if (n === 1) {\n    this.lastChar[0] = buf[buf.length - 1];\n  } else {\n    this.lastChar[0] = buf[buf.length - 2];\n    this.lastChar[1] = buf[buf.length - 1];\n  }\n  return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n  var r = buf && buf.length ? this.write(buf) : '';\n  if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n  return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n  return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n  return buf && buf.length ? this.write(buf) : '';\n}","'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } = require('../../ours/primordials')\nconst { Buffer } = require('buffer')\nconst { ERR_INVALID_ARG_TYPE, ERR_STREAM_NULL_VALUES } = require('../../ours/errors').codes\nfunction from(Readable, iterable, opts) {\n  let iterator\n  if (typeof iterable === 'string' || iterable instanceof Buffer) {\n    return new Readable({\n      objectMode: true,\n      ...opts,\n      read() {\n        this.push(iterable)\n        this.push(null)\n      }\n    })\n  }\n  let isAsync\n  if (iterable && iterable[SymbolAsyncIterator]) {\n    isAsync = true\n    iterator = iterable[SymbolAsyncIterator]()\n  } else if (iterable && iterable[SymbolIterator]) {\n    isAsync = false\n    iterator = iterable[SymbolIterator]()\n  } else {\n    throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable)\n  }\n  const readable = new Readable({\n    objectMode: true,\n    highWaterMark: 1,\n    // TODO(ronag): What options should be allowed?\n    ...opts\n  })\n\n  // Flag to protect against _read\n  // being called before last iteration completion.\n  let reading = false\n  readable._read = function () {\n    if (!reading) {\n      reading = true\n      next()\n    }\n  }\n  readable._destroy = function (error, cb) {\n    PromisePrototypeThen(\n      close(error),\n      () => process.nextTick(cb, error),\n      // nextTick is here in case cb throws\n      (e) => process.nextTick(cb, e || error)\n    )\n  }\n  async function close(error) {\n    const hadError = error !== undefined && error !== null\n    const hasThrow = typeof iterator.throw === 'function'\n    if (hadError && hasThrow) {\n      const { value, done } = await iterator.throw(error)\n      await value\n      if (done) {\n        return\n      }\n    }\n    if (typeof iterator.return === 'function') {\n      const { value } = await iterator.return()\n      await value\n    }\n  }\n  async function next() {\n    for (;;) {\n      try {\n        const { value, done } = isAsync ? await iterator.next() : iterator.next()\n        if (done) {\n          readable.push(null)\n        } else {\n          const res = value && typeof value.then === 'function' ? await value : value\n          if (res === null) {\n            reading = false\n            throw new ERR_STREAM_NULL_VALUES()\n          } else if (readable.push(res)) {\n            continue\n          } else {\n            reading = false\n          }\n        }\n      } catch (err) {\n        readable.destroy(err)\n      }\n      break\n    }\n  }\n  return readable\n}\nmodule.exports = from\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst {\n  ArrayPrototypeIndexOf,\n  NumberIsInteger,\n  NumberIsNaN,\n  NumberParseInt,\n  ObjectDefineProperties,\n  ObjectKeys,\n  ObjectSetPrototypeOf,\n  Promise,\n  SafeSet,\n  SymbolAsyncDispose,\n  SymbolAsyncIterator,\n  Symbol\n} = require('../../ours/primordials')\nmodule.exports = Readable\nReadable.ReadableState = ReadableState\nconst { EventEmitter: EE } = require('events')\nconst { Stream, prependListener } = require('./legacy')\nconst { Buffer } = require('buffer')\nconst { addAbortSignal } = require('./add-abort-signal')\nconst eos = require('./end-of-stream')\nlet debug = require('../../ours/util').debuglog('stream', (fn) => {\n  debug = fn\n})\nconst BufferList = require('./buffer_list')\nconst destroyImpl = require('./destroy')\nconst { getHighWaterMark, getDefaultHighWaterMark } = require('./state')\nconst {\n  aggregateTwoErrors,\n  codes: {\n    ERR_INVALID_ARG_TYPE,\n    ERR_METHOD_NOT_IMPLEMENTED,\n    ERR_OUT_OF_RANGE,\n    ERR_STREAM_PUSH_AFTER_EOF,\n    ERR_STREAM_UNSHIFT_AFTER_END_EVENT\n  },\n  AbortError\n} = require('../../ours/errors')\nconst { validateObject } = require('../validators')\nconst kPaused = Symbol('kPaused')\nconst { StringDecoder } = require('string_decoder/')\nconst from = require('./from')\nObjectSetPrototypeOf(Readable.prototype, Stream.prototype)\nObjectSetPrototypeOf(Readable, Stream)\nconst nop = () => {}\nconst { errorOrDestroy } = destroyImpl\nconst kObjectMode = 1 << 0\nconst kEnded = 1 << 1\nconst kEndEmitted = 1 << 2\nconst kReading = 1 << 3\nconst kConstructed = 1 << 4\nconst kSync = 1 << 5\nconst kNeedReadable = 1 << 6\nconst kEmittedReadable = 1 << 7\nconst kReadableListening = 1 << 8\nconst kResumeScheduled = 1 << 9\nconst kErrorEmitted = 1 << 10\nconst kEmitClose = 1 << 11\nconst kAutoDestroy = 1 << 12\nconst kDestroyed = 1 << 13\nconst kClosed = 1 << 14\nconst kCloseEmitted = 1 << 15\nconst kMultiAwaitDrain = 1 << 16\nconst kReadingMore = 1 << 17\nconst kDataEmitted = 1 << 18\n\n// TODO(benjamingr) it is likely slower to do it this way than with free functions\nfunction makeBitMapDescriptor(bit) {\n  return {\n    enumerable: false,\n    get() {\n      return (this.state & bit) !== 0\n    },\n    set(value) {\n      if (value) this.state |= bit\n      else this.state &= ~bit\n    }\n  }\n}\nObjectDefineProperties(ReadableState.prototype, {\n  objectMode: makeBitMapDescriptor(kObjectMode),\n  ended: makeBitMapDescriptor(kEnded),\n  endEmitted: makeBitMapDescriptor(kEndEmitted),\n  reading: makeBitMapDescriptor(kReading),\n  // Stream is still being constructed and cannot be\n  // destroyed until construction finished or failed.\n  // Async construction is opt in, therefore we start as\n  // constructed.\n  constructed: makeBitMapDescriptor(kConstructed),\n  // A flag to be able to tell if the event 'readable'/'data' is emitted\n  // immediately, or on a later tick.  We set this to true at first, because\n  // any actions that shouldn't happen until \"later\" should generally also\n  // not happen before the first read call.\n  sync: makeBitMapDescriptor(kSync),\n  // Whenever we return null, then we set a flag to say\n  // that we're awaiting a 'readable' event emission.\n  needReadable: makeBitMapDescriptor(kNeedReadable),\n  emittedReadable: makeBitMapDescriptor(kEmittedReadable),\n  readableListening: makeBitMapDescriptor(kReadableListening),\n  resumeScheduled: makeBitMapDescriptor(kResumeScheduled),\n  // True if the error was already emitted and should not be thrown again.\n  errorEmitted: makeBitMapDescriptor(kErrorEmitted),\n  emitClose: makeBitMapDescriptor(kEmitClose),\n  autoDestroy: makeBitMapDescriptor(kAutoDestroy),\n  // Has it been destroyed.\n  destroyed: makeBitMapDescriptor(kDestroyed),\n  // Indicates whether the stream has finished destroying.\n  closed: makeBitMapDescriptor(kClosed),\n  // True if close has been emitted or would have been emitted\n  // depending on emitClose.\n  closeEmitted: makeBitMapDescriptor(kCloseEmitted),\n  multiAwaitDrain: makeBitMapDescriptor(kMultiAwaitDrain),\n  // If true, a maybeReadMore has been scheduled.\n  readingMore: makeBitMapDescriptor(kReadingMore),\n  dataEmitted: makeBitMapDescriptor(kDataEmitted)\n})\nfunction ReadableState(options, stream, isDuplex) {\n  // Duplex streams are both readable and writable, but share\n  // the same options object.\n  // However, some cases require setting options to different\n  // values for the readable and the writable sides of the duplex stream.\n  // These options can be provided separately as readableXXX and writableXXX.\n  if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof require('./duplex')\n\n  // Bit map field to store ReadableState more effciently with 1 bit per field\n  // instead of a V8 slot per field.\n  this.state = kEmitClose | kAutoDestroy | kConstructed | kSync\n  // Object stream flag. Used to make read(n) ignore n and to\n  // make all the buffer merging and length checks go away.\n  if (options && options.objectMode) this.state |= kObjectMode\n  if (isDuplex && options && options.readableObjectMode) this.state |= kObjectMode\n\n  // The point at which it stops calling _read() to fill the buffer\n  // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n  this.highWaterMark = options\n    ? getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex)\n    : getDefaultHighWaterMark(false)\n\n  // A linked list is used to store data chunks instead of an array because the\n  // linked list can remove elements from the beginning faster than\n  // array.shift().\n  this.buffer = new BufferList()\n  this.length = 0\n  this.pipes = []\n  this.flowing = null\n  this[kPaused] = null\n\n  // Should close be emitted on destroy. Defaults to true.\n  if (options && options.emitClose === false) this.state &= ~kEmitClose\n\n  // Should .destroy() be called after 'end' (and potentially 'finish').\n  if (options && options.autoDestroy === false) this.state &= ~kAutoDestroy\n\n  // Indicates whether the stream has errored. When true no further\n  // _read calls, 'data' or 'readable' events should occur. This is needed\n  // since when autoDestroy is disabled we need a way to tell whether the\n  // stream has failed.\n  this.errored = null\n\n  // Crypto is kind of old and crusty.  Historically, its default string\n  // encoding is 'binary' so we have to make this configurable.\n  // Everything else in the universe uses 'utf8', though.\n  this.defaultEncoding = (options && options.defaultEncoding) || 'utf8'\n\n  // Ref the piped dest which we need a drain event on it\n  // type: null | Writable | Set.\n  this.awaitDrainWriters = null\n  this.decoder = null\n  this.encoding = null\n  if (options && options.encoding) {\n    this.decoder = new StringDecoder(options.encoding)\n    this.encoding = options.encoding\n  }\n}\nfunction Readable(options) {\n  if (!(this instanceof Readable)) return new Readable(options)\n\n  // Checking for a Stream.Duplex instance is faster here instead of inside\n  // the ReadableState constructor, at least with V8 6.5.\n  const isDuplex = this instanceof require('./duplex')\n  this._readableState = new ReadableState(options, this, isDuplex)\n  if (options) {\n    if (typeof options.read === 'function') this._read = options.read\n    if (typeof options.destroy === 'function') this._destroy = options.destroy\n    if (typeof options.construct === 'function') this._construct = options.construct\n    if (options.signal && !isDuplex) addAbortSignal(options.signal, this)\n  }\n  Stream.call(this, options)\n  destroyImpl.construct(this, () => {\n    if (this._readableState.needReadable) {\n      maybeReadMore(this, this._readableState)\n    }\n  })\n}\nReadable.prototype.destroy = destroyImpl.destroy\nReadable.prototype._undestroy = destroyImpl.undestroy\nReadable.prototype._destroy = function (err, cb) {\n  cb(err)\n}\nReadable.prototype[EE.captureRejectionSymbol] = function (err) {\n  this.destroy(err)\n}\nReadable.prototype[SymbolAsyncDispose] = function () {\n  let error\n  if (!this.destroyed) {\n    error = this.readableEnded ? null : new AbortError()\n    this.destroy(error)\n  }\n  return new Promise((resolve, reject) => eos(this, (err) => (err && err !== error ? reject(err) : resolve(null))))\n}\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n  return readableAddChunk(this, chunk, encoding, false)\n}\n\n// Unshift should *always* be something directly out of read().\nReadable.prototype.unshift = function (chunk, encoding) {\n  return readableAddChunk(this, chunk, encoding, true)\n}\nfunction readableAddChunk(stream, chunk, encoding, addToFront) {\n  debug('readableAddChunk', chunk)\n  const state = stream._readableState\n  let err\n  if ((state.state & kObjectMode) === 0) {\n    if (typeof chunk === 'string') {\n      encoding = encoding || state.defaultEncoding\n      if (state.encoding !== encoding) {\n        if (addToFront && state.encoding) {\n          // When unshifting, if state.encoding is set, we have to save\n          // the string in the BufferList with the state encoding.\n          chunk = Buffer.from(chunk, encoding).toString(state.encoding)\n        } else {\n          chunk = Buffer.from(chunk, encoding)\n          encoding = ''\n        }\n      }\n    } else if (chunk instanceof Buffer) {\n      encoding = ''\n    } else if (Stream._isUint8Array(chunk)) {\n      chunk = Stream._uint8ArrayToBuffer(chunk)\n      encoding = ''\n    } else if (chunk != null) {\n      err = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk)\n    }\n  }\n  if (err) {\n    errorOrDestroy(stream, err)\n  } else if (chunk === null) {\n    state.state &= ~kReading\n    onEofChunk(stream, state)\n  } else if ((state.state & kObjectMode) !== 0 || (chunk && chunk.length > 0)) {\n    if (addToFront) {\n      if ((state.state & kEndEmitted) !== 0) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT())\n      else if (state.destroyed || state.errored) return false\n      else addChunk(stream, state, chunk, true)\n    } else if (state.ended) {\n      errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF())\n    } else if (state.destroyed || state.errored) {\n      return false\n    } else {\n      state.state &= ~kReading\n      if (state.decoder && !encoding) {\n        chunk = state.decoder.write(chunk)\n        if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false)\n        else maybeReadMore(stream, state)\n      } else {\n        addChunk(stream, state, chunk, false)\n      }\n    }\n  } else if (!addToFront) {\n    state.state &= ~kReading\n    maybeReadMore(stream, state)\n  }\n\n  // We can push more data if we are below the highWaterMark.\n  // Also, if we have no data yet, we can stand some more bytes.\n  // This is to work around cases where hwm=0, such as the repl.\n  return !state.ended && (state.length < state.highWaterMark || state.length === 0)\n}\nfunction addChunk(stream, state, chunk, addToFront) {\n  if (state.flowing && state.length === 0 && !state.sync && stream.listenerCount('data') > 0) {\n    // Use the guard to avoid creating `Set()` repeatedly\n    // when we have multiple pipes.\n    if ((state.state & kMultiAwaitDrain) !== 0) {\n      state.awaitDrainWriters.clear()\n    } else {\n      state.awaitDrainWriters = null\n    }\n    state.dataEmitted = true\n    stream.emit('data', chunk)\n  } else {\n    // Update the buffer info.\n    state.length += state.objectMode ? 1 : chunk.length\n    if (addToFront) state.buffer.unshift(chunk)\n    else state.buffer.push(chunk)\n    if ((state.state & kNeedReadable) !== 0) emitReadable(stream)\n  }\n  maybeReadMore(stream, state)\n}\nReadable.prototype.isPaused = function () {\n  const state = this._readableState\n  return state[kPaused] === true || state.flowing === false\n}\n\n// Backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n  const decoder = new StringDecoder(enc)\n  this._readableState.decoder = decoder\n  // If setEncoding(null), decoder.encoding equals utf8.\n  this._readableState.encoding = this._readableState.decoder.encoding\n  const buffer = this._readableState.buffer\n  // Iterate over current buffer to convert already stored Buffers:\n  let content = ''\n  for (const data of buffer) {\n    content += decoder.write(data)\n  }\n  buffer.clear()\n  if (content !== '') buffer.push(content)\n  this._readableState.length = content.length\n  return this\n}\n\n// Don't raise the hwm > 1GB.\nconst MAX_HWM = 0x40000000\nfunction computeNewHighWaterMark(n) {\n  if (n > MAX_HWM) {\n    throw new ERR_OUT_OF_RANGE('size', '<= 1GiB', n)\n  } else {\n    // Get the next highest power of 2 to prevent increasing hwm excessively in\n    // tiny amounts.\n    n--\n    n |= n >>> 1\n    n |= n >>> 2\n    n |= n >>> 4\n    n |= n >>> 8\n    n |= n >>> 16\n    n++\n  }\n  return n\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n  if (n <= 0 || (state.length === 0 && state.ended)) return 0\n  if ((state.state & kObjectMode) !== 0) return 1\n  if (NumberIsNaN(n)) {\n    // Only flow one buffer at a time.\n    if (state.flowing && state.length) return state.buffer.first().length\n    return state.length\n  }\n  if (n <= state.length) return n\n  return state.ended ? state.length : 0\n}\n\n// You can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n  debug('read', n)\n  // Same as parseInt(undefined, 10), however V8 7.3 performance regressed\n  // in this scenario, so we are doing it manually.\n  if (n === undefined) {\n    n = NaN\n  } else if (!NumberIsInteger(n)) {\n    n = NumberParseInt(n, 10)\n  }\n  const state = this._readableState\n  const nOrig = n\n\n  // If we're asking for more than the current hwm, then raise the hwm.\n  if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n)\n  if (n !== 0) state.state &= ~kEmittedReadable\n\n  // If we're doing read(0) to trigger a readable event, but we\n  // already have a bunch of data in the buffer, then just trigger\n  // the 'readable' event and move on.\n  if (\n    n === 0 &&\n    state.needReadable &&\n    ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)\n  ) {\n    debug('read: emitReadable', state.length, state.ended)\n    if (state.length === 0 && state.ended) endReadable(this)\n    else emitReadable(this)\n    return null\n  }\n  n = howMuchToRead(n, state)\n\n  // If we've ended, and we're now clear, then finish it up.\n  if (n === 0 && state.ended) {\n    if (state.length === 0) endReadable(this)\n    return null\n  }\n\n  // All the actual chunk generation logic needs to be\n  // *below* the call to _read.  The reason is that in certain\n  // synthetic stream cases, such as passthrough streams, _read\n  // may be a completely synchronous operation which may change\n  // the state of the read buffer, providing enough data when\n  // before there was *not* enough.\n  //\n  // So, the steps are:\n  // 1. Figure out what the state of things will be after we do\n  // a read from the buffer.\n  //\n  // 2. If that resulting state will trigger a _read, then call _read.\n  // Note that this may be asynchronous, or synchronous.  Yes, it is\n  // deeply ugly to write APIs this way, but that still doesn't mean\n  // that the Readable class should behave improperly, as streams are\n  // designed to be sync/async agnostic.\n  // Take note if the _read call is sync or async (ie, if the read call\n  // has returned yet), so that we know whether or not it's safe to emit\n  // 'readable' etc.\n  //\n  // 3. Actually pull the requested chunks out of the buffer and return.\n\n  // if we need a readable event, then we need to do some reading.\n  let doRead = (state.state & kNeedReadable) !== 0\n  debug('need readable', doRead)\n\n  // If we currently have less than the highWaterMark, then also read some.\n  if (state.length === 0 || state.length - n < state.highWaterMark) {\n    doRead = true\n    debug('length less than watermark', doRead)\n  }\n\n  // However, if we've ended, then there's no point, if we're already\n  // reading, then it's unnecessary, if we're constructing we have to wait,\n  // and if we're destroyed or errored, then it's not allowed,\n  if (state.ended || state.reading || state.destroyed || state.errored || !state.constructed) {\n    doRead = false\n    debug('reading, ended or constructing', doRead)\n  } else if (doRead) {\n    debug('do read')\n    state.state |= kReading | kSync\n    // If the length is currently zero, then we *need* a readable event.\n    if (state.length === 0) state.state |= kNeedReadable\n\n    // Call internal read method\n    try {\n      this._read(state.highWaterMark)\n    } catch (err) {\n      errorOrDestroy(this, err)\n    }\n    state.state &= ~kSync\n\n    // If _read pushed data synchronously, then `reading` will be false,\n    // and we need to re-evaluate how much data we can return to the user.\n    if (!state.reading) n = howMuchToRead(nOrig, state)\n  }\n  let ret\n  if (n > 0) ret = fromList(n, state)\n  else ret = null\n  if (ret === null) {\n    state.needReadable = state.length <= state.highWaterMark\n    n = 0\n  } else {\n    state.length -= n\n    if (state.multiAwaitDrain) {\n      state.awaitDrainWriters.clear()\n    } else {\n      state.awaitDrainWriters = null\n    }\n  }\n  if (state.length === 0) {\n    // If we have nothing in the buffer, then we want to know\n    // as soon as we *do* get something into the buffer.\n    if (!state.ended) state.needReadable = true\n\n    // If we tried to read() past the EOF, then emit end on the next tick.\n    if (nOrig !== n && state.ended) endReadable(this)\n  }\n  if (ret !== null && !state.errorEmitted && !state.closeEmitted) {\n    state.dataEmitted = true\n    this.emit('data', ret)\n  }\n  return ret\n}\nfunction onEofChunk(stream, state) {\n  debug('onEofChunk')\n  if (state.ended) return\n  if (state.decoder) {\n    const chunk = state.decoder.end()\n    if (chunk && chunk.length) {\n      state.buffer.push(chunk)\n      state.length += state.objectMode ? 1 : chunk.length\n    }\n  }\n  state.ended = true\n  if (state.sync) {\n    // If we are sync, wait until next tick to emit the data.\n    // Otherwise we risk emitting data in the flow()\n    // the readable code triggers during a read() call.\n    emitReadable(stream)\n  } else {\n    // Emit 'readable' now to make sure it gets picked up.\n    state.needReadable = false\n    state.emittedReadable = true\n    // We have to emit readable now that we are EOF. Modules\n    // in the ecosystem (e.g. dicer) rely on this event being sync.\n    emitReadable_(stream)\n  }\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow.  This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n  const state = stream._readableState\n  debug('emitReadable', state.needReadable, state.emittedReadable)\n  state.needReadable = false\n  if (!state.emittedReadable) {\n    debug('emitReadable', state.flowing)\n    state.emittedReadable = true\n    process.nextTick(emitReadable_, stream)\n  }\n}\nfunction emitReadable_(stream) {\n  const state = stream._readableState\n  debug('emitReadable_', state.destroyed, state.length, state.ended)\n  if (!state.destroyed && !state.errored && (state.length || state.ended)) {\n    stream.emit('readable')\n    state.emittedReadable = false\n  }\n\n  // The stream needs another readable event if:\n  // 1. It is not flowing, as the flow mechanism will take\n  //    care of it.\n  // 2. It is not ended.\n  // 3. It is below the highWaterMark, so we can schedule\n  //    another readable later.\n  state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark\n  flow(stream)\n}\n\n// At this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data.  that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n  if (!state.readingMore && state.constructed) {\n    state.readingMore = true\n    process.nextTick(maybeReadMore_, stream, state)\n  }\n}\nfunction maybeReadMore_(stream, state) {\n  // Attempt to read more data if we should.\n  //\n  // The conditions for reading more data are (one of):\n  // - Not enough data buffered (state.length < state.highWaterMark). The loop\n  //   is responsible for filling the buffer with enough data if such data\n  //   is available. If highWaterMark is 0 and we are not in the flowing mode\n  //   we should _not_ attempt to buffer any extra data. We'll get more data\n  //   when the stream consumer calls read() instead.\n  // - No data in the buffer, and the stream is in flowing mode. In this mode\n  //   the loop below is responsible for ensuring read() is called. Failing to\n  //   call read here would abort the flow and there's no other mechanism for\n  //   continuing the flow if the stream consumer has just subscribed to the\n  //   'data' event.\n  //\n  // In addition to the above conditions to keep reading data, the following\n  // conditions prevent the data from being read:\n  // - The stream has ended (state.ended).\n  // - There is already a pending 'read' operation (state.reading). This is a\n  //   case where the stream has called the implementation defined _read()\n  //   method, but they are processing the call asynchronously and have _not_\n  //   called push() with new data. In this case we skip performing more\n  //   read()s. The execution ends in this method again after the _read() ends\n  //   up calling push() with more data.\n  while (\n    !state.reading &&\n    !state.ended &&\n    (state.length < state.highWaterMark || (state.flowing && state.length === 0))\n  ) {\n    const len = state.length\n    debug('maybeReadMore read 0')\n    stream.read(0)\n    if (len === state.length)\n      // Didn't get any data, stop spinning.\n      break\n  }\n  state.readingMore = false\n}\n\n// Abstract method.  to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n  throw new ERR_METHOD_NOT_IMPLEMENTED('_read()')\n}\nReadable.prototype.pipe = function (dest, pipeOpts) {\n  const src = this\n  const state = this._readableState\n  if (state.pipes.length === 1) {\n    if (!state.multiAwaitDrain) {\n      state.multiAwaitDrain = true\n      state.awaitDrainWriters = new SafeSet(state.awaitDrainWriters ? [state.awaitDrainWriters] : [])\n    }\n  }\n  state.pipes.push(dest)\n  debug('pipe count=%d opts=%j', state.pipes.length, pipeOpts)\n  const doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr\n  const endFn = doEnd ? onend : unpipe\n  if (state.endEmitted) process.nextTick(endFn)\n  else src.once('end', endFn)\n  dest.on('unpipe', onunpipe)\n  function onunpipe(readable, unpipeInfo) {\n    debug('onunpipe')\n    if (readable === src) {\n      if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n        unpipeInfo.hasUnpiped = true\n        cleanup()\n      }\n    }\n  }\n  function onend() {\n    debug('onend')\n    dest.end()\n  }\n  let ondrain\n  let cleanedUp = false\n  function cleanup() {\n    debug('cleanup')\n    // Cleanup event handlers once the pipe is broken.\n    dest.removeListener('close', onclose)\n    dest.removeListener('finish', onfinish)\n    if (ondrain) {\n      dest.removeListener('drain', ondrain)\n    }\n    dest.removeListener('error', onerror)\n    dest.removeListener('unpipe', onunpipe)\n    src.removeListener('end', onend)\n    src.removeListener('end', unpipe)\n    src.removeListener('data', ondata)\n    cleanedUp = true\n\n    // If the reader is waiting for a drain event from this\n    // specific writer, then it would cause it to never start\n    // flowing again.\n    // So, if this is awaiting a drain, then we just call it now.\n    // If we don't know, then assume that we are waiting for one.\n    if (ondrain && state.awaitDrainWriters && (!dest._writableState || dest._writableState.needDrain)) ondrain()\n  }\n  function pause() {\n    // If the user unpiped during `dest.write()`, it is possible\n    // to get stuck in a permanently paused state if that write\n    // also returned false.\n    // => Check whether `dest` is still a piping destination.\n    if (!cleanedUp) {\n      if (state.pipes.length === 1 && state.pipes[0] === dest) {\n        debug('false write response, pause', 0)\n        state.awaitDrainWriters = dest\n        state.multiAwaitDrain = false\n      } else if (state.pipes.length > 1 && state.pipes.includes(dest)) {\n        debug('false write response, pause', state.awaitDrainWriters.size)\n        state.awaitDrainWriters.add(dest)\n      }\n      src.pause()\n    }\n    if (!ondrain) {\n      // When the dest drains, it reduces the awaitDrain counter\n      // on the source.  This would be more elegant with a .once()\n      // handler in flow(), but adding and removing repeatedly is\n      // too slow.\n      ondrain = pipeOnDrain(src, dest)\n      dest.on('drain', ondrain)\n    }\n  }\n  src.on('data', ondata)\n  function ondata(chunk) {\n    debug('ondata')\n    const ret = dest.write(chunk)\n    debug('dest.write', ret)\n    if (ret === false) {\n      pause()\n    }\n  }\n\n  // If the dest has an error, then stop piping into it.\n  // However, don't suppress the throwing behavior for this.\n  function onerror(er) {\n    debug('onerror', er)\n    unpipe()\n    dest.removeListener('error', onerror)\n    if (dest.listenerCount('error') === 0) {\n      const s = dest._writableState || dest._readableState\n      if (s && !s.errorEmitted) {\n        // User incorrectly emitted 'error' directly on the stream.\n        errorOrDestroy(dest, er)\n      } else {\n        dest.emit('error', er)\n      }\n    }\n  }\n\n  // Make sure our error handler is attached before userland ones.\n  prependListener(dest, 'error', onerror)\n\n  // Both close and finish should trigger unpipe, but only once.\n  function onclose() {\n    dest.removeListener('finish', onfinish)\n    unpipe()\n  }\n  dest.once('close', onclose)\n  function onfinish() {\n    debug('onfinish')\n    dest.removeListener('close', onclose)\n    unpipe()\n  }\n  dest.once('finish', onfinish)\n  function unpipe() {\n    debug('unpipe')\n    src.unpipe(dest)\n  }\n\n  // Tell the dest that it's being piped to.\n  dest.emit('pipe', src)\n\n  // Start the flow if it hasn't been started already.\n\n  if (dest.writableNeedDrain === true) {\n    pause()\n  } else if (!state.flowing) {\n    debug('pipe resume')\n    src.resume()\n  }\n  return dest\n}\nfunction pipeOnDrain(src, dest) {\n  return function pipeOnDrainFunctionResult() {\n    const state = src._readableState\n\n    // `ondrain` will call directly,\n    // `this` maybe not a reference to dest,\n    // so we use the real dest here.\n    if (state.awaitDrainWriters === dest) {\n      debug('pipeOnDrain', 1)\n      state.awaitDrainWriters = null\n    } else if (state.multiAwaitDrain) {\n      debug('pipeOnDrain', state.awaitDrainWriters.size)\n      state.awaitDrainWriters.delete(dest)\n    }\n    if ((!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) && src.listenerCount('data')) {\n      src.resume()\n    }\n  }\n}\nReadable.prototype.unpipe = function (dest) {\n  const state = this._readableState\n  const unpipeInfo = {\n    hasUnpiped: false\n  }\n\n  // If we're not piping anywhere, then do nothing.\n  if (state.pipes.length === 0) return this\n  if (!dest) {\n    // remove all.\n    const dests = state.pipes\n    state.pipes = []\n    this.pause()\n    for (let i = 0; i < dests.length; i++)\n      dests[i].emit('unpipe', this, {\n        hasUnpiped: false\n      })\n    return this\n  }\n\n  // Try to find the right one.\n  const index = ArrayPrototypeIndexOf(state.pipes, dest)\n  if (index === -1) return this\n  state.pipes.splice(index, 1)\n  if (state.pipes.length === 0) this.pause()\n  dest.emit('unpipe', this, unpipeInfo)\n  return this\n}\n\n// Set up data events if they are asked for\n// Ensure readable listeners eventually get something.\nReadable.prototype.on = function (ev, fn) {\n  const res = Stream.prototype.on.call(this, ev, fn)\n  const state = this._readableState\n  if (ev === 'data') {\n    // Update readableListening so that resume() may be a no-op\n    // a few lines down. This is needed to support once('readable').\n    state.readableListening = this.listenerCount('readable') > 0\n\n    // Try start flowing on next tick if stream isn't explicitly paused.\n    if (state.flowing !== false) this.resume()\n  } else if (ev === 'readable') {\n    if (!state.endEmitted && !state.readableListening) {\n      state.readableListening = state.needReadable = true\n      state.flowing = false\n      state.emittedReadable = false\n      debug('on readable', state.length, state.reading)\n      if (state.length) {\n        emitReadable(this)\n      } else if (!state.reading) {\n        process.nextTick(nReadingNextTick, this)\n      }\n    }\n  }\n  return res\n}\nReadable.prototype.addListener = Readable.prototype.on\nReadable.prototype.removeListener = function (ev, fn) {\n  const res = Stream.prototype.removeListener.call(this, ev, fn)\n  if (ev === 'readable') {\n    // We need to check if there is someone still listening to\n    // readable and reset the state. However this needs to happen\n    // after readable has been emitted but before I/O (nextTick) to\n    // support once('readable', fn) cycles. This means that calling\n    // resume within the same tick will have no\n    // effect.\n    process.nextTick(updateReadableListening, this)\n  }\n  return res\n}\nReadable.prototype.off = Readable.prototype.removeListener\nReadable.prototype.removeAllListeners = function (ev) {\n  const res = Stream.prototype.removeAllListeners.apply(this, arguments)\n  if (ev === 'readable' || ev === undefined) {\n    // We need to check if there is someone still listening to\n    // readable and reset the state. However this needs to happen\n    // after readable has been emitted but before I/O (nextTick) to\n    // support once('readable', fn) cycles. This means that calling\n    // resume within the same tick will have no\n    // effect.\n    process.nextTick(updateReadableListening, this)\n  }\n  return res\n}\nfunction updateReadableListening(self) {\n  const state = self._readableState\n  state.readableListening = self.listenerCount('readable') > 0\n  if (state.resumeScheduled && state[kPaused] === false) {\n    // Flowing needs to be set to true now, otherwise\n    // the upcoming resume will not flow.\n    state.flowing = true\n\n    // Crude way to check if we should resume.\n  } else if (self.listenerCount('data') > 0) {\n    self.resume()\n  } else if (!state.readableListening) {\n    state.flowing = null\n  }\n}\nfunction nReadingNextTick(self) {\n  debug('readable nexttick read 0')\n  self.read(0)\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n  const state = this._readableState\n  if (!state.flowing) {\n    debug('resume')\n    // We flow only if there is no one listening\n    // for readable, but we still have to call\n    // resume().\n    state.flowing = !state.readableListening\n    resume(this, state)\n  }\n  state[kPaused] = false\n  return this\n}\nfunction resume(stream, state) {\n  if (!state.resumeScheduled) {\n    state.resumeScheduled = true\n    process.nextTick(resume_, stream, state)\n  }\n}\nfunction resume_(stream, state) {\n  debug('resume', state.reading)\n  if (!state.reading) {\n    stream.read(0)\n  }\n  state.resumeScheduled = false\n  stream.emit('resume')\n  flow(stream)\n  if (state.flowing && !state.reading) stream.read(0)\n}\nReadable.prototype.pause = function () {\n  debug('call pause flowing=%j', this._readableState.flowing)\n  if (this._readableState.flowing !== false) {\n    debug('pause')\n    this._readableState.flowing = false\n    this.emit('pause')\n  }\n  this._readableState[kPaused] = true\n  return this\n}\nfunction flow(stream) {\n  const state = stream._readableState\n  debug('flow', state.flowing)\n  while (state.flowing && stream.read() !== null);\n}\n\n// Wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n  let paused = false\n\n  // TODO (ronag): Should this.destroy(err) emit\n  // 'error' on the wrapped stream? Would require\n  // a static factory method, e.g. Readable.wrap(stream).\n\n  stream.on('data', (chunk) => {\n    if (!this.push(chunk) && stream.pause) {\n      paused = true\n      stream.pause()\n    }\n  })\n  stream.on('end', () => {\n    this.push(null)\n  })\n  stream.on('error', (err) => {\n    errorOrDestroy(this, err)\n  })\n  stream.on('close', () => {\n    this.destroy()\n  })\n  stream.on('destroy', () => {\n    this.destroy()\n  })\n  this._read = () => {\n    if (paused && stream.resume) {\n      paused = false\n      stream.resume()\n    }\n  }\n\n  // Proxy all the other methods. Important when wrapping filters and duplexes.\n  const streamKeys = ObjectKeys(stream)\n  for (let j = 1; j < streamKeys.length; j++) {\n    const i = streamKeys[j]\n    if (this[i] === undefined && typeof stream[i] === 'function') {\n      this[i] = stream[i].bind(stream)\n    }\n  }\n  return this\n}\nReadable.prototype[SymbolAsyncIterator] = function () {\n  return streamToAsyncIterator(this)\n}\nReadable.prototype.iterator = function (options) {\n  if (options !== undefined) {\n    validateObject(options, 'options')\n  }\n  return streamToAsyncIterator(this, options)\n}\nfunction streamToAsyncIterator(stream, options) {\n  if (typeof stream.read !== 'function') {\n    stream = Readable.wrap(stream, {\n      objectMode: true\n    })\n  }\n  const iter = createAsyncIterator(stream, options)\n  iter.stream = stream\n  return iter\n}\nasync function* createAsyncIterator(stream, options) {\n  let callback = nop\n  function next(resolve) {\n    if (this === stream) {\n      callback()\n      callback = nop\n    } else {\n      callback = resolve\n    }\n  }\n  stream.on('readable', next)\n  let error\n  const cleanup = eos(\n    stream,\n    {\n      writable: false\n    },\n    (err) => {\n      error = err ? aggregateTwoErrors(error, err) : null\n      callback()\n      callback = nop\n    }\n  )\n  try {\n    while (true) {\n      const chunk = stream.destroyed ? null : stream.read()\n      if (chunk !== null) {\n        yield chunk\n      } else if (error) {\n        throw error\n      } else if (error === null) {\n        return\n      } else {\n        await new Promise(next)\n      }\n    }\n  } catch (err) {\n    error = aggregateTwoErrors(error, err)\n    throw error\n  } finally {\n    if (\n      (error || (options === null || options === undefined ? undefined : options.destroyOnReturn) !== false) &&\n      (error === undefined || stream._readableState.autoDestroy)\n    ) {\n      destroyImpl.destroyer(stream, null)\n    } else {\n      stream.off('readable', next)\n      cleanup()\n    }\n  }\n}\n\n// Making it explicit these properties are not enumerable\n// because otherwise some prototype manipulation in\n// userland will fail.\nObjectDefineProperties(Readable.prototype, {\n  readable: {\n    __proto__: null,\n    get() {\n      const r = this._readableState\n      // r.readable === false means that this is part of a Duplex stream\n      // where the readable side was disabled upon construction.\n      // Compat. The user might manually disable readable side through\n      // deprecated setter.\n      return !!r && r.readable !== false && !r.destroyed && !r.errorEmitted && !r.endEmitted\n    },\n    set(val) {\n      // Backwards compat.\n      if (this._readableState) {\n        this._readableState.readable = !!val\n      }\n    }\n  },\n  readableDidRead: {\n    __proto__: null,\n    enumerable: false,\n    get: function () {\n      return this._readableState.dataEmitted\n    }\n  },\n  readableAborted: {\n    __proto__: null,\n    enumerable: false,\n    get: function () {\n      return !!(\n        this._readableState.readable !== false &&\n        (this._readableState.destroyed || this._readableState.errored) &&\n        !this._readableState.endEmitted\n      )\n    }\n  },\n  readableHighWaterMark: {\n    __proto__: null,\n    enumerable: false,\n    get: function () {\n      return this._readableState.highWaterMark\n    }\n  },\n  readableBuffer: {\n    __proto__: null,\n    enumerable: false,\n    get: function () {\n      return this._readableState && this._readableState.buffer\n    }\n  },\n  readableFlowing: {\n    __proto__: null,\n    enumerable: false,\n    get: function () {\n      return this._readableState.flowing\n    },\n    set: function (state) {\n      if (this._readableState) {\n        this._readableState.flowing = state\n      }\n    }\n  },\n  readableLength: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._readableState.length\n    }\n  },\n  readableObjectMode: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._readableState ? this._readableState.objectMode : false\n    }\n  },\n  readableEncoding: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._readableState ? this._readableState.encoding : null\n    }\n  },\n  errored: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._readableState ? this._readableState.errored : null\n    }\n  },\n  closed: {\n    __proto__: null,\n    get() {\n      return this._readableState ? this._readableState.closed : false\n    }\n  },\n  destroyed: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._readableState ? this._readableState.destroyed : false\n    },\n    set(value) {\n      // We ignore the value if the stream\n      // has not been initialized yet.\n      if (!this._readableState) {\n        return\n      }\n\n      // Backward compatibility, the user is explicitly\n      // managing destroyed.\n      this._readableState.destroyed = value\n    }\n  },\n  readableEnded: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._readableState ? this._readableState.endEmitted : false\n    }\n  }\n})\nObjectDefineProperties(ReadableState.prototype, {\n  // Legacy getter for `pipesCount`.\n  pipesCount: {\n    __proto__: null,\n    get() {\n      return this.pipes.length\n    }\n  },\n  // Legacy property for `paused`.\n  paused: {\n    __proto__: null,\n    get() {\n      return this[kPaused] !== false\n    },\n    set(value) {\n      this[kPaused] = !!value\n    }\n  }\n})\n\n// Exposed for testing purposes only.\nReadable._fromList = fromList\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n  // nothing buffered.\n  if (state.length === 0) return null\n  let ret\n  if (state.objectMode) ret = state.buffer.shift()\n  else if (!n || n >= state.length) {\n    // Read it all, truncate the list.\n    if (state.decoder) ret = state.buffer.join('')\n    else if (state.buffer.length === 1) ret = state.buffer.first()\n    else ret = state.buffer.concat(state.length)\n    state.buffer.clear()\n  } else {\n    // read part of list.\n    ret = state.buffer.consume(n, state.decoder)\n  }\n  return ret\n}\nfunction endReadable(stream) {\n  const state = stream._readableState\n  debug('endReadable', state.endEmitted)\n  if (!state.endEmitted) {\n    state.ended = true\n    process.nextTick(endReadableNT, state, stream)\n  }\n}\nfunction endReadableNT(state, stream) {\n  debug('endReadableNT', state.endEmitted, state.length)\n\n  // Check that we didn't get one last unshift.\n  if (!state.errored && !state.closeEmitted && !state.endEmitted && state.length === 0) {\n    state.endEmitted = true\n    stream.emit('end')\n    if (stream.writable && stream.allowHalfOpen === false) {\n      process.nextTick(endWritableNT, stream)\n    } else if (state.autoDestroy) {\n      // In case of duplex streams we need a way to detect\n      // if the writable side is ready for autoDestroy as well.\n      const wState = stream._writableState\n      const autoDestroy =\n        !wState ||\n        (wState.autoDestroy &&\n          // We don't expect the writable to ever 'finish'\n          // if writable is explicitly set to false.\n          (wState.finished || wState.writable === false))\n      if (autoDestroy) {\n        stream.destroy()\n      }\n    }\n  }\n}\nfunction endWritableNT(stream) {\n  const writable = stream.writable && !stream.writableEnded && !stream.destroyed\n  if (writable) {\n    stream.end()\n  }\n}\nReadable.from = function (iterable, opts) {\n  return from(Readable, iterable, opts)\n}\nlet webStreamsAdapters\n\n// Lazy to avoid circular references\nfunction lazyWebStreams() {\n  if (webStreamsAdapters === undefined) webStreamsAdapters = {}\n  return webStreamsAdapters\n}\nReadable.fromWeb = function (readableStream, options) {\n  return lazyWebStreams().newStreamReadableFromReadableStream(readableStream, options)\n}\nReadable.toWeb = function (streamReadable, options) {\n  return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable, options)\n}\nReadable.wrap = function (src, options) {\n  var _ref, _src$readableObjectMo\n  return new Readable({\n    objectMode:\n      (_ref =\n        (_src$readableObjectMo = src.readableObjectMode) !== null && _src$readableObjectMo !== undefined\n          ? _src$readableObjectMo\n          : src.objectMode) !== null && _ref !== undefined\n        ? _ref\n        : true,\n    ...options,\n    destroy(err, callback) {\n      destroyImpl.destroyer(src, err)\n      callback(err)\n    }\n  }).wrap(src)\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n'use strict'\n\n/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\nconst {\n  ArrayPrototypeSlice,\n  Error,\n  FunctionPrototypeSymbolHasInstance,\n  ObjectDefineProperty,\n  ObjectDefineProperties,\n  ObjectSetPrototypeOf,\n  StringPrototypeToLowerCase,\n  Symbol,\n  SymbolHasInstance\n} = require('../../ours/primordials')\nmodule.exports = Writable\nWritable.WritableState = WritableState\nconst { EventEmitter: EE } = require('events')\nconst Stream = require('./legacy').Stream\nconst { Buffer } = require('buffer')\nconst destroyImpl = require('./destroy')\nconst { addAbortSignal } = require('./add-abort-signal')\nconst { getHighWaterMark, getDefaultHighWaterMark } = require('./state')\nconst {\n  ERR_INVALID_ARG_TYPE,\n  ERR_METHOD_NOT_IMPLEMENTED,\n  ERR_MULTIPLE_CALLBACK,\n  ERR_STREAM_CANNOT_PIPE,\n  ERR_STREAM_DESTROYED,\n  ERR_STREAM_ALREADY_FINISHED,\n  ERR_STREAM_NULL_VALUES,\n  ERR_STREAM_WRITE_AFTER_END,\n  ERR_UNKNOWN_ENCODING\n} = require('../../ours/errors').codes\nconst { errorOrDestroy } = destroyImpl\nObjectSetPrototypeOf(Writable.prototype, Stream.prototype)\nObjectSetPrototypeOf(Writable, Stream)\nfunction nop() {}\nconst kOnFinished = Symbol('kOnFinished')\nfunction WritableState(options, stream, isDuplex) {\n  // Duplex streams are both readable and writable, but share\n  // the same options object.\n  // However, some cases require setting options to different\n  // values for the readable and the writable sides of the duplex stream,\n  // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.\n  if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof require('./duplex')\n\n  // Object stream flag to indicate whether or not this stream\n  // contains buffers or objects.\n  this.objectMode = !!(options && options.objectMode)\n  if (isDuplex) this.objectMode = this.objectMode || !!(options && options.writableObjectMode)\n\n  // The point at which write() starts returning false\n  // Note: 0 is a valid value, means that we always return false if\n  // the entire buffer is not flushed immediately on write().\n  this.highWaterMark = options\n    ? getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex)\n    : getDefaultHighWaterMark(false)\n\n  // if _final has been called.\n  this.finalCalled = false\n\n  // drain event flag.\n  this.needDrain = false\n  // At the start of calling end()\n  this.ending = false\n  // When end() has been called, and returned.\n  this.ended = false\n  // When 'finish' is emitted.\n  this.finished = false\n\n  // Has it been destroyed\n  this.destroyed = false\n\n  // Should we decode strings into buffers before passing to _write?\n  // this is here so that some node-core streams can optimize string\n  // handling at a lower level.\n  const noDecode = !!(options && options.decodeStrings === false)\n  this.decodeStrings = !noDecode\n\n  // Crypto is kind of old and crusty.  Historically, its default string\n  // encoding is 'binary' so we have to make this configurable.\n  // Everything else in the universe uses 'utf8', though.\n  this.defaultEncoding = (options && options.defaultEncoding) || 'utf8'\n\n  // Not an actual buffer we keep track of, but a measurement\n  // of how much we're waiting to get pushed to some underlying\n  // socket or file.\n  this.length = 0\n\n  // A flag to see when we're in the middle of a write.\n  this.writing = false\n\n  // When true all writes will be buffered until .uncork() call.\n  this.corked = 0\n\n  // A flag to be able to tell if the onwrite cb is called immediately,\n  // or on a later tick.  We set this to true at first, because any\n  // actions that shouldn't happen until \"later\" should generally also\n  // not happen before the first write call.\n  this.sync = true\n\n  // A flag to know if we're processing previously buffered items, which\n  // may call the _write() callback in the same tick, so that we don't\n  // end up in an overlapped onwrite situation.\n  this.bufferProcessing = false\n\n  // The callback that's passed to _write(chunk, cb).\n  this.onwrite = onwrite.bind(undefined, stream)\n\n  // The callback that the user supplies to write(chunk, encoding, cb).\n  this.writecb = null\n\n  // The amount that is being written when _write is called.\n  this.writelen = 0\n\n  // Storage for data passed to the afterWrite() callback in case of\n  // synchronous _write() completion.\n  this.afterWriteTickInfo = null\n  resetBuffer(this)\n\n  // Number of pending user-supplied write callbacks\n  // this must be 0 before 'finish' can be emitted.\n  this.pendingcb = 0\n\n  // Stream is still being constructed and cannot be\n  // destroyed until construction finished or failed.\n  // Async construction is opt in, therefore we start as\n  // constructed.\n  this.constructed = true\n\n  // Emit prefinish if the only thing we're waiting for is _write cbs\n  // This is relevant for synchronous Transform streams.\n  this.prefinished = false\n\n  // True if the error was already emitted and should not be thrown again.\n  this.errorEmitted = false\n\n  // Should close be emitted on destroy. Defaults to true.\n  this.emitClose = !options || options.emitClose !== false\n\n  // Should .destroy() be called after 'finish' (and potentially 'end').\n  this.autoDestroy = !options || options.autoDestroy !== false\n\n  // Indicates whether the stream has errored. When true all write() calls\n  // should return false. This is needed since when autoDestroy\n  // is disabled we need a way to tell whether the stream has failed.\n  this.errored = null\n\n  // Indicates whether the stream has finished destroying.\n  this.closed = false\n\n  // True if close has been emitted or would have been emitted\n  // depending on emitClose.\n  this.closeEmitted = false\n  this[kOnFinished] = []\n}\nfunction resetBuffer(state) {\n  state.buffered = []\n  state.bufferedIndex = 0\n  state.allBuffers = true\n  state.allNoop = true\n}\nWritableState.prototype.getBuffer = function getBuffer() {\n  return ArrayPrototypeSlice(this.buffered, this.bufferedIndex)\n}\nObjectDefineProperty(WritableState.prototype, 'bufferedRequestCount', {\n  __proto__: null,\n  get() {\n    return this.buffered.length - this.bufferedIndex\n  }\n})\nfunction Writable(options) {\n  // Writable ctor is applied to Duplexes, too.\n  // `realHasInstance` is necessary because using plain `instanceof`\n  // would return false, as no `_writableState` property is attached.\n\n  // Trying to use the custom `instanceof` for Writable here will also break the\n  // Node.js LazyTransform implementation, which has a non-trivial getter for\n  // `_writableState` that would lead to infinite recursion.\n\n  // Checking for a Stream.Duplex instance is faster here instead of inside\n  // the WritableState constructor, at least with V8 6.5.\n  const isDuplex = this instanceof require('./duplex')\n  if (!isDuplex && !FunctionPrototypeSymbolHasInstance(Writable, this)) return new Writable(options)\n  this._writableState = new WritableState(options, this, isDuplex)\n  if (options) {\n    if (typeof options.write === 'function') this._write = options.write\n    if (typeof options.writev === 'function') this._writev = options.writev\n    if (typeof options.destroy === 'function') this._destroy = options.destroy\n    if (typeof options.final === 'function') this._final = options.final\n    if (typeof options.construct === 'function') this._construct = options.construct\n    if (options.signal) addAbortSignal(options.signal, this)\n  }\n  Stream.call(this, options)\n  destroyImpl.construct(this, () => {\n    const state = this._writableState\n    if (!state.writing) {\n      clearBuffer(this, state)\n    }\n    finishMaybe(this, state)\n  })\n}\nObjectDefineProperty(Writable, SymbolHasInstance, {\n  __proto__: null,\n  value: function (object) {\n    if (FunctionPrototypeSymbolHasInstance(this, object)) return true\n    if (this !== Writable) return false\n    return object && object._writableState instanceof WritableState\n  }\n})\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n  errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE())\n}\nfunction _write(stream, chunk, encoding, cb) {\n  const state = stream._writableState\n  if (typeof encoding === 'function') {\n    cb = encoding\n    encoding = state.defaultEncoding\n  } else {\n    if (!encoding) encoding = state.defaultEncoding\n    else if (encoding !== 'buffer' && !Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding)\n    if (typeof cb !== 'function') cb = nop\n  }\n  if (chunk === null) {\n    throw new ERR_STREAM_NULL_VALUES()\n  } else if (!state.objectMode) {\n    if (typeof chunk === 'string') {\n      if (state.decodeStrings !== false) {\n        chunk = Buffer.from(chunk, encoding)\n        encoding = 'buffer'\n      }\n    } else if (chunk instanceof Buffer) {\n      encoding = 'buffer'\n    } else if (Stream._isUint8Array(chunk)) {\n      chunk = Stream._uint8ArrayToBuffer(chunk)\n      encoding = 'buffer'\n    } else {\n      throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk)\n    }\n  }\n  let err\n  if (state.ending) {\n    err = new ERR_STREAM_WRITE_AFTER_END()\n  } else if (state.destroyed) {\n    err = new ERR_STREAM_DESTROYED('write')\n  }\n  if (err) {\n    process.nextTick(cb, err)\n    errorOrDestroy(stream, err, true)\n    return err\n  }\n  state.pendingcb++\n  return writeOrBuffer(stream, state, chunk, encoding, cb)\n}\nWritable.prototype.write = function (chunk, encoding, cb) {\n  return _write(this, chunk, encoding, cb) === true\n}\nWritable.prototype.cork = function () {\n  this._writableState.corked++\n}\nWritable.prototype.uncork = function () {\n  const state = this._writableState\n  if (state.corked) {\n    state.corked--\n    if (!state.writing) clearBuffer(this, state)\n  }\n}\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n  // node::ParseEncoding() requires lower case.\n  if (typeof encoding === 'string') encoding = StringPrototypeToLowerCase(encoding)\n  if (!Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding)\n  this._writableState.defaultEncoding = encoding\n  return this\n}\n\n// If we're already writing something, then just put this\n// in the queue, and wait our turn.  Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, chunk, encoding, callback) {\n  const len = state.objectMode ? 1 : chunk.length\n  state.length += len\n\n  // stream._write resets state.length\n  const ret = state.length < state.highWaterMark\n  // We must ensure that previous needDrain will not be reset to false.\n  if (!ret) state.needDrain = true\n  if (state.writing || state.corked || state.errored || !state.constructed) {\n    state.buffered.push({\n      chunk,\n      encoding,\n      callback\n    })\n    if (state.allBuffers && encoding !== 'buffer') {\n      state.allBuffers = false\n    }\n    if (state.allNoop && callback !== nop) {\n      state.allNoop = false\n    }\n  } else {\n    state.writelen = len\n    state.writecb = callback\n    state.writing = true\n    state.sync = true\n    stream._write(chunk, encoding, state.onwrite)\n    state.sync = false\n  }\n\n  // Return false if errored or destroyed in order to break\n  // any synchronous while(stream.write(data)) loops.\n  return ret && !state.errored && !state.destroyed\n}\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n  state.writelen = len\n  state.writecb = cb\n  state.writing = true\n  state.sync = true\n  if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'))\n  else if (writev) stream._writev(chunk, state.onwrite)\n  else stream._write(chunk, encoding, state.onwrite)\n  state.sync = false\n}\nfunction onwriteError(stream, state, er, cb) {\n  --state.pendingcb\n  cb(er)\n  // Ensure callbacks are invoked even when autoDestroy is\n  // not enabled. Passing `er` here doesn't make sense since\n  // it's related to one specific write, not to the buffered\n  // writes.\n  errorBuffer(state)\n  // This can emit error, but error must always follow cb.\n  errorOrDestroy(stream, er)\n}\nfunction onwrite(stream, er) {\n  const state = stream._writableState\n  const sync = state.sync\n  const cb = state.writecb\n  if (typeof cb !== 'function') {\n    errorOrDestroy(stream, new ERR_MULTIPLE_CALLBACK())\n    return\n  }\n  state.writing = false\n  state.writecb = null\n  state.length -= state.writelen\n  state.writelen = 0\n  if (er) {\n    // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364\n    er.stack // eslint-disable-line no-unused-expressions\n\n    if (!state.errored) {\n      state.errored = er\n    }\n\n    // In case of duplex streams we need to notify the readable side of the\n    // error.\n    if (stream._readableState && !stream._readableState.errored) {\n      stream._readableState.errored = er\n    }\n    if (sync) {\n      process.nextTick(onwriteError, stream, state, er, cb)\n    } else {\n      onwriteError(stream, state, er, cb)\n    }\n  } else {\n    if (state.buffered.length > state.bufferedIndex) {\n      clearBuffer(stream, state)\n    }\n    if (sync) {\n      // It is a common case that the callback passed to .write() is always\n      // the same. In that case, we do not schedule a new nextTick(), but\n      // rather just increase a counter, to improve performance and avoid\n      // memory allocations.\n      if (state.afterWriteTickInfo !== null && state.afterWriteTickInfo.cb === cb) {\n        state.afterWriteTickInfo.count++\n      } else {\n        state.afterWriteTickInfo = {\n          count: 1,\n          cb,\n          stream,\n          state\n        }\n        process.nextTick(afterWriteTick, state.afterWriteTickInfo)\n      }\n    } else {\n      afterWrite(stream, state, 1, cb)\n    }\n  }\n}\nfunction afterWriteTick({ stream, state, count, cb }) {\n  state.afterWriteTickInfo = null\n  return afterWrite(stream, state, count, cb)\n}\nfunction afterWrite(stream, state, count, cb) {\n  const needDrain = !state.ending && !stream.destroyed && state.length === 0 && state.needDrain\n  if (needDrain) {\n    state.needDrain = false\n    stream.emit('drain')\n  }\n  while (count-- > 0) {\n    state.pendingcb--\n    cb()\n  }\n  if (state.destroyed) {\n    errorBuffer(state)\n  }\n  finishMaybe(stream, state)\n}\n\n// If there's something in the buffer waiting, then invoke callbacks.\nfunction errorBuffer(state) {\n  if (state.writing) {\n    return\n  }\n  for (let n = state.bufferedIndex; n < state.buffered.length; ++n) {\n    var _state$errored\n    const { chunk, callback } = state.buffered[n]\n    const len = state.objectMode ? 1 : chunk.length\n    state.length -= len\n    callback(\n      (_state$errored = state.errored) !== null && _state$errored !== undefined\n        ? _state$errored\n        : new ERR_STREAM_DESTROYED('write')\n    )\n  }\n  const onfinishCallbacks = state[kOnFinished].splice(0)\n  for (let i = 0; i < onfinishCallbacks.length; i++) {\n    var _state$errored2\n    onfinishCallbacks[i](\n      (_state$errored2 = state.errored) !== null && _state$errored2 !== undefined\n        ? _state$errored2\n        : new ERR_STREAM_DESTROYED('end')\n    )\n  }\n  resetBuffer(state)\n}\n\n// If there's something in the buffer waiting, then process it.\nfunction clearBuffer(stream, state) {\n  if (state.corked || state.bufferProcessing || state.destroyed || !state.constructed) {\n    return\n  }\n  const { buffered, bufferedIndex, objectMode } = state\n  const bufferedLength = buffered.length - bufferedIndex\n  if (!bufferedLength) {\n    return\n  }\n  let i = bufferedIndex\n  state.bufferProcessing = true\n  if (bufferedLength > 1 && stream._writev) {\n    state.pendingcb -= bufferedLength - 1\n    const callback = state.allNoop\n      ? nop\n      : (err) => {\n          for (let n = i; n < buffered.length; ++n) {\n            buffered[n].callback(err)\n          }\n        }\n    // Make a copy of `buffered` if it's going to be used by `callback` above,\n    // since `doWrite` will mutate the array.\n    const chunks = state.allNoop && i === 0 ? buffered : ArrayPrototypeSlice(buffered, i)\n    chunks.allBuffers = state.allBuffers\n    doWrite(stream, state, true, state.length, chunks, '', callback)\n    resetBuffer(state)\n  } else {\n    do {\n      const { chunk, encoding, callback } = buffered[i]\n      buffered[i++] = null\n      const len = objectMode ? 1 : chunk.length\n      doWrite(stream, state, false, len, chunk, encoding, callback)\n    } while (i < buffered.length && !state.writing)\n    if (i === buffered.length) {\n      resetBuffer(state)\n    } else if (i > 256) {\n      buffered.splice(0, i)\n      state.bufferedIndex = 0\n    } else {\n      state.bufferedIndex = i\n    }\n  }\n  state.bufferProcessing = false\n}\nWritable.prototype._write = function (chunk, encoding, cb) {\n  if (this._writev) {\n    this._writev(\n      [\n        {\n          chunk,\n          encoding\n        }\n      ],\n      cb\n    )\n  } else {\n    throw new ERR_METHOD_NOT_IMPLEMENTED('_write()')\n  }\n}\nWritable.prototype._writev = null\nWritable.prototype.end = function (chunk, encoding, cb) {\n  const state = this._writableState\n  if (typeof chunk === 'function') {\n    cb = chunk\n    chunk = null\n    encoding = null\n  } else if (typeof encoding === 'function') {\n    cb = encoding\n    encoding = null\n  }\n  let err\n  if (chunk !== null && chunk !== undefined) {\n    const ret = _write(this, chunk, encoding)\n    if (ret instanceof Error) {\n      err = ret\n    }\n  }\n\n  // .end() fully uncorks.\n  if (state.corked) {\n    state.corked = 1\n    this.uncork()\n  }\n  if (err) {\n    // Do nothing...\n  } else if (!state.errored && !state.ending) {\n    // This is forgiving in terms of unnecessary calls to end() and can hide\n    // logic errors. However, usually such errors are harmless and causing a\n    // hard error can be disproportionately destructive. It is not always\n    // trivial for the user to determine whether end() needs to be called\n    // or not.\n\n    state.ending = true\n    finishMaybe(this, state, true)\n    state.ended = true\n  } else if (state.finished) {\n    err = new ERR_STREAM_ALREADY_FINISHED('end')\n  } else if (state.destroyed) {\n    err = new ERR_STREAM_DESTROYED('end')\n  }\n  if (typeof cb === 'function') {\n    if (err || state.finished) {\n      process.nextTick(cb, err)\n    } else {\n      state[kOnFinished].push(cb)\n    }\n  }\n  return this\n}\nfunction needFinish(state) {\n  return (\n    state.ending &&\n    !state.destroyed &&\n    state.constructed &&\n    state.length === 0 &&\n    !state.errored &&\n    state.buffered.length === 0 &&\n    !state.finished &&\n    !state.writing &&\n    !state.errorEmitted &&\n    !state.closeEmitted\n  )\n}\nfunction callFinal(stream, state) {\n  let called = false\n  function onFinish(err) {\n    if (called) {\n      errorOrDestroy(stream, err !== null && err !== undefined ? err : ERR_MULTIPLE_CALLBACK())\n      return\n    }\n    called = true\n    state.pendingcb--\n    if (err) {\n      const onfinishCallbacks = state[kOnFinished].splice(0)\n      for (let i = 0; i < onfinishCallbacks.length; i++) {\n        onfinishCallbacks[i](err)\n      }\n      errorOrDestroy(stream, err, state.sync)\n    } else if (needFinish(state)) {\n      state.prefinished = true\n      stream.emit('prefinish')\n      // Backwards compat. Don't check state.sync here.\n      // Some streams assume 'finish' will be emitted\n      // asynchronously relative to _final callback.\n      state.pendingcb++\n      process.nextTick(finish, stream, state)\n    }\n  }\n  state.sync = true\n  state.pendingcb++\n  try {\n    stream._final(onFinish)\n  } catch (err) {\n    onFinish(err)\n  }\n  state.sync = false\n}\nfunction prefinish(stream, state) {\n  if (!state.prefinished && !state.finalCalled) {\n    if (typeof stream._final === 'function' && !state.destroyed) {\n      state.finalCalled = true\n      callFinal(stream, state)\n    } else {\n      state.prefinished = true\n      stream.emit('prefinish')\n    }\n  }\n}\nfunction finishMaybe(stream, state, sync) {\n  if (needFinish(state)) {\n    prefinish(stream, state)\n    if (state.pendingcb === 0) {\n      if (sync) {\n        state.pendingcb++\n        process.nextTick(\n          (stream, state) => {\n            if (needFinish(state)) {\n              finish(stream, state)\n            } else {\n              state.pendingcb--\n            }\n          },\n          stream,\n          state\n        )\n      } else if (needFinish(state)) {\n        state.pendingcb++\n        finish(stream, state)\n      }\n    }\n  }\n}\nfunction finish(stream, state) {\n  state.pendingcb--\n  state.finished = true\n  const onfinishCallbacks = state[kOnFinished].splice(0)\n  for (let i = 0; i < onfinishCallbacks.length; i++) {\n    onfinishCallbacks[i]()\n  }\n  stream.emit('finish')\n  if (state.autoDestroy) {\n    // In case of duplex streams we need a way to detect\n    // if the readable side is ready for autoDestroy as well.\n    const rState = stream._readableState\n    const autoDestroy =\n      !rState ||\n      (rState.autoDestroy &&\n        // We don't expect the readable to ever 'end'\n        // if readable is explicitly set to false.\n        (rState.endEmitted || rState.readable === false))\n    if (autoDestroy) {\n      stream.destroy()\n    }\n  }\n}\nObjectDefineProperties(Writable.prototype, {\n  closed: {\n    __proto__: null,\n    get() {\n      return this._writableState ? this._writableState.closed : false\n    }\n  },\n  destroyed: {\n    __proto__: null,\n    get() {\n      return this._writableState ? this._writableState.destroyed : false\n    },\n    set(value) {\n      // Backward compatibility, the user is explicitly managing destroyed.\n      if (this._writableState) {\n        this._writableState.destroyed = value\n      }\n    }\n  },\n  writable: {\n    __proto__: null,\n    get() {\n      const w = this._writableState\n      // w.writable === false means that this is part of a Duplex stream\n      // where the writable side was disabled upon construction.\n      // Compat. The user might manually disable writable side through\n      // deprecated setter.\n      return !!w && w.writable !== false && !w.destroyed && !w.errored && !w.ending && !w.ended\n    },\n    set(val) {\n      // Backwards compatible.\n      if (this._writableState) {\n        this._writableState.writable = !!val\n      }\n    }\n  },\n  writableFinished: {\n    __proto__: null,\n    get() {\n      return this._writableState ? this._writableState.finished : false\n    }\n  },\n  writableObjectMode: {\n    __proto__: null,\n    get() {\n      return this._writableState ? this._writableState.objectMode : false\n    }\n  },\n  writableBuffer: {\n    __proto__: null,\n    get() {\n      return this._writableState && this._writableState.getBuffer()\n    }\n  },\n  writableEnded: {\n    __proto__: null,\n    get() {\n      return this._writableState ? this._writableState.ending : false\n    }\n  },\n  writableNeedDrain: {\n    __proto__: null,\n    get() {\n      const wState = this._writableState\n      if (!wState) return false\n      return !wState.destroyed && !wState.ending && wState.needDrain\n    }\n  },\n  writableHighWaterMark: {\n    __proto__: null,\n    get() {\n      return this._writableState && this._writableState.highWaterMark\n    }\n  },\n  writableCorked: {\n    __proto__: null,\n    get() {\n      return this._writableState ? this._writableState.corked : 0\n    }\n  },\n  writableLength: {\n    __proto__: null,\n    get() {\n      return this._writableState && this._writableState.length\n    }\n  },\n  errored: {\n    __proto__: null,\n    enumerable: false,\n    get() {\n      return this._writableState ? this._writableState.errored : null\n    }\n  },\n  writableAborted: {\n    __proto__: null,\n    enumerable: false,\n    get: function () {\n      return !!(\n        this._writableState.writable !== false &&\n        (this._writableState.destroyed || this._writableState.errored) &&\n        !this._writableState.finished\n      )\n    }\n  }\n})\nconst destroy = destroyImpl.destroy\nWritable.prototype.destroy = function (err, cb) {\n  const state = this._writableState\n\n  // Invoke pending callbacks.\n  if (!state.destroyed && (state.bufferedIndex < state.buffered.length || state[kOnFinished].length)) {\n    process.nextTick(errorBuffer, state)\n  }\n  destroy.call(this, err, cb)\n  return this\n}\nWritable.prototype._undestroy = destroyImpl.undestroy\nWritable.prototype._destroy = function (err, cb) {\n  cb(err)\n}\nWritable.prototype[EE.captureRejectionSymbol] = function (err) {\n  this.destroy(err)\n}\nlet webStreamsAdapters\n\n// Lazy to avoid circular references\nfunction lazyWebStreams() {\n  if (webStreamsAdapters === undefined) webStreamsAdapters = {}\n  return webStreamsAdapters\n}\nWritable.fromWeb = function (writableStream, options) {\n  return lazyWebStreams().newStreamWritableFromWritableStream(writableStream, options)\n}\nWritable.toWeb = function (streamWritable) {\n  return lazyWebStreams().newWritableStreamFromStreamWritable(streamWritable)\n}\n","/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n\n;('use strict')\nconst bufferModule = require('buffer')\nconst {\n  isReadable,\n  isWritable,\n  isIterable,\n  isNodeStream,\n  isReadableNodeStream,\n  isWritableNodeStream,\n  isDuplexNodeStream,\n  isReadableStream,\n  isWritableStream\n} = require('./utils')\nconst eos = require('./end-of-stream')\nconst {\n  AbortError,\n  codes: { ERR_INVALID_ARG_TYPE, ERR_INVALID_RETURN_VALUE }\n} = require('../../ours/errors')\nconst { destroyer } = require('./destroy')\nconst Duplex = require('./duplex')\nconst Readable = require('./readable')\nconst Writable = require('./writable')\nconst { createDeferredPromise } = require('../../ours/util')\nconst from = require('./from')\nconst Blob = globalThis.Blob || bufferModule.Blob\nconst isBlob =\n  typeof Blob !== 'undefined'\n    ? function isBlob(b) {\n        return b instanceof Blob\n      }\n    : function isBlob(b) {\n        return false\n      }\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nconst { FunctionPrototypeCall } = require('../../ours/primordials')\n\n// This is needed for pre node 17.\nclass Duplexify extends Duplex {\n  constructor(options) {\n    super(options)\n\n    // https://github.com/nodejs/node/pull/34385\n\n    if ((options === null || options === undefined ? undefined : options.readable) === false) {\n      this._readableState.readable = false\n      this._readableState.ended = true\n      this._readableState.endEmitted = true\n    }\n    if ((options === null || options === undefined ? undefined : options.writable) === false) {\n      this._writableState.writable = false\n      this._writableState.ending = true\n      this._writableState.ended = true\n      this._writableState.finished = true\n    }\n  }\n}\nmodule.exports = function duplexify(body, name) {\n  if (isDuplexNodeStream(body)) {\n    return body\n  }\n  if (isReadableNodeStream(body)) {\n    return _duplexify({\n      readable: body\n    })\n  }\n  if (isWritableNodeStream(body)) {\n    return _duplexify({\n      writable: body\n    })\n  }\n  if (isNodeStream(body)) {\n    return _duplexify({\n      writable: false,\n      readable: false\n    })\n  }\n  if (isReadableStream(body)) {\n    return _duplexify({\n      readable: Readable.fromWeb(body)\n    })\n  }\n  if (isWritableStream(body)) {\n    return _duplexify({\n      writable: Writable.fromWeb(body)\n    })\n  }\n  if (typeof body === 'function') {\n    const { value, write, final, destroy } = fromAsyncGen(body)\n    if (isIterable(value)) {\n      return from(Duplexify, value, {\n        // TODO (ronag): highWaterMark?\n        objectMode: true,\n        write,\n        final,\n        destroy\n      })\n    }\n    const then = value === null || value === undefined ? undefined : value.then\n    if (typeof then === 'function') {\n      let d\n      const promise = FunctionPrototypeCall(\n        then,\n        value,\n        (val) => {\n          if (val != null) {\n            throw new ERR_INVALID_RETURN_VALUE('nully', 'body', val)\n          }\n        },\n        (err) => {\n          destroyer(d, err)\n        }\n      )\n      return (d = new Duplexify({\n        // TODO (ronag): highWaterMark?\n        objectMode: true,\n        readable: false,\n        write,\n        final(cb) {\n          final(async () => {\n            try {\n              await promise\n              process.nextTick(cb, null)\n            } catch (err) {\n              process.nextTick(cb, err)\n            }\n          })\n        },\n        destroy\n      }))\n    }\n    throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or AsyncFunction', name, value)\n  }\n  if (isBlob(body)) {\n    return duplexify(body.arrayBuffer())\n  }\n  if (isIterable(body)) {\n    return from(Duplexify, body, {\n      // TODO (ronag): highWaterMark?\n      objectMode: true,\n      writable: false\n    })\n  }\n  if (\n    isReadableStream(body === null || body === undefined ? undefined : body.readable) &&\n    isWritableStream(body === null || body === undefined ? undefined : body.writable)\n  ) {\n    return Duplexify.fromWeb(body)\n  }\n  if (\n    typeof (body === null || body === undefined ? undefined : body.writable) === 'object' ||\n    typeof (body === null || body === undefined ? undefined : body.readable) === 'object'\n  ) {\n    const readable =\n      body !== null && body !== undefined && body.readable\n        ? isReadableNodeStream(body === null || body === undefined ? undefined : body.readable)\n          ? body === null || body === undefined\n            ? undefined\n            : body.readable\n          : duplexify(body.readable)\n        : undefined\n    const writable =\n      body !== null && body !== undefined && body.writable\n        ? isWritableNodeStream(body === null || body === undefined ? undefined : body.writable)\n          ? body === null || body === undefined\n            ? undefined\n            : body.writable\n          : duplexify(body.writable)\n        : undefined\n    return _duplexify({\n      readable,\n      writable\n    })\n  }\n  const then = body === null || body === undefined ? undefined : body.then\n  if (typeof then === 'function') {\n    let d\n    FunctionPrototypeCall(\n      then,\n      body,\n      (val) => {\n        if (val != null) {\n          d.push(val)\n        }\n        d.push(null)\n      },\n      (err) => {\n        destroyer(d, err)\n      }\n    )\n    return (d = new Duplexify({\n      objectMode: true,\n      writable: false,\n      read() {}\n    }))\n  }\n  throw new ERR_INVALID_ARG_TYPE(\n    name,\n    [\n      'Blob',\n      'ReadableStream',\n      'WritableStream',\n      'Stream',\n      'Iterable',\n      'AsyncIterable',\n      'Function',\n      '{ readable, writable } pair',\n      'Promise'\n    ],\n    body\n  )\n}\nfunction fromAsyncGen(fn) {\n  let { promise, resolve } = createDeferredPromise()\n  const ac = new AbortController()\n  const signal = ac.signal\n  const value = fn(\n    (async function* () {\n      while (true) {\n        const _promise = promise\n        promise = null\n        const { chunk, done, cb } = await _promise\n        process.nextTick(cb)\n        if (done) return\n        if (signal.aborted)\n          throw new AbortError(undefined, {\n            cause: signal.reason\n          })\n        ;({ promise, resolve } = createDeferredPromise())\n        yield chunk\n      }\n    })(),\n    {\n      signal\n    }\n  )\n  return {\n    value,\n    write(chunk, encoding, cb) {\n      const _resolve = resolve\n      resolve = null\n      _resolve({\n        chunk,\n        done: false,\n        cb\n      })\n    },\n    final(cb) {\n      const _resolve = resolve\n      resolve = null\n      _resolve({\n        done: true,\n        cb\n      })\n    },\n    destroy(err, cb) {\n      ac.abort()\n      cb(err)\n    }\n  }\n}\nfunction _duplexify(pair) {\n  const r = pair.readable && typeof pair.readable.read !== 'function' ? Readable.wrap(pair.readable) : pair.readable\n  const w = pair.writable\n  let readable = !!isReadable(r)\n  let writable = !!isWritable(w)\n  let ondrain\n  let onfinish\n  let onreadable\n  let onclose\n  let d\n  function onfinished(err) {\n    const cb = onclose\n    onclose = null\n    if (cb) {\n      cb(err)\n    } else if (err) {\n      d.destroy(err)\n    }\n  }\n\n  // TODO(ronag): Avoid double buffering.\n  // Implement Writable/Readable/Duplex traits.\n  // See, https://github.com/nodejs/node/pull/33515.\n  d = new Duplexify({\n    // TODO (ronag): highWaterMark?\n    readableObjectMode: !!(r !== null && r !== undefined && r.readableObjectMode),\n    writableObjectMode: !!(w !== null && w !== undefined && w.writableObjectMode),\n    readable,\n    writable\n  })\n  if (writable) {\n    eos(w, (err) => {\n      writable = false\n      if (err) {\n        destroyer(r, err)\n      }\n      onfinished(err)\n    })\n    d._write = function (chunk, encoding, callback) {\n      if (w.write(chunk, encoding)) {\n        callback()\n      } else {\n        ondrain = callback\n      }\n    }\n    d._final = function (callback) {\n      w.end()\n      onfinish = callback\n    }\n    w.on('drain', function () {\n      if (ondrain) {\n        const cb = ondrain\n        ondrain = null\n        cb()\n      }\n    })\n    w.on('finish', function () {\n      if (onfinish) {\n        const cb = onfinish\n        onfinish = null\n        cb()\n      }\n    })\n  }\n  if (readable) {\n    eos(r, (err) => {\n      readable = false\n      if (err) {\n        destroyer(r, err)\n      }\n      onfinished(err)\n    })\n    r.on('readable', function () {\n      if (onreadable) {\n        const cb = onreadable\n        onreadable = null\n        cb()\n      }\n    })\n    r.on('end', function () {\n      d.push(null)\n    })\n    d._read = function () {\n      while (true) {\n        const buf = r.read()\n        if (buf === null) {\n          onreadable = d._read\n          return\n        }\n        if (!d.push(buf)) {\n          return\n        }\n      }\n    }\n  }\n  d._destroy = function (err, callback) {\n    if (!err && onclose !== null) {\n      err = new AbortError()\n    }\n    onreadable = null\n    ondrain = null\n    onfinish = null\n    if (onclose === null) {\n      callback(err)\n    } else {\n      onclose = callback\n      destroyer(w, err)\n      destroyer(r, err)\n    }\n  }\n  return d\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototype inheritance, this class\n// prototypically inherits from Readable, and then parasitically from\n// Writable.\n\n'use strict'\n\nconst {\n  ObjectDefineProperties,\n  ObjectGetOwnPropertyDescriptor,\n  ObjectKeys,\n  ObjectSetPrototypeOf\n} = require('../../ours/primordials')\nmodule.exports = Duplex\nconst Readable = require('./readable')\nconst Writable = require('./writable')\nObjectSetPrototypeOf(Duplex.prototype, Readable.prototype)\nObjectSetPrototypeOf(Duplex, Readable)\n{\n  const keys = ObjectKeys(Writable.prototype)\n  // Allow the keys array to be GC'ed.\n  for (let i = 0; i < keys.length; i++) {\n    const method = keys[i]\n    if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]\n  }\n}\nfunction Duplex(options) {\n  if (!(this instanceof Duplex)) return new Duplex(options)\n  Readable.call(this, options)\n  Writable.call(this, options)\n  if (options) {\n    this.allowHalfOpen = options.allowHalfOpen !== false\n    if (options.readable === false) {\n      this._readableState.readable = false\n      this._readableState.ended = true\n      this._readableState.endEmitted = true\n    }\n    if (options.writable === false) {\n      this._writableState.writable = false\n      this._writableState.ending = true\n      this._writableState.ended = true\n      this._writableState.finished = true\n    }\n  } else {\n    this.allowHalfOpen = true\n  }\n}\nObjectDefineProperties(Duplex.prototype, {\n  writable: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writable')\n  },\n  writableHighWaterMark: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableHighWaterMark')\n  },\n  writableObjectMode: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableObjectMode')\n  },\n  writableBuffer: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableBuffer')\n  },\n  writableLength: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableLength')\n  },\n  writableFinished: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableFinished')\n  },\n  writableCorked: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableCorked')\n  },\n  writableEnded: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableEnded')\n  },\n  writableNeedDrain: {\n    __proto__: null,\n    ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableNeedDrain')\n  },\n  destroyed: {\n    __proto__: null,\n    get() {\n      if (this._readableState === undefined || this._writableState === undefined) {\n        return false\n      }\n      return this._readableState.destroyed && this._writableState.destroyed\n    },\n    set(value) {\n      // Backward compatibility, the user is explicitly\n      // managing destroyed.\n      if (this._readableState && this._writableState) {\n        this._readableState.destroyed = value\n        this._writableState.destroyed = value\n      }\n    }\n  }\n})\nlet webStreamsAdapters\n\n// Lazy to avoid circular references\nfunction lazyWebStreams() {\n  if (webStreamsAdapters === undefined) webStreamsAdapters = {}\n  return webStreamsAdapters\n}\nDuplex.fromWeb = function (pair, options) {\n  return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair, options)\n}\nDuplex.toWeb = function (duplex) {\n  return lazyWebStreams().newReadableWritablePairFromDuplex(duplex)\n}\nlet duplexify\nDuplex.from = function (body) {\n  if (!duplexify) {\n    duplexify = require('./duplexify')\n  }\n  return duplexify(body, 'body')\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data.  Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored.  (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation.  For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes.  When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up.  When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer.  When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks.  If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk.  However,\n// a pathological inflate type of transform can cause excessive buffering\n// here.  For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output.  Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output.  In this case, you could write a very small\n// amount of input, and end up with a very large amount of output.  In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform.  A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n'use strict'\n\nconst { ObjectSetPrototypeOf, Symbol } = require('../../ours/primordials')\nmodule.exports = Transform\nconst { ERR_METHOD_NOT_IMPLEMENTED } = require('../../ours/errors').codes\nconst Duplex = require('./duplex')\nconst { getHighWaterMark } = require('./state')\nObjectSetPrototypeOf(Transform.prototype, Duplex.prototype)\nObjectSetPrototypeOf(Transform, Duplex)\nconst kCallback = Symbol('kCallback')\nfunction Transform(options) {\n  if (!(this instanceof Transform)) return new Transform(options)\n\n  // TODO (ronag): This should preferably always be\n  // applied but would be semver-major. Or even better;\n  // make Transform a Readable with the Writable interface.\n  const readableHighWaterMark = options ? getHighWaterMark(this, options, 'readableHighWaterMark', true) : null\n  if (readableHighWaterMark === 0) {\n    // A Duplex will buffer both on the writable and readable side while\n    // a Transform just wants to buffer hwm number of elements. To avoid\n    // buffering twice we disable buffering on the writable side.\n    options = {\n      ...options,\n      highWaterMark: null,\n      readableHighWaterMark,\n      // TODO (ronag): 0 is not optimal since we have\n      // a \"bug\" where we check needDrain before calling _write and not after.\n      // Refs: https://github.com/nodejs/node/pull/32887\n      // Refs: https://github.com/nodejs/node/pull/35941\n      writableHighWaterMark: options.writableHighWaterMark || 0\n    }\n  }\n  Duplex.call(this, options)\n\n  // We have implemented the _read method, and done the other things\n  // that Readable wants before the first _read call, so unset the\n  // sync guard flag.\n  this._readableState.sync = false\n  this[kCallback] = null\n  if (options) {\n    if (typeof options.transform === 'function') this._transform = options.transform\n    if (typeof options.flush === 'function') this._flush = options.flush\n  }\n\n  // When the writable side finishes, then flush out anything remaining.\n  // Backwards compat. Some Transform streams incorrectly implement _final\n  // instead of or in addition to _flush. By using 'prefinish' instead of\n  // implementing _final we continue supporting this unfortunate use case.\n  this.on('prefinish', prefinish)\n}\nfunction final(cb) {\n  if (typeof this._flush === 'function' && !this.destroyed) {\n    this._flush((er, data) => {\n      if (er) {\n        if (cb) {\n          cb(er)\n        } else {\n          this.destroy(er)\n        }\n        return\n      }\n      if (data != null) {\n        this.push(data)\n      }\n      this.push(null)\n      if (cb) {\n        cb()\n      }\n    })\n  } else {\n    this.push(null)\n    if (cb) {\n      cb()\n    }\n  }\n}\nfunction prefinish() {\n  if (this._final !== final) {\n    final.call(this)\n  }\n}\nTransform.prototype._final = final\nTransform.prototype._transform = function (chunk, encoding, callback) {\n  throw new ERR_METHOD_NOT_IMPLEMENTED('_transform()')\n}\nTransform.prototype._write = function (chunk, encoding, callback) {\n  const rState = this._readableState\n  const wState = this._writableState\n  const length = rState.length\n  this._transform(chunk, encoding, (err, val) => {\n    if (err) {\n      callback(err)\n      return\n    }\n    if (val != null) {\n      this.push(val)\n    }\n    if (\n      wState.ended ||\n      // Backwards compat.\n      length === rState.length ||\n      // Backwards compat.\n      rState.length < rState.highWaterMark\n    ) {\n      callback()\n    } else {\n      this[kCallback] = callback\n    }\n  })\n}\nTransform.prototype._read = function () {\n  if (this[kCallback]) {\n    const callback = this[kCallback]\n    this[kCallback] = null\n    callback()\n  }\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n'use strict'\n\nconst { ObjectSetPrototypeOf } = require('../../ours/primordials')\nmodule.exports = PassThrough\nconst Transform = require('./transform')\nObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype)\nObjectSetPrototypeOf(PassThrough, Transform)\nfunction PassThrough(options) {\n  if (!(this instanceof PassThrough)) return new PassThrough(options)\n  Transform.call(this, options)\n}\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n  cb(null, chunk)\n}\n","/* replacement start */\n\nconst process = require('process/')\n\n/* replacement end */\n// Ported from https://github.com/mafintosh/pump with\n// permission from the author, Mathias Buus (@mafintosh).\n\n;('use strict')\nconst { ArrayIsArray, Promise, SymbolAsyncIterator, SymbolDispose } = require('../../ours/primordials')\nconst eos = require('./end-of-stream')\nconst { once } = require('../../ours/util')\nconst destroyImpl = require('./destroy')\nconst Duplex = require('./duplex')\nconst {\n  aggregateTwoErrors,\n  codes: {\n    ERR_INVALID_ARG_TYPE,\n    ERR_INVALID_RETURN_VALUE,\n    ERR_MISSING_ARGS,\n    ERR_STREAM_DESTROYED,\n    ERR_STREAM_PREMATURE_CLOSE\n  },\n  AbortError\n} = require('../../ours/errors')\nconst { validateFunction, validateAbortSignal } = require('../validators')\nconst {\n  isIterable,\n  isReadable,\n  isReadableNodeStream,\n  isNodeStream,\n  isTransformStream,\n  isWebStream,\n  isReadableStream,\n  isReadableFinished\n} = require('./utils')\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nlet PassThrough\nlet Readable\nlet addAbortListener\nfunction destroyer(stream, reading, writing) {\n  let finished = false\n  stream.on('close', () => {\n    finished = true\n  })\n  const cleanup = eos(\n    stream,\n    {\n      readable: reading,\n      writable: writing\n    },\n    (err) => {\n      finished = !err\n    }\n  )\n  return {\n    destroy: (err) => {\n      if (finished) return\n      finished = true\n      destroyImpl.destroyer(stream, err || new ERR_STREAM_DESTROYED('pipe'))\n    },\n    cleanup\n  }\n}\nfunction popCallback(streams) {\n  // Streams should never be an empty array. It should always contain at least\n  // a single stream. Therefore optimize for the average case instead of\n  // checking for length === 0 as well.\n  validateFunction(streams[streams.length - 1], 'streams[stream.length - 1]')\n  return streams.pop()\n}\nfunction makeAsyncIterable(val) {\n  if (isIterable(val)) {\n    return val\n  } else if (isReadableNodeStream(val)) {\n    // Legacy streams are not Iterable.\n    return fromReadable(val)\n  }\n  throw new ERR_INVALID_ARG_TYPE('val', ['Readable', 'Iterable', 'AsyncIterable'], val)\n}\nasync function* fromReadable(val) {\n  if (!Readable) {\n    Readable = require('./readable')\n  }\n  yield* Readable.prototype[SymbolAsyncIterator].call(val)\n}\nasync function pumpToNode(iterable, writable, finish, { end }) {\n  let error\n  let onresolve = null\n  const resume = (err) => {\n    if (err) {\n      error = err\n    }\n    if (onresolve) {\n      const callback = onresolve\n      onresolve = null\n      callback()\n    }\n  }\n  const wait = () =>\n    new Promise((resolve, reject) => {\n      if (error) {\n        reject(error)\n      } else {\n        onresolve = () => {\n          if (error) {\n            reject(error)\n          } else {\n            resolve()\n          }\n        }\n      }\n    })\n  writable.on('drain', resume)\n  const cleanup = eos(\n    writable,\n    {\n      readable: false\n    },\n    resume\n  )\n  try {\n    if (writable.writableNeedDrain) {\n      await wait()\n    }\n    for await (const chunk of iterable) {\n      if (!writable.write(chunk)) {\n        await wait()\n      }\n    }\n    if (end) {\n      writable.end()\n      await wait()\n    }\n    finish()\n  } catch (err) {\n    finish(error !== err ? aggregateTwoErrors(error, err) : err)\n  } finally {\n    cleanup()\n    writable.off('drain', resume)\n  }\n}\nasync function pumpToWeb(readable, writable, finish, { end }) {\n  if (isTransformStream(writable)) {\n    writable = writable.writable\n  }\n  // https://streams.spec.whatwg.org/#example-manual-write-with-backpressure\n  const writer = writable.getWriter()\n  try {\n    for await (const chunk of readable) {\n      await writer.ready\n      writer.write(chunk).catch(() => {})\n    }\n    await writer.ready\n    if (end) {\n      await writer.close()\n    }\n    finish()\n  } catch (err) {\n    try {\n      await writer.abort(err)\n      finish(err)\n    } catch (err) {\n      finish(err)\n    }\n  }\n}\nfunction pipeline(...streams) {\n  return pipelineImpl(streams, once(popCallback(streams)))\n}\nfunction pipelineImpl(streams, callback, opts) {\n  if (streams.length === 1 && ArrayIsArray(streams[0])) {\n    streams = streams[0]\n  }\n  if (streams.length < 2) {\n    throw new ERR_MISSING_ARGS('streams')\n  }\n  const ac = new AbortController()\n  const signal = ac.signal\n  const outerSignal = opts === null || opts === undefined ? undefined : opts.signal\n\n  // Need to cleanup event listeners if last stream is readable\n  // https://github.com/nodejs/node/issues/35452\n  const lastStreamCleanup = []\n  validateAbortSignal(outerSignal, 'options.signal')\n  function abort() {\n    finishImpl(new AbortError())\n  }\n  addAbortListener = addAbortListener || require('../../ours/util').addAbortListener\n  let disposable\n  if (outerSignal) {\n    disposable = addAbortListener(outerSignal, abort)\n  }\n  let error\n  let value\n  const destroys = []\n  let finishCount = 0\n  function finish(err) {\n    finishImpl(err, --finishCount === 0)\n  }\n  function finishImpl(err, final) {\n    var _disposable\n    if (err && (!error || error.code === 'ERR_STREAM_PREMATURE_CLOSE')) {\n      error = err\n    }\n    if (!error && !final) {\n      return\n    }\n    while (destroys.length) {\n      destroys.shift()(error)\n    }\n    ;(_disposable = disposable) === null || _disposable === undefined ? undefined : _disposable[SymbolDispose]()\n    ac.abort()\n    if (final) {\n      if (!error) {\n        lastStreamCleanup.forEach((fn) => fn())\n      }\n      process.nextTick(callback, error, value)\n    }\n  }\n  let ret\n  for (let i = 0; i < streams.length; i++) {\n    const stream = streams[i]\n    const reading = i < streams.length - 1\n    const writing = i > 0\n    const end = reading || (opts === null || opts === undefined ? undefined : opts.end) !== false\n    const isLastStream = i === streams.length - 1\n    if (isNodeStream(stream)) {\n      if (end) {\n        const { destroy, cleanup } = destroyer(stream, reading, writing)\n        destroys.push(destroy)\n        if (isReadable(stream) && isLastStream) {\n          lastStreamCleanup.push(cleanup)\n        }\n      }\n\n      // Catch stream errors that occur after pipe/pump has completed.\n      function onError(err) {\n        if (err && err.name !== 'AbortError' && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n          finish(err)\n        }\n      }\n      stream.on('error', onError)\n      if (isReadable(stream) && isLastStream) {\n        lastStreamCleanup.push(() => {\n          stream.removeListener('error', onError)\n        })\n      }\n    }\n    if (i === 0) {\n      if (typeof stream === 'function') {\n        ret = stream({\n          signal\n        })\n        if (!isIterable(ret)) {\n          throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or Stream', 'source', ret)\n        }\n      } else if (isIterable(stream) || isReadableNodeStream(stream) || isTransformStream(stream)) {\n        ret = stream\n      } else {\n        ret = Duplex.from(stream)\n      }\n    } else if (typeof stream === 'function') {\n      if (isTransformStream(ret)) {\n        var _ret\n        ret = makeAsyncIterable((_ret = ret) === null || _ret === undefined ? undefined : _ret.readable)\n      } else {\n        ret = makeAsyncIterable(ret)\n      }\n      ret = stream(ret, {\n        signal\n      })\n      if (reading) {\n        if (!isIterable(ret, true)) {\n          throw new ERR_INVALID_RETURN_VALUE('AsyncIterable', `transform[${i - 1}]`, ret)\n        }\n      } else {\n        var _ret2\n        if (!PassThrough) {\n          PassThrough = require('./passthrough')\n        }\n\n        // If the last argument to pipeline is not a stream\n        // we must create a proxy stream so that pipeline(...)\n        // always returns a stream which can be further\n        // composed through `.pipe(stream)`.\n\n        const pt = new PassThrough({\n          objectMode: true\n        })\n\n        // Handle Promises/A+ spec, `then` could be a getter that throws on\n        // second use.\n        const then = (_ret2 = ret) === null || _ret2 === undefined ? undefined : _ret2.then\n        if (typeof then === 'function') {\n          finishCount++\n          then.call(\n            ret,\n            (val) => {\n              value = val\n              if (val != null) {\n                pt.write(val)\n              }\n              if (end) {\n                pt.end()\n              }\n              process.nextTick(finish)\n            },\n            (err) => {\n              pt.destroy(err)\n              process.nextTick(finish, err)\n            }\n          )\n        } else if (isIterable(ret, true)) {\n          finishCount++\n          pumpToNode(ret, pt, finish, {\n            end\n          })\n        } else if (isReadableStream(ret) || isTransformStream(ret)) {\n          const toRead = ret.readable || ret\n          finishCount++\n          pumpToNode(toRead, pt, finish, {\n            end\n          })\n        } else {\n          throw new ERR_INVALID_RETURN_VALUE('AsyncIterable or Promise', 'destination', ret)\n        }\n        ret = pt\n        const { destroy, cleanup } = destroyer(ret, false, true)\n        destroys.push(destroy)\n        if (isLastStream) {\n          lastStreamCleanup.push(cleanup)\n        }\n      }\n    } else if (isNodeStream(stream)) {\n      if (isReadableNodeStream(ret)) {\n        finishCount += 2\n        const cleanup = pipe(ret, stream, finish, {\n          end\n        })\n        if (isReadable(stream) && isLastStream) {\n          lastStreamCleanup.push(cleanup)\n        }\n      } else if (isTransformStream(ret) || isReadableStream(ret)) {\n        const toRead = ret.readable || ret\n        finishCount++\n        pumpToNode(toRead, stream, finish, {\n          end\n        })\n      } else if (isIterable(ret)) {\n        finishCount++\n        pumpToNode(ret, stream, finish, {\n          end\n        })\n      } else {\n        throw new ERR_INVALID_ARG_TYPE(\n          'val',\n          ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'],\n          ret\n        )\n      }\n      ret = stream\n    } else if (isWebStream(stream)) {\n      if (isReadableNodeStream(ret)) {\n        finishCount++\n        pumpToWeb(makeAsyncIterable(ret), stream, finish, {\n          end\n        })\n      } else if (isReadableStream(ret) || isIterable(ret)) {\n        finishCount++\n        pumpToWeb(ret, stream, finish, {\n          end\n        })\n      } else if (isTransformStream(ret)) {\n        finishCount++\n        pumpToWeb(ret.readable, stream, finish, {\n          end\n        })\n      } else {\n        throw new ERR_INVALID_ARG_TYPE(\n          'val',\n          ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'],\n          ret\n        )\n      }\n      ret = stream\n    } else {\n      ret = Duplex.from(stream)\n    }\n  }\n  if (\n    (signal !== null && signal !== undefined && signal.aborted) ||\n    (outerSignal !== null && outerSignal !== undefined && outerSignal.aborted)\n  ) {\n    process.nextTick(abort)\n  }\n  return ret\n}\nfunction pipe(src, dst, finish, { end }) {\n  let ended = false\n  dst.on('close', () => {\n    if (!ended) {\n      // Finish if the destination closes before the source has completed.\n      finish(new ERR_STREAM_PREMATURE_CLOSE())\n    }\n  })\n  src.pipe(dst, {\n    end: false\n  }) // If end is true we already will have a listener to end dst.\n\n  if (end) {\n    // Compat. Before node v10.12.0 stdio used to throw an error so\n    // pipe() did/does not end() stdio destinations.\n    // Now they allow it but \"secretly\" don't close the underlying fd.\n\n    function endFn() {\n      ended = true\n      dst.end()\n    }\n    if (isReadableFinished(src)) {\n      // End the destination if the source has already ended.\n      process.nextTick(endFn)\n    } else {\n      src.once('end', endFn)\n    }\n  } else {\n    finish()\n  }\n  eos(\n    src,\n    {\n      readable: true,\n      writable: false\n    },\n    (err) => {\n      const rState = src._readableState\n      if (\n        err &&\n        err.code === 'ERR_STREAM_PREMATURE_CLOSE' &&\n        rState &&\n        rState.ended &&\n        !rState.errored &&\n        !rState.errorEmitted\n      ) {\n        // Some readable streams will emit 'close' before 'end'. However, since\n        // this is on the readable side 'end' should still be emitted if the\n        // stream has been ended and no error emitted. This should be allowed in\n        // favor of backwards compatibility. Since the stream is piped to a\n        // destination this should not result in any observable difference.\n        // We don't need to check if this is a writable premature close since\n        // eos will only fail with premature close on the reading side for\n        // duplex streams.\n        src.once('end', finish).once('error', finish)\n      } else {\n        finish(err)\n      }\n    }\n  )\n  return eos(\n    dst,\n    {\n      readable: false,\n      writable: true\n    },\n    finish\n  )\n}\nmodule.exports = {\n  pipelineImpl,\n  pipeline\n}\n","'use strict'\n\nconst { pipeline } = require('./pipeline')\nconst Duplex = require('./duplex')\nconst { destroyer } = require('./destroy')\nconst {\n  isNodeStream,\n  isReadable,\n  isWritable,\n  isWebStream,\n  isTransformStream,\n  isWritableStream,\n  isReadableStream\n} = require('./utils')\nconst {\n  AbortError,\n  codes: { ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS }\n} = require('../../ours/errors')\nconst eos = require('./end-of-stream')\nmodule.exports = function compose(...streams) {\n  if (streams.length === 0) {\n    throw new ERR_MISSING_ARGS('streams')\n  }\n  if (streams.length === 1) {\n    return Duplex.from(streams[0])\n  }\n  const orgStreams = [...streams]\n  if (typeof streams[0] === 'function') {\n    streams[0] = Duplex.from(streams[0])\n  }\n  if (typeof streams[streams.length - 1] === 'function') {\n    const idx = streams.length - 1\n    streams[idx] = Duplex.from(streams[idx])\n  }\n  for (let n = 0; n < streams.length; ++n) {\n    if (!isNodeStream(streams[n]) && !isWebStream(streams[n])) {\n      // TODO(ronag): Add checks for non streams.\n      continue\n    }\n    if (\n      n < streams.length - 1 &&\n      !(isReadable(streams[n]) || isReadableStream(streams[n]) || isTransformStream(streams[n]))\n    ) {\n      throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be readable')\n    }\n    if (n > 0 && !(isWritable(streams[n]) || isWritableStream(streams[n]) || isTransformStream(streams[n]))) {\n      throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be writable')\n    }\n  }\n  let ondrain\n  let onfinish\n  let onreadable\n  let onclose\n  let d\n  function onfinished(err) {\n    const cb = onclose\n    onclose = null\n    if (cb) {\n      cb(err)\n    } else if (err) {\n      d.destroy(err)\n    } else if (!readable && !writable) {\n      d.destroy()\n    }\n  }\n  const head = streams[0]\n  const tail = pipeline(streams, onfinished)\n  const writable = !!(isWritable(head) || isWritableStream(head) || isTransformStream(head))\n  const readable = !!(isReadable(tail) || isReadableStream(tail) || isTransformStream(tail))\n\n  // TODO(ronag): Avoid double buffering.\n  // Implement Writable/Readable/Duplex traits.\n  // See, https://github.com/nodejs/node/pull/33515.\n  d = new Duplex({\n    // TODO (ronag): highWaterMark?\n    writableObjectMode: !!(head !== null && head !== undefined && head.writableObjectMode),\n    readableObjectMode: !!(tail !== null && tail !== undefined && tail.readableObjectMode),\n    writable,\n    readable\n  })\n  if (writable) {\n    if (isNodeStream(head)) {\n      d._write = function (chunk, encoding, callback) {\n        if (head.write(chunk, encoding)) {\n          callback()\n        } else {\n          ondrain = callback\n        }\n      }\n      d._final = function (callback) {\n        head.end()\n        onfinish = callback\n      }\n      head.on('drain', function () {\n        if (ondrain) {\n          const cb = ondrain\n          ondrain = null\n          cb()\n        }\n      })\n    } else if (isWebStream(head)) {\n      const writable = isTransformStream(head) ? head.writable : head\n      const writer = writable.getWriter()\n      d._write = async function (chunk, encoding, callback) {\n        try {\n          await writer.ready\n          writer.write(chunk).catch(() => {})\n          callback()\n        } catch (err) {\n          callback(err)\n        }\n      }\n      d._final = async function (callback) {\n        try {\n          await writer.ready\n          writer.close().catch(() => {})\n          onfinish = callback\n        } catch (err) {\n          callback(err)\n        }\n      }\n    }\n    const toRead = isTransformStream(tail) ? tail.readable : tail\n    eos(toRead, () => {\n      if (onfinish) {\n        const cb = onfinish\n        onfinish = null\n        cb()\n      }\n    })\n  }\n  if (readable) {\n    if (isNodeStream(tail)) {\n      tail.on('readable', function () {\n        if (onreadable) {\n          const cb = onreadable\n          onreadable = null\n          cb()\n        }\n      })\n      tail.on('end', function () {\n        d.push(null)\n      })\n      d._read = function () {\n        while (true) {\n          const buf = tail.read()\n          if (buf === null) {\n            onreadable = d._read\n            return\n          }\n          if (!d.push(buf)) {\n            return\n          }\n        }\n      }\n    } else if (isWebStream(tail)) {\n      const readable = isTransformStream(tail) ? tail.readable : tail\n      const reader = readable.getReader()\n      d._read = async function () {\n        while (true) {\n          try {\n            const { value, done } = await reader.read()\n            if (!d.push(value)) {\n              return\n            }\n            if (done) {\n              d.push(null)\n              return\n            }\n          } catch {\n            return\n          }\n        }\n      }\n    }\n  }\n  d._destroy = function (err, callback) {\n    if (!err && onclose !== null) {\n      err = new AbortError()\n    }\n    onreadable = null\n    ondrain = null\n    onfinish = null\n    if (onclose === null) {\n      callback(err)\n    } else {\n      onclose = callback\n      if (isNodeStream(tail)) {\n        destroyer(tail, err)\n      }\n    }\n  }\n  return d\n}\n","'use strict'\n\nconst AbortController = globalThis.AbortController || require('abort-controller').AbortController\nconst {\n  codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE },\n  AbortError\n} = require('../../ours/errors')\nconst { validateAbortSignal, validateInteger, validateObject } = require('../validators')\nconst kWeakHandler = require('../../ours/primordials').Symbol('kWeak')\nconst kResistStopPropagation = require('../../ours/primordials').Symbol('kResistStopPropagation')\nconst { finished } = require('./end-of-stream')\nconst staticCompose = require('./compose')\nconst { addAbortSignalNoValidate } = require('./add-abort-signal')\nconst { isWritable, isNodeStream } = require('./utils')\nconst { deprecate } = require('../../ours/util')\nconst {\n  ArrayPrototypePush,\n  Boolean,\n  MathFloor,\n  Number,\n  NumberIsNaN,\n  Promise,\n  PromiseReject,\n  PromiseResolve,\n  PromisePrototypeThen,\n  Symbol\n} = require('../../ours/primordials')\nconst kEmpty = Symbol('kEmpty')\nconst kEof = Symbol('kEof')\nfunction compose(stream, options) {\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  if (isNodeStream(stream) && !isWritable(stream)) {\n    throw new ERR_INVALID_ARG_VALUE('stream', stream, 'must be writable')\n  }\n  const composedStream = staticCompose(this, stream)\n  if (options !== null && options !== undefined && options.signal) {\n    // Not validating as we already validated before\n    addAbortSignalNoValidate(options.signal, composedStream)\n  }\n  return composedStream\n}\nfunction map(fn, options) {\n  if (typeof fn !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n  }\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  let concurrency = 1\n  if ((options === null || options === undefined ? undefined : options.concurrency) != null) {\n    concurrency = MathFloor(options.concurrency)\n  }\n  let highWaterMark = concurrency - 1\n  if ((options === null || options === undefined ? undefined : options.highWaterMark) != null) {\n    highWaterMark = MathFloor(options.highWaterMark)\n  }\n  validateInteger(concurrency, 'options.concurrency', 1)\n  validateInteger(highWaterMark, 'options.highWaterMark', 0)\n  highWaterMark += concurrency\n  return async function* map() {\n    const signal = require('../../ours/util').AbortSignalAny(\n      [options === null || options === undefined ? undefined : options.signal].filter(Boolean)\n    )\n    const stream = this\n    const queue = []\n    const signalOpt = {\n      signal\n    }\n    let next\n    let resume\n    let done = false\n    let cnt = 0\n    function onCatch() {\n      done = true\n      afterItemProcessed()\n    }\n    function afterItemProcessed() {\n      cnt -= 1\n      maybeResume()\n    }\n    function maybeResume() {\n      if (resume && !done && cnt < concurrency && queue.length < highWaterMark) {\n        resume()\n        resume = null\n      }\n    }\n    async function pump() {\n      try {\n        for await (let val of stream) {\n          if (done) {\n            return\n          }\n          if (signal.aborted) {\n            throw new AbortError()\n          }\n          try {\n            val = fn(val, signalOpt)\n            if (val === kEmpty) {\n              continue\n            }\n            val = PromiseResolve(val)\n          } catch (err) {\n            val = PromiseReject(err)\n          }\n          cnt += 1\n          PromisePrototypeThen(val, afterItemProcessed, onCatch)\n          queue.push(val)\n          if (next) {\n            next()\n            next = null\n          }\n          if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) {\n            await new Promise((resolve) => {\n              resume = resolve\n            })\n          }\n        }\n        queue.push(kEof)\n      } catch (err) {\n        const val = PromiseReject(err)\n        PromisePrototypeThen(val, afterItemProcessed, onCatch)\n        queue.push(val)\n      } finally {\n        done = true\n        if (next) {\n          next()\n          next = null\n        }\n      }\n    }\n    pump()\n    try {\n      while (true) {\n        while (queue.length > 0) {\n          const val = await queue[0]\n          if (val === kEof) {\n            return\n          }\n          if (signal.aborted) {\n            throw new AbortError()\n          }\n          if (val !== kEmpty) {\n            yield val\n          }\n          queue.shift()\n          maybeResume()\n        }\n        await new Promise((resolve) => {\n          next = resolve\n        })\n      }\n    } finally {\n      done = true\n      if (resume) {\n        resume()\n        resume = null\n      }\n    }\n  }.call(this)\n}\nfunction asIndexedPairs(options = undefined) {\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  return async function* asIndexedPairs() {\n    let index = 0\n    for await (const val of this) {\n      var _options$signal\n      if (\n        options !== null &&\n        options !== undefined &&\n        (_options$signal = options.signal) !== null &&\n        _options$signal !== undefined &&\n        _options$signal.aborted\n      ) {\n        throw new AbortError({\n          cause: options.signal.reason\n        })\n      }\n      yield [index++, val]\n    }\n  }.call(this)\n}\nasync function some(fn, options = undefined) {\n  for await (const unused of filter.call(this, fn, options)) {\n    return true\n  }\n  return false\n}\nasync function every(fn, options = undefined) {\n  if (typeof fn !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n  }\n  // https://en.wikipedia.org/wiki/De_Morgan%27s_laws\n  return !(await some.call(\n    this,\n    async (...args) => {\n      return !(await fn(...args))\n    },\n    options\n  ))\n}\nasync function find(fn, options) {\n  for await (const result of filter.call(this, fn, options)) {\n    return result\n  }\n  return undefined\n}\nasync function forEach(fn, options) {\n  if (typeof fn !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n  }\n  async function forEachFn(value, options) {\n    await fn(value, options)\n    return kEmpty\n  }\n  // eslint-disable-next-line no-unused-vars\n  for await (const unused of map.call(this, forEachFn, options));\n}\nfunction filter(fn, options) {\n  if (typeof fn !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn)\n  }\n  async function filterFn(value, options) {\n    if (await fn(value, options)) {\n      return value\n    }\n    return kEmpty\n  }\n  return map.call(this, filterFn, options)\n}\n\n// Specific to provide better error to reduce since the argument is only\n// missing if the stream has no items in it - but the code is still appropriate\nclass ReduceAwareErrMissingArgs extends ERR_MISSING_ARGS {\n  constructor() {\n    super('reduce')\n    this.message = 'Reduce of an empty stream requires an initial value'\n  }\n}\nasync function reduce(reducer, initialValue, options) {\n  var _options$signal2\n  if (typeof reducer !== 'function') {\n    throw new ERR_INVALID_ARG_TYPE('reducer', ['Function', 'AsyncFunction'], reducer)\n  }\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  let hasInitialValue = arguments.length > 1\n  if (\n    options !== null &&\n    options !== undefined &&\n    (_options$signal2 = options.signal) !== null &&\n    _options$signal2 !== undefined &&\n    _options$signal2.aborted\n  ) {\n    const err = new AbortError(undefined, {\n      cause: options.signal.reason\n    })\n    this.once('error', () => {}) // The error is already propagated\n    await finished(this.destroy(err))\n    throw err\n  }\n  const ac = new AbortController()\n  const signal = ac.signal\n  if (options !== null && options !== undefined && options.signal) {\n    const opts = {\n      once: true,\n      [kWeakHandler]: this,\n      [kResistStopPropagation]: true\n    }\n    options.signal.addEventListener('abort', () => ac.abort(), opts)\n  }\n  let gotAnyItemFromStream = false\n  try {\n    for await (const value of this) {\n      var _options$signal3\n      gotAnyItemFromStream = true\n      if (\n        options !== null &&\n        options !== undefined &&\n        (_options$signal3 = options.signal) !== null &&\n        _options$signal3 !== undefined &&\n        _options$signal3.aborted\n      ) {\n        throw new AbortError()\n      }\n      if (!hasInitialValue) {\n        initialValue = value\n        hasInitialValue = true\n      } else {\n        initialValue = await reducer(initialValue, value, {\n          signal\n        })\n      }\n    }\n    if (!gotAnyItemFromStream && !hasInitialValue) {\n      throw new ReduceAwareErrMissingArgs()\n    }\n  } finally {\n    ac.abort()\n  }\n  return initialValue\n}\nasync function toArray(options) {\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  const result = []\n  for await (const val of this) {\n    var _options$signal4\n    if (\n      options !== null &&\n      options !== undefined &&\n      (_options$signal4 = options.signal) !== null &&\n      _options$signal4 !== undefined &&\n      _options$signal4.aborted\n    ) {\n      throw new AbortError(undefined, {\n        cause: options.signal.reason\n      })\n    }\n    ArrayPrototypePush(result, val)\n  }\n  return result\n}\nfunction flatMap(fn, options) {\n  const values = map.call(this, fn, options)\n  return async function* flatMap() {\n    for await (const val of values) {\n      yield* val\n    }\n  }.call(this)\n}\nfunction toIntegerOrInfinity(number) {\n  // We coerce here to align with the spec\n  // https://github.com/tc39/proposal-iterator-helpers/issues/169\n  number = Number(number)\n  if (NumberIsNaN(number)) {\n    return 0\n  }\n  if (number < 0) {\n    throw new ERR_OUT_OF_RANGE('number', '>= 0', number)\n  }\n  return number\n}\nfunction drop(number, options = undefined) {\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  number = toIntegerOrInfinity(number)\n  return async function* drop() {\n    var _options$signal5\n    if (\n      options !== null &&\n      options !== undefined &&\n      (_options$signal5 = options.signal) !== null &&\n      _options$signal5 !== undefined &&\n      _options$signal5.aborted\n    ) {\n      throw new AbortError()\n    }\n    for await (const val of this) {\n      var _options$signal6\n      if (\n        options !== null &&\n        options !== undefined &&\n        (_options$signal6 = options.signal) !== null &&\n        _options$signal6 !== undefined &&\n        _options$signal6.aborted\n      ) {\n        throw new AbortError()\n      }\n      if (number-- <= 0) {\n        yield val\n      }\n    }\n  }.call(this)\n}\nfunction take(number, options = undefined) {\n  if (options != null) {\n    validateObject(options, 'options')\n  }\n  if ((options === null || options === undefined ? undefined : options.signal) != null) {\n    validateAbortSignal(options.signal, 'options.signal')\n  }\n  number = toIntegerOrInfinity(number)\n  return async function* take() {\n    var _options$signal7\n    if (\n      options !== null &&\n      options !== undefined &&\n      (_options$signal7 = options.signal) !== null &&\n      _options$signal7 !== undefined &&\n      _options$signal7.aborted\n    ) {\n      throw new AbortError()\n    }\n    for await (const val of this) {\n      var _options$signal8\n      if (\n        options !== null &&\n        options !== undefined &&\n        (_options$signal8 = options.signal) !== null &&\n        _options$signal8 !== undefined &&\n        _options$signal8.aborted\n      ) {\n        throw new AbortError()\n      }\n      if (number-- > 0) {\n        yield val\n      }\n\n      // Don't get another item from iterator in case we reached the end\n      if (number <= 0) {\n        return\n      }\n    }\n  }.call(this)\n}\nmodule.exports.streamReturningOperators = {\n  asIndexedPairs: deprecate(asIndexedPairs, 'readable.asIndexedPairs will be removed in a future version.'),\n  drop,\n  filter,\n  flatMap,\n  map,\n  take,\n  compose\n}\nmodule.exports.promiseReturningOperators = {\n  every,\n  forEach,\n  reduce,\n  toArray,\n  some,\n  find\n}\n","'use strict'\n\nconst { ArrayPrototypePop, Promise } = require('../ours/primordials')\nconst { isIterable, isNodeStream, isWebStream } = require('../internal/streams/utils')\nconst { pipelineImpl: pl } = require('../internal/streams/pipeline')\nconst { finished } = require('../internal/streams/end-of-stream')\nrequire('../../lib/stream.js')\nfunction pipeline(...streams) {\n  return new Promise((resolve, reject) => {\n    let signal\n    let end\n    const lastArg = streams[streams.length - 1]\n    if (\n      lastArg &&\n      typeof lastArg === 'object' &&\n      !isNodeStream(lastArg) &&\n      !isIterable(lastArg) &&\n      !isWebStream(lastArg)\n    ) {\n      const options = ArrayPrototypePop(streams)\n      signal = options.signal\n      end = options.end\n    }\n    pl(\n      streams,\n      (err, value) => {\n        if (err) {\n          reject(err)\n        } else {\n          resolve(value)\n        }\n      },\n      {\n        signal,\n        end\n      }\n    )\n  })\n}\nmodule.exports = {\n  finished,\n  pipeline\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict'\n\n/* replacement start */\n\nconst { Buffer } = require('buffer')\n\n/* replacement end */\n\nconst { ObjectDefineProperty, ObjectKeys, ReflectApply } = require('./ours/primordials')\nconst {\n  promisify: { custom: customPromisify }\n} = require('./ours/util')\nconst { streamReturningOperators, promiseReturningOperators } = require('./internal/streams/operators')\nconst {\n  codes: { ERR_ILLEGAL_CONSTRUCTOR }\n} = require('./ours/errors')\nconst compose = require('./internal/streams/compose')\nconst { setDefaultHighWaterMark, getDefaultHighWaterMark } = require('./internal/streams/state')\nconst { pipeline } = require('./internal/streams/pipeline')\nconst { destroyer } = require('./internal/streams/destroy')\nconst eos = require('./internal/streams/end-of-stream')\nconst internalBuffer = {}\nconst promises = require('./stream/promises')\nconst utils = require('./internal/streams/utils')\nconst Stream = (module.exports = require('./internal/streams/legacy').Stream)\nStream.isDestroyed = utils.isDestroyed\nStream.isDisturbed = utils.isDisturbed\nStream.isErrored = utils.isErrored\nStream.isReadable = utils.isReadable\nStream.isWritable = utils.isWritable\nStream.Readable = require('./internal/streams/readable')\nfor (const key of ObjectKeys(streamReturningOperators)) {\n  const op = streamReturningOperators[key]\n  function fn(...args) {\n    if (new.target) {\n      throw ERR_ILLEGAL_CONSTRUCTOR()\n    }\n    return Stream.Readable.from(ReflectApply(op, this, args))\n  }\n  ObjectDefineProperty(fn, 'name', {\n    __proto__: null,\n    value: op.name\n  })\n  ObjectDefineProperty(fn, 'length', {\n    __proto__: null,\n    value: op.length\n  })\n  ObjectDefineProperty(Stream.Readable.prototype, key, {\n    __proto__: null,\n    value: fn,\n    enumerable: false,\n    configurable: true,\n    writable: true\n  })\n}\nfor (const key of ObjectKeys(promiseReturningOperators)) {\n  const op = promiseReturningOperators[key]\n  function fn(...args) {\n    if (new.target) {\n      throw ERR_ILLEGAL_CONSTRUCTOR()\n    }\n    return ReflectApply(op, this, args)\n  }\n  ObjectDefineProperty(fn, 'name', {\n    __proto__: null,\n    value: op.name\n  })\n  ObjectDefineProperty(fn, 'length', {\n    __proto__: null,\n    value: op.length\n  })\n  ObjectDefineProperty(Stream.Readable.prototype, key, {\n    __proto__: null,\n    value: fn,\n    enumerable: false,\n    configurable: true,\n    writable: true\n  })\n}\nStream.Writable = require('./internal/streams/writable')\nStream.Duplex = require('./internal/streams/duplex')\nStream.Transform = require('./internal/streams/transform')\nStream.PassThrough = require('./internal/streams/passthrough')\nStream.pipeline = pipeline\nconst { addAbortSignal } = require('./internal/streams/add-abort-signal')\nStream.addAbortSignal = addAbortSignal\nStream.finished = eos\nStream.destroy = destroyer\nStream.compose = compose\nStream.setDefaultHighWaterMark = setDefaultHighWaterMark\nStream.getDefaultHighWaterMark = getDefaultHighWaterMark\nObjectDefineProperty(Stream, 'promises', {\n  __proto__: null,\n  configurable: true,\n  enumerable: true,\n  get() {\n    return promises\n  }\n})\nObjectDefineProperty(pipeline, customPromisify, {\n  __proto__: null,\n  enumerable: true,\n  get() {\n    return promises.pipeline\n  }\n})\nObjectDefineProperty(eos, customPromisify, {\n  __proto__: null,\n  enumerable: true,\n  get() {\n    return promises.finished\n  }\n})\n\n// Backwards-compat with node 0.4.x\nStream.Stream = Stream\nStream._isUint8Array = function isUint8Array(value) {\n  return value instanceof Uint8Array\n}\nStream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) {\n  return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)\n}\n","'use strict'\n\nconst Stream = require('stream')\nif (Stream && process.env.READABLE_STREAM === 'disable') {\n  const promises = Stream.promises\n\n  // Explicit export naming is needed for ESM\n  module.exports._uint8ArrayToBuffer = Stream._uint8ArrayToBuffer\n  module.exports._isUint8Array = Stream._isUint8Array\n  module.exports.isDisturbed = Stream.isDisturbed\n  module.exports.isErrored = Stream.isErrored\n  module.exports.isReadable = Stream.isReadable\n  module.exports.Readable = Stream.Readable\n  module.exports.Writable = Stream.Writable\n  module.exports.Duplex = Stream.Duplex\n  module.exports.Transform = Stream.Transform\n  module.exports.PassThrough = Stream.PassThrough\n  module.exports.addAbortSignal = Stream.addAbortSignal\n  module.exports.finished = Stream.finished\n  module.exports.destroy = Stream.destroy\n  module.exports.pipeline = Stream.pipeline\n  module.exports.compose = Stream.compose\n  Object.defineProperty(Stream, 'promises', {\n    configurable: true,\n    enumerable: true,\n    get() {\n      return promises\n    }\n  })\n  module.exports.Stream = Stream.Stream\n} else {\n  const CustomStream = require('../stream')\n  const promises = require('../stream/promises')\n  const originalDestroy = CustomStream.Readable.destroy\n  module.exports = CustomStream.Readable\n\n  // Explicit export naming is needed for ESM\n  module.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer\n  module.exports._isUint8Array = CustomStream._isUint8Array\n  module.exports.isDisturbed = CustomStream.isDisturbed\n  module.exports.isErrored = CustomStream.isErrored\n  module.exports.isReadable = CustomStream.isReadable\n  module.exports.Readable = CustomStream.Readable\n  module.exports.Writable = CustomStream.Writable\n  module.exports.Duplex = CustomStream.Duplex\n  module.exports.Transform = CustomStream.Transform\n  module.exports.PassThrough = CustomStream.PassThrough\n  module.exports.addAbortSignal = CustomStream.addAbortSignal\n  module.exports.finished = CustomStream.finished\n  module.exports.destroy = CustomStream.destroy\n  module.exports.destroy = originalDestroy\n  module.exports.pipeline = CustomStream.pipeline\n  module.exports.compose = CustomStream.compose\n  Object.defineProperty(CustomStream, 'promises', {\n    configurable: true,\n    enumerable: true,\n    get() {\n      return promises\n    }\n  })\n  module.exports.Stream = CustomStream.Stream\n}\n\n// Allow default importing\nmodule.exports.default = module.exports\n","/**\n * node-crc32-stream\n *\n * Copyright (c) 2014 Chris Talkington, contributors.\n * Licensed under the MIT license.\n * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT\n */\n\n 'use strict';\n\nconst {Transform} = require('readable-stream');\n\nconst crc32 = require('crc-32');\n\nclass CRC32Stream extends Transform {\n  constructor(options) {\n    super(options);\n    this.checksum = Buffer.allocUnsafe(4);\n    this.checksum.writeInt32BE(0, 0);\n\n    this.rawSize = 0;\n  }\n\n  _transform(chunk, encoding, callback) {\n    if (chunk) {\n      this.checksum = crc32.buf(chunk, this.checksum) >>> 0;\n      this.rawSize += chunk.length;\n    }\n\n    callback(null, chunk);\n  }\n\n  digest(encoding) {\n    const checksum = Buffer.allocUnsafe(4);\n    checksum.writeUInt32BE(this.checksum >>> 0, 0);\n    return encoding ? checksum.toString(encoding) : checksum;\n  }\n\n  hex() {\n    return this.digest('hex').toUpperCase();\n  }\n\n  size() {\n    return this.rawSize;\n  }\n}\n\nmodule.exports = CRC32Stream;\n","/**\n * node-crc32-stream\n *\n * Copyright (c) 2014 Chris Talkington, contributors.\n * Licensed under the MIT license.\n * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT\n */\n\n'use strict';\n\nconst {DeflateRaw} = require('zlib');\n\nconst crc32 = require('crc-32');\n\nclass DeflateCRC32Stream extends DeflateRaw {\n  constructor(options) {\n    super(options);\n\n    this.checksum = Buffer.allocUnsafe(4);\n    this.checksum.writeInt32BE(0, 0);\n\n    this.rawSize = 0;\n    this.compressedSize = 0;\n  }\n\n  push(chunk, encoding) {\n    if (chunk) {\n      this.compressedSize += chunk.length;\n    }\n\n    return super.push(chunk, encoding);\n  }\n\n  _transform(chunk, encoding, callback) {\n    if (chunk) {\n      this.checksum = crc32.buf(chunk, this.checksum) >>> 0;\n      this.rawSize += chunk.length;\n    }\n\n    super._transform(chunk, encoding, callback)\n  }\n\n  digest(encoding) {\n    const checksum = Buffer.allocUnsafe(4);\n    checksum.writeUInt32BE(this.checksum >>> 0, 0);\n    return encoding ? checksum.toString(encoding) : checksum;\n  }\n\n  hex() {\n    return this.digest('hex').toUpperCase();\n  }\n\n  size(compressed = false) {\n    if (compressed) {\n      return this.compressedSize;\n    } else {\n      return this.rawSize;\n    }\n  }\n}\n\nmodule.exports = DeflateCRC32Stream;\n","/**\n * node-crc32-stream\n *\n * Copyright (c) 2014 Chris Talkington, contributors.\n * Licensed under the MIT license.\n * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT\n */\n\n'use strict';\n\nmodule.exports = {\n  CRC32Stream: require('./crc32-stream'),\n  DeflateCRC32Stream: require('./deflate-crc32-stream')\n}\n","/**\n * node-compress-commons\n *\n * Copyright (c) 2014 Chris Talkington, contributors.\n * Licensed under the MIT license.\n * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT\n */\nvar inherits = require('util').inherits;\nvar crc32 = require('crc-32');\nvar {CRC32Stream} = require('crc32-stream');\nvar {DeflateCRC32Stream} = require('crc32-stream');\n\nvar ArchiveOutputStream = require('../archive-output-stream');\nvar ZipArchiveEntry = require('./zip-archive-entry');\nvar GeneralPurposeBit = require('./general-purpose-bit');\n\nvar constants = require('./constants');\nvar util = require('../../util');\nvar zipUtil = require('./util');\n\nvar ZipArchiveOutputStream = module.exports = function(options) {\n  if (!(this instanceof ZipArchiveOutputStream)) {\n    return new ZipArchiveOutputStream(options);\n  }\n\n  options = this.options = this._defaults(options);\n\n  ArchiveOutputStream.call(this, options);\n\n  this._entry = null;\n  this._entries = [];\n  this._archive = {\n    centralLength: 0,\n    centralOffset: 0,\n    comment: '',\n    finish: false,\n    finished: false,\n    processing: false,\n    forceZip64: options.forceZip64,\n    forceLocalTime: options.forceLocalTime\n  };\n};\n\ninherits(ZipArchiveOutputStream, ArchiveOutputStream);\n\nZipArchiveOutputStream.prototype._afterAppend = function(ae) {\n  this._entries.push(ae);\n\n  if (ae.getGeneralPurposeBit().usesDataDescriptor()) {\n    this._writeDataDescriptor(ae);\n  }\n\n  this._archive.processing = false;\n  this._entry = null;\n\n  if (this._archive.finish && !this._archive.finished) {\n    this._finish();\n  }\n};\n\nZipArchiveOutputStream.prototype._appendBuffer = function(ae, source, callback) {\n  if (source.length === 0) {\n    ae.setMethod(constants.METHOD_STORED);\n  }\n\n  var method = ae.getMethod();\n\n  if (method === constants.METHOD_STORED) {\n    ae.setSize(source.length);\n    ae.setCompressedSize(source.length);\n    ae.setCrc(crc32.buf(source) >>> 0);\n  }\n\n  this._writeLocalFileHeader(ae);\n\n  if (method === constants.METHOD_STORED) {\n    this.write(source);\n    this._afterAppend(ae);\n    callback(null, ae);\n    return;\n  } else if (method === constants.METHOD_DEFLATED) {\n    this._smartStream(ae, callback).end(source);\n    return;\n  } else {\n    callback(new Error('compression method ' + method + ' not implemented'));\n    return;\n  }\n};\n\nZipArchiveOutputStream.prototype._appendStream = function(ae, source, callback) {\n  ae.getGeneralPurposeBit().useDataDescriptor(true);\n  ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR);\n\n  this._writeLocalFileHeader(ae);\n\n  var smart = this._smartStream(ae, callback);\n  source.once('error', function(err) {\n    smart.emit('error', err);\n    smart.end();\n  })\n  source.pipe(smart);\n};\n\nZipArchiveOutputStream.prototype._defaults = function(o) {\n  if (typeof o !== 'object') {\n    o = {};\n  }\n\n  if (typeof o.zlib !== 'object') {\n    o.zlib = {};\n  }\n\n  if (typeof o.zlib.level !== 'number') {\n    o.zlib.level = constants.ZLIB_BEST_SPEED;\n  }\n\n  o.forceZip64 = !!o.forceZip64;\n  o.forceLocalTime = !!o.forceLocalTime;\n\n  return o;\n};\n\nZipArchiveOutputStream.prototype._finish = function() {\n  this._archive.centralOffset = this.offset;\n\n  this._entries.forEach(function(ae) {\n    this._writeCentralFileHeader(ae);\n  }.bind(this));\n\n  this._archive.centralLength = this.offset - this._archive.centralOffset;\n\n  if (this.isZip64()) {\n    this._writeCentralDirectoryZip64();\n  }\n\n  this._writeCentralDirectoryEnd();\n\n  this._archive.processing = false;\n  this._archive.finish = true;\n  this._archive.finished = true;\n  this.end();\n};\n\nZipArchiveOutputStream.prototype._normalizeEntry = function(ae) {\n  if (ae.getMethod() === -1) {\n    ae.setMethod(constants.METHOD_DEFLATED);\n  }\n\n  if (ae.getMethod() === constants.METHOD_DEFLATED) {\n    ae.getGeneralPurposeBit().useDataDescriptor(true);\n    ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR);\n  }\n\n  if (ae.getTime() === -1) {\n    ae.setTime(new Date(), this._archive.forceLocalTime);\n  }\n\n  ae._offsets = {\n    file: 0,\n    data: 0,\n    contents: 0,\n  };\n};\n\nZipArchiveOutputStream.prototype._smartStream = function(ae, callback) {\n  var deflate = ae.getMethod() === constants.METHOD_DEFLATED;\n  var process = deflate ? new DeflateCRC32Stream(this.options.zlib) : new CRC32Stream();\n  var error = null;\n\n  function handleStuff() {\n    var digest = process.digest().readUInt32BE(0);\n    ae.setCrc(digest);\n    ae.setSize(process.size());\n    ae.setCompressedSize(process.size(true));\n    this._afterAppend(ae);\n    callback(error, ae);\n  }\n\n  process.once('end', handleStuff.bind(this));\n  process.once('error', function(err) {\n    error = err;\n  });\n\n  process.pipe(this, { end: false });\n\n  return process;\n};\n\nZipArchiveOutputStream.prototype._writeCentralDirectoryEnd = function() {\n  var records = this._entries.length;\n  var size = this._archive.centralLength;\n  var offset = this._archive.centralOffset;\n\n  if (this.isZip64()) {\n    records = constants.ZIP64_MAGIC_SHORT;\n    size = constants.ZIP64_MAGIC;\n    offset = constants.ZIP64_MAGIC;\n  }\n\n  // signature\n  this.write(zipUtil.getLongBytes(constants.SIG_EOCD));\n\n  // disk numbers\n  this.write(constants.SHORT_ZERO);\n  this.write(constants.SHORT_ZERO);\n\n  // number of entries\n  this.write(zipUtil.getShortBytes(records));\n  this.write(zipUtil.getShortBytes(records));\n\n  // length and location of CD\n  this.write(zipUtil.getLongBytes(size));\n  this.write(zipUtil.getLongBytes(offset));\n\n  // archive comment\n  var comment = this.getComment();\n  var commentLength = Buffer.byteLength(comment);\n  this.write(zipUtil.getShortBytes(commentLength));\n  this.write(comment);\n};\n\nZipArchiveOutputStream.prototype._writeCentralDirectoryZip64 = function() {\n  // signature\n  this.write(zipUtil.getLongBytes(constants.SIG_ZIP64_EOCD));\n\n  // size of the ZIP64 EOCD record\n  this.write(zipUtil.getEightBytes(44));\n\n  // version made by\n  this.write(zipUtil.getShortBytes(constants.MIN_VERSION_ZIP64));\n\n  // version to extract\n  this.write(zipUtil.getShortBytes(constants.MIN_VERSION_ZIP64));\n\n  // disk numbers\n  this.write(constants.LONG_ZERO);\n  this.write(constants.LONG_ZERO);\n\n  // number of entries\n  this.write(zipUtil.getEightBytes(this._entries.length));\n  this.write(zipUtil.getEightBytes(this._entries.length));\n\n  // length and location of CD\n  this.write(zipUtil.getEightBytes(this._archive.centralLength));\n  this.write(zipUtil.getEightBytes(this._archive.centralOffset));\n\n  // extensible data sector\n  // not implemented at this time\n\n  // end of central directory locator\n  this.write(zipUtil.getLongBytes(constants.SIG_ZIP64_EOCD_LOC));\n\n  // disk number holding the ZIP64 EOCD record\n  this.write(constants.LONG_ZERO);\n\n  // relative offset of the ZIP64 EOCD record\n  this.write(zipUtil.getEightBytes(this._archive.centralOffset + this._archive.centralLength));\n\n  // total number of disks\n  this.write(zipUtil.getLongBytes(1));\n};\n\nZipArchiveOutputStream.prototype._writeCentralFileHeader = function(ae) {\n  var gpb = ae.getGeneralPurposeBit();\n  var method = ae.getMethod();\n  var fileOffset = ae._offsets.file;\n\n  var size = ae.getSize();\n  var compressedSize = ae.getCompressedSize();\n\n  if (ae.isZip64() || fileOffset > constants.ZIP64_MAGIC) {\n    size = constants.ZIP64_MAGIC;\n    compressedSize = constants.ZIP64_MAGIC;\n    fileOffset = constants.ZIP64_MAGIC;\n\n    ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64);\n\n    var extraBuf = Buffer.concat([\n      zipUtil.getShortBytes(constants.ZIP64_EXTRA_ID),\n      zipUtil.getShortBytes(24),\n      zipUtil.getEightBytes(ae.getSize()),\n      zipUtil.getEightBytes(ae.getCompressedSize()),\n      zipUtil.getEightBytes(ae._offsets.file)\n    ], 28);\n\n    ae.setExtra(extraBuf);\n  }\n\n  // signature\n  this.write(zipUtil.getLongBytes(constants.SIG_CFH));\n\n  // version made by\n  this.write(zipUtil.getShortBytes((ae.getPlatform() << 8) | constants.VERSION_MADEBY));\n\n  // version to extract and general bit flag\n  this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract()));\n  this.write(gpb.encode());\n\n  // compression method\n  this.write(zipUtil.getShortBytes(method));\n\n  // datetime\n  this.write(zipUtil.getLongBytes(ae.getTimeDos()));\n\n  // crc32 checksum\n  this.write(zipUtil.getLongBytes(ae.getCrc()));\n\n  // sizes\n  this.write(zipUtil.getLongBytes(compressedSize));\n  this.write(zipUtil.getLongBytes(size));\n\n  var name = ae.getName();\n  var comment = ae.getComment();\n  var extra = ae.getCentralDirectoryExtra();\n\n  if (gpb.usesUTF8ForNames()) {\n    name = Buffer.from(name);\n    comment = Buffer.from(comment);\n  }\n\n  // name length\n  this.write(zipUtil.getShortBytes(name.length));\n\n  // extra length\n  this.write(zipUtil.getShortBytes(extra.length));\n\n  // comments length\n  this.write(zipUtil.getShortBytes(comment.length));\n\n  // disk number start\n  this.write(constants.SHORT_ZERO);\n\n  // internal attributes\n  this.write(zipUtil.getShortBytes(ae.getInternalAttributes()));\n\n  // external attributes\n  this.write(zipUtil.getLongBytes(ae.getExternalAttributes()));\n\n  // relative offset of LFH\n  this.write(zipUtil.getLongBytes(fileOffset));\n\n  // name\n  this.write(name);\n\n  // extra\n  this.write(extra);\n\n  // comment\n  this.write(comment);\n};\n\nZipArchiveOutputStream.prototype._writeDataDescriptor = function(ae) {\n  // signature\n  this.write(zipUtil.getLongBytes(constants.SIG_DD));\n\n  // crc32 checksum\n  this.write(zipUtil.getLongBytes(ae.getCrc()));\n\n  // sizes\n  if (ae.isZip64()) {\n    this.write(zipUtil.getEightBytes(ae.getCompressedSize()));\n    this.write(zipUtil.getEightBytes(ae.getSize()));\n  } else {\n    this.write(zipUtil.getLongBytes(ae.getCompressedSize()));\n    this.write(zipUtil.getLongBytes(ae.getSize()));\n  }\n};\n\nZipArchiveOutputStream.prototype._writeLocalFileHeader = function(ae) {\n  var gpb = ae.getGeneralPurposeBit();\n  var method = ae.getMethod();\n  var name = ae.getName();\n  var extra = ae.getLocalFileDataExtra();\n\n  if (ae.isZip64()) {\n    gpb.useDataDescriptor(true);\n    ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64);\n  }\n\n  if (gpb.usesUTF8ForNames()) {\n    name = Buffer.from(name);\n  }\n\n  ae._offsets.file = this.offset;\n\n  // signature\n  this.write(zipUtil.getLongBytes(constants.SIG_LFH));\n\n  // version to extract and general bit flag\n  this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract()));\n  this.write(gpb.encode());\n\n  // compression method\n  this.write(zipUtil.getShortBytes(method));\n\n  // datetime\n  this.write(zipUtil.getLongBytes(ae.getTimeDos()));\n\n  ae._offsets.data = this.offset;\n\n  // crc32 checksum and sizes\n  if (gpb.usesDataDescriptor()) {\n    this.write(constants.LONG_ZERO);\n    this.write(constants.LONG_ZERO);\n    this.write(constants.LONG_ZERO);\n  } else {\n    this.write(zipUtil.getLongBytes(ae.getCrc()));\n    this.write(zipUtil.getLongBytes(ae.getCompressedSize()));\n    this.write(zipUtil.getLongBytes(ae.getSize()));\n  }\n\n  // name length\n  this.write(zipUtil.getShortBytes(name.length));\n\n  // extra length\n  this.write(zipUtil.getShortBytes(extra.length));\n\n  // name\n  this.write(name);\n\n  // extra\n  this.write(extra);\n\n  ae._offsets.contents = this.offset;\n};\n\nZipArchiveOutputStream.prototype.getComment = function(comment) {\n  return this._archive.comment !== null ? this._archive.comment : '';\n};\n\nZipArchiveOutputStream.prototype.isZip64 = function() {\n  return this._archive.forceZip64 || this._entries.length > constants.ZIP64_MAGIC_SHORT || this._archive.centralLength > constants.ZIP64_MAGIC || this._archive.centralOffset > constants.ZIP64_MAGIC;\n};\n\nZipArchiveOutputStream.prototype.setComment = function(comment) {\n  this._archive.comment = comment;\n};\n","/**\n * node-compress-commons\n *\n * Copyright (c) 2014 Chris Talkington, contributors.\n * Licensed under the MIT license.\n * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT\n */\nmodule.exports = {\n  ArchiveEntry: require('./archivers/archive-entry'),\n  ZipArchiveEntry: require('./archivers/zip/zip-archive-entry'),\n  ArchiveOutputStream: require('./archivers/archive-output-stream'),\n  ZipArchiveOutputStream: require('./archivers/zip/zip-archive-output-stream')\n};","/**\n * ZipStream\n *\n * @ignore\n * @license [MIT]{@link https://github.com/archiverjs/node-zip-stream/blob/master/LICENSE}\n * @copyright (c) 2014 Chris Talkington, contributors.\n */\nvar inherits = require('util').inherits;\n\nvar ZipArchiveOutputStream = require('compress-commons').ZipArchiveOutputStream;\nvar ZipArchiveEntry = require('compress-commons').ZipArchiveEntry;\n\nvar util = require('archiver-utils');\n\n/**\n * @constructor\n * @extends external:ZipArchiveOutputStream\n * @param {Object} [options]\n * @param {String} [options.comment] Sets the zip archive comment.\n * @param {Boolean} [options.forceLocalTime=false] Forces the archive to contain local file times instead of UTC.\n * @param {Boolean} [options.forceZip64=false] Forces the archive to contain ZIP64 headers.\n * @param {Boolean} [options.store=false] Sets the compression method to STORE.\n * @param {Object} [options.zlib] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options}\n * to control compression.\n */\nvar ZipStream = module.exports = function(options) {\n  if (!(this instanceof ZipStream)) {\n    return new ZipStream(options);\n  }\n\n  options = this.options = options || {};\n  options.zlib = options.zlib || {};\n\n  ZipArchiveOutputStream.call(this, options);\n\n  if (typeof options.level === 'number' && options.level >= 0) {\n    options.zlib.level = options.level;\n    delete options.level;\n  }\n\n  if (!options.forceZip64 && typeof options.zlib.level === 'number' && options.zlib.level === 0) {\n    options.store = true;\n  }\n\n  options.namePrependSlash = options.namePrependSlash || false;\n\n  if (options.comment && options.comment.length > 0) {\n    this.setComment(options.comment);\n  }\n};\n\ninherits(ZipStream, ZipArchiveOutputStream);\n\n/**\n * Normalizes entry data with fallbacks for key properties.\n *\n * @private\n * @param  {Object} data\n * @return {Object}\n */\nZipStream.prototype._normalizeFileData = function(data) {\n  data = util.defaults(data, {\n    type: 'file',\n    name: null,\n    namePrependSlash: this.options.namePrependSlash,\n    linkname: null,\n    date: null,\n    mode: null,\n    store: this.options.store,\n    comment: ''\n  });\n\n  var isDir = data.type === 'directory';\n  var isSymlink = data.type === 'symlink';\n\n  if (data.name) {\n    data.name = util.sanitizePath(data.name);\n\n    if (!isSymlink && data.name.slice(-1) === '/') {\n      isDir = true;\n      data.type = 'directory';\n    } else if (isDir) {\n      data.name += '/';\n    }\n  }\n\n  if (isDir || isSymlink) {\n    data.store = true;\n  }\n\n  data.date = util.dateify(data.date);\n\n  return data;\n};\n\n/**\n * Appends an entry given an input source (text string, buffer, or stream).\n *\n * @param  {(Buffer|Stream|String)} source The input source.\n * @param  {Object} data\n * @param  {String} data.name Sets the entry name including internal path.\n * @param  {String} [data.comment] Sets the entry comment.\n * @param  {(String|Date)} [data.date=NOW()] Sets the entry date.\n * @param  {Number} [data.mode=D:0755/F:0644] Sets the entry permissions.\n * @param  {Boolean} [data.store=options.store] Sets the compression method to STORE.\n * @param  {String} [data.type=file] Sets the entry type. Defaults to `directory`\n * if name ends with trailing slash.\n * @param  {Function} callback\n * @return this\n */\nZipStream.prototype.entry = function(source, data, callback) {\n  if (typeof callback !== 'function') {\n    callback = this._emitErrorCallback.bind(this);\n  }\n\n  data = this._normalizeFileData(data);\n\n  if (data.type !== 'file' && data.type !== 'directory' && data.type !== 'symlink') {\n    callback(new Error(data.type + ' entries not currently supported'));\n    return;\n  }\n\n  if (typeof data.name !== 'string' || data.name.length === 0) {\n    callback(new Error('entry name must be a non-empty string value'));\n    return;\n  }\n\n  if (data.type === 'symlink' && typeof data.linkname !== 'string') {\n    callback(new Error('entry linkname must be a non-empty string value when type equals symlink'));\n    return;\n  }\n\n  var entry = new ZipArchiveEntry(data.name);\n  entry.setTime(data.date, this.options.forceLocalTime);\n\n  if (data.namePrependSlash) {\n    entry.setName(data.name, true);\n  }\n\n  if (data.store) {\n    entry.setMethod(0);\n  }\n\n  if (data.comment.length > 0) {\n    entry.setComment(data.comment);\n  }\n\n  if (data.type === 'symlink' && typeof data.mode !== 'number') {\n    data.mode = 40960; // 0120000\n  }\n\n  if (typeof data.mode === 'number') {\n    if (data.type === 'symlink') {\n      data.mode |= 40960;\n    }\n\n    entry.setUnixMode(data.mode);\n  }\n\n  if (data.type === 'symlink' && typeof data.linkname === 'string') {\n    source = Buffer.from(data.linkname);\n  }\n\n  return ZipArchiveOutputStream.prototype.entry.call(this, entry, source, callback);\n};\n\n/**\n * Finalizes the instance and prevents further appending to the archive\n * structure (queue will continue til drained).\n *\n * @return void\n */\nZipStream.prototype.finalize = function() {\n  this.finish();\n};\n\n/**\n * Returns the current number of bytes written to this stream.\n * @function ZipStream#getBytesWritten\n * @returns {Number}\n */\n\n/**\n * Compress Commons ZipArchiveOutputStream\n * @external ZipArchiveOutputStream\n * @see {@link https://github.com/archiverjs/node-compress-commons}\n */\n","/**\n * ZIP Format Plugin\n *\n * @module plugins/zip\n * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE}\n * @copyright (c) 2012-2014 Chris Talkington, contributors.\n */\nvar engine = require('zip-stream');\nvar util = require('archiver-utils');\n\n/**\n * @constructor\n * @param {ZipOptions} [options]\n * @param {String} [options.comment] Sets the zip archive comment.\n * @param {Boolean} [options.forceLocalTime=false] Forces the archive to contain local file times instead of UTC.\n * @param {Boolean} [options.forceZip64=false] Forces the archive to contain ZIP64 headers.\n * @param {Boolean} [options.namePrependSlash=false] Prepends a forward slash to archive file paths.\n * @param {Boolean} [options.store=false] Sets the compression method to STORE.\n * @param {Object} [options.zlib] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options}\n */\nvar Zip = function(options) {\n  if (!(this instanceof Zip)) {\n    return new Zip(options);\n  }\n\n  options = this.options = util.defaults(options, {\n    comment: '',\n    forceUTC: false,\n    namePrependSlash: false,\n    store: false\n  });\n\n  this.supports = {\n    directory: true,\n    symlink: true\n  };\n\n  this.engine = new engine(options);\n};\n\n/**\n * @param  {(Buffer|Stream)} source\n * @param  {ZipEntryData} data\n * @param  {String} data.name Sets the entry name including internal path.\n * @param  {(String|Date)} [data.date=NOW()] Sets the entry date.\n * @param  {Number} [data.mode=D:0755/F:0644] Sets the entry permissions.\n * @param  {String} [data.prefix] Sets a path prefix for the entry name. Useful\n * when working with methods like `directory` or `glob`.\n * @param  {fs.Stats} [data.stats] Sets the fs stat data for this entry allowing\n * for reduction of fs stat calls when stat data is already known.\n * @param  {Boolean} [data.store=ZipOptions.store] Sets the compression method to STORE.\n * @param  {Function} callback\n * @return void\n */\nZip.prototype.append = function(source, data, callback) {\n  this.engine.entry(source, data, callback);\n};\n\n/**\n * @return void\n */\nZip.prototype.finalize = function() {\n  this.engine.finalize();\n};\n\n/**\n * @return this.engine\n */\nZip.prototype.on = function() {\n  return this.engine.on.apply(this.engine, arguments);\n};\n\n/**\n * @return this.engine\n */\nZip.prototype.pipe = function() {\n  return this.engine.pipe.apply(this.engine, arguments);\n};\n\n/**\n * @return this.engine\n */\nZip.prototype.unpipe = function() {\n  return this.engine.unpipe.apply(this.engine, arguments);\n};\n\nmodule.exports = Zip;\n\n/**\n * @typedef {Object} ZipOptions\n * @global\n * @property {String} [comment] Sets the zip archive comment.\n * @property {Boolean} [forceLocalTime=false] Forces the archive to contain local file times instead of UTC.\n * @property {Boolean} [forceZip64=false] Forces the archive to contain ZIP64 headers.\n * @prpperty {Boolean} [namePrependSlash=false] Prepends a forward slash to archive file paths.\n * @property {Boolean} [store=false] Sets the compression method to STORE.\n * @property {Object} [zlib] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options}\n * to control compression.\n * @property {*} [*] See [zip-stream]{@link https://archiverjs.com/zip-stream/ZipStream.html} documentation for current list of properties.\n */\n\n/**\n * @typedef {Object} ZipEntryData\n * @global\n * @property {String} name Sets the entry name including internal path.\n * @property {(String|Date)} [date=NOW()] Sets the entry date.\n * @property {Number} [mode=D:0755/F:0644] Sets the entry permissions.\n * @property {Boolean} [namePrependSlash=ZipOptions.namePrependSlash] Prepends a forward slash to archive file paths.\n * @property {String} [prefix] Sets a path prefix for the entry name. Useful\n * when working with methods like `directory` or `glob`.\n * @property {fs.Stats} [stats] Sets the fs stat data for this entry allowing\n * for reduction of fs stat calls when stat data is already known.\n * @property {Boolean} [store=ZipOptions.store] Sets the compression method to STORE.\n */\n\n/**\n * ZipStream Module\n * @external ZipStream\n * @see {@link https://www.archiverjs.com/zip-stream/ZipStream.html}\n */\n","module.exports = class FixedFIFO {\n  constructor (hwm) {\n    if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')\n    this.buffer = new Array(hwm)\n    this.mask = hwm - 1\n    this.top = 0\n    this.btm = 0\n    this.next = null\n  }\n\n  clear () {\n    this.top = this.btm = 0\n    this.next = null\n    this.buffer.fill(undefined)\n  }\n\n  push (data) {\n    if (this.buffer[this.top] !== undefined) return false\n    this.buffer[this.top] = data\n    this.top = (this.top + 1) & this.mask\n    return true\n  }\n\n  shift () {\n    const last = this.buffer[this.btm]\n    if (last === undefined) return undefined\n    this.buffer[this.btm] = undefined\n    this.btm = (this.btm + 1) & this.mask\n    return last\n  }\n\n  peek () {\n    return this.buffer[this.btm]\n  }\n\n  isEmpty () {\n    return this.buffer[this.btm] === undefined\n  }\n}\n","const FixedFIFO = require('./fixed-size')\n\nmodule.exports = class FastFIFO {\n  constructor (hwm) {\n    this.hwm = hwm || 16\n    this.head = new FixedFIFO(this.hwm)\n    this.tail = this.head\n    this.length = 0\n  }\n\n  clear () {\n    this.head = this.tail\n    this.head.clear()\n    this.length = 0\n  }\n\n  push (val) {\n    this.length++\n    if (!this.head.push(val)) {\n      const prev = this.head\n      this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length)\n      this.head.push(val)\n    }\n  }\n\n  shift () {\n    if (this.length !== 0) this.length--\n    const val = this.tail.shift()\n    if (val === undefined && this.tail.next) {\n      const next = this.tail.next\n      this.tail.next = null\n      this.tail = next\n      return this.tail.shift()\n    }\n\n    return val\n  }\n\n  peek () {\n    const val = this.tail.peek()\n    if (val === undefined && this.tail.next) return this.tail.next.peek()\n    return val\n  }\n\n  isEmpty () {\n    return this.length === 0\n  }\n}\n","function isBuffer (value) {\n  return Buffer.isBuffer(value) || value instanceof Uint8Array\n}\n\nfunction isEncoding (encoding) {\n  return Buffer.isEncoding(encoding)\n}\n\nfunction alloc (size, fill, encoding) {\n  return Buffer.alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n  return Buffer.allocUnsafe(size)\n}\n\nfunction allocUnsafeSlow (size) {\n  return Buffer.allocUnsafeSlow(size)\n}\n\nfunction byteLength (string, encoding) {\n  return Buffer.byteLength(string, encoding)\n}\n\nfunction compare (a, b) {\n  return Buffer.compare(a, b)\n}\n\nfunction concat (buffers, totalLength) {\n  return Buffer.concat(buffers, totalLength)\n}\n\nfunction copy (source, target, targetStart, start, end) {\n  return toBuffer(source).copy(target, targetStart, start, end)\n}\n\nfunction equals (a, b) {\n  return toBuffer(a).equals(b)\n}\n\nfunction fill (buffer, value, offset, end, encoding) {\n  return toBuffer(buffer).fill(value, offset, end, encoding)\n}\n\nfunction from (value, encodingOrOffset, length) {\n  return Buffer.from(value, encodingOrOffset, length)\n}\n\nfunction includes (buffer, value, byteOffset, encoding) {\n  return toBuffer(buffer).includes(value, byteOffset, encoding)\n}\n\nfunction indexOf (buffer, value, byfeOffset, encoding) {\n  return toBuffer(buffer).indexOf(value, byfeOffset, encoding)\n}\n\nfunction lastIndexOf (buffer, value, byteOffset, encoding) {\n  return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding)\n}\n\nfunction swap16 (buffer) {\n  return toBuffer(buffer).swap16()\n}\n\nfunction swap32 (buffer) {\n  return toBuffer(buffer).swap32()\n}\n\nfunction swap64 (buffer) {\n  return toBuffer(buffer).swap64()\n}\n\nfunction toBuffer (buffer) {\n  if (Buffer.isBuffer(buffer)) return buffer\n  return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength)\n}\n\nfunction toString (buffer, encoding, start, end) {\n  return toBuffer(buffer).toString(encoding, start, end)\n}\n\nfunction write (buffer, string, offset, length, encoding) {\n  return toBuffer(buffer).write(string, offset, length, encoding)\n}\n\nfunction writeDoubleLE (buffer, value, offset) {\n  return toBuffer(buffer).writeDoubleLE(value, offset)\n}\n\nfunction writeFloatLE (buffer, value, offset) {\n  return toBuffer(buffer).writeFloatLE(value, offset)\n}\n\nfunction writeUInt32LE (buffer, value, offset) {\n  return toBuffer(buffer).writeUInt32LE(value, offset)\n}\n\nfunction writeInt32LE (buffer, value, offset) {\n  return toBuffer(buffer).writeInt32LE(value, offset)\n}\n\nfunction readDoubleLE (buffer, offset) {\n  return toBuffer(buffer).readDoubleLE(offset)\n}\n\nfunction readFloatLE (buffer, offset) {\n  return toBuffer(buffer).readFloatLE(offset)\n}\n\nfunction readUInt32LE (buffer, offset) {\n  return toBuffer(buffer).readUInt32LE(offset)\n}\n\nfunction readInt32LE (buffer, offset) {\n  return toBuffer(buffer).readInt32LE(offset)\n}\n\nfunction writeDoubleBE (buffer, value, offset) {\n  return toBuffer(buffer).writeDoubleBE(value, offset)\n}\n\nfunction writeFloatBE (buffer, value, offset) {\n  return toBuffer(buffer).writeFloatBE(value, offset)\n}\n\nfunction writeUInt32BE (buffer, value, offset) {\n  return toBuffer(buffer).writeUInt32BE(value, offset)\n}\n\nfunction writeInt32BE (buffer, value, offset) {\n  return toBuffer(buffer).writeInt32BE(value, offset)\n}\n\nfunction readDoubleBE (buffer, offset) {\n  return toBuffer(buffer).readDoubleBE(offset)\n}\n\nfunction readFloatBE (buffer, offset) {\n  return toBuffer(buffer).readFloatBE(offset)\n}\n\nfunction readUInt32BE (buffer, offset) {\n  return toBuffer(buffer).readUInt32BE(offset)\n}\n\nfunction readInt32BE (buffer, offset) {\n  return toBuffer(buffer).readInt32BE(offset)\n}\n\nmodule.exports = {\n  isBuffer,\n  isEncoding,\n  alloc,\n  allocUnsafe,\n  allocUnsafeSlow,\n  byteLength,\n  compare,\n  concat,\n  copy,\n  equals,\n  fill,\n  from,\n  includes,\n  indexOf,\n  lastIndexOf,\n  swap16,\n  swap32,\n  swap64,\n  toBuffer,\n  toString,\n  write,\n  writeDoubleLE,\n  writeFloatLE,\n  writeUInt32LE,\n  writeInt32LE,\n  readDoubleLE,\n  readFloatLE,\n  readUInt32LE,\n  readInt32LE,\n  writeDoubleBE,\n  writeFloatBE,\n  writeUInt32BE,\n  writeInt32BE,\n  readDoubleBE,\n  readFloatBE,\n  readUInt32BE,\n  readInt32BE\n\n}\n","const b4a = require('b4a')\n\nmodule.exports = class PassThroughDecoder {\n  constructor (encoding) {\n    this.encoding = encoding\n  }\n\n  get remaining () {\n    return 0\n  }\n\n  decode (tail) {\n    return b4a.toString(tail, this.encoding)\n  }\n\n  flush () {\n    return ''\n  }\n}\n","const b4a = require('b4a')\n\n/**\n * https://encoding.spec.whatwg.org/#utf-8-decoder\n */\nmodule.exports = class UTF8Decoder {\n  constructor () {\n    this.codePoint = 0\n    this.bytesSeen = 0\n    this.bytesNeeded = 0\n    this.lowerBoundary = 0x80\n    this.upperBoundary = 0xbf\n  }\n\n  get remaining () {\n    return this.bytesSeen\n  }\n\n  decode (data) {\n    // If we have a fast path, just sniff if the last part is a boundary\n    if (this.bytesNeeded === 0) {\n      let isBoundary = true\n\n      for (let i = Math.max(0, data.byteLength - 4), n = data.byteLength; i < n && isBoundary; i++) {\n        isBoundary = data[i] <= 0x7f\n      }\n\n      if (isBoundary) return b4a.toString(data, 'utf8')\n    }\n\n    let result = ''\n\n    for (let i = 0, n = data.byteLength; i < n; i++) {\n      const byte = data[i]\n\n      if (this.bytesNeeded === 0) {\n        if (byte <= 0x7f) {\n          result += String.fromCharCode(byte)\n        } else {\n          this.bytesSeen = 1\n\n          if (byte >= 0xc2 && byte <= 0xdf) {\n            this.bytesNeeded = 2\n            this.codePoint = byte & 0x1f\n          } else if (byte >= 0xe0 && byte <= 0xef) {\n            if (byte === 0xe0) this.lowerBoundary = 0xa0\n            else if (byte === 0xed) this.upperBoundary = 0x9f\n            this.bytesNeeded = 3\n            this.codePoint = byte & 0xf\n          } else if (byte >= 0xf0 && byte <= 0xf4) {\n            if (byte === 0xf0) this.lowerBoundary = 0x90\n            if (byte === 0xf4) this.upperBoundary = 0x8f\n            this.bytesNeeded = 4\n            this.codePoint = byte & 0x7\n          } else {\n            result += '\\ufffd'\n          }\n        }\n\n        continue\n      }\n\n      if (byte < this.lowerBoundary || byte > this.upperBoundary) {\n        this.codePoint = 0\n        this.bytesNeeded = 0\n        this.bytesSeen = 0\n        this.lowerBoundary = 0x80\n        this.upperBoundary = 0xbf\n\n        result += '\\ufffd'\n\n        continue\n      }\n\n      this.lowerBoundary = 0x80\n      this.upperBoundary = 0xbf\n\n      this.codePoint = (this.codePoint << 6) | (byte & 0x3f)\n      this.bytesSeen++\n\n      if (this.bytesSeen !== this.bytesNeeded) continue\n\n      result += String.fromCodePoint(this.codePoint)\n\n      this.codePoint = 0\n      this.bytesNeeded = 0\n      this.bytesSeen = 0\n    }\n\n    return result\n  }\n\n  flush () {\n    const result = this.bytesNeeded > 0 ? '\\ufffd' : ''\n\n    this.codePoint = 0\n    this.bytesNeeded = 0\n    this.bytesSeen = 0\n    this.lowerBoundary = 0x80\n    this.upperBoundary = 0xbf\n\n    return result\n  }\n}\n","const PassThroughDecoder = require('./lib/pass-through-decoder')\nconst UTF8Decoder = require('./lib/utf8-decoder')\n\nmodule.exports = class TextDecoder {\n  constructor (encoding = 'utf8') {\n    this.encoding = normalizeEncoding(encoding)\n\n    switch (this.encoding) {\n      case 'utf8':\n        this.decoder = new UTF8Decoder()\n        break\n      case 'utf16le':\n      case 'base64':\n        throw new Error('Unsupported encoding: ' + this.encoding)\n      default:\n        this.decoder = new PassThroughDecoder(this.encoding)\n    }\n  }\n\n  get remaining () {\n    return this.decoder.remaining\n  }\n\n  push (data) {\n    if (typeof data === 'string') return data\n    return this.decoder.decode(data)\n  }\n\n  // For Node.js compatibility\n  write (data) {\n    return this.push(data)\n  }\n\n  end (data) {\n    let result = ''\n    if (data) result = this.push(data)\n    result += this.decoder.flush()\n    return result\n  }\n}\n\nfunction normalizeEncoding (encoding) {\n  encoding = encoding.toLowerCase()\n\n  switch (encoding) {\n    case 'utf8':\n    case 'utf-8':\n      return 'utf8'\n    case 'ucs2':\n    case 'ucs-2':\n    case 'utf16le':\n    case 'utf-16le':\n      return 'utf16le'\n    case 'latin1':\n    case 'binary':\n      return 'latin1'\n    case 'base64':\n    case 'ascii':\n    case 'hex':\n      return encoding\n    default:\n      throw new Error('Unknown encoding: ' + encoding)\n  }\n};\n","const { EventEmitter } = require('events')\nconst STREAM_DESTROYED = new Error('Stream was destroyed')\nconst PREMATURE_CLOSE = new Error('Premature close')\n\nconst FIFO = require('fast-fifo')\nconst TextDecoder = require('text-decoder')\n\n/* eslint-disable no-multi-spaces */\n\n// 29 bits used total (4 from shared, 14 from read, and 11 from write)\nconst MAX = ((1 << 29) - 1)\n\n// Shared state\nconst OPENING       = 0b0001\nconst PREDESTROYING = 0b0010\nconst DESTROYING    = 0b0100\nconst DESTROYED     = 0b1000\n\nconst NOT_OPENING = MAX ^ OPENING\nconst NOT_PREDESTROYING = MAX ^ PREDESTROYING\n\n// Read state (4 bit offset from shared state)\nconst READ_ACTIVE           = 0b00000000000001 << 4\nconst READ_UPDATING         = 0b00000000000010 << 4\nconst READ_PRIMARY          = 0b00000000000100 << 4\nconst READ_QUEUED           = 0b00000000001000 << 4\nconst READ_RESUMED          = 0b00000000010000 << 4\nconst READ_PIPE_DRAINED     = 0b00000000100000 << 4\nconst READ_ENDING           = 0b00000001000000 << 4\nconst READ_EMIT_DATA        = 0b00000010000000 << 4\nconst READ_EMIT_READABLE    = 0b00000100000000 << 4\nconst READ_EMITTED_READABLE = 0b00001000000000 << 4\nconst READ_DONE             = 0b00010000000000 << 4\nconst READ_NEXT_TICK        = 0b00100000000000 << 4\nconst READ_NEEDS_PUSH       = 0b01000000000000 << 4\nconst READ_READ_AHEAD       = 0b10000000000000 << 4\n\n// Combined read state\nconst READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED\nconst READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH\nconst READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE\nconst READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED\nconst READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD\n\nconst READ_NOT_ACTIVE             = MAX ^ READ_ACTIVE\nconst READ_NON_PRIMARY            = MAX ^ READ_PRIMARY\nconst READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH)\nconst READ_PUSHED                 = MAX ^ READ_NEEDS_PUSH\nconst READ_PAUSED                 = MAX ^ READ_RESUMED\nconst READ_NOT_QUEUED             = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE)\nconst READ_NOT_ENDING             = MAX ^ READ_ENDING\nconst READ_PIPE_NOT_DRAINED       = MAX ^ READ_FLOWING\nconst READ_NOT_NEXT_TICK          = MAX ^ READ_NEXT_TICK\nconst READ_NOT_UPDATING           = MAX ^ READ_UPDATING\nconst READ_NO_READ_AHEAD          = MAX ^ READ_READ_AHEAD\nconst READ_PAUSED_NO_READ_AHEAD   = MAX ^ READ_RESUMED_READ_AHEAD\n\n// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state)\nconst WRITE_ACTIVE     = 0b00000000001 << 18\nconst WRITE_UPDATING   = 0b00000000010 << 18\nconst WRITE_PRIMARY    = 0b00000000100 << 18\nconst WRITE_QUEUED     = 0b00000001000 << 18\nconst WRITE_UNDRAINED  = 0b00000010000 << 18\nconst WRITE_DONE       = 0b00000100000 << 18\nconst WRITE_EMIT_DRAIN = 0b00001000000 << 18\nconst WRITE_NEXT_TICK  = 0b00010000000 << 18\nconst WRITE_WRITING    = 0b00100000000 << 18\nconst WRITE_FINISHING  = 0b01000000000 << 18\nconst WRITE_CORKED     = 0b10000000000 << 18\n\nconst WRITE_NOT_ACTIVE    = MAX ^ (WRITE_ACTIVE | WRITE_WRITING)\nconst WRITE_NON_PRIMARY   = MAX ^ WRITE_PRIMARY\nconst WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING)\nconst WRITE_DRAINED       = MAX ^ WRITE_UNDRAINED\nconst WRITE_NOT_QUEUED    = MAX ^ WRITE_QUEUED\nconst WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK\nconst WRITE_NOT_UPDATING  = MAX ^ WRITE_UPDATING\nconst WRITE_NOT_CORKED    = MAX ^ WRITE_CORKED\n\n// Combined shared state\nconst ACTIVE = READ_ACTIVE | WRITE_ACTIVE\nconst NOT_ACTIVE = MAX ^ ACTIVE\nconst DONE = READ_DONE | WRITE_DONE\nconst DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING\nconst OPEN_STATUS = DESTROY_STATUS | OPENING\nconst AUTO_DESTROY = DESTROY_STATUS | DONE\nconst NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY\nconst ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK\nconst TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE\nconst IS_OPENING = OPEN_STATUS | TICKING\n\n// Combined shared state and read state\nconst READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE\nconst READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED\nconst READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED\nconst READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE\nconst SHOULD_NOT_READ = OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD\nconst READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE\nconst READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY\nconst READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING\n\n// Combined write state\nconst WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE\nconst WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED\nconst WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE\nconst WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE\nconst WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED\nconst WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE\nconst WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING\nconst WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE\nconst WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE\nconst WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY\nconst WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS\n\nconst asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator')\n\nclass WritableState {\n  constructor (stream, { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}) {\n    this.stream = stream\n    this.queue = new FIFO()\n    this.highWaterMark = highWaterMark\n    this.buffered = 0\n    this.error = null\n    this.pipeline = null\n    this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr\n    this.byteLength = byteLengthWritable || byteLength || defaultByteLength\n    this.map = mapWritable || map\n    this.afterWrite = afterWrite.bind(this)\n    this.afterUpdateNextTick = updateWriteNT.bind(this)\n  }\n\n  get ended () {\n    return (this.stream._duplexState & WRITE_DONE) !== 0\n  }\n\n  push (data) {\n    if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false\n    if (this.map !== null) data = this.map(data)\n\n    this.buffered += this.byteLength(data)\n    this.queue.push(data)\n\n    if (this.buffered < this.highWaterMark) {\n      this.stream._duplexState |= WRITE_QUEUED\n      return true\n    }\n\n    this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED\n    return false\n  }\n\n  shift () {\n    const data = this.queue.shift()\n\n    this.buffered -= this.byteLength(data)\n    if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED\n\n    return data\n  }\n\n  end (data) {\n    if (typeof data === 'function') this.stream.once('finish', data)\n    else if (data !== undefined && data !== null) this.push(data)\n    this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY\n  }\n\n  autoBatch (data, cb) {\n    const buffer = []\n    const stream = this.stream\n\n    buffer.push(data)\n    while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) {\n      buffer.push(stream._writableState.shift())\n    }\n\n    if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null)\n    stream._writev(buffer, cb)\n  }\n\n  update () {\n    const stream = this.stream\n\n    stream._duplexState |= WRITE_UPDATING\n\n    do {\n      while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) {\n        const data = this.shift()\n        stream._duplexState |= WRITE_ACTIVE_AND_WRITING\n        stream._write(data, this.afterWrite)\n      }\n\n      if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()\n    } while (this.continueUpdate() === true)\n\n    stream._duplexState &= WRITE_NOT_UPDATING\n  }\n\n  updateNonPrimary () {\n    const stream = this.stream\n\n    if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) {\n      stream._duplexState = stream._duplexState | WRITE_ACTIVE\n      stream._final(afterFinal.bind(this))\n      return\n    }\n\n    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {\n      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {\n        stream._duplexState |= ACTIVE\n        stream._destroy(afterDestroy.bind(this))\n      }\n      return\n    }\n\n    if ((stream._duplexState & IS_OPENING) === OPENING) {\n      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING\n      stream._open(afterOpen.bind(this))\n    }\n  }\n\n  continueUpdate () {\n    if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false\n    this.stream._duplexState &= WRITE_NOT_NEXT_TICK\n    return true\n  }\n\n  updateCallback () {\n    if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) this.update()\n    else this.updateNextTick()\n  }\n\n  updateNextTick () {\n    if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return\n    this.stream._duplexState |= WRITE_NEXT_TICK\n    if ((this.stream._duplexState & WRITE_UPDATING) === 0) queueMicrotask(this.afterUpdateNextTick)\n  }\n}\n\nclass ReadableState {\n  constructor (stream, { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}) {\n    this.stream = stream\n    this.queue = new FIFO()\n    this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark\n    this.buffered = 0\n    this.readAhead = highWaterMark > 0\n    this.error = null\n    this.pipeline = null\n    this.byteLength = byteLengthReadable || byteLength || defaultByteLength\n    this.map = mapReadable || map\n    this.pipeTo = null\n    this.afterRead = afterRead.bind(this)\n    this.afterUpdateNextTick = updateReadNT.bind(this)\n  }\n\n  get ended () {\n    return (this.stream._duplexState & READ_DONE) !== 0\n  }\n\n  pipe (pipeTo, cb) {\n    if (this.pipeTo !== null) throw new Error('Can only pipe to one destination')\n    if (typeof cb !== 'function') cb = null\n\n    this.stream._duplexState |= READ_PIPE_DRAINED\n    this.pipeTo = pipeTo\n    this.pipeline = new Pipeline(this.stream, pipeTo, cb)\n\n    if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes\n\n    if (isStreamx(pipeTo)) {\n      pipeTo._writableState.pipeline = this.pipeline\n      if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes\n      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself\n    } else {\n      const onerror = this.pipeline.done.bind(this.pipeline, pipeTo)\n      const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg\n      pipeTo.on('error', onerror)\n      pipeTo.on('close', onclose)\n      pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline))\n    }\n\n    pipeTo.on('drain', afterDrain.bind(this))\n    this.stream.emit('piping', pipeTo)\n    pipeTo.emit('pipe', this.stream)\n  }\n\n  push (data) {\n    const stream = this.stream\n\n    if (data === null) {\n      this.highWaterMark = 0\n      stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED\n      return false\n    }\n\n    if (this.map !== null) {\n      data = this.map(data)\n      if (data === null) {\n        stream._duplexState &= READ_PUSHED\n        return this.buffered < this.highWaterMark\n      }\n    }\n\n    this.buffered += this.byteLength(data)\n    this.queue.push(data)\n\n    stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED\n\n    return this.buffered < this.highWaterMark\n  }\n\n  shift () {\n    const data = this.queue.shift()\n\n    this.buffered -= this.byteLength(data)\n    if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED\n    return data\n  }\n\n  unshift (data) {\n    const pending = [this.map !== null ? this.map(data) : data]\n    while (this.buffered > 0) pending.push(this.shift())\n\n    for (let i = 0; i < pending.length - 1; i++) {\n      const data = pending[i]\n      this.buffered += this.byteLength(data)\n      this.queue.push(data)\n    }\n\n    this.push(pending[pending.length - 1])\n  }\n\n  read () {\n    const stream = this.stream\n\n    if ((stream._duplexState & READ_STATUS) === READ_QUEUED) {\n      const data = this.shift()\n      if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream._duplexState &= READ_PIPE_NOT_DRAINED\n      if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit('data', data)\n      return data\n    }\n\n    if (this.readAhead === false) {\n      stream._duplexState |= READ_READ_AHEAD\n      this.updateNextTick()\n    }\n\n    return null\n  }\n\n  drain () {\n    const stream = this.stream\n\n    while ((stream._duplexState & READ_STATUS) === READ_QUEUED && (stream._duplexState & READ_FLOWING) !== 0) {\n      const data = this.shift()\n      if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream._duplexState &= READ_PIPE_NOT_DRAINED\n      if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit('data', data)\n    }\n  }\n\n  update () {\n    const stream = this.stream\n\n    stream._duplexState |= READ_UPDATING\n\n    do {\n      this.drain()\n\n      while (this.buffered < this.highWaterMark && (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD) {\n        stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH\n        stream._read(this.afterRead)\n        this.drain()\n      }\n\n      if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) {\n        stream._duplexState |= READ_EMITTED_READABLE\n        stream.emit('readable')\n      }\n\n      if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary()\n    } while (this.continueUpdate() === true)\n\n    stream._duplexState &= READ_NOT_UPDATING\n  }\n\n  updateNonPrimary () {\n    const stream = this.stream\n\n    if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) {\n      stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING\n      stream.emit('end')\n      if ((stream._duplexState & AUTO_DESTROY) === DONE) stream._duplexState |= DESTROYING\n      if (this.pipeTo !== null) this.pipeTo.end()\n    }\n\n    if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) {\n      if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) {\n        stream._duplexState |= ACTIVE\n        stream._destroy(afterDestroy.bind(this))\n      }\n      return\n    }\n\n    if ((stream._duplexState & IS_OPENING) === OPENING) {\n      stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING\n      stream._open(afterOpen.bind(this))\n    }\n  }\n\n  continueUpdate () {\n    if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false\n    this.stream._duplexState &= READ_NOT_NEXT_TICK\n    return true\n  }\n\n  updateCallback () {\n    if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) this.update()\n    else this.updateNextTick()\n  }\n\n  updateNextTickIfOpen () {\n    if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return\n    this.stream._duplexState |= READ_NEXT_TICK\n    if ((this.stream._duplexState & READ_UPDATING) === 0) queueMicrotask(this.afterUpdateNextTick)\n  }\n\n  updateNextTick () {\n    if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return\n    this.stream._duplexState |= READ_NEXT_TICK\n    if ((this.stream._duplexState & READ_UPDATING) === 0) queueMicrotask(this.afterUpdateNextTick)\n  }\n}\n\nclass TransformState {\n  constructor (stream) {\n    this.data = null\n    this.afterTransform = afterTransform.bind(stream)\n    this.afterFinal = null\n  }\n}\n\nclass Pipeline {\n  constructor (src, dst, cb) {\n    this.from = src\n    this.to = dst\n    this.afterPipe = cb\n    this.error = null\n    this.pipeToFinished = false\n  }\n\n  finished () {\n    this.pipeToFinished = true\n  }\n\n  done (stream, err) {\n    if (err) this.error = err\n\n    if (stream === this.to) {\n      this.to = null\n\n      if (this.from !== null) {\n        if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) {\n          this.from.destroy(this.error || new Error('Writable stream closed prematurely'))\n        }\n        return\n      }\n    }\n\n    if (stream === this.from) {\n      this.from = null\n\n      if (this.to !== null) {\n        if ((stream._duplexState & READ_DONE) === 0) {\n          this.to.destroy(this.error || new Error('Readable stream closed before ending'))\n        }\n        return\n      }\n    }\n\n    if (this.afterPipe !== null) this.afterPipe(this.error)\n    this.to = this.from = this.afterPipe = null\n  }\n}\n\nfunction afterDrain () {\n  this.stream._duplexState |= READ_PIPE_DRAINED\n  this.updateCallback()\n}\n\nfunction afterFinal (err) {\n  const stream = this.stream\n  if (err) stream.destroy(err)\n  if ((stream._duplexState & DESTROY_STATUS) === 0) {\n    stream._duplexState |= WRITE_DONE\n    stream.emit('finish')\n  }\n  if ((stream._duplexState & AUTO_DESTROY) === DONE) {\n    stream._duplexState |= DESTROYING\n  }\n\n  stream._duplexState &= WRITE_NOT_FINISHING\n\n  // no need to wait the extra tick here, so we short circuit that\n  if ((stream._duplexState & WRITE_UPDATING) === 0) this.update()\n  else this.updateNextTick()\n}\n\nfunction afterDestroy (err) {\n  const stream = this.stream\n\n  if (!err && this.error !== STREAM_DESTROYED) err = this.error\n  if (err) stream.emit('error', err)\n  stream._duplexState |= DESTROYED\n  stream.emit('close')\n\n  const rs = stream._readableState\n  const ws = stream._writableState\n\n  if (rs !== null && rs.pipeline !== null) rs.pipeline.done(stream, err)\n\n  if (ws !== null) {\n    while (ws.drains !== null && ws.drains.length > 0) ws.drains.shift().resolve(false)\n    if (ws.pipeline !== null) ws.pipeline.done(stream, err)\n  }\n}\n\nfunction afterWrite (err) {\n  const stream = this.stream\n\n  if (err) stream.destroy(err)\n  stream._duplexState &= WRITE_NOT_ACTIVE\n\n  if (this.drains !== null) tickDrains(this.drains)\n\n  if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) {\n    stream._duplexState &= WRITE_DRAINED\n    if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) {\n      stream.emit('drain')\n    }\n  }\n\n  this.updateCallback()\n}\n\nfunction afterRead (err) {\n  if (err) this.stream.destroy(err)\n  this.stream._duplexState &= READ_NOT_ACTIVE\n  if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) this.stream._duplexState &= READ_NO_READ_AHEAD\n  this.updateCallback()\n}\n\nfunction updateReadNT () {\n  if ((this.stream._duplexState & READ_UPDATING) === 0) {\n    this.stream._duplexState &= READ_NOT_NEXT_TICK\n    this.update()\n  }\n}\n\nfunction updateWriteNT () {\n  if ((this.stream._duplexState & WRITE_UPDATING) === 0) {\n    this.stream._duplexState &= WRITE_NOT_NEXT_TICK\n    this.update()\n  }\n}\n\nfunction tickDrains (drains) {\n  for (let i = 0; i < drains.length; i++) {\n    // drains.writes are monotonic, so if one is 0 its always the first one\n    if (--drains[i].writes === 0) {\n      drains.shift().resolve(true)\n      i--\n    }\n  }\n}\n\nfunction afterOpen (err) {\n  const stream = this.stream\n\n  if (err) stream.destroy(err)\n\n  if ((stream._duplexState & DESTROYING) === 0) {\n    if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) stream._duplexState |= READ_PRIMARY\n    if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) stream._duplexState |= WRITE_PRIMARY\n    stream.emit('open')\n  }\n\n  stream._duplexState &= NOT_ACTIVE\n\n  if (stream._writableState !== null) {\n    stream._writableState.updateCallback()\n  }\n\n  if (stream._readableState !== null) {\n    stream._readableState.updateCallback()\n  }\n}\n\nfunction afterTransform (err, data) {\n  if (data !== undefined && data !== null) this.push(data)\n  this._writableState.afterWrite(err)\n}\n\nfunction newListener (name) {\n  if (this._readableState !== null) {\n    if (name === 'data') {\n      this._duplexState |= (READ_EMIT_DATA | READ_RESUMED_READ_AHEAD)\n      this._readableState.updateNextTick()\n    }\n    if (name === 'readable') {\n      this._duplexState |= READ_EMIT_READABLE\n      this._readableState.updateNextTick()\n    }\n  }\n\n  if (this._writableState !== null) {\n    if (name === 'drain') {\n      this._duplexState |= WRITE_EMIT_DRAIN\n      this._writableState.updateNextTick()\n    }\n  }\n}\n\nclass Stream extends EventEmitter {\n  constructor (opts) {\n    super()\n\n    this._duplexState = 0\n    this._readableState = null\n    this._writableState = null\n\n    if (opts) {\n      if (opts.open) this._open = opts.open\n      if (opts.destroy) this._destroy = opts.destroy\n      if (opts.predestroy) this._predestroy = opts.predestroy\n      if (opts.signal) {\n        opts.signal.addEventListener('abort', abort.bind(this))\n      }\n    }\n\n    this.on('newListener', newListener)\n  }\n\n  _open (cb) {\n    cb(null)\n  }\n\n  _destroy (cb) {\n    cb(null)\n  }\n\n  _predestroy () {\n    // does nothing\n  }\n\n  get readable () {\n    return this._readableState !== null ? true : undefined\n  }\n\n  get writable () {\n    return this._writableState !== null ? true : undefined\n  }\n\n  get destroyed () {\n    return (this._duplexState & DESTROYED) !== 0\n  }\n\n  get destroying () {\n    return (this._duplexState & DESTROY_STATUS) !== 0\n  }\n\n  destroy (err) {\n    if ((this._duplexState & DESTROY_STATUS) === 0) {\n      if (!err) err = STREAM_DESTROYED\n      this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY\n\n      if (this._readableState !== null) {\n        this._readableState.highWaterMark = 0\n        this._readableState.error = err\n      }\n      if (this._writableState !== null) {\n        this._writableState.highWaterMark = 0\n        this._writableState.error = err\n      }\n\n      this._duplexState |= PREDESTROYING\n      this._predestroy()\n      this._duplexState &= NOT_PREDESTROYING\n\n      if (this._readableState !== null) this._readableState.updateNextTick()\n      if (this._writableState !== null) this._writableState.updateNextTick()\n    }\n  }\n}\n\nclass Readable extends Stream {\n  constructor (opts) {\n    super(opts)\n\n    this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD\n    this._readableState = new ReadableState(this, opts)\n\n    if (opts) {\n      if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD\n      if (opts.read) this._read = opts.read\n      if (opts.eagerOpen) this._readableState.updateNextTick()\n      if (opts.encoding) this.setEncoding(opts.encoding)\n    }\n  }\n\n  setEncoding (encoding) {\n    const dec = new TextDecoder(encoding)\n    const map = this._readableState.map || echo\n    this._readableState.map = mapOrSkip\n    return this\n\n    function mapOrSkip (data) {\n      const next = dec.push(data)\n      return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next)\n    }\n  }\n\n  _read (cb) {\n    cb(null)\n  }\n\n  pipe (dest, cb) {\n    this._readableState.updateNextTick()\n    this._readableState.pipe(dest, cb)\n    return dest\n  }\n\n  read () {\n    this._readableState.updateNextTick()\n    return this._readableState.read()\n  }\n\n  push (data) {\n    this._readableState.updateNextTickIfOpen()\n    return this._readableState.push(data)\n  }\n\n  unshift (data) {\n    this._readableState.updateNextTickIfOpen()\n    return this._readableState.unshift(data)\n  }\n\n  resume () {\n    this._duplexState |= READ_RESUMED_READ_AHEAD\n    this._readableState.updateNextTick()\n    return this\n  }\n\n  pause () {\n    this._duplexState &= (this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED)\n    return this\n  }\n\n  static _fromAsyncIterator (ite, opts) {\n    let destroy\n\n    const rs = new Readable({\n      ...opts,\n      read (cb) {\n        ite.next().then(push).then(cb.bind(null, null)).catch(cb)\n      },\n      predestroy () {\n        destroy = ite.return()\n      },\n      destroy (cb) {\n        if (!destroy) return cb(null)\n        destroy.then(cb.bind(null, null)).catch(cb)\n      }\n    })\n\n    return rs\n\n    function push (data) {\n      if (data.done) rs.push(null)\n      else rs.push(data.value)\n    }\n  }\n\n  static from (data, opts) {\n    if (isReadStreamx(data)) return data\n    if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts)\n    if (!Array.isArray(data)) data = data === undefined ? [] : [data]\n\n    let i = 0\n    return new Readable({\n      ...opts,\n      read (cb) {\n        this.push(i === data.length ? null : data[i++])\n        cb(null)\n      }\n    })\n  }\n\n  static isBackpressured (rs) {\n    return (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 || rs._readableState.buffered >= rs._readableState.highWaterMark\n  }\n\n  static isPaused (rs) {\n    return (rs._duplexState & READ_RESUMED) === 0\n  }\n\n  [asyncIterator] () {\n    const stream = this\n\n    let error = null\n    let promiseResolve = null\n    let promiseReject = null\n\n    this.on('error', (err) => { error = err })\n    this.on('readable', onreadable)\n    this.on('close', onclose)\n\n    return {\n      [asyncIterator] () {\n        return this\n      },\n      next () {\n        return new Promise(function (resolve, reject) {\n          promiseResolve = resolve\n          promiseReject = reject\n          const data = stream.read()\n          if (data !== null) ondata(data)\n          else if ((stream._duplexState & DESTROYED) !== 0) ondata(null)\n        })\n      },\n      return () {\n        return destroy(null)\n      },\n      throw (err) {\n        return destroy(err)\n      }\n    }\n\n    function onreadable () {\n      if (promiseResolve !== null) ondata(stream.read())\n    }\n\n    function onclose () {\n      if (promiseResolve !== null) ondata(null)\n    }\n\n    function ondata (data) {\n      if (promiseReject === null) return\n      if (error) promiseReject(error)\n      else if (data === null && (stream._duplexState & READ_DONE) === 0) promiseReject(STREAM_DESTROYED)\n      else promiseResolve({ value: data, done: data === null })\n      promiseReject = promiseResolve = null\n    }\n\n    function destroy (err) {\n      stream.destroy(err)\n      return new Promise((resolve, reject) => {\n        if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true })\n        stream.once('close', function () {\n          if (err) reject(err)\n          else resolve({ value: undefined, done: true })\n        })\n      })\n    }\n  }\n}\n\nclass Writable extends Stream {\n  constructor (opts) {\n    super(opts)\n\n    this._duplexState |= OPENING | READ_DONE\n    this._writableState = new WritableState(this, opts)\n\n    if (opts) {\n      if (opts.writev) this._writev = opts.writev\n      if (opts.write) this._write = opts.write\n      if (opts.final) this._final = opts.final\n      if (opts.eagerOpen) this._writableState.updateNextTick()\n    }\n  }\n\n  cork () {\n    this._duplexState |= WRITE_CORKED\n  }\n\n  uncork () {\n    this._duplexState &= WRITE_NOT_CORKED\n    this._writableState.updateNextTick()\n  }\n\n  _writev (batch, cb) {\n    cb(null)\n  }\n\n  _write (data, cb) {\n    this._writableState.autoBatch(data, cb)\n  }\n\n  _final (cb) {\n    cb(null)\n  }\n\n  static isBackpressured (ws) {\n    return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0\n  }\n\n  static drained (ws) {\n    if (ws.destroyed) return Promise.resolve(false)\n    const state = ws._writableState\n    const pending = (isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length)\n    const writes = pending + ((ws._duplexState & WRITE_WRITING) ? 1 : 0)\n    if (writes === 0) return Promise.resolve(true)\n    if (state.drains === null) state.drains = []\n    return new Promise((resolve) => {\n      state.drains.push({ writes, resolve })\n    })\n  }\n\n  write (data) {\n    this._writableState.updateNextTick()\n    return this._writableState.push(data)\n  }\n\n  end (data) {\n    this._writableState.updateNextTick()\n    this._writableState.end(data)\n    return this\n  }\n}\n\nclass Duplex extends Readable { // and Writable\n  constructor (opts) {\n    super(opts)\n\n    this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD)\n    this._writableState = new WritableState(this, opts)\n\n    if (opts) {\n      if (opts.writev) this._writev = opts.writev\n      if (opts.write) this._write = opts.write\n      if (opts.final) this._final = opts.final\n    }\n  }\n\n  cork () {\n    this._duplexState |= WRITE_CORKED\n  }\n\n  uncork () {\n    this._duplexState &= WRITE_NOT_CORKED\n    this._writableState.updateNextTick()\n  }\n\n  _writev (batch, cb) {\n    cb(null)\n  }\n\n  _write (data, cb) {\n    this._writableState.autoBatch(data, cb)\n  }\n\n  _final (cb) {\n    cb(null)\n  }\n\n  write (data) {\n    this._writableState.updateNextTick()\n    return this._writableState.push(data)\n  }\n\n  end (data) {\n    this._writableState.updateNextTick()\n    this._writableState.end(data)\n    return this\n  }\n}\n\nclass Transform extends Duplex {\n  constructor (opts) {\n    super(opts)\n    this._transformState = new TransformState(this)\n\n    if (opts) {\n      if (opts.transform) this._transform = opts.transform\n      if (opts.flush) this._flush = opts.flush\n    }\n  }\n\n  _write (data, cb) {\n    if (this._readableState.buffered >= this._readableState.highWaterMark) {\n      this._transformState.data = data\n    } else {\n      this._transform(data, this._transformState.afterTransform)\n    }\n  }\n\n  _read (cb) {\n    if (this._transformState.data !== null) {\n      const data = this._transformState.data\n      this._transformState.data = null\n      cb(null)\n      this._transform(data, this._transformState.afterTransform)\n    } else {\n      cb(null)\n    }\n  }\n\n  destroy (err) {\n    super.destroy(err)\n    if (this._transformState.data !== null) {\n      this._transformState.data = null\n      this._transformState.afterTransform()\n    }\n  }\n\n  _transform (data, cb) {\n    cb(null, data)\n  }\n\n  _flush (cb) {\n    cb(null)\n  }\n\n  _final (cb) {\n    this._transformState.afterFinal = cb\n    this._flush(transformAfterFlush.bind(this))\n  }\n}\n\nclass PassThrough extends Transform {}\n\nfunction transformAfterFlush (err, data) {\n  const cb = this._transformState.afterFinal\n  if (err) return cb(err)\n  if (data !== null && data !== undefined) this.push(data)\n  this.push(null)\n  cb(null)\n}\n\nfunction pipelinePromise (...streams) {\n  return new Promise((resolve, reject) => {\n    return pipeline(...streams, (err) => {\n      if (err) return reject(err)\n      resolve()\n    })\n  })\n}\n\nfunction pipeline (stream, ...streams) {\n  const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]\n  const done = (all.length && typeof all[all.length - 1] === 'function') ? all.pop() : null\n\n  if (all.length < 2) throw new Error('Pipeline requires at least 2 streams')\n\n  let src = all[0]\n  let dest = null\n  let error = null\n\n  for (let i = 1; i < all.length; i++) {\n    dest = all[i]\n\n    if (isStreamx(src)) {\n      src.pipe(dest, onerror)\n    } else {\n      errorHandle(src, true, i > 1, onerror)\n      src.pipe(dest)\n    }\n\n    src = dest\n  }\n\n  if (done) {\n    let fin = false\n\n    const autoDestroy = isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy)\n\n    dest.on('error', (err) => {\n      if (error === null) error = err\n    })\n\n    dest.on('finish', () => {\n      fin = true\n      if (!autoDestroy) done(error)\n    })\n\n    if (autoDestroy) {\n      dest.on('close', () => done(error || (fin ? null : PREMATURE_CLOSE)))\n    }\n  }\n\n  return dest\n\n  function errorHandle (s, rd, wr, onerror) {\n    s.on('error', onerror)\n    s.on('close', onclose)\n\n    function onclose () {\n      if (rd && s._readableState && !s._readableState.ended) return onerror(PREMATURE_CLOSE)\n      if (wr && s._writableState && !s._writableState.ended) return onerror(PREMATURE_CLOSE)\n    }\n  }\n\n  function onerror (err) {\n    if (!err || error) return\n    error = err\n\n    for (const s of all) {\n      s.destroy(err)\n    }\n  }\n}\n\nfunction echo (s) {\n  return s\n}\n\nfunction isStream (stream) {\n  return !!stream._readableState || !!stream._writableState\n}\n\nfunction isStreamx (stream) {\n  return typeof stream._duplexState === 'number' && isStream(stream)\n}\n\nfunction isEnded (stream) {\n  return !!stream._readableState && stream._readableState.ended\n}\n\nfunction isFinished (stream) {\n  return !!stream._writableState && stream._writableState.ended\n}\n\nfunction getStreamError (stream, opts = {}) {\n  const err = (stream._readableState && stream._readableState.error) || (stream._writableState && stream._writableState.error)\n\n  // avoid implicit errors by default\n  return (!opts.all && err === STREAM_DESTROYED) ? null : err\n}\n\nfunction isReadStreamx (stream) {\n  return isStreamx(stream) && stream.readable\n}\n\nfunction isDisturbed (stream) {\n  return (stream._duplexState & OPENING) !== OPENING || (stream._duplexState & ACTIVE_OR_TICKING) !== 0\n}\n\nfunction isTypedArray (data) {\n  return typeof data === 'object' && data !== null && typeof data.byteLength === 'number'\n}\n\nfunction defaultByteLength (data) {\n  return isTypedArray(data) ? data.byteLength : 1024\n}\n\nfunction noop () {}\n\nfunction abort () {\n  this.destroy(new Error('Stream aborted.'))\n}\n\nfunction isWritev (s) {\n  return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev\n}\n\nmodule.exports = {\n  pipeline,\n  pipelinePromise,\n  isStream,\n  isStreamx,\n  isEnded,\n  isFinished,\n  isDisturbed,\n  getStreamError,\n  Stream,\n  Writable,\n  Readable,\n  Duplex,\n  Transform,\n  // Export PassThrough for compatibility with Node.js core's stream module\n  PassThrough\n}\n","const b4a = require('b4a')\n\nconst ZEROS = '0000000000000000000'\nconst SEVENS = '7777777777777777777'\nconst ZERO_OFFSET = '0'.charCodeAt(0)\nconst USTAR_MAGIC = b4a.from([0x75, 0x73, 0x74, 0x61, 0x72, 0x00]) // ustar\\x00\nconst USTAR_VER = b4a.from([ZERO_OFFSET, ZERO_OFFSET])\nconst GNU_MAGIC = b4a.from([0x75, 0x73, 0x74, 0x61, 0x72, 0x20]) // ustar\\x20\nconst GNU_VER = b4a.from([0x20, 0x00])\nconst MASK = 0o7777\nconst MAGIC_OFFSET = 257\nconst VERSION_OFFSET = 263\n\nexports.decodeLongPath = function decodeLongPath (buf, encoding) {\n  return decodeStr(buf, 0, buf.length, encoding)\n}\n\nexports.encodePax = function encodePax (opts) { // TODO: encode more stuff in pax\n  let result = ''\n  if (opts.name) result += addLength(' path=' + opts.name + '\\n')\n  if (opts.linkname) result += addLength(' linkpath=' + opts.linkname + '\\n')\n  const pax = opts.pax\n  if (pax) {\n    for (const key in pax) {\n      result += addLength(' ' + key + '=' + pax[key] + '\\n')\n    }\n  }\n  return b4a.from(result)\n}\n\nexports.decodePax = function decodePax (buf) {\n  const result = {}\n\n  while (buf.length) {\n    let i = 0\n    while (i < buf.length && buf[i] !== 32) i++\n    const len = parseInt(b4a.toString(buf.subarray(0, i)), 10)\n    if (!len) return result\n\n    const b = b4a.toString(buf.subarray(i + 1, len - 1))\n    const keyIndex = b.indexOf('=')\n    if (keyIndex === -1) return result\n    result[b.slice(0, keyIndex)] = b.slice(keyIndex + 1)\n\n    buf = buf.subarray(len)\n  }\n\n  return result\n}\n\nexports.encode = function encode (opts) {\n  const buf = b4a.alloc(512)\n  let name = opts.name\n  let prefix = ''\n\n  if (opts.typeflag === 5 && name[name.length - 1] !== '/') name += '/'\n  if (b4a.byteLength(name) !== name.length) return null // utf-8\n\n  while (b4a.byteLength(name) > 100) {\n    const i = name.indexOf('/')\n    if (i === -1) return null\n    prefix += prefix ? '/' + name.slice(0, i) : name.slice(0, i)\n    name = name.slice(i + 1)\n  }\n\n  if (b4a.byteLength(name) > 100 || b4a.byteLength(prefix) > 155) return null\n  if (opts.linkname && b4a.byteLength(opts.linkname) > 100) return null\n\n  b4a.write(buf, name)\n  b4a.write(buf, encodeOct(opts.mode & MASK, 6), 100)\n  b4a.write(buf, encodeOct(opts.uid, 6), 108)\n  b4a.write(buf, encodeOct(opts.gid, 6), 116)\n  encodeSize(opts.size, buf, 124)\n  b4a.write(buf, encodeOct((opts.mtime.getTime() / 1000) | 0, 11), 136)\n\n  buf[156] = ZERO_OFFSET + toTypeflag(opts.type)\n\n  if (opts.linkname) b4a.write(buf, opts.linkname, 157)\n\n  b4a.copy(USTAR_MAGIC, buf, MAGIC_OFFSET)\n  b4a.copy(USTAR_VER, buf, VERSION_OFFSET)\n  if (opts.uname) b4a.write(buf, opts.uname, 265)\n  if (opts.gname) b4a.write(buf, opts.gname, 297)\n  b4a.write(buf, encodeOct(opts.devmajor || 0, 6), 329)\n  b4a.write(buf, encodeOct(opts.devminor || 0, 6), 337)\n\n  if (prefix) b4a.write(buf, prefix, 345)\n\n  b4a.write(buf, encodeOct(cksum(buf), 6), 148)\n\n  return buf\n}\n\nexports.decode = function decode (buf, filenameEncoding, allowUnknownFormat) {\n  let typeflag = buf[156] === 0 ? 0 : buf[156] - ZERO_OFFSET\n\n  let name = decodeStr(buf, 0, 100, filenameEncoding)\n  const mode = decodeOct(buf, 100, 8)\n  const uid = decodeOct(buf, 108, 8)\n  const gid = decodeOct(buf, 116, 8)\n  const size = decodeOct(buf, 124, 12)\n  const mtime = decodeOct(buf, 136, 12)\n  const type = toType(typeflag)\n  const linkname = buf[157] === 0 ? null : decodeStr(buf, 157, 100, filenameEncoding)\n  const uname = decodeStr(buf, 265, 32)\n  const gname = decodeStr(buf, 297, 32)\n  const devmajor = decodeOct(buf, 329, 8)\n  const devminor = decodeOct(buf, 337, 8)\n\n  const c = cksum(buf)\n\n  // checksum is still initial value if header was null.\n  if (c === 8 * 32) return null\n\n  // valid checksum\n  if (c !== decodeOct(buf, 148, 8)) throw new Error('Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?')\n\n  if (isUSTAR(buf)) {\n    // ustar (posix) format.\n    // prepend prefix, if present.\n    if (buf[345]) name = decodeStr(buf, 345, 155, filenameEncoding) + '/' + name\n  } else if (isGNU(buf)) {\n    // 'gnu'/'oldgnu' format. Similar to ustar, but has support for incremental and\n    // multi-volume tarballs.\n  } else {\n    if (!allowUnknownFormat) {\n      throw new Error('Invalid tar header: unknown format.')\n    }\n  }\n\n  // to support old tar versions that use trailing / to indicate dirs\n  if (typeflag === 0 && name && name[name.length - 1] === '/') typeflag = 5\n\n  return {\n    name,\n    mode,\n    uid,\n    gid,\n    size,\n    mtime: new Date(1000 * mtime),\n    type,\n    linkname,\n    uname,\n    gname,\n    devmajor,\n    devminor,\n    pax: null\n  }\n}\n\nfunction isUSTAR (buf) {\n  return b4a.equals(USTAR_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6))\n}\n\nfunction isGNU (buf) {\n  return b4a.equals(GNU_MAGIC, buf.subarray(MAGIC_OFFSET, MAGIC_OFFSET + 6)) &&\n    b4a.equals(GNU_VER, buf.subarray(VERSION_OFFSET, VERSION_OFFSET + 2))\n}\n\nfunction clamp (index, len, defaultValue) {\n  if (typeof index !== 'number') return defaultValue\n  index = ~~index // Coerce to integer.\n  if (index >= len) return len\n  if (index >= 0) return index\n  index += len\n  if (index >= 0) return index\n  return 0\n}\n\nfunction toType (flag) {\n  switch (flag) {\n    case 0:\n      return 'file'\n    case 1:\n      return 'link'\n    case 2:\n      return 'symlink'\n    case 3:\n      return 'character-device'\n    case 4:\n      return 'block-device'\n    case 5:\n      return 'directory'\n    case 6:\n      return 'fifo'\n    case 7:\n      return 'contiguous-file'\n    case 72:\n      return 'pax-header'\n    case 55:\n      return 'pax-global-header'\n    case 27:\n      return 'gnu-long-link-path'\n    case 28:\n    case 30:\n      return 'gnu-long-path'\n  }\n\n  return null\n}\n\nfunction toTypeflag (flag) {\n  switch (flag) {\n    case 'file':\n      return 0\n    case 'link':\n      return 1\n    case 'symlink':\n      return 2\n    case 'character-device':\n      return 3\n    case 'block-device':\n      return 4\n    case 'directory':\n      return 5\n    case 'fifo':\n      return 6\n    case 'contiguous-file':\n      return 7\n    case 'pax-header':\n      return 72\n  }\n\n  return 0\n}\n\nfunction indexOf (block, num, offset, end) {\n  for (; offset < end; offset++) {\n    if (block[offset] === num) return offset\n  }\n  return end\n}\n\nfunction cksum (block) {\n  let sum = 8 * 32\n  for (let i = 0; i < 148; i++) sum += block[i]\n  for (let j = 156; j < 512; j++) sum += block[j]\n  return sum\n}\n\nfunction encodeOct (val, n) {\n  val = val.toString(8)\n  if (val.length > n) return SEVENS.slice(0, n) + ' '\n  return ZEROS.slice(0, n - val.length) + val + ' '\n}\n\nfunction encodeSizeBin (num, buf, off) {\n  buf[off] = 0x80\n  for (let i = 11; i > 0; i--) {\n    buf[off + i] = num & 0xff\n    num = Math.floor(num / 0x100)\n  }\n}\n\nfunction encodeSize (num, buf, off) {\n  if (num.toString(8).length > 11) {\n    encodeSizeBin(num, buf, off)\n  } else {\n    b4a.write(buf, encodeOct(num, 11), off)\n  }\n}\n\n/* Copied from the node-tar repo and modified to meet\n * tar-stream coding standard.\n *\n * Source: https://github.com/npm/node-tar/blob/51b6627a1f357d2eb433e7378e5f05e83b7aa6cd/lib/header.js#L349\n */\nfunction parse256 (buf) {\n  // first byte MUST be either 80 or FF\n  // 80 for positive, FF for 2's comp\n  let positive\n  if (buf[0] === 0x80) positive = true\n  else if (buf[0] === 0xFF) positive = false\n  else return null\n\n  // build up a base-256 tuple from the least sig to the highest\n  const tuple = []\n  let i\n  for (i = buf.length - 1; i > 0; i--) {\n    const byte = buf[i]\n    if (positive) tuple.push(byte)\n    else tuple.push(0xFF - byte)\n  }\n\n  let sum = 0\n  const l = tuple.length\n  for (i = 0; i < l; i++) {\n    sum += tuple[i] * Math.pow(256, i)\n  }\n\n  return positive ? sum : -1 * sum\n}\n\nfunction decodeOct (val, offset, length) {\n  val = val.subarray(offset, offset + length)\n  offset = 0\n\n  // If prefixed with 0x80 then parse as a base-256 integer\n  if (val[offset] & 0x80) {\n    return parse256(val)\n  } else {\n    // Older versions of tar can prefix with spaces\n    while (offset < val.length && val[offset] === 32) offset++\n    const end = clamp(indexOf(val, 32, offset, val.length), val.length, val.length)\n    while (offset < end && val[offset] === 0) offset++\n    if (end === offset) return 0\n    return parseInt(b4a.toString(val.subarray(offset, end)), 8)\n  }\n}\n\nfunction decodeStr (val, offset, length, encoding) {\n  return b4a.toString(val.subarray(offset, indexOf(val, 0, offset, offset + length)), encoding)\n}\n\nfunction addLength (str) {\n  const len = b4a.byteLength(str)\n  let digits = Math.floor(Math.log(len) / Math.log(10)) + 1\n  if (len + digits >= Math.pow(10, digits)) digits++\n\n  return (len + digits) + str\n}\n","const { Writable, Readable, getStreamError } = require('streamx')\nconst FIFO = require('fast-fifo')\nconst b4a = require('b4a')\nconst headers = require('./headers')\n\nconst EMPTY = b4a.alloc(0)\n\nclass BufferList {\n  constructor () {\n    this.buffered = 0\n    this.shifted = 0\n    this.queue = new FIFO()\n\n    this._offset = 0\n  }\n\n  push (buffer) {\n    this.buffered += buffer.byteLength\n    this.queue.push(buffer)\n  }\n\n  shiftFirst (size) {\n    return this._buffered === 0 ? null : this._next(size)\n  }\n\n  shift (size) {\n    if (size > this.buffered) return null\n    if (size === 0) return EMPTY\n\n    let chunk = this._next(size)\n\n    if (size === chunk.byteLength) return chunk // likely case\n\n    const chunks = [chunk]\n\n    while ((size -= chunk.byteLength) > 0) {\n      chunk = this._next(size)\n      chunks.push(chunk)\n    }\n\n    return b4a.concat(chunks)\n  }\n\n  _next (size) {\n    const buf = this.queue.peek()\n    const rem = buf.byteLength - this._offset\n\n    if (size >= rem) {\n      const sub = this._offset ? buf.subarray(this._offset, buf.byteLength) : buf\n      this.queue.shift()\n      this._offset = 0\n      this.buffered -= rem\n      this.shifted += rem\n      return sub\n    }\n\n    this.buffered -= size\n    this.shifted += size\n\n    return buf.subarray(this._offset, (this._offset += size))\n  }\n}\n\nclass Source extends Readable {\n  constructor (self, header, offset) {\n    super()\n\n    this.header = header\n    this.offset = offset\n\n    this._parent = self\n  }\n\n  _read (cb) {\n    if (this.header.size === 0) {\n      this.push(null)\n    }\n    if (this._parent._stream === this) {\n      this._parent._update()\n    }\n    cb(null)\n  }\n\n  _predestroy () {\n    this._parent.destroy(getStreamError(this))\n  }\n\n  _detach () {\n    if (this._parent._stream === this) {\n      this._parent._stream = null\n      this._parent._missing = overflow(this.header.size)\n      this._parent._update()\n    }\n  }\n\n  _destroy (cb) {\n    this._detach()\n    cb(null)\n  }\n}\n\nclass Extract extends Writable {\n  constructor (opts) {\n    super(opts)\n\n    if (!opts) opts = {}\n\n    this._buffer = new BufferList()\n    this._offset = 0\n    this._header = null\n    this._stream = null\n    this._missing = 0\n    this._longHeader = false\n    this._callback = noop\n    this._locked = false\n    this._finished = false\n    this._pax = null\n    this._paxGlobal = null\n    this._gnuLongPath = null\n    this._gnuLongLinkPath = null\n    this._filenameEncoding = opts.filenameEncoding || 'utf-8'\n    this._allowUnknownFormat = !!opts.allowUnknownFormat\n    this._unlockBound = this._unlock.bind(this)\n  }\n\n  _unlock (err) {\n    this._locked = false\n\n    if (err) {\n      this.destroy(err)\n      this._continueWrite(err)\n      return\n    }\n\n    this._update()\n  }\n\n  _consumeHeader () {\n    if (this._locked) return false\n\n    this._offset = this._buffer.shifted\n\n    try {\n      this._header = headers.decode(this._buffer.shift(512), this._filenameEncoding, this._allowUnknownFormat)\n    } catch (err) {\n      this._continueWrite(err)\n      return false\n    }\n\n    if (!this._header) return true\n\n    switch (this._header.type) {\n      case 'gnu-long-path':\n      case 'gnu-long-link-path':\n      case 'pax-global-header':\n      case 'pax-header':\n        this._longHeader = true\n        this._missing = this._header.size\n        return true\n    }\n\n    this._locked = true\n    this._applyLongHeaders()\n\n    if (this._header.size === 0 || this._header.type === 'directory') {\n      this.emit('entry', this._header, this._createStream(), this._unlockBound)\n      return true\n    }\n\n    this._stream = this._createStream()\n    this._missing = this._header.size\n\n    this.emit('entry', this._header, this._stream, this._unlockBound)\n    return true\n  }\n\n  _applyLongHeaders () {\n    if (this._gnuLongPath) {\n      this._header.name = this._gnuLongPath\n      this._gnuLongPath = null\n    }\n\n    if (this._gnuLongLinkPath) {\n      this._header.linkname = this._gnuLongLinkPath\n      this._gnuLongLinkPath = null\n    }\n\n    if (this._pax) {\n      if (this._pax.path) this._header.name = this._pax.path\n      if (this._pax.linkpath) this._header.linkname = this._pax.linkpath\n      if (this._pax.size) this._header.size = parseInt(this._pax.size, 10)\n      this._header.pax = this._pax\n      this._pax = null\n    }\n  }\n\n  _decodeLongHeader (buf) {\n    switch (this._header.type) {\n      case 'gnu-long-path':\n        this._gnuLongPath = headers.decodeLongPath(buf, this._filenameEncoding)\n        break\n      case 'gnu-long-link-path':\n        this._gnuLongLinkPath = headers.decodeLongPath(buf, this._filenameEncoding)\n        break\n      case 'pax-global-header':\n        this._paxGlobal = headers.decodePax(buf)\n        break\n      case 'pax-header':\n        this._pax = this._paxGlobal === null\n          ? headers.decodePax(buf)\n          : Object.assign({}, this._paxGlobal, headers.decodePax(buf))\n        break\n    }\n  }\n\n  _consumeLongHeader () {\n    this._longHeader = false\n    this._missing = overflow(this._header.size)\n\n    const buf = this._buffer.shift(this._header.size)\n\n    try {\n      this._decodeLongHeader(buf)\n    } catch (err) {\n      this._continueWrite(err)\n      return false\n    }\n\n    return true\n  }\n\n  _consumeStream () {\n    const buf = this._buffer.shiftFirst(this._missing)\n    if (buf === null) return false\n\n    this._missing -= buf.byteLength\n    const drained = this._stream.push(buf)\n\n    if (this._missing === 0) {\n      this._stream.push(null)\n      if (drained) this._stream._detach()\n      return drained && this._locked === false\n    }\n\n    return drained\n  }\n\n  _createStream () {\n    return new Source(this, this._header, this._offset)\n  }\n\n  _update () {\n    while (this._buffer.buffered > 0 && !this.destroying) {\n      if (this._missing > 0) {\n        if (this._stream !== null) {\n          if (this._consumeStream() === false) return\n          continue\n        }\n\n        if (this._longHeader === true) {\n          if (this._missing > this._buffer.buffered) break\n          if (this._consumeLongHeader() === false) return false\n          continue\n        }\n\n        const ignore = this._buffer.shiftFirst(this._missing)\n        if (ignore !== null) this._missing -= ignore.byteLength\n        continue\n      }\n\n      if (this._buffer.buffered < 512) break\n      if (this._stream !== null || this._consumeHeader() === false) return\n    }\n\n    this._continueWrite(null)\n  }\n\n  _continueWrite (err) {\n    const cb = this._callback\n    this._callback = noop\n    cb(err)\n  }\n\n  _write (data, cb) {\n    this._callback = cb\n    this._buffer.push(data)\n    this._update()\n  }\n\n  _final (cb) {\n    this._finished = this._missing === 0 && this._buffer.buffered === 0\n    cb(this._finished ? null : new Error('Unexpected end of data'))\n  }\n\n  _predestroy () {\n    this._continueWrite(null)\n  }\n\n  _destroy (cb) {\n    if (this._stream) this._stream.destroy(getStreamError(this))\n    cb(null)\n  }\n\n  [Symbol.asyncIterator] () {\n    let error = null\n\n    let promiseResolve = null\n    let promiseReject = null\n\n    let entryStream = null\n    let entryCallback = null\n\n    const extract = this\n\n    this.on('entry', onentry)\n    this.on('error', (err) => { error = err })\n    this.on('close', onclose)\n\n    return {\n      [Symbol.asyncIterator] () {\n        return this\n      },\n      next () {\n        return new Promise(onnext)\n      },\n      return () {\n        return destroy(null)\n      },\n      throw (err) {\n        return destroy(err)\n      }\n    }\n\n    function consumeCallback (err) {\n      if (!entryCallback) return\n      const cb = entryCallback\n      entryCallback = null\n      cb(err)\n    }\n\n    function onnext (resolve, reject) {\n      if (error) {\n        return reject(error)\n      }\n\n      if (entryStream) {\n        resolve({ value: entryStream, done: false })\n        entryStream = null\n        return\n      }\n\n      promiseResolve = resolve\n      promiseReject = reject\n\n      consumeCallback(null)\n\n      if (extract._finished && promiseResolve) {\n        promiseResolve({ value: undefined, done: true })\n        promiseResolve = promiseReject = null\n      }\n    }\n\n    function onentry (header, stream, callback) {\n      entryCallback = callback\n      stream.on('error', noop) // no way around this due to tick sillyness\n\n      if (promiseResolve) {\n        promiseResolve({ value: stream, done: false })\n        promiseResolve = promiseReject = null\n      } else {\n        entryStream = stream\n      }\n    }\n\n    function onclose () {\n      consumeCallback(error)\n      if (!promiseResolve) return\n      if (error) promiseReject(error)\n      else promiseResolve({ value: undefined, done: true })\n      promiseResolve = promiseReject = null\n    }\n\n    function destroy (err) {\n      extract.destroy(err)\n      consumeCallback(err)\n      return new Promise((resolve, reject) => {\n        if (extract.destroyed) return resolve({ value: undefined, done: true })\n        extract.once('close', function () {\n          if (err) reject(err)\n          else resolve({ value: undefined, done: true })\n        })\n      })\n    }\n  }\n}\n\nmodule.exports = function extract (opts) {\n  return new Extract(opts)\n}\n\nfunction noop () {}\n\nfunction overflow (size) {\n  size &= 511\n  return size && 512 - size\n}\n","const constants = { // just for envs without fs\n  S_IFMT: 61440,\n  S_IFDIR: 16384,\n  S_IFCHR: 8192,\n  S_IFBLK: 24576,\n  S_IFIFO: 4096,\n  S_IFLNK: 40960\n}\n\ntry {\n  module.exports = require('fs').constants || constants\n} catch {\n  module.exports = constants\n}\n","const { Readable, Writable, getStreamError } = require('streamx')\nconst b4a = require('b4a')\n\nconst constants = require('./constants')\nconst headers = require('./headers')\n\nconst DMODE = 0o755\nconst FMODE = 0o644\n\nconst END_OF_TAR = b4a.alloc(1024)\n\nclass Sink extends Writable {\n  constructor (pack, header, callback) {\n    super({ mapWritable, eagerOpen: true })\n\n    this.written = 0\n    this.header = header\n\n    this._callback = callback\n    this._linkname = null\n    this._isLinkname = header.type === 'symlink' && !header.linkname\n    this._isVoid = header.type !== 'file' && header.type !== 'contiguous-file'\n    this._finished = false\n    this._pack = pack\n    this._openCallback = null\n\n    if (this._pack._stream === null) this._pack._stream = this\n    else this._pack._pending.push(this)\n  }\n\n  _open (cb) {\n    this._openCallback = cb\n    if (this._pack._stream === this) this._continueOpen()\n  }\n\n  _continuePack (err) {\n    if (this._callback === null) return\n\n    const callback = this._callback\n    this._callback = null\n\n    callback(err)\n  }\n\n  _continueOpen () {\n    if (this._pack._stream === null) this._pack._stream = this\n\n    const cb = this._openCallback\n    this._openCallback = null\n    if (cb === null) return\n\n    if (this._pack.destroying) return cb(new Error('pack stream destroyed'))\n    if (this._pack._finalized) return cb(new Error('pack stream is already finalized'))\n\n    this._pack._stream = this\n\n    if (!this._isLinkname) {\n      this._pack._encode(this.header)\n    }\n\n    if (this._isVoid) {\n      this._finish()\n      this._continuePack(null)\n    }\n\n    cb(null)\n  }\n\n  _write (data, cb) {\n    if (this._isLinkname) {\n      this._linkname = this._linkname ? b4a.concat([this._linkname, data]) : data\n      return cb(null)\n    }\n\n    if (this._isVoid) {\n      if (data.byteLength > 0) {\n        return cb(new Error('No body allowed for this entry'))\n      }\n      return cb()\n    }\n\n    this.written += data.byteLength\n    if (this._pack.push(data)) return cb()\n    this._pack._drain = cb\n  }\n\n  _finish () {\n    if (this._finished) return\n    this._finished = true\n\n    if (this._isLinkname) {\n      this.header.linkname = this._linkname ? b4a.toString(this._linkname, 'utf-8') : ''\n      this._pack._encode(this.header)\n    }\n\n    overflow(this._pack, this.header.size)\n\n    this._pack._done(this)\n  }\n\n  _final (cb) {\n    if (this.written !== this.header.size) { // corrupting tar\n      return cb(new Error('Size mismatch'))\n    }\n\n    this._finish()\n    cb(null)\n  }\n\n  _getError () {\n    return getStreamError(this) || new Error('tar entry destroyed')\n  }\n\n  _predestroy () {\n    this._pack.destroy(this._getError())\n  }\n\n  _destroy (cb) {\n    this._pack._done(this)\n\n    this._continuePack(this._finished ? null : this._getError())\n\n    cb()\n  }\n}\n\nclass Pack extends Readable {\n  constructor (opts) {\n    super(opts)\n    this._drain = noop\n    this._finalized = false\n    this._finalizing = false\n    this._pending = []\n    this._stream = null\n  }\n\n  entry (header, buffer, callback) {\n    if (this._finalized || this.destroying) throw new Error('already finalized or destroyed')\n\n    if (typeof buffer === 'function') {\n      callback = buffer\n      buffer = null\n    }\n\n    if (!callback) callback = noop\n\n    if (!header.size || header.type === 'symlink') header.size = 0\n    if (!header.type) header.type = modeToType(header.mode)\n    if (!header.mode) header.mode = header.type === 'directory' ? DMODE : FMODE\n    if (!header.uid) header.uid = 0\n    if (!header.gid) header.gid = 0\n    if (!header.mtime) header.mtime = new Date()\n\n    if (typeof buffer === 'string') buffer = b4a.from(buffer)\n\n    const sink = new Sink(this, header, callback)\n\n    if (b4a.isBuffer(buffer)) {\n      header.size = buffer.byteLength\n      sink.write(buffer)\n      sink.end()\n      return sink\n    }\n\n    if (sink._isVoid) {\n      return sink\n    }\n\n    return sink\n  }\n\n  finalize () {\n    if (this._stream || this._pending.length > 0) {\n      this._finalizing = true\n      return\n    }\n\n    if (this._finalized) return\n    this._finalized = true\n\n    this.push(END_OF_TAR)\n    this.push(null)\n  }\n\n  _done (stream) {\n    if (stream !== this._stream) return\n\n    this._stream = null\n\n    if (this._finalizing) this.finalize()\n    if (this._pending.length) this._pending.shift()._continueOpen()\n  }\n\n  _encode (header) {\n    if (!header.pax) {\n      const buf = headers.encode(header)\n      if (buf) {\n        this.push(buf)\n        return\n      }\n    }\n    this._encodePax(header)\n  }\n\n  _encodePax (header) {\n    const paxHeader = headers.encodePax({\n      name: header.name,\n      linkname: header.linkname,\n      pax: header.pax\n    })\n\n    const newHeader = {\n      name: 'PaxHeader',\n      mode: header.mode,\n      uid: header.uid,\n      gid: header.gid,\n      size: paxHeader.byteLength,\n      mtime: header.mtime,\n      type: 'pax-header',\n      linkname: header.linkname && 'PaxHeader',\n      uname: header.uname,\n      gname: header.gname,\n      devmajor: header.devmajor,\n      devminor: header.devminor\n    }\n\n    this.push(headers.encode(newHeader))\n    this.push(paxHeader)\n    overflow(this, paxHeader.byteLength)\n\n    newHeader.size = header.size\n    newHeader.type = header.type\n    this.push(headers.encode(newHeader))\n  }\n\n  _doDrain () {\n    const drain = this._drain\n    this._drain = noop\n    drain()\n  }\n\n  _predestroy () {\n    const err = getStreamError(this)\n\n    if (this._stream) this._stream.destroy(err)\n\n    while (this._pending.length) {\n      const stream = this._pending.shift()\n      stream.destroy(err)\n      stream._continueOpen()\n    }\n\n    this._doDrain()\n  }\n\n  _read (cb) {\n    this._doDrain()\n    cb()\n  }\n}\n\nmodule.exports = function pack (opts) {\n  return new Pack(opts)\n}\n\nfunction modeToType (mode) {\n  switch (mode & constants.S_IFMT) {\n    case constants.S_IFBLK: return 'block-device'\n    case constants.S_IFCHR: return 'character-device'\n    case constants.S_IFDIR: return 'directory'\n    case constants.S_IFIFO: return 'fifo'\n    case constants.S_IFLNK: return 'symlink'\n  }\n\n  return 'file'\n}\n\nfunction noop () {}\n\nfunction overflow (self, size) {\n  size &= 511\n  if (size) self.push(END_OF_TAR.subarray(0, 512 - size))\n}\n\nfunction mapWritable (buf) {\n  return b4a.isBuffer(buf) ? buf : b4a.from(buf)\n}\n","exports.extract = require('./extract')\nexports.pack = require('./pack')\n","/**\n * TAR Format Plugin\n *\n * @module plugins/tar\n * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE}\n * @copyright (c) 2012-2014 Chris Talkington, contributors.\n */\nvar zlib = require('zlib');\n\nvar engine = require('tar-stream');\nvar util = require('archiver-utils');\n\n/**\n * @constructor\n * @param {TarOptions} options\n */\nvar Tar = function(options) {\n  if (!(this instanceof Tar)) {\n    return new Tar(options);\n  }\n\n  options = this.options = util.defaults(options, {\n    gzip: false\n  });\n\n  if (typeof options.gzipOptions !== 'object') {\n    options.gzipOptions = {};\n  }\n\n  this.supports = {\n    directory: true,\n    symlink: true\n  };\n\n  this.engine = engine.pack(options);\n  this.compressor = false;\n\n  if (options.gzip) {\n    this.compressor = zlib.createGzip(options.gzipOptions);\n    this.compressor.on('error', this._onCompressorError.bind(this));\n  }\n};\n\n/**\n * [_onCompressorError description]\n *\n * @private\n * @param  {Error} err\n * @return void\n */\nTar.prototype._onCompressorError = function(err) {\n  this.engine.emit('error', err);\n};\n\n/**\n * [append description]\n *\n * @param  {(Buffer|Stream)} source\n * @param  {TarEntryData} data\n * @param  {Function} callback\n * @return void\n */\nTar.prototype.append = function(source, data, callback) {\n  var self = this;\n\n  data.mtime = data.date;\n\n  function append(err, sourceBuffer) {\n    if (err) {\n      callback(err);\n      return;\n    }\n\n    self.engine.entry(data, sourceBuffer, function(err) {\n      callback(err, data);\n    });\n  }\n\n  if (data.sourceType === 'buffer') {\n    append(null, source);\n  } else if (data.sourceType === 'stream' && data.stats) {\n    data.size = data.stats.size;\n\n    var entry = self.engine.entry(data, function(err) {\n      callback(err, data);\n    });\n\n    source.pipe(entry);\n  } else if (data.sourceType === 'stream') {\n    util.collectStream(source, append);\n  }\n};\n\n/**\n * [finalize description]\n *\n * @return void\n */\nTar.prototype.finalize = function() {\n  this.engine.finalize();\n};\n\n/**\n * [on description]\n *\n * @return this.engine\n */\nTar.prototype.on = function() {\n  return this.engine.on.apply(this.engine, arguments);\n};\n\n/**\n * [pipe description]\n *\n * @param  {String} destination\n * @param  {Object} options\n * @return this.engine\n */\nTar.prototype.pipe = function(destination, options) {\n  if (this.compressor) {\n    return this.engine.pipe.apply(this.engine, [this.compressor]).pipe(destination, options);\n  } else {\n    return this.engine.pipe.apply(this.engine, arguments);\n  }\n};\n\n/**\n * [unpipe description]\n *\n * @return this.engine\n */\nTar.prototype.unpipe = function() {\n  if (this.compressor) {\n    return this.compressor.unpipe.apply(this.compressor, arguments);\n  } else {\n    return this.engine.unpipe.apply(this.engine, arguments);\n  }\n};\n\nmodule.exports = Tar;\n\n/**\n * @typedef {Object} TarOptions\n * @global\n * @property {Boolean} [gzip=false] Compress the tar archive using gzip.\n * @property {Object} [gzipOptions] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options}\n * to control compression.\n * @property {*} [*] See [tar-stream]{@link https://github.com/mafintosh/tar-stream} documentation for additional properties.\n */\n\n/**\n * @typedef {Object} TarEntryData\n * @global\n * @property {String} name Sets the entry name including internal path.\n * @property {(String|Date)} [date=NOW()] Sets the entry date.\n * @property {Number} [mode=D:0755/F:0644] Sets the entry permissions.\n * @property {String} [prefix] Sets a path prefix for the entry name. Useful\n * when working with methods like `directory` or `glob`.\n * @property {fs.Stats} [stats] Sets the fs stat data for this entry allowing\n * for reduction of fs stat calls when stat data is already known.\n */\n\n/**\n * TarStream Module\n * @external TarStream\n * @see {@link https://github.com/mafintosh/tar-stream}\n */\n","'use strict';\n\nfunction getDefaultExportFromCjs (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\nconst CRC_TABLE = new Int32Array([\n  0,\n  1996959894,\n  3993919788,\n  2567524794,\n  124634137,\n  1886057615,\n  3915621685,\n  2657392035,\n  249268274,\n  2044508324,\n  3772115230,\n  2547177864,\n  162941995,\n  2125561021,\n  3887607047,\n  2428444049,\n  498536548,\n  1789927666,\n  4089016648,\n  2227061214,\n  450548861,\n  1843258603,\n  4107580753,\n  2211677639,\n  325883990,\n  1684777152,\n  4251122042,\n  2321926636,\n  335633487,\n  1661365465,\n  4195302755,\n  2366115317,\n  997073096,\n  1281953886,\n  3579855332,\n  2724688242,\n  1006888145,\n  1258607687,\n  3524101629,\n  2768942443,\n  901097722,\n  1119000684,\n  3686517206,\n  2898065728,\n  853044451,\n  1172266101,\n  3705015759,\n  2882616665,\n  651767980,\n  1373503546,\n  3369554304,\n  3218104598,\n  565507253,\n  1454621731,\n  3485111705,\n  3099436303,\n  671266974,\n  1594198024,\n  3322730930,\n  2970347812,\n  795835527,\n  1483230225,\n  3244367275,\n  3060149565,\n  1994146192,\n  31158534,\n  2563907772,\n  4023717930,\n  1907459465,\n  112637215,\n  2680153253,\n  3904427059,\n  2013776290,\n  251722036,\n  2517215374,\n  3775830040,\n  2137656763,\n  141376813,\n  2439277719,\n  3865271297,\n  1802195444,\n  476864866,\n  2238001368,\n  4066508878,\n  1812370925,\n  453092731,\n  2181625025,\n  4111451223,\n  1706088902,\n  314042704,\n  2344532202,\n  4240017532,\n  1658658271,\n  366619977,\n  2362670323,\n  4224994405,\n  1303535960,\n  984961486,\n  2747007092,\n  3569037538,\n  1256170817,\n  1037604311,\n  2765210733,\n  3554079995,\n  1131014506,\n  879679996,\n  2909243462,\n  3663771856,\n  1141124467,\n  855842277,\n  2852801631,\n  3708648649,\n  1342533948,\n  654459306,\n  3188396048,\n  3373015174,\n  1466479909,\n  544179635,\n  3110523913,\n  3462522015,\n  1591671054,\n  702138776,\n  2966460450,\n  3352799412,\n  1504918807,\n  783551873,\n  3082640443,\n  3233442989,\n  3988292384,\n  2596254646,\n  62317068,\n  1957810842,\n  3939845945,\n  2647816111,\n  81470997,\n  1943803523,\n  3814918930,\n  2489596804,\n  225274430,\n  2053790376,\n  3826175755,\n  2466906013,\n  167816743,\n  2097651377,\n  4027552580,\n  2265490386,\n  503444072,\n  1762050814,\n  4150417245,\n  2154129355,\n  426522225,\n  1852507879,\n  4275313526,\n  2312317920,\n  282753626,\n  1742555852,\n  4189708143,\n  2394877945,\n  397917763,\n  1622183637,\n  3604390888,\n  2714866558,\n  953729732,\n  1340076626,\n  3518719985,\n  2797360999,\n  1068828381,\n  1219638859,\n  3624741850,\n  2936675148,\n  906185462,\n  1090812512,\n  3747672003,\n  2825379669,\n  829329135,\n  1181335161,\n  3412177804,\n  3160834842,\n  628085408,\n  1382605366,\n  3423369109,\n  3138078467,\n  570562233,\n  1426400815,\n  3317316542,\n  2998733608,\n  733239954,\n  1555261956,\n  3268935591,\n  3050360625,\n  752459403,\n  1541320221,\n  2607071920,\n  3965973030,\n  1969922972,\n  40735498,\n  2617837225,\n  3943577151,\n  1913087877,\n  83908371,\n  2512341634,\n  3803740692,\n  2075208622,\n  213261112,\n  2463272603,\n  3855990285,\n  2094854071,\n  198958881,\n  2262029012,\n  4057260610,\n  1759359992,\n  534414190,\n  2176718541,\n  4139329115,\n  1873836001,\n  414664567,\n  2282248934,\n  4279200368,\n  1711684554,\n  285281116,\n  2405801727,\n  4167216745,\n  1634467795,\n  376229701,\n  2685067896,\n  3608007406,\n  1308918612,\n  956543938,\n  2808555105,\n  3495958263,\n  1231636301,\n  1047427035,\n  2932959818,\n  3654703836,\n  1088359270,\n  936918e3,\n  2847714899,\n  3736837829,\n  1202900863,\n  817233897,\n  3183342108,\n  3401237130,\n  1404277552,\n  615818150,\n  3134207493,\n  3453421203,\n  1423857449,\n  601450431,\n  3009837614,\n  3294710456,\n  1567103746,\n  711928724,\n  3020668471,\n  3272380065,\n  1510334235,\n  755167117\n]);\nfunction ensureBuffer(input) {\n  if (Buffer.isBuffer(input)) {\n    return input;\n  }\n  if (typeof input === \"number\") {\n    return Buffer.alloc(input);\n  } else if (typeof input === \"string\") {\n    return Buffer.from(input);\n  } else {\n    throw new Error(\"input must be buffer, number, or string, received \" + typeof input);\n  }\n}\nfunction bufferizeInt(num) {\n  const tmp = ensureBuffer(4);\n  tmp.writeInt32BE(num, 0);\n  return tmp;\n}\nfunction _crc32(buf, previous) {\n  buf = ensureBuffer(buf);\n  if (Buffer.isBuffer(previous)) {\n    previous = previous.readUInt32BE(0);\n  }\n  let crc = ~~previous ^ -1;\n  for (var n = 0; n < buf.length; n++) {\n    crc = CRC_TABLE[(crc ^ buf[n]) & 255] ^ crc >>> 8;\n  }\n  return crc ^ -1;\n}\nfunction crc32() {\n  return bufferizeInt(_crc32.apply(null, arguments));\n}\ncrc32.signed = function() {\n  return _crc32.apply(null, arguments);\n};\ncrc32.unsigned = function() {\n  return _crc32.apply(null, arguments) >>> 0;\n};\nvar bufferCrc32 = crc32;\n\nconst index = /*@__PURE__*/getDefaultExportFromCjs(bufferCrc32);\n\nmodule.exports = index;\n","/**\n * JSON Format Plugin\n *\n * @module plugins/json\n * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE}\n * @copyright (c) 2012-2014 Chris Talkington, contributors.\n */\nvar inherits = require('util').inherits;\nvar Transform = require('readable-stream').Transform;\n\nvar crc32 = require('buffer-crc32');\nvar util = require('archiver-utils');\n\n/**\n * @constructor\n * @param {(JsonOptions|TransformOptions)} options\n */\nvar Json = function(options) {\n  if (!(this instanceof Json)) {\n    return new Json(options);\n  }\n\n  options = this.options = util.defaults(options, {});\n\n  Transform.call(this, options);\n\n  this.supports = {\n    directory: true,\n    symlink: true\n  };\n\n  this.files = [];\n};\n\ninherits(Json, Transform);\n\n/**\n * [_transform description]\n *\n * @private\n * @param  {Buffer}   chunk\n * @param  {String}   encoding\n * @param  {Function} callback\n * @return void\n */\nJson.prototype._transform = function(chunk, encoding, callback) {\n  callback(null, chunk);\n};\n\n/**\n * [_writeStringified description]\n *\n * @private\n * @return void\n */\nJson.prototype._writeStringified = function() {\n  var fileString = JSON.stringify(this.files);\n  this.write(fileString);\n};\n\n/**\n * [append description]\n *\n * @param  {(Buffer|Stream)}   source\n * @param  {EntryData}   data\n * @param  {Function} callback\n * @return void\n */\nJson.prototype.append = function(source, data, callback) {\n  var self = this;\n\n  data.crc32 = 0;\n\n  function onend(err, sourceBuffer) {\n    if (err) {\n      callback(err);\n      return;\n    }\n\n    data.size = sourceBuffer.length || 0;\n    data.crc32 = crc32.unsigned(sourceBuffer);\n\n    self.files.push(data);\n\n    callback(null, data);\n  }\n\n  if (data.sourceType === 'buffer') {\n    onend(null, source);\n  } else if (data.sourceType === 'stream') {\n    util.collectStream(source, onend);\n  }\n};\n\n/**\n * [finalize description]\n *\n * @return void\n */\nJson.prototype.finalize = function() {\n  this._writeStringified();\n  this.end();\n};\n\nmodule.exports = Json;\n\n/**\n * @typedef {Object} JsonOptions\n * @global\n */\n","/**\n * Archiver Vending\n *\n * @ignore\n * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE}\n * @copyright (c) 2012-2014 Chris Talkington, contributors.\n */\nvar Archiver = require('./lib/core');\n\nvar formats = {};\n\n/**\n * Dispenses a new Archiver instance.\n *\n * @constructor\n * @param  {String} format The archive format to use.\n * @param  {Object} options See [Archiver]{@link Archiver}\n * @return {Archiver}\n */\nvar vending = function(format, options) {\n  return vending.create(format, options);\n};\n\n/**\n * Creates a new Archiver instance.\n *\n * @param  {String} format The archive format to use.\n * @param  {Object} options See [Archiver]{@link Archiver}\n * @return {Archiver}\n */\nvending.create = function(format, options) {\n  if (formats[format]) {\n    var instance = new Archiver(format, options);\n    instance.setFormat(format);\n    instance.setModule(new formats[format](options));\n\n    return instance;\n  } else {\n    throw new Error('create(' + format + '): format not registered');\n  }\n};\n\n/**\n * Registers a format for use with archiver.\n *\n * @param  {String} format The name of the format.\n * @param  {Function} module The function for archiver to interact with.\n * @return void\n */\nvending.registerFormat = function(format, module) {\n  if (formats[format]) {\n    throw new Error('register(' + format + '): format already registered');\n  }\n\n  if (typeof module !== 'function') {\n    throw new Error('register(' + format + '): format module invalid');\n  }\n\n  if (typeof module.prototype.append !== 'function' || typeof module.prototype.finalize !== 'function') {\n    throw new Error('register(' + format + '): format module missing methods');\n  }\n\n  formats[format] = module;\n};\n\n/**\n * Check if the format is already registered.\n * \n * @param {String} format the name of the format.\n * @return boolean\n */\nvending.isRegisteredFormat = function (format) {\n  if (formats[format]) {\n    return true;\n  }\n  \n  return false;\n};\n\nvending.registerFormat('zip', require('./lib/plugins/zip'));\nvending.registerFormat('tar', require('./lib/plugins/tar'));\nvending.registerFormat('json', require('./lib/plugins/json'));\n\nmodule.exports = vending;","module.exports = Traverse;\nfunction Traverse (obj) {\n    if (!(this instanceof Traverse)) return new Traverse(obj);\n    this.value = obj;\n}\n\nTraverse.prototype.get = function (ps) {\n    var node = this.value;\n    for (var i = 0; i < ps.length; i ++) {\n        var key = ps[i];\n        if (!Object.hasOwnProperty.call(node, key)) {\n            node = undefined;\n            break;\n        }\n        node = node[key];\n    }\n    return node;\n};\n\nTraverse.prototype.set = function (ps, value) {\n    var node = this.value;\n    for (var i = 0; i < ps.length - 1; i ++) {\n        var key = ps[i];\n        if (!Object.hasOwnProperty.call(node, key)) node[key] = {};\n        node = node[key];\n    }\n    node[ps[i]] = value;\n    return value;\n};\n\nTraverse.prototype.map = function (cb) {\n    return walk(this.value, cb, true);\n};\n\nTraverse.prototype.forEach = function (cb) {\n    this.value = walk(this.value, cb, false);\n    return this.value;\n};\n\nTraverse.prototype.reduce = function (cb, init) {\n    var skip = arguments.length === 1;\n    var acc = skip ? this.value : init;\n    this.forEach(function (x) {\n        if (!this.isRoot || !skip) {\n            acc = cb.call(this, acc, x);\n        }\n    });\n    return acc;\n};\n\nTraverse.prototype.deepEqual = function (obj) {\n    if (arguments.length !== 1) {\n        throw new Error(\n            'deepEqual requires exactly one object to compare against'\n        );\n    }\n    \n    var equal = true;\n    var node = obj;\n    \n    this.forEach(function (y) {\n        var notEqual = (function () {\n            equal = false;\n            //this.stop();\n            return undefined;\n        }).bind(this);\n        \n        //if (node === undefined || node === null) return notEqual();\n        \n        if (!this.isRoot) {\n        /*\n            if (!Object.hasOwnProperty.call(node, this.key)) {\n                return notEqual();\n            }\n        */\n            if (typeof node !== 'object') return notEqual();\n            node = node[this.key];\n        }\n        \n        var x = node;\n        \n        this.post(function () {\n            node = x;\n        });\n        \n        var toS = function (o) {\n            return Object.prototype.toString.call(o);\n        };\n        \n        if (this.circular) {\n            if (Traverse(obj).get(this.circular.path) !== x) notEqual();\n        }\n        else if (typeof x !== typeof y) {\n            notEqual();\n        }\n        else if (x === null || y === null || x === undefined || y === undefined) {\n            if (x !== y) notEqual();\n        }\n        else if (x.__proto__ !== y.__proto__) {\n            notEqual();\n        }\n        else if (x === y) {\n            // nop\n        }\n        else if (typeof x === 'function') {\n            if (x instanceof RegExp) {\n                // both regexps on account of the __proto__ check\n                if (x.toString() != y.toString()) notEqual();\n            }\n            else if (x !== y) notEqual();\n        }\n        else if (typeof x === 'object') {\n            if (toS(y) === '[object Arguments]'\n            || toS(x) === '[object Arguments]') {\n                if (toS(x) !== toS(y)) {\n                    notEqual();\n                }\n            }\n            else if (x instanceof Date || y instanceof Date) {\n                if (!(x instanceof Date) || !(y instanceof Date)\n                || x.getTime() !== y.getTime()) {\n                    notEqual();\n                }\n            }\n            else {\n                var kx = Object.keys(x);\n                var ky = Object.keys(y);\n                if (kx.length !== ky.length) return notEqual();\n                for (var i = 0; i < kx.length; i++) {\n                    var k = kx[i];\n                    if (!Object.hasOwnProperty.call(y, k)) {\n                        notEqual();\n                    }\n                }\n            }\n        }\n    });\n    \n    return equal;\n};\n\nTraverse.prototype.paths = function () {\n    var acc = [];\n    this.forEach(function (x) {\n        acc.push(this.path); \n    });\n    return acc;\n};\n\nTraverse.prototype.nodes = function () {\n    var acc = [];\n    this.forEach(function (x) {\n        acc.push(this.node);\n    });\n    return acc;\n};\n\nTraverse.prototype.clone = function () {\n    var parents = [], nodes = [];\n    \n    return (function clone (src) {\n        for (var i = 0; i < parents.length; i++) {\n            if (parents[i] === src) {\n                return nodes[i];\n            }\n        }\n        \n        if (typeof src === 'object' && src !== null) {\n            var dst = copy(src);\n            \n            parents.push(src);\n            nodes.push(dst);\n            \n            Object.keys(src).forEach(function (key) {\n                dst[key] = clone(src[key]);\n            });\n            \n            parents.pop();\n            nodes.pop();\n            return dst;\n        }\n        else {\n            return src;\n        }\n    })(this.value);\n};\n\nfunction walk (root, cb, immutable) {\n    var path = [];\n    var parents = [];\n    var alive = true;\n    \n    return (function walker (node_) {\n        var node = immutable ? copy(node_) : node_;\n        var modifiers = {};\n        \n        var state = {\n            node : node,\n            node_ : node_,\n            path : [].concat(path),\n            parent : parents.slice(-1)[0],\n            key : path.slice(-1)[0],\n            isRoot : path.length === 0,\n            level : path.length,\n            circular : null,\n            update : function (x) {\n                if (!state.isRoot) {\n                    state.parent.node[state.key] = x;\n                }\n                state.node = x;\n            },\n            'delete' : function () {\n                delete state.parent.node[state.key];\n            },\n            remove : function () {\n                if (Array.isArray(state.parent.node)) {\n                    state.parent.node.splice(state.key, 1);\n                }\n                else {\n                    delete state.parent.node[state.key];\n                }\n            },\n            before : function (f) { modifiers.before = f },\n            after : function (f) { modifiers.after = f },\n            pre : function (f) { modifiers.pre = f },\n            post : function (f) { modifiers.post = f },\n            stop : function () { alive = false }\n        };\n        \n        if (!alive) return state;\n        \n        if (typeof node === 'object' && node !== null) {\n            state.isLeaf = Object.keys(node).length == 0;\n            \n            for (var i = 0; i < parents.length; i++) {\n                if (parents[i].node_ === node_) {\n                    state.circular = parents[i];\n                    break;\n                }\n            }\n        }\n        else {\n            state.isLeaf = true;\n        }\n        \n        state.notLeaf = !state.isLeaf;\n        state.notRoot = !state.isRoot;\n        \n        // use return values to update if defined\n        var ret = cb.call(state, state.node);\n        if (ret !== undefined && state.update) state.update(ret);\n        if (modifiers.before) modifiers.before.call(state, state.node);\n        \n        if (typeof state.node == 'object'\n        && state.node !== null && !state.circular) {\n            parents.push(state);\n            \n            var keys = Object.keys(state.node);\n            keys.forEach(function (key, i) {\n                path.push(key);\n                \n                if (modifiers.pre) modifiers.pre.call(state, state.node[key], key);\n                \n                var child = walker(state.node[key]);\n                if (immutable && Object.hasOwnProperty.call(state.node, key)) {\n                    state.node[key] = child.node;\n                }\n                \n                child.isLast = i == keys.length - 1;\n                child.isFirst = i == 0;\n                \n                if (modifiers.post) modifiers.post.call(state, child);\n                \n                path.pop();\n            });\n            parents.pop();\n        }\n        \n        if (modifiers.after) modifiers.after.call(state, state.node);\n        \n        return state;\n    })(root).node;\n}\n\nObject.keys(Traverse.prototype).forEach(function (key) {\n    Traverse[key] = function (obj) {\n        var args = [].slice.call(arguments, 1);\n        var t = Traverse(obj);\n        return t[key].apply(t, args);\n    };\n});\n\nfunction copy (src) {\n    if (typeof src === 'object' && src !== null) {\n        var dst;\n        \n        if (Array.isArray(src)) {\n            dst = [];\n        }\n        else if (src instanceof Date) {\n            dst = new Date(src);\n        }\n        else if (src instanceof Boolean) {\n            dst = new Boolean(src);\n        }\n        else if (src instanceof Number) {\n            dst = new Number(src);\n        }\n        else if (src instanceof String) {\n            dst = new String(src);\n        }\n        else {\n            dst = Object.create(Object.getPrototypeOf(src));\n        }\n        \n        Object.keys(src).forEach(function (key) {\n            dst[key] = src[key];\n        });\n        return dst;\n    }\n    else return src;\n}\n","var Traverse = require('traverse');\nvar EventEmitter = require('events').EventEmitter;\n\nmodule.exports = Chainsaw;\nfunction Chainsaw (builder) {\n    var saw = Chainsaw.saw(builder, {});\n    var r = builder.call(saw.handlers, saw);\n    if (r !== undefined) saw.handlers = r;\n    saw.record();\n    return saw.chain();\n};\n\nChainsaw.light = function ChainsawLight (builder) {\n    var saw = Chainsaw.saw(builder, {});\n    var r = builder.call(saw.handlers, saw);\n    if (r !== undefined) saw.handlers = r;\n    return saw.chain();\n};\n\nChainsaw.saw = function (builder, handlers) {\n    var saw = new EventEmitter;\n    saw.handlers = handlers;\n    saw.actions = [];\n\n    saw.chain = function () {\n        var ch = Traverse(saw.handlers).map(function (node) {\n            if (this.isRoot) return node;\n            var ps = this.path;\n\n            if (typeof node === 'function') {\n                this.update(function () {\n                    saw.actions.push({\n                        path : ps,\n                        args : [].slice.call(arguments)\n                    });\n                    return ch;\n                });\n            }\n        });\n\n        process.nextTick(function () {\n            saw.emit('begin');\n            saw.next();\n        });\n\n        return ch;\n    };\n\n    saw.pop = function () {\n        return saw.actions.shift();\n    };\n\n    saw.next = function () {\n        var action = saw.pop();\n\n        if (!action) {\n            saw.emit('end');\n        }\n        else if (!action.trap) {\n            var node = saw.handlers;\n            action.path.forEach(function (key) { node = node[key] });\n            node.apply(saw.handlers, action.args);\n        }\n    };\n\n    saw.nest = function (cb) {\n        var args = [].slice.call(arguments, 1);\n        var autonext = true;\n\n        if (typeof cb === 'boolean') {\n            var autonext = cb;\n            cb = args.shift();\n        }\n\n        var s = Chainsaw.saw(builder, {});\n        var r = builder.call(s.handlers, s);\n\n        if (r !== undefined) s.handlers = r;\n\n        // If we are recording...\n        if (\"undefined\" !== typeof saw.step) {\n            // ... our children should, too\n            s.record();\n        }\n\n        cb.apply(s.chain(), args);\n        if (autonext !== false) s.on('end', saw.next);\n    };\n\n    saw.record = function () {\n        upgradeChainsaw(saw);\n    };\n\n    ['trap', 'down', 'jump'].forEach(function (method) {\n        saw[method] = function () {\n            throw new Error(\"To use the trap, down and jump features, please \"+\n                            \"call record() first to start recording actions.\");\n        };\n    });\n\n    return saw;\n};\n\nfunction upgradeChainsaw(saw) {\n    saw.step = 0;\n\n    // override pop\n    saw.pop = function () {\n        return saw.actions[saw.step++];\n    };\n\n    saw.trap = function (name, cb) {\n        var ps = Array.isArray(name) ? name : [name];\n        saw.actions.push({\n            path : ps,\n            step : saw.step,\n            cb : cb,\n            trap : true\n        });\n    };\n\n    saw.down = function (name) {\n        var ps = (Array.isArray(name) ? name : [name]).join('/');\n        var i = saw.actions.slice(saw.step).map(function (x) {\n            if (x.trap && x.step <= saw.step) return false;\n            return x.path.join('/') == ps;\n        }).indexOf(true);\n\n        if (i >= 0) saw.step += i;\n        else saw.step = saw.actions.length;\n\n        var act = saw.actions[saw.step - 1];\n        if (act && act.trap) {\n            // It's a trap!\n            saw.step = act.step;\n            act.cb();\n        }\n        else saw.next();\n    };\n\n    saw.jump = function (step) {\n        saw.step = step;\n        saw.next();\n    };\n};\n","module.exports = Buffers;\n\nfunction Buffers (bufs) {\n    if (!(this instanceof Buffers)) return new Buffers(bufs);\n    this.buffers = bufs || [];\n    this.length = this.buffers.reduce(function (size, buf) {\n        return size + buf.length\n    }, 0);\n}\n\nBuffers.prototype.push = function () {\n    for (var i = 0; i < arguments.length; i++) {\n        if (!Buffer.isBuffer(arguments[i])) {\n            throw new TypeError('Tried to push a non-buffer');\n        }\n    }\n    \n    for (var i = 0; i < arguments.length; i++) {\n        var buf = arguments[i];\n        this.buffers.push(buf);\n        this.length += buf.length;\n    }\n    return this.length;\n};\n\nBuffers.prototype.unshift = function () {\n    for (var i = 0; i < arguments.length; i++) {\n        if (!Buffer.isBuffer(arguments[i])) {\n            throw new TypeError('Tried to unshift a non-buffer');\n        }\n    }\n    \n    for (var i = 0; i < arguments.length; i++) {\n        var buf = arguments[i];\n        this.buffers.unshift(buf);\n        this.length += buf.length;\n    }\n    return this.length;\n};\n\nBuffers.prototype.copy = function (dst, dStart, start, end) {\n    return this.slice(start, end).copy(dst, dStart, 0, end - start);\n};\n\nBuffers.prototype.splice = function (i, howMany) {\n    var buffers = this.buffers;\n    var index = i >= 0 ? i : this.length - i;\n    var reps = [].slice.call(arguments, 2);\n    \n    if (howMany === undefined) {\n        howMany = this.length - index;\n    }\n    else if (howMany > this.length - index) {\n        howMany = this.length - index;\n    }\n    \n    for (var i = 0; i < reps.length; i++) {\n        this.length += reps[i].length;\n    }\n    \n    var removed = new Buffers();\n    var bytes = 0;\n    \n    var startBytes = 0;\n    for (\n        var ii = 0;\n        ii < buffers.length && startBytes + buffers[ii].length < index;\n        ii ++\n    ) { startBytes += buffers[ii].length }\n    \n    if (index - startBytes > 0) {\n        var start = index - startBytes;\n        \n        if (start + howMany < buffers[ii].length) {\n            removed.push(buffers[ii].slice(start, start + howMany));\n            \n            var orig = buffers[ii];\n            //var buf = new Buffer(orig.length - howMany);\n            var buf0 = new Buffer(start);\n            for (var i = 0; i < start; i++) {\n                buf0[i] = orig[i];\n            }\n            \n            var buf1 = new Buffer(orig.length - start - howMany);\n            for (var i = start + howMany; i < orig.length; i++) {\n                buf1[ i - howMany - start ] = orig[i]\n            }\n            \n            if (reps.length > 0) {\n                var reps_ = reps.slice();\n                reps_.unshift(buf0);\n                reps_.push(buf1);\n                buffers.splice.apply(buffers, [ ii, 1 ].concat(reps_));\n                ii += reps_.length;\n                reps = [];\n            }\n            else {\n                buffers.splice(ii, 1, buf0, buf1);\n                //buffers[ii] = buf;\n                ii += 2;\n            }\n        }\n        else {\n            removed.push(buffers[ii].slice(start));\n            buffers[ii] = buffers[ii].slice(0, start);\n            ii ++;\n        }\n    }\n    \n    if (reps.length > 0) {\n        buffers.splice.apply(buffers, [ ii, 0 ].concat(reps));\n        ii += reps.length;\n    }\n    \n    while (removed.length < howMany) {\n        var buf = buffers[ii];\n        var len = buf.length;\n        var take = Math.min(len, howMany - removed.length);\n        \n        if (take === len) {\n            removed.push(buf);\n            buffers.splice(ii, 1);\n        }\n        else {\n            removed.push(buf.slice(0, take));\n            buffers[ii] = buffers[ii].slice(take);\n        }\n    }\n    \n    this.length -= removed.length;\n    \n    return removed;\n};\n \nBuffers.prototype.slice = function (i, j) {\n    var buffers = this.buffers;\n    if (j === undefined) j = this.length;\n    if (i === undefined) i = 0;\n    \n    if (j > this.length) j = this.length;\n    \n    var startBytes = 0;\n    for (\n        var si = 0;\n        si < buffers.length && startBytes + buffers[si].length <= i;\n        si ++\n    ) { startBytes += buffers[si].length }\n    \n    var target = new Buffer(j - i);\n    \n    var ti = 0;\n    for (var ii = si; ti < j - i && ii < buffers.length; ii++) {\n        var len = buffers[ii].length;\n        \n        var start = ti === 0 ? i - startBytes : 0;\n        var end = ti + len >= j - i\n            ? Math.min(start + (j - i) - ti, len)\n            : len\n        ;\n        \n        buffers[ii].copy(target, ti, start, end);\n        ti += end - start;\n    }\n    \n    return target;\n};\n\nBuffers.prototype.pos = function (i) {\n    if (i < 0 || i >= this.length) throw new Error('oob');\n    var l = i, bi = 0, bu = null;\n    for (;;) {\n        bu = this.buffers[bi];\n        if (l < bu.length) {\n            return {buf: bi, offset: l};\n        } else {\n            l -= bu.length;\n        }\n        bi++;\n    }\n};\n\nBuffers.prototype.get = function get (i) {\n    var pos = this.pos(i);\n\n    return this.buffers[pos.buf].get(pos.offset);\n};\n\nBuffers.prototype.set = function set (i, b) {\n    var pos = this.pos(i);\n\n    return this.buffers[pos.buf].set(pos.offset, b);\n};\n\nBuffers.prototype.indexOf = function (needle, offset) {\n    if (\"string\" === typeof needle) {\n        needle = new Buffer(needle);\n    } else if (needle instanceof Buffer) {\n        // already a buffer\n    } else {\n        throw new Error('Invalid type for a search string');\n    }\n\n    if (!needle.length) {\n        return 0;\n    }\n\n    if (!this.length) {\n        return -1;\n    }\n\n    var i = 0, j = 0, match = 0, mstart, pos = 0;\n\n    // start search from a particular point in the virtual buffer\n    if (offset) {\n        var p = this.pos(offset);\n        i = p.buf;\n        j = p.offset;\n        pos = offset;\n    }\n\n    // for each character in virtual buffer\n    for (;;) {\n        while (j >= this.buffers[i].length) {\n            j = 0;\n            i++;\n\n            if (i >= this.buffers.length) {\n                // search string not found\n                return -1;\n            }\n        }\n\n        var char = this.buffers[i][j];\n\n        if (char == needle[match]) {\n            // keep track where match started\n            if (match == 0) {\n                mstart = {\n                    i: i,\n                    j: j,\n                    pos: pos\n                };\n            }\n            match++;\n            if (match == needle.length) {\n                // full match\n                return mstart.pos;\n            }\n        } else if (match != 0) {\n            // a partial match ended, go back to match starting position\n            // this will continue the search at the next character\n            i = mstart.i;\n            j = mstart.j;\n            pos = mstart.pos;\n            match = 0;\n        }\n\n        j++;\n        pos++;\n    }\n};\n\nBuffers.prototype.toBuffer = function() {\n    return this.slice();\n}\n\nBuffers.prototype.toString = function(encoding, start, end) {\n    return this.slice(start, end).toString(encoding);\n}\n","module.exports = function (store) {\n    function getset (name, value) {\n        var node = vars.store;\n        var keys = name.split('.');\n        keys.slice(0,-1).forEach(function (k) {\n            if (node[k] === undefined) node[k] = {};\n            node = node[k]\n        });\n        var key = keys[keys.length - 1];\n        if (arguments.length == 1) {\n            return node[key];\n        }\n        else {\n            return node[key] = value;\n        }\n    }\n    \n    var vars = {\n        get : function (name) {\n            return getset(name);\n        },\n        set : function (name, value) {\n            return getset(name, value);\n        },\n        store : store || {},\n    };\n    return vars;\n};\n","var Chainsaw = require('chainsaw');\nvar EventEmitter = require('events').EventEmitter;\nvar Buffers = require('buffers');\nvar Vars = require('./lib/vars.js');\nvar Stream = require('stream').Stream;\n\nexports = module.exports = function (bufOrEm, eventName) {\n    if (Buffer.isBuffer(bufOrEm)) {\n        return exports.parse(bufOrEm);\n    }\n    \n    var s = exports.stream();\n    if (bufOrEm && bufOrEm.pipe) {\n        bufOrEm.pipe(s);\n    }\n    else if (bufOrEm) {\n        bufOrEm.on(eventName || 'data', function (buf) {\n            s.write(buf);\n        });\n        \n        bufOrEm.on('end', function () {\n            s.end();\n        });\n    }\n    return s;\n};\n\nexports.stream = function (input) {\n    if (input) return exports.apply(null, arguments);\n    \n    var pending = null;\n    function getBytes (bytes, cb, skip) {\n        pending = {\n            bytes : bytes,\n            skip : skip,\n            cb : function (buf) {\n                pending = null;\n                cb(buf);\n            },\n        };\n        dispatch();\n    }\n    \n    var offset = null;\n    function dispatch () {\n        if (!pending) {\n            if (caughtEnd) done = true;\n            return;\n        }\n        if (typeof pending === 'function') {\n            pending();\n        }\n        else {\n            var bytes = offset + pending.bytes;\n            \n            if (buffers.length >= bytes) {\n                var buf;\n                if (offset == null) {\n                    buf = buffers.splice(0, bytes);\n                    if (!pending.skip) {\n                        buf = buf.slice();\n                    }\n                }\n                else {\n                    if (!pending.skip) {\n                        buf = buffers.slice(offset, bytes);\n                    }\n                    offset = bytes;\n                }\n                \n                if (pending.skip) {\n                    pending.cb();\n                }\n                else {\n                    pending.cb(buf);\n                }\n            }\n        }\n    }\n    \n    function builder (saw) {\n        function next () { if (!done) saw.next() }\n        \n        var self = words(function (bytes, cb) {\n            return function (name) {\n                getBytes(bytes, function (buf) {\n                    vars.set(name, cb(buf));\n                    next();\n                });\n            };\n        });\n        \n        self.tap = function (cb) {\n            saw.nest(cb, vars.store);\n        };\n        \n        self.into = function (key, cb) {\n            if (!vars.get(key)) vars.set(key, {});\n            var parent = vars;\n            vars = Vars(parent.get(key));\n            \n            saw.nest(function () {\n                cb.apply(this, arguments);\n                this.tap(function () {\n                    vars = parent;\n                });\n            }, vars.store);\n        };\n        \n        self.flush = function () {\n            vars.store = {};\n            next();\n        };\n        \n        self.loop = function (cb) {\n            var end = false;\n            \n            saw.nest(false, function loop () {\n                this.vars = vars.store;\n                cb.call(this, function () {\n                    end = true;\n                    next();\n                }, vars.store);\n                this.tap(function () {\n                    if (end) saw.next()\n                    else loop.call(this)\n                }.bind(this));\n            }, vars.store);\n        };\n        \n        self.buffer = function (name, bytes) {\n            if (typeof bytes === 'string') {\n                bytes = vars.get(bytes);\n            }\n            \n            getBytes(bytes, function (buf) {\n                vars.set(name, buf);\n                next();\n            });\n        };\n        \n        self.skip = function (bytes) {\n            if (typeof bytes === 'string') {\n                bytes = vars.get(bytes);\n            }\n            \n            getBytes(bytes, function () {\n                next();\n            });\n        };\n        \n        self.scan = function find (name, search) {\n            if (typeof search === 'string') {\n                search = new Buffer(search);\n            }\n            else if (!Buffer.isBuffer(search)) {\n                throw new Error('search must be a Buffer or a string');\n            }\n            \n            var taken = 0;\n            pending = function () {\n                var pos = buffers.indexOf(search, offset + taken);\n                var i = pos-offset-taken;\n                if (pos !== -1) {\n                    pending = null;\n                    if (offset != null) {\n                        vars.set(\n                            name,\n                            buffers.slice(offset, offset + taken + i)\n                        );\n                        offset += taken + i + search.length;\n                    }\n                    else {\n                        vars.set(\n                            name,\n                            buffers.slice(0, taken + i)\n                        );\n                        buffers.splice(0, taken + i + search.length);\n                    }\n                    next();\n                    dispatch();\n                } else {\n                    i = Math.max(buffers.length - search.length - offset - taken, 0);\n\t\t\t\t}\n                taken += i;\n            };\n            dispatch();\n        };\n        \n        self.peek = function (cb) {\n            offset = 0;\n            saw.nest(function () {\n                cb.call(this, vars.store);\n                this.tap(function () {\n                    offset = null;\n                });\n            });\n        };\n        \n        return self;\n    };\n    \n    var stream = Chainsaw.light(builder);\n    stream.writable = true;\n    \n    var buffers = Buffers();\n    \n    stream.write = function (buf) {\n        buffers.push(buf);\n        dispatch();\n    };\n    \n    var vars = Vars();\n    \n    var done = false, caughtEnd = false;\n    stream.end = function () {\n        caughtEnd = true;\n    };\n    \n    stream.pipe = Stream.prototype.pipe;\n    Object.getOwnPropertyNames(EventEmitter.prototype).forEach(function (name) {\n        stream[name] = EventEmitter.prototype[name];\n    });\n    \n    return stream;\n};\n\nexports.parse = function parse (buffer) {\n    var self = words(function (bytes, cb) {\n        return function (name) {\n            if (offset + bytes <= buffer.length) {\n                var buf = buffer.slice(offset, offset + bytes);\n                offset += bytes;\n                vars.set(name, cb(buf));\n            }\n            else {\n                vars.set(name, null);\n            }\n            return self;\n        };\n    });\n    \n    var offset = 0;\n    var vars = Vars();\n    self.vars = vars.store;\n    \n    self.tap = function (cb) {\n        cb.call(self, vars.store);\n        return self;\n    };\n    \n    self.into = function (key, cb) {\n        if (!vars.get(key)) {\n            vars.set(key, {});\n        }\n        var parent = vars;\n        vars = Vars(parent.get(key));\n        cb.call(self, vars.store);\n        vars = parent;\n        return self;\n    };\n    \n    self.loop = function (cb) {\n        var end = false;\n        var ender = function () { end = true };\n        while (end === false) {\n            cb.call(self, ender, vars.store);\n        }\n        return self;\n    };\n    \n    self.buffer = function (name, size) {\n        if (typeof size === 'string') {\n            size = vars.get(size);\n        }\n        var buf = buffer.slice(offset, Math.min(buffer.length, offset + size));\n        offset += size;\n        vars.set(name, buf);\n        \n        return self;\n    };\n    \n    self.skip = function (bytes) {\n        if (typeof bytes === 'string') {\n            bytes = vars.get(bytes);\n        }\n        offset += bytes;\n        \n        return self;\n    };\n    \n    self.scan = function (name, search) {\n        if (typeof search === 'string') {\n            search = new Buffer(search);\n        }\n        else if (!Buffer.isBuffer(search)) {\n            throw new Error('search must be a Buffer or a string');\n        }\n        vars.set(name, null);\n        \n        // simple but slow string search\n        for (var i = 0; i + offset <= buffer.length - search.length + 1; i++) {\n            for (\n                var j = 0;\n                j < search.length && buffer[offset+i+j] === search[j];\n                j++\n            );\n            if (j === search.length) break;\n        }\n        \n        vars.set(name, buffer.slice(offset, offset + i));\n        offset += i + search.length;\n        return self;\n    };\n    \n    self.peek = function (cb) {\n        var was = offset;\n        cb.call(self, vars.store);\n        offset = was;\n        return self;\n    };\n    \n    self.flush = function () {\n        vars.store = {};\n        return self;\n    };\n    \n    self.eof = function () {\n        return offset >= buffer.length;\n    };\n    \n    return self;\n};\n\n// convert byte strings to unsigned little endian numbers\nfunction decodeLEu (bytes) {\n    var acc = 0;\n    for (var i = 0; i < bytes.length; i++) {\n        acc += Math.pow(256,i) * bytes[i];\n    }\n    return acc;\n}\n\n// convert byte strings to unsigned big endian numbers\nfunction decodeBEu (bytes) {\n    var acc = 0;\n    for (var i = 0; i < bytes.length; i++) {\n        acc += Math.pow(256, bytes.length - i - 1) * bytes[i];\n    }\n    return acc;\n}\n\n// convert byte strings to signed big endian numbers\nfunction decodeBEs (bytes) {\n    var val = decodeBEu(bytes);\n    if ((bytes[0] & 0x80) == 0x80) {\n        val -= Math.pow(256, bytes.length);\n    }\n    return val;\n}\n\n// convert byte strings to signed little endian numbers\nfunction decodeLEs (bytes) {\n    var val = decodeLEu(bytes);\n    if ((bytes[bytes.length - 1] & 0x80) == 0x80) {\n        val -= Math.pow(256, bytes.length);\n    }\n    return val;\n}\n\nfunction words (decode) {\n    var self = {};\n    \n    [ 1, 2, 4, 8 ].forEach(function (bytes) {\n        var bits = bytes * 8;\n        \n        self['word' + bits + 'le']\n        = self['word' + bits + 'lu']\n        = decode(bytes, decodeLEu);\n        \n        self['word' + bits + 'ls']\n        = decode(bytes, decodeLEs);\n        \n        self['word' + bits + 'be']\n        = self['word' + bits + 'bu']\n        = decode(bytes, decodeBEu);\n        \n        self['word' + bits + 'bs']\n        = decode(bytes, decodeBEs);\n    });\n    \n    // word8be(n) == word8le(n) for all n\n    self.word8 = self.word8u = self.word8be;\n    self.word8s = self.word8bs;\n    \n    return self;\n}\n","var Transform = require('stream').Transform;\nvar util = require('util');\n\nfunction MatcherStream(patternDesc, matchFn) {\n    if (!(this instanceof MatcherStream)) {\n        return new MatcherStream();\n    }\n\n    Transform.call(this);\n\n    var p = typeof patternDesc === 'object' ? patternDesc.pattern : patternDesc;\n\n    this.pattern = Buffer.isBuffer(p) ? p : Buffer.from(p);\n    this.requiredLength = this.pattern.length;\n    if (patternDesc.requiredExtraSize) this.requiredLength += patternDesc.requiredExtraSize;\n\n    this.data = new Buffer('');\n    this.bytesSoFar = 0;\n\n    this.matchFn = matchFn;\n}\n\nutil.inherits(MatcherStream, Transform);\n\nMatcherStream.prototype.checkDataChunk = function (ignoreMatchZero) {\n    var enoughData = this.data.length >= this.requiredLength; // strict more than ?\n    if (!enoughData) { return; }\n\n    var matchIndex = this.data.indexOf(this.pattern, ignoreMatchZero ? 1 : 0);\n    if (matchIndex >= 0 && matchIndex + this.requiredLength > this.data.length) {\n        if (matchIndex > 0) {\n            var packet = this.data.slice(0, matchIndex);\n            this.push(packet);\n            this.bytesSoFar += matchIndex;\n            this.data = this.data.slice(matchIndex);\n        }\n        return;\n    }\n\n    if (matchIndex === -1) {\n        var packetLen = this.data.length - this.requiredLength + 1;\n\n        var packet = this.data.slice(0, packetLen);\n        this.push(packet);\n        this.bytesSoFar += packetLen;\n        this.data = this.data.slice(packetLen);\n        return;\n    }\n\n    // found match\n    if (matchIndex > 0) {\n        var packet = this.data.slice(0, matchIndex);\n        this.data = this.data.slice(matchIndex);\n        this.push(packet);\n        this.bytesSoFar += matchIndex;\n    }\n\n    var finished = this.matchFn ? this.matchFn(this.data, this.bytesSoFar) : true;\n    if (finished) {\n        this.data = new Buffer('');\n        return;\n    }\n\n    return true;\n}\n\nMatcherStream.prototype._transform = function (chunk, encoding, cb) {\n    this.data = Buffer.concat([this.data, chunk]);\n\n    var firstIteration = true;\n    while (this.checkDataChunk(!firstIteration)) {\n        firstIteration = false;\n    }\n\n    cb();\n}\n\nMatcherStream.prototype._flush = function (cb) {\n    if (this.data.length > 0) {\n        var firstIteration = true;\n        while (this.checkDataChunk(!firstIteration)) {\n            firstIteration = false;\n        }\n    }\n\n    if (this.data.length > 0) {\n        this.push(this.data);\n        this.data = null;\n    }\n\n    cb();\n}\n\nmodule.exports = MatcherStream;","'use strict';\n\nvar stream = require('stream');\nvar inherits = require('util').inherits;\n\nfunction Entry() {\n    if (!(this instanceof Entry)) {\n        return new Entry();\n    }\n\n    stream.PassThrough.call(this);\n\n    this.path = null;\n    this.type = null;\n    this.isDirectory = false;\n}\n\ninherits(Entry, stream.PassThrough);\n\nEntry.prototype.autodrain = function () {\n    return this.pipe(new stream.Transform({ transform: function (d, e, cb) { cb(); } }));\n}\n\nmodule.exports = Entry;","'use strict';\n\nvar binary = require('binary');\nvar stream = require('stream');\nvar util = require('util');\nvar zlib = require('zlib');\nvar MatcherStream = require('./matcher-stream');\nvar Entry = require('./entry');\n\nconst states = {\n    STREAM_START:                         0,\n    START:                                1,\n    LOCAL_FILE_HEADER:                    2,\n    LOCAL_FILE_HEADER_SUFFIX:             3,\n    FILE_DATA:                            4,\n    FILE_DATA_END:                        5,\n    DATA_DESCRIPTOR:                      6,\n    CENTRAL_DIRECTORY_FILE_HEADER:        7,\n    CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX: 8,\n    CDIR64_END:                           9,\n    CDIR64_END_DATA_SECTOR:               10,\n    CDIR64_LOCATOR:                       11,\n    CENTRAL_DIRECTORY_END:                12,\n    CENTRAL_DIRECTORY_END_COMMENT:        13,\n    TRAILING_JUNK:                        14,\n\n    ERROR: 99\n}\n\nconst FOUR_GIGS = 4294967296;\n\nconst SIG_LOCAL_FILE_HEADER  = 0x04034b50;\nconst SIG_DATA_DESCRIPTOR    = 0x08074b50;\nconst SIG_CDIR_RECORD        = 0x02014b50;\nconst SIG_CDIR64_RECORD_END  = 0x06064b50;\nconst SIG_CDIR64_LOCATOR_END = 0x07064b50;\nconst SIG_CDIR_RECORD_END    = 0x06054b50;\n\nfunction UnzipStream(options) {\n    if (!(this instanceof UnzipStream)) {\n        return new UnzipStream(options);\n    }\n\n    stream.Transform.call(this);\n\n    this.options = options || {};\n    this.data = new Buffer('');\n    this.state = states.STREAM_START;\n    this.skippedBytes = 0;\n    this.parsedEntity = null;\n    this.outStreamInfo = {};\n}\n\nutil.inherits(UnzipStream, stream.Transform);\n\nUnzipStream.prototype.processDataChunk = function (chunk) {\n    var requiredLength;\n\n    switch (this.state) {\n        case states.STREAM_START:\n        case states.START:\n            requiredLength = 4;\n            break;\n        case states.LOCAL_FILE_HEADER:\n            requiredLength = 26;\n            break;\n        case states.LOCAL_FILE_HEADER_SUFFIX:\n            requiredLength = this.parsedEntity.fileNameLength + this.parsedEntity.extraFieldLength;\n            break;\n        case states.DATA_DESCRIPTOR:\n            requiredLength = 12;\n            break;\n        case states.CENTRAL_DIRECTORY_FILE_HEADER:\n            requiredLength = 42;\n            break;\n        case states.CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX:\n            requiredLength = this.parsedEntity.fileNameLength + this.parsedEntity.extraFieldLength + this.parsedEntity.fileCommentLength;\n            break;\n        case states.CDIR64_END:\n            requiredLength = 52;\n            break;\n        case states.CDIR64_END_DATA_SECTOR:\n            requiredLength = this.parsedEntity.centralDirectoryRecordSize - 44;\n            break;\n        case states.CDIR64_LOCATOR:\n            requiredLength = 16;\n            break;\n        case states.CENTRAL_DIRECTORY_END:\n            requiredLength = 18;\n            break;\n        case states.CENTRAL_DIRECTORY_END_COMMENT:\n            requiredLength = this.parsedEntity.commentLength;\n            break;\n        case states.FILE_DATA:\n            return 0;\n        case states.FILE_DATA_END:\n            return 0;\n        case states.TRAILING_JUNK:\n            if (this.options.debug) console.log(\"found\", chunk.length, \"bytes of TRAILING_JUNK\");\n            return chunk.length;\n        default:\n            return chunk.length;\n    }\n\n    var chunkLength = chunk.length;\n    if (chunkLength < requiredLength) {\n        return 0;\n    }\n\n    switch (this.state) {\n        case states.STREAM_START:\n        case states.START:\n            var signature = chunk.readUInt32LE(0);\n            switch (signature) {\n                case SIG_LOCAL_FILE_HEADER:\n                    this.state = states.LOCAL_FILE_HEADER;\n                    break;\n                case SIG_CDIR_RECORD:\n                    this.state = states.CENTRAL_DIRECTORY_FILE_HEADER;\n                    break;\n                case SIG_CDIR64_RECORD_END:\n                    this.state = states.CDIR64_END;\n                    break;\n                case SIG_CDIR64_LOCATOR_END:\n                    this.state = states.CDIR64_LOCATOR;\n                    break;\n                case SIG_CDIR_RECORD_END:\n                    this.state = states.CENTRAL_DIRECTORY_END;\n                    break;\n                default:\n                    var isStreamStart = this.state === states.STREAM_START;\n                    if (!isStreamStart && (signature & 0xffff) !== 0x4b50 && this.skippedBytes < 26) {\n                        // we'll allow a padding of max 28 bytes\n                        var remaining = signature;\n                        var toSkip = 4;\n                        for (var i = 1; i < 4 && remaining !== 0; i++) {\n                            remaining = remaining >>> 8;\n                            if ((remaining & 0xff) === 0x50) {\n                                toSkip = i;\n                                break;\n                            }\n                        }\n                        this.skippedBytes += toSkip;\n                        if (this.options.debug) console.log('Skipped', this.skippedBytes, 'bytes');\n                        return toSkip;\n                    }\n                    this.state = states.ERROR;\n                    var errMsg = isStreamStart ? \"Not a valid zip file\" : \"Invalid signature in zip file\";\n                    if (this.options.debug) {\n                        var sig = chunk.readUInt32LE(0);\n                        var asString;\n                        try { asString = chunk.slice(0, 4).toString(); } catch (e) {}\n                        console.log(\"Unexpected signature in zip file: 0x\" + sig.toString(16), '\"' + asString + '\", skipped', this.skippedBytes, 'bytes');\n                    }\n                    this.emit(\"error\", new Error(errMsg));\n                    return chunk.length;\n            }\n            this.skippedBytes = 0;\n            return requiredLength;\n\n        case states.LOCAL_FILE_HEADER:\n            this.parsedEntity = this._readFile(chunk);\n            this.state = states.LOCAL_FILE_HEADER_SUFFIX;\n\n            return requiredLength;\n\n        case states.LOCAL_FILE_HEADER_SUFFIX:\n            var entry = new Entry();\n            var isUtf8 = (this.parsedEntity.flags & 0x800) !== 0;\n            entry.path = this._decodeString(chunk.slice(0, this.parsedEntity.fileNameLength), isUtf8);\n            var extraDataBuffer = chunk.slice(this.parsedEntity.fileNameLength, this.parsedEntity.fileNameLength + this.parsedEntity.extraFieldLength);\n            var extra = this._readExtraFields(extraDataBuffer);\n            if (extra && extra.parsed) {\n                if (extra.parsed.path && !isUtf8) {\n                    entry.path = extra.parsed.path;\n                }\n                if (Number.isFinite(extra.parsed.uncompressedSize) && this.parsedEntity.uncompressedSize === FOUR_GIGS-1) {\n                    this.parsedEntity.uncompressedSize = extra.parsed.uncompressedSize;\n                }\n                if (Number.isFinite(extra.parsed.compressedSize) && this.parsedEntity.compressedSize === FOUR_GIGS-1) {\n                    this.parsedEntity.compressedSize = extra.parsed.compressedSize;\n                }\n            }\n            this.parsedEntity.extra = extra.parsed || {};\n\n            if (this.options.debug) {\n                const debugObj = Object.assign({}, this.parsedEntity, {\n                    path: entry.path,\n                    flags: '0x' + this.parsedEntity.flags.toString(16),\n                    extraFields: extra && extra.debug\n                });\n                console.log(\"decoded LOCAL_FILE_HEADER:\", JSON.stringify(debugObj, null, 2));\n            }\n            this._prepareOutStream(this.parsedEntity, entry);\n\n            this.emit(\"entry\", entry);\n\n            this.state = states.FILE_DATA;\n\n            return requiredLength;\n\n        case states.CENTRAL_DIRECTORY_FILE_HEADER:\n            this.parsedEntity = this._readCentralDirectoryEntry(chunk);\n            this.state = states.CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX;\n\n            return requiredLength;\n\n        case states.CENTRAL_DIRECTORY_FILE_HEADER_SUFFIX:\n            // got file name in chunk[0..]\n            var isUtf8 = (this.parsedEntity.flags & 0x800) !== 0;\n            var path = this._decodeString(chunk.slice(0, this.parsedEntity.fileNameLength), isUtf8);\n            var extraDataBuffer = chunk.slice(this.parsedEntity.fileNameLength, this.parsedEntity.fileNameLength + this.parsedEntity.extraFieldLength);\n            var extra = this._readExtraFields(extraDataBuffer);\n            if (extra && extra.parsed && extra.parsed.path && !isUtf8) {\n                path = extra.parsed.path;\n            }\n            this.parsedEntity.extra = extra.parsed;\n\n            var isUnix = ((this.parsedEntity.versionMadeBy & 0xff00) >> 8) === 3;\n            var unixAttrs, isSymlink;\n            if (isUnix) {\n                unixAttrs = this.parsedEntity.externalFileAttributes >>> 16;\n                var fileType = unixAttrs >>> 12;\n                isSymlink = (fileType & 0o12) === 0o12; // __S_IFLNK\n            }\n            if (this.options.debug) {\n                const debugObj = Object.assign({}, this.parsedEntity, {\n                    path: path,\n                    flags: '0x' + this.parsedEntity.flags.toString(16),\n                    unixAttrs: unixAttrs && '0' + unixAttrs.toString(8),\n                    isSymlink: isSymlink,\n                    extraFields: extra.debug,\n                });\n                console.log(\"decoded CENTRAL_DIRECTORY_FILE_HEADER:\", JSON.stringify(debugObj, null, 2));\n            }\n            this.state = states.START;\n\n            return requiredLength;\n\n        case states.CDIR64_END:\n            this.parsedEntity = this._readEndOfCentralDirectory64(chunk);\n            if (this.options.debug) {\n                console.log(\"decoded CDIR64_END_RECORD:\", this.parsedEntity);\n            }\n            this.state = states.CDIR64_END_DATA_SECTOR;\n\n            return requiredLength;\n\n        case states.CDIR64_END_DATA_SECTOR:\n            this.state = states.START;\n\n            return requiredLength;\n\n        case states.CDIR64_LOCATOR:\n            // ignore, nothing interesting\n            this.state = states.START;\n\n            return requiredLength;\n\n        case states.CENTRAL_DIRECTORY_END:\n            this.parsedEntity = this._readEndOfCentralDirectory(chunk);\n            if (this.options.debug) {\n                console.log(\"decoded CENTRAL_DIRECTORY_END:\", this.parsedEntity);\n            }\n            this.state = states.CENTRAL_DIRECTORY_END_COMMENT;\n\n            return requiredLength;\n\n        case states.CENTRAL_DIRECTORY_END_COMMENT:\n            if (this.options.debug) {\n                console.log(\"decoded CENTRAL_DIRECTORY_END_COMMENT:\", chunk.slice(0, requiredLength).toString());\n            }\n            this.state = states.TRAILING_JUNK;\n\n            return requiredLength;\n\n        case states.ERROR:\n            return chunk.length; // discard\n\n        default:\n            console.log(\"didn't handle state #\", this.state, \"discarding\");\n            return chunk.length;\n    }\n}\n\nUnzipStream.prototype._prepareOutStream = function (vars, entry) {\n    var self = this;\n\n    var isDirectory = vars.uncompressedSize === 0 && /[\\/\\\\]$/.test(entry.path);\n    // protect against malicious zip files which want to extract to parent dirs\n    entry.path = entry.path.replace(/(?<=^|[/\\\\]+)[.][.]+(?=[/\\\\]+|$)/g, \".\");\n    entry.type = isDirectory ? 'Directory' : 'File';\n    entry.isDirectory = isDirectory;\n\n    var fileSizeKnown = !(vars.flags & 0x08);\n    if (fileSizeKnown) {\n        entry.size = vars.uncompressedSize;\n    }\n\n    var isVersionSupported = vars.versionsNeededToExtract <= 45;\n\n    this.outStreamInfo = {\n        stream: null,\n        limit: fileSizeKnown ? vars.compressedSize : -1,\n        written: 0\n    };\n\n    if (!fileSizeKnown) {\n        var pattern = new Buffer(4);\n        pattern.writeUInt32LE(SIG_DATA_DESCRIPTOR, 0);\n        var zip64Mode = vars.extra.zip64Mode;\n        var extraSize = zip64Mode ? 20 : 12;\n        var searchPattern = {\n            pattern: pattern,\n            requiredExtraSize: extraSize\n        }\n\n        var matcherStream = new MatcherStream(searchPattern, function (matchedChunk, sizeSoFar) {\n            var vars = self._readDataDescriptor(matchedChunk, zip64Mode);\n\n            var compressedSizeMatches = vars.compressedSize === sizeSoFar;\n            // let's also deal with archives with 4GiB+ files without zip64\n            if (!zip64Mode && !compressedSizeMatches && sizeSoFar >= FOUR_GIGS) {\n                var overflown = sizeSoFar - FOUR_GIGS;\n                while (overflown >= 0) {\n                    compressedSizeMatches = vars.compressedSize === overflown;\n                    if (compressedSizeMatches) break;\n                    overflown -= FOUR_GIGS;\n                }\n            }\n            if (!compressedSizeMatches) { return; }\n\n            self.state = states.FILE_DATA_END;\n            var sliceOffset = zip64Mode ? 24 : 16;\n            if (self.data.length > 0) {\n                self.data = Buffer.concat([matchedChunk.slice(sliceOffset), self.data]);\n            } else {\n                self.data = matchedChunk.slice(sliceOffset);\n            }\n\n            return true;\n        });\n        this.outStreamInfo.stream = matcherStream;\n    } else {\n        this.outStreamInfo.stream = new stream.PassThrough();\n    }\n\n    var isEncrypted = (vars.flags & 0x01) || (vars.flags & 0x40);\n    if (isEncrypted || !isVersionSupported) {\n        var message = isEncrypted ? \"Encrypted files are not supported!\"\n            : (\"Zip version \" + Math.floor(vars.versionsNeededToExtract / 10) + \".\" + vars.versionsNeededToExtract % 10 + \" is not supported\");\n\n        entry.skip = true;\n        setImmediate(() => {\n            self.emit('error', new Error(message));\n        });\n\n        // try to skip over this entry\n        this.outStreamInfo.stream.pipe(new Entry().autodrain());\n        return;\n    }\n\n    var isCompressed = vars.compressionMethod > 0;\n    if (isCompressed) {\n        var inflater = zlib.createInflateRaw();\n        inflater.on('error', function (err) {\n            self.state = states.ERROR;\n            self.emit('error', err);\n        });\n        this.outStreamInfo.stream.pipe(inflater).pipe(entry);\n    } else {\n        this.outStreamInfo.stream.pipe(entry);\n    }\n\n    if (this._drainAllEntries) {\n        entry.autodrain();\n    }\n}\n\nUnzipStream.prototype._readFile = function (data) {\n    var vars = binary.parse(data)\n        .word16lu('versionsNeededToExtract')\n        .word16lu('flags')\n        .word16lu('compressionMethod')\n        .word16lu('lastModifiedTime')\n        .word16lu('lastModifiedDate')\n        .word32lu('crc32')\n        .word32lu('compressedSize')\n        .word32lu('uncompressedSize')\n        .word16lu('fileNameLength')\n        .word16lu('extraFieldLength')\n        .vars;\n\n    return vars;\n}\n\nUnzipStream.prototype._readExtraFields = function (data) {\n    var extra = {};\n    var result = { parsed: extra };\n    if (this.options.debug) {\n        result.debug = [];\n    }\n    var index = 0;\n    while (index < data.length) {\n        var vars = binary.parse(data)\n            .skip(index)\n            .word16lu('extraId')\n            .word16lu('extraSize')\n            .vars;\n\n        index += 4;\n\n        var fieldType = undefined;\n        switch (vars.extraId) {\n            case 0x0001:\n                fieldType = \"Zip64 extended information extra field\";\n                var z64vars = binary.parse(data.slice(index, index+vars.extraSize))\n                    .word64lu('uncompressedSize')\n                    .word64lu('compressedSize')\n                    .word64lu('offsetToLocalHeader')\n                    .word32lu('diskStartNumber')\n                    .vars;\n                if (z64vars.uncompressedSize !== null) {\n                    extra.uncompressedSize = z64vars.uncompressedSize;\n                }\n                if (z64vars.compressedSize !== null) {\n                    extra.compressedSize = z64vars.compressedSize;\n                }\n                extra.zip64Mode = true;\n                break;\n            case 0x000a:\n                fieldType = \"NTFS extra field\";\n                break;\n            case 0x5455:\n                fieldType = \"extended timestamp\";\n                var timestampFields = data.readUInt8(index);\n                var offset = 1;\n                if (vars.extraSize >= offset + 4 && timestampFields & 1) {\n                    extra.mtime = new Date(data.readUInt32LE(index + offset) * 1000);\n                    offset += 4;\n                }\n                if (vars.extraSize >= offset + 4 && timestampFields & 2) {\n                    extra.atime = new Date(data.readUInt32LE(index + offset) * 1000);\n                    offset += 4;\n                }\n                if (vars.extraSize >= offset + 4 && timestampFields & 4) {\n                    extra.ctime = new Date(data.readUInt32LE(index + offset) * 1000);\n                }\n                break;\n            case 0x7075:\n                fieldType = \"Info-ZIP Unicode Path Extra Field\";\n                var fieldVer = data.readUInt8(index);\n                if (fieldVer === 1) {\n                    var offset = 1;\n                    // TODO: should be checking this against our path buffer\n                    var nameCrc32 = data.readUInt32LE(index + offset);\n                    offset += 4;\n                    var pathBuffer = data.slice(index + offset);\n                    extra.path = pathBuffer.toString();\n                }\n                break;\n            case 0x000d:\n            case 0x5855:\n                fieldType = vars.extraId === 0x000d ? \"PKWARE Unix\" : \"Info-ZIP UNIX (type 1)\";\n                var offset = 0;\n                if (vars.extraSize >= 8) {\n                    var atime = new Date(data.readUInt32LE(index + offset) * 1000);\n                    offset += 4;\n                    var mtime = new Date(data.readUInt32LE(index + offset) * 1000);\n                    offset += 4;\n                    extra.atime = atime;\n                    extra.mtime = mtime;\n\n                    if (vars.extraSize >= 12) {\n                        var uid = data.readUInt16LE(index + offset);\n                        offset += 2;\n                        var gid = data.readUInt16LE(index + offset);\n                        offset += 2;\n                        extra.uid = uid;\n                        extra.gid = gid;\n                    }\n                }\n                break;\n            case 0x7855:\n                fieldType = \"Info-ZIP UNIX (type 2)\";\n                var offset = 0;\n                if (vars.extraSize >= 4) {\n                    var uid = data.readUInt16LE(index + offset);\n                    offset += 2;\n                    var gid = data.readUInt16LE(index + offset);\n                    offset += 2;\n                    extra.uid = uid;\n                    extra.gid = gid;\n                }\n                break;\n            case 0x7875:\n                fieldType = \"Info-ZIP New Unix\";\n                var offset = 0;\n                var extraVer = data.readUInt8(index);\n                offset += 1;\n                if (extraVer === 1) {\n                    var uidSize = data.readUInt8(index + offset);\n                    offset += 1;\n                    if (uidSize <= 6) {\n                        extra.uid = data.readUIntLE(index + offset, uidSize);\n                    }\n                    offset += uidSize;\n\n                    var gidSize = data.readUInt8(index + offset);\n                    offset += 1;\n                    if (gidSize <= 6) {\n                        extra.gid = data.readUIntLE(index + offset, gidSize);\n                    }\n                }\n                break;\n            case 0x756e:\n                fieldType = \"ASi Unix\";\n                var offset = 0;\n                if (vars.extraSize >= 14) {\n                    var crc = data.readUInt32LE(index + offset);\n                    offset += 4;\n                    var mode = data.readUInt16LE(index + offset);\n                    offset += 2;\n                    var sizdev = data.readUInt32LE(index + offset);\n                    offset += 4;\n                    var uid = data.readUInt16LE(index + offset);\n                    offset += 2;\n                    var gid = data.readUInt16LE(index + offset);\n                    offset += 2;\n                    extra.mode = mode;\n                    extra.uid = uid;\n                    extra.gid = gid;\n                    if (vars.extraSize > 14) {\n                        var start = index + offset;\n                        var end = index + vars.extraSize - 14;\n                        var symlinkName = this._decodeString(data.slice(start, end));\n                        extra.symlink = symlinkName;\n                    }\n                }\n                break;\n        }\n\n        if (this.options.debug) {\n            result.debug.push({\n                extraId: '0x' + vars.extraId.toString(16),\n                description: fieldType,\n                data: data.slice(index, index + vars.extraSize).inspect()\n            });\n        }\n\n        index += vars.extraSize;\n    }\n\n    return result;\n}\n\nUnzipStream.prototype._readDataDescriptor = function (data, zip64Mode) {\n    if (zip64Mode) {\n        var vars = binary.parse(data)\n            .word32lu('dataDescriptorSignature')\n            .word32lu('crc32')\n            .word64lu('compressedSize')\n            .word64lu('uncompressedSize')\n            .vars;\n\n        return vars;\n    }\n\n    var vars = binary.parse(data)\n        .word32lu('dataDescriptorSignature')\n        .word32lu('crc32')\n        .word32lu('compressedSize')\n        .word32lu('uncompressedSize')\n        .vars;\n\n    return vars;\n}\n\nUnzipStream.prototype._readCentralDirectoryEntry = function (data) {\n    var vars = binary.parse(data)\n        .word16lu('versionMadeBy')\n        .word16lu('versionsNeededToExtract')\n        .word16lu('flags')\n        .word16lu('compressionMethod')\n        .word16lu('lastModifiedTime')\n        .word16lu('lastModifiedDate')\n        .word32lu('crc32')\n        .word32lu('compressedSize')\n        .word32lu('uncompressedSize')\n        .word16lu('fileNameLength')\n        .word16lu('extraFieldLength')\n        .word16lu('fileCommentLength')\n        .word16lu('diskNumber')\n        .word16lu('internalFileAttributes')\n        .word32lu('externalFileAttributes')\n        .word32lu('offsetToLocalFileHeader')\n        .vars;\n\n    return vars;\n}\n\nUnzipStream.prototype._readEndOfCentralDirectory64 = function (data) {\n    var vars = binary.parse(data)\n        .word64lu('centralDirectoryRecordSize')\n        .word16lu('versionMadeBy')\n        .word16lu('versionsNeededToExtract')\n        .word32lu('diskNumber')\n        .word32lu('diskNumberWithCentralDirectoryStart')\n        .word64lu('centralDirectoryEntries')\n        .word64lu('totalCentralDirectoryEntries')\n        .word64lu('sizeOfCentralDirectory')\n        .word64lu('offsetToStartOfCentralDirectory')\n        .vars;\n\n    return vars;\n}\n\nUnzipStream.prototype._readEndOfCentralDirectory = function (data) {\n    var vars = binary.parse(data)\n        .word16lu('diskNumber')\n        .word16lu('diskStart')\n        .word16lu('centralDirectoryEntries')\n        .word16lu('totalCentralDirectoryEntries')\n        .word32lu('sizeOfCentralDirectory')\n        .word32lu('offsetToStartOfCentralDirectory')\n        .word16lu('commentLength')\n        .vars;\n\n    return vars;\n}\n\nconst cp437 = '\\u0000☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ';\n\nUnzipStream.prototype._decodeString = function (buffer, isUtf8) {\n    if (isUtf8) {\n        return buffer.toString('utf8');\n    }\n    // allow passing custom decoder\n    if (this.options.decodeString) {\n        return this.options.decodeString(buffer);\n    }\n    let result = \"\";\n    for (var i=0; i 0) {\n        this.data = this.data.slice(consume);\n        if (this.data.length === 0) break;\n    }\n\n    if (this.state === states.FILE_DATA) {\n        if (this.outStreamInfo.limit >= 0) {\n            var remaining = this.outStreamInfo.limit - this.outStreamInfo.written;\n            var packet;\n            if (remaining < this.data.length) {\n                packet = this.data.slice(0, remaining);\n                this.data = this.data.slice(remaining);\n            } else {\n                packet = this.data;\n                this.data = new Buffer('');\n            }\n\n            this.outStreamInfo.written += packet.length;\n            if (this.outStreamInfo.limit === this.outStreamInfo.written) {\n                this.state = states.START;\n\n                this.outStreamInfo.stream.end(packet, encoding, cb);\n            } else {\n                this.outStreamInfo.stream.write(packet, encoding, cb);\n            }\n        } else {\n            var packet = this.data;\n            this.data = new Buffer('');\n\n            this.outStreamInfo.written += packet.length;\n            var outputStream = this.outStreamInfo.stream;\n            outputStream.write(packet, encoding, () => {\n                if (this.state === states.FILE_DATA_END) {\n                    this.state = states.START;\n                    return outputStream.end(cb);\n                }\n                cb();\n            });\n        }\n        // we've written to the output stream, letting that write deal with the callback\n        return;\n    }\n\n    cb();\n}\n\nUnzipStream.prototype.drainAll = function () {\n    this._drainAllEntries = true;\n}\n\nUnzipStream.prototype._transform = function (chunk, encoding, cb) {\n    var self = this;\n    if (self.data.length > 0) {\n        self.data = Buffer.concat([self.data, chunk]);\n    } else {\n        self.data = chunk;\n    }\n\n    var startDataLength = self.data.length;\n    var done = function () {\n        if (self.data.length > 0 && self.data.length < startDataLength) {\n            startDataLength = self.data.length;\n            self._parseOrOutput(encoding, done);\n            return;\n        }\n        cb();\n    };\n    self._parseOrOutput(encoding, done);\n}\n\nUnzipStream.prototype._flush = function (cb) {\n    var self = this;\n    if (self.data.length > 0) {\n        self._parseOrOutput('buffer', function () {\n            if (self.data.length > 0) return setImmediate(function () { self._flush(cb); });\n            cb();\n        });\n\n        return;\n    }\n\n    if (self.state === states.FILE_DATA) {\n        // uh oh, something went wrong\n        return cb(new Error(\"Stream finished in an invalid state, uncompression failed\"));\n    }\n\n    setImmediate(cb);\n}\n\nmodule.exports = UnzipStream;\n","var Transform = require('stream').Transform;\nvar util = require('util');\nvar UnzipStream = require('./unzip-stream');\n\nfunction ParserStream(opts) {\n    if (!(this instanceof ParserStream)) {\n        return new ParserStream(opts);\n    }\n\n    var transformOpts = opts || {};\n    Transform.call(this, { readableObjectMode: true });\n\n    this.opts = opts || {};\n    this.unzipStream = new UnzipStream(this.opts);\n\n    var self = this;\n    this.unzipStream.on('entry', function(entry) {\n        self.push(entry);\n    });\n    this.unzipStream.on('error', function(error) {\n        self.emit('error', error);\n    });\n}\n\nutil.inherits(ParserStream, Transform);\n\nParserStream.prototype._transform = function (chunk, encoding, cb) {\n    this.unzipStream.write(chunk, encoding, cb);\n}\n\nParserStream.prototype._flush = function (cb) {\n    var self = this;\n    this.unzipStream.end(function() {\n        process.nextTick(function() { self.emit('close'); });\n        cb();\n    });\n}\n\nParserStream.prototype.on = function(eventName, fn) {\n    if (eventName === 'entry') {\n        return Transform.prototype.on.call(this, 'data', fn);\n    }\n    return Transform.prototype.on.call(this, eventName, fn);\n}\n\nParserStream.prototype.drainAll = function () {\n    this.unzipStream.drainAll();\n    return this.pipe(new Transform({ objectMode: true, transform: function (d, e, cb) { cb(); } }));\n}\n\nmodule.exports = ParserStream;\n","var path = require('path');\nvar fs = require('fs');\nvar _0777 = parseInt('0777', 8);\n\nmodule.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;\n\nfunction mkdirP (p, opts, f, made) {\n    if (typeof opts === 'function') {\n        f = opts;\n        opts = {};\n    }\n    else if (!opts || typeof opts !== 'object') {\n        opts = { mode: opts };\n    }\n    \n    var mode = opts.mode;\n    var xfs = opts.fs || fs;\n    \n    if (mode === undefined) {\n        mode = _0777\n    }\n    if (!made) made = null;\n    \n    var cb = f || /* istanbul ignore next */ function () {};\n    p = path.resolve(p);\n    \n    xfs.mkdir(p, mode, function (er) {\n        if (!er) {\n            made = made || p;\n            return cb(null, made);\n        }\n        switch (er.code) {\n            case 'ENOENT':\n                /* istanbul ignore if */\n                if (path.dirname(p) === p) return cb(er);\n                mkdirP(path.dirname(p), opts, function (er, made) {\n                    /* istanbul ignore if */\n                    if (er) cb(er, made);\n                    else mkdirP(p, opts, cb, made);\n                });\n                break;\n\n            // In the case of any other error, just see if there's a dir\n            // there already.  If so, then hooray!  If not, then something\n            // is borked.\n            default:\n                xfs.stat(p, function (er2, stat) {\n                    // if the stat fails, then that's super weird.\n                    // let the original error be the failure reason.\n                    if (er2 || !stat.isDirectory()) cb(er, made)\n                    else cb(null, made);\n                });\n                break;\n        }\n    });\n}\n\nmkdirP.sync = function sync (p, opts, made) {\n    if (!opts || typeof opts !== 'object') {\n        opts = { mode: opts };\n    }\n    \n    var mode = opts.mode;\n    var xfs = opts.fs || fs;\n    \n    if (mode === undefined) {\n        mode = _0777\n    }\n    if (!made) made = null;\n\n    p = path.resolve(p);\n\n    try {\n        xfs.mkdirSync(p, mode);\n        made = made || p;\n    }\n    catch (err0) {\n        switch (err0.code) {\n            case 'ENOENT' :\n                made = sync(path.dirname(p), opts, made);\n                sync(p, opts, made);\n                break;\n\n            // In the case of any other error, just see if there's a dir\n            // there already.  If so, then hooray!  If not, then something\n            // is borked.\n            default:\n                var stat;\n                try {\n                    stat = xfs.statSync(p);\n                }\n                catch (err1) /* istanbul ignore next */ {\n                    throw err0;\n                }\n                /* istanbul ignore if */\n                if (!stat.isDirectory()) throw err0;\n                break;\n        }\n    }\n\n    return made;\n};\n","var fs = require('fs');\nvar path = require('path');\nvar util = require('util');\nvar mkdirp = require('mkdirp');\nvar Transform = require('stream').Transform;\nvar UnzipStream = require('./unzip-stream');\n\nfunction Extract (opts) {\n    if (!(this instanceof Extract))\n    return new Extract(opts);\n\n    Transform.call(this);\n\n    this.opts = opts || {};\n    this.unzipStream = new UnzipStream(this.opts);\n    this.unfinishedEntries = 0;\n    this.afterFlushWait = false;\n    this.createdDirectories = {};\n\n    var self = this;\n    this.unzipStream.on('entry', this._processEntry.bind(this));\n    this.unzipStream.on('error', function(error) {\n        self.emit('error', error);\n    });\n}\n\nutil.inherits(Extract, Transform);\n\nExtract.prototype._transform = function (chunk, encoding, cb) {\n    this.unzipStream.write(chunk, encoding, cb);\n}\n\nExtract.prototype._flush = function (cb) {\n    var self = this;\n\n    var allDone = function() {\n        process.nextTick(function() { self.emit('close'); });\n        cb();\n    }\n\n    this.unzipStream.end(function() {\n        if (self.unfinishedEntries > 0) {\n            self.afterFlushWait = true;\n            return self.on('await-finished', allDone);\n        }\n        allDone();\n    });\n}\n\nExtract.prototype._processEntry = function (entry) {\n    var self = this;\n    var destPath = path.join(this.opts.path, entry.path);\n    var directory = entry.isDirectory ? destPath : path.dirname(destPath);\n\n    this.unfinishedEntries++;\n\n    var writeFileFn = function() {\n        var pipedStream = fs.createWriteStream(destPath);\n\n        pipedStream.on('close', function() {\n            self.unfinishedEntries--;\n            self._notifyAwaiter();\n        });\n        pipedStream.on('error', function (error) {\n            self.emit('error', error);\n        });\n        entry.pipe(pipedStream);\n    }\n\n    if (this.createdDirectories[directory] || directory === '.') {\n        return writeFileFn();\n    }\n\n    // FIXME: calls to mkdirp can still be duplicated\n    mkdirp(directory, function(err) {\n        if (err) return self.emit('error', err);\n\n        self.createdDirectories[directory] = true;\n\n        if (entry.isDirectory) {\n            self.unfinishedEntries--;\n            self._notifyAwaiter();\n            return;\n        }\n\n        writeFileFn();\n    });\n}\n\nExtract.prototype._notifyAwaiter = function() {\n    if (this.afterFlushWait && this.unfinishedEntries === 0) {\n        this.emit('await-finished');\n        this.afterFlushWait = false;\n    }\n}\n\nmodule.exports = Extract;","'use strict';\n\nexports.Parse = require('./lib/parser-stream');\nexports.Extract = require('./lib/extract');","'use strict'\n\nexports.fromCallback = function (fn) {\n  return Object.defineProperty(function (...args) {\n    if (typeof args[args.length - 1] === 'function') fn.apply(this, args)\n    else {\n      return new Promise((resolve, reject) => {\n        args.push((err, res) => (err != null) ? reject(err) : resolve(res))\n        fn.apply(this, args)\n      })\n    }\n  }, 'name', { value: fn.name })\n}\n\nexports.fromPromise = function (fn) {\n  return Object.defineProperty(function (...args) {\n    const cb = args[args.length - 1]\n    if (typeof cb !== 'function') return fn.apply(this, args)\n    else {\n      args.pop()\n      fn.apply(this, args).then(r => cb(null, r), cb)\n    }\n  }, 'name', { value: fn.name })\n}\n","'use strict'\n// This is adapted from https://github.com/normalize/mz\n// Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors\nconst u = require('universalify').fromCallback\nconst fs = require('graceful-fs')\n\nconst api = [\n  'access',\n  'appendFile',\n  'chmod',\n  'chown',\n  'close',\n  'copyFile',\n  'cp',\n  'fchmod',\n  'fchown',\n  'fdatasync',\n  'fstat',\n  'fsync',\n  'ftruncate',\n  'futimes',\n  'glob',\n  'lchmod',\n  'lchown',\n  'lutimes',\n  'link',\n  'lstat',\n  'mkdir',\n  'mkdtemp',\n  'open',\n  'opendir',\n  'readdir',\n  'readFile',\n  'readlink',\n  'realpath',\n  'rename',\n  'rm',\n  'rmdir',\n  'stat',\n  'statfs',\n  'symlink',\n  'truncate',\n  'unlink',\n  'utimes',\n  'writeFile'\n].filter(key => {\n  // Some commands are not available on some systems. Ex:\n  // fs.cp was added in Node.js v16.7.0\n  // fs.statfs was added in Node v19.6.0, v18.15.0\n  // fs.glob was added in Node.js v22.0.0\n  // fs.lchown is not available on at least some Linux\n  return typeof fs[key] === 'function'\n})\n\n// Export cloned fs:\nObject.assign(exports, fs)\n\n// Universalify async methods:\napi.forEach(method => {\n  exports[method] = u(fs[method])\n})\n\n// We differ from mz/fs in that we still ship the old, broken, fs.exists()\n// since we are a drop-in replacement for the native module\nexports.exists = function (filename, callback) {\n  if (typeof callback === 'function') {\n    return fs.exists(filename, callback)\n  }\n  return new Promise(resolve => {\n    return fs.exists(filename, resolve)\n  })\n}\n\n// fs.read(), fs.write(), fs.readv(), & fs.writev() need special treatment due to multiple callback args\n\nexports.read = function (fd, buffer, offset, length, position, callback) {\n  if (typeof callback === 'function') {\n    return fs.read(fd, buffer, offset, length, position, callback)\n  }\n  return new Promise((resolve, reject) => {\n    fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => {\n      if (err) return reject(err)\n      resolve({ bytesRead, buffer })\n    })\n  })\n}\n\n// Function signature can be\n// fs.write(fd, buffer[, offset[, length[, position]]], callback)\n// OR\n// fs.write(fd, string[, position[, encoding]], callback)\n// We need to handle both cases, so we use ...args\nexports.write = function (fd, buffer, ...args) {\n  if (typeof args[args.length - 1] === 'function') {\n    return fs.write(fd, buffer, ...args)\n  }\n\n  return new Promise((resolve, reject) => {\n    fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => {\n      if (err) return reject(err)\n      resolve({ bytesWritten, buffer })\n    })\n  })\n}\n\n// Function signature is\n// s.readv(fd, buffers[, position], callback)\n// We need to handle the optional arg, so we use ...args\nexports.readv = function (fd, buffers, ...args) {\n  if (typeof args[args.length - 1] === 'function') {\n    return fs.readv(fd, buffers, ...args)\n  }\n\n  return new Promise((resolve, reject) => {\n    fs.readv(fd, buffers, ...args, (err, bytesRead, buffers) => {\n      if (err) return reject(err)\n      resolve({ bytesRead, buffers })\n    })\n  })\n}\n\n// Function signature is\n// s.writev(fd, buffers[, position], callback)\n// We need to handle the optional arg, so we use ...args\nexports.writev = function (fd, buffers, ...args) {\n  if (typeof args[args.length - 1] === 'function') {\n    return fs.writev(fd, buffers, ...args)\n  }\n\n  return new Promise((resolve, reject) => {\n    fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => {\n      if (err) return reject(err)\n      resolve({ bytesWritten, buffers })\n    })\n  })\n}\n\n// fs.realpath.native sometimes not available if fs is monkey-patched\nif (typeof fs.realpath.native === 'function') {\n  exports.realpath.native = u(fs.realpath.native)\n} else {\n  process.emitWarning(\n    'fs.realpath.native is not a function. Is fs being monkey-patched?',\n    'Warning', 'fs-extra-WARN0003'\n  )\n}\n","// Adapted from https://github.com/sindresorhus/make-dir\n// Copyright (c) Sindre Sorhus  (sindresorhus.com)\n// 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:\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n// 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.\n'use strict'\nconst path = require('path')\n\n// https://github.com/nodejs/node/issues/8987\n// https://github.com/libuv/libuv/pull/1088\nmodule.exports.checkPath = function checkPath (pth) {\n  if (process.platform === 'win32') {\n    const pathHasInvalidWinCharacters = /[<>:\"|?*]/.test(pth.replace(path.parse(pth).root, ''))\n\n    if (pathHasInvalidWinCharacters) {\n      const error = new Error(`Path contains invalid characters: ${pth}`)\n      error.code = 'EINVAL'\n      throw error\n    }\n  }\n}\n","'use strict'\nconst fs = require('../fs')\nconst { checkPath } = require('./utils')\n\nconst getMode = options => {\n  const defaults = { mode: 0o777 }\n  if (typeof options === 'number') return options\n  return ({ ...defaults, ...options }).mode\n}\n\nmodule.exports.makeDir = async (dir, options) => {\n  checkPath(dir)\n\n  return fs.mkdir(dir, {\n    mode: getMode(options),\n    recursive: true\n  })\n}\n\nmodule.exports.makeDirSync = (dir, options) => {\n  checkPath(dir)\n\n  return fs.mkdirSync(dir, {\n    mode: getMode(options),\n    recursive: true\n  })\n}\n","'use strict'\nconst u = require('universalify').fromPromise\nconst { makeDir: _makeDir, makeDirSync } = require('./make-dir')\nconst makeDir = u(_makeDir)\n\nmodule.exports = {\n  mkdirs: makeDir,\n  mkdirsSync: makeDirSync,\n  // alias\n  mkdirp: makeDir,\n  mkdirpSync: makeDirSync,\n  ensureDir: makeDir,\n  ensureDirSync: makeDirSync\n}\n","'use strict'\nconst u = require('universalify').fromPromise\nconst fs = require('../fs')\n\nfunction pathExists (path) {\n  return fs.access(path).then(() => true).catch(() => false)\n}\n\nmodule.exports = {\n  pathExists: u(pathExists),\n  pathExistsSync: fs.existsSync\n}\n","'use strict'\n\nconst fs = require('../fs')\nconst u = require('universalify').fromPromise\n\nasync function utimesMillis (path, atime, mtime) {\n  // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback)\n  const fd = await fs.open(path, 'r+')\n\n  let closeErr = null\n\n  try {\n    await fs.futimes(fd, atime, mtime)\n  } finally {\n    try {\n      await fs.close(fd)\n    } catch (e) {\n      closeErr = e\n    }\n  }\n\n  if (closeErr) {\n    throw closeErr\n  }\n}\n\nfunction utimesMillisSync (path, atime, mtime) {\n  const fd = fs.openSync(path, 'r+')\n  fs.futimesSync(fd, atime, mtime)\n  return fs.closeSync(fd)\n}\n\nmodule.exports = {\n  utimesMillis: u(utimesMillis),\n  utimesMillisSync\n}\n","'use strict'\n\nconst fs = require('../fs')\nconst path = require('path')\nconst u = require('universalify').fromPromise\n\nfunction getStats (src, dest, opts) {\n  const statFunc = opts.dereference\n    ? (file) => fs.stat(file, { bigint: true })\n    : (file) => fs.lstat(file, { bigint: true })\n  return Promise.all([\n    statFunc(src),\n    statFunc(dest).catch(err => {\n      if (err.code === 'ENOENT') return null\n      throw err\n    })\n  ]).then(([srcStat, destStat]) => ({ srcStat, destStat }))\n}\n\nfunction getStatsSync (src, dest, opts) {\n  let destStat\n  const statFunc = opts.dereference\n    ? (file) => fs.statSync(file, { bigint: true })\n    : (file) => fs.lstatSync(file, { bigint: true })\n  const srcStat = statFunc(src)\n  try {\n    destStat = statFunc(dest)\n  } catch (err) {\n    if (err.code === 'ENOENT') return { srcStat, destStat: null }\n    throw err\n  }\n  return { srcStat, destStat }\n}\n\nasync function checkPaths (src, dest, funcName, opts) {\n  const { srcStat, destStat } = await getStats(src, dest, opts)\n  if (destStat) {\n    if (areIdentical(srcStat, destStat)) {\n      const srcBaseName = path.basename(src)\n      const destBaseName = path.basename(dest)\n      if (funcName === 'move' &&\n        srcBaseName !== destBaseName &&\n        srcBaseName.toLowerCase() === destBaseName.toLowerCase()) {\n        return { srcStat, destStat, isChangingCase: true }\n      }\n      throw new Error('Source and destination must not be the same.')\n    }\n    if (srcStat.isDirectory() && !destStat.isDirectory()) {\n      throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)\n    }\n    if (!srcStat.isDirectory() && destStat.isDirectory()) {\n      throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)\n    }\n  }\n\n  if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {\n    throw new Error(errMsg(src, dest, funcName))\n  }\n\n  return { srcStat, destStat }\n}\n\nfunction checkPathsSync (src, dest, funcName, opts) {\n  const { srcStat, destStat } = getStatsSync(src, dest, opts)\n\n  if (destStat) {\n    if (areIdentical(srcStat, destStat)) {\n      const srcBaseName = path.basename(src)\n      const destBaseName = path.basename(dest)\n      if (funcName === 'move' &&\n        srcBaseName !== destBaseName &&\n        srcBaseName.toLowerCase() === destBaseName.toLowerCase()) {\n        return { srcStat, destStat, isChangingCase: true }\n      }\n      throw new Error('Source and destination must not be the same.')\n    }\n    if (srcStat.isDirectory() && !destStat.isDirectory()) {\n      throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)\n    }\n    if (!srcStat.isDirectory() && destStat.isDirectory()) {\n      throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)\n    }\n  }\n\n  if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {\n    throw new Error(errMsg(src, dest, funcName))\n  }\n  return { srcStat, destStat }\n}\n\n// recursively check if dest parent is a subdirectory of src.\n// It works for all file types including symlinks since it\n// checks the src and dest inodes. It starts from the deepest\n// parent and stops once it reaches the src parent or the root path.\nasync function checkParentPaths (src, srcStat, dest, funcName) {\n  const srcParent = path.resolve(path.dirname(src))\n  const destParent = path.resolve(path.dirname(dest))\n  if (destParent === srcParent || destParent === path.parse(destParent).root) return\n\n  let destStat\n  try {\n    destStat = await fs.stat(destParent, { bigint: true })\n  } catch (err) {\n    if (err.code === 'ENOENT') return\n    throw err\n  }\n\n  if (areIdentical(srcStat, destStat)) {\n    throw new Error(errMsg(src, dest, funcName))\n  }\n\n  return checkParentPaths(src, srcStat, destParent, funcName)\n}\n\nfunction checkParentPathsSync (src, srcStat, dest, funcName) {\n  const srcParent = path.resolve(path.dirname(src))\n  const destParent = path.resolve(path.dirname(dest))\n  if (destParent === srcParent || destParent === path.parse(destParent).root) return\n  let destStat\n  try {\n    destStat = fs.statSync(destParent, { bigint: true })\n  } catch (err) {\n    if (err.code === 'ENOENT') return\n    throw err\n  }\n  if (areIdentical(srcStat, destStat)) {\n    throw new Error(errMsg(src, dest, funcName))\n  }\n  return checkParentPathsSync(src, srcStat, destParent, funcName)\n}\n\nfunction areIdentical (srcStat, destStat) {\n  return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev\n}\n\n// return true if dest is a subdir of src, otherwise false.\n// It only checks the path strings.\nfunction isSrcSubdir (src, dest) {\n  const srcArr = path.resolve(src).split(path.sep).filter(i => i)\n  const destArr = path.resolve(dest).split(path.sep).filter(i => i)\n  return srcArr.every((cur, i) => destArr[i] === cur)\n}\n\nfunction errMsg (src, dest, funcName) {\n  return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`\n}\n\nmodule.exports = {\n  // checkPaths\n  checkPaths: u(checkPaths),\n  checkPathsSync,\n  // checkParent\n  checkParentPaths: u(checkParentPaths),\n  checkParentPathsSync,\n  // Misc\n  isSrcSubdir,\n  areIdentical\n}\n","'use strict'\n\nconst fs = require('../fs')\nconst path = require('path')\nconst { mkdirs } = require('../mkdirs')\nconst { pathExists } = require('../path-exists')\nconst { utimesMillis } = require('../util/utimes')\nconst stat = require('../util/stat')\n\nasync function copy (src, dest, opts = {}) {\n  if (typeof opts === 'function') {\n    opts = { filter: opts }\n  }\n\n  opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now\n  opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber\n\n  // Warn about using preserveTimestamps on 32-bit node\n  if (opts.preserveTimestamps && process.arch === 'ia32') {\n    process.emitWarning(\n      'Using the preserveTimestamps option in 32-bit node is not recommended;\\n\\n' +\n      '\\tsee https://github.com/jprichardson/node-fs-extra/issues/269',\n      'Warning', 'fs-extra-WARN0001'\n    )\n  }\n\n  const { srcStat, destStat } = await stat.checkPaths(src, dest, 'copy', opts)\n\n  await stat.checkParentPaths(src, srcStat, dest, 'copy')\n\n  const include = await runFilter(src, dest, opts)\n\n  if (!include) return\n\n  // check if the parent of dest exists, and create it if it doesn't exist\n  const destParent = path.dirname(dest)\n  const dirExists = await pathExists(destParent)\n  if (!dirExists) {\n    await mkdirs(destParent)\n  }\n\n  await getStatsAndPerformCopy(destStat, src, dest, opts)\n}\n\nasync function runFilter (src, dest, opts) {\n  if (!opts.filter) return true\n  return opts.filter(src, dest)\n}\n\nasync function getStatsAndPerformCopy (destStat, src, dest, opts) {\n  const statFn = opts.dereference ? fs.stat : fs.lstat\n  const srcStat = await statFn(src)\n\n  if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts)\n\n  if (\n    srcStat.isFile() ||\n    srcStat.isCharacterDevice() ||\n    srcStat.isBlockDevice()\n  ) return onFile(srcStat, destStat, src, dest, opts)\n\n  if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts)\n  if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`)\n  if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`)\n  throw new Error(`Unknown file: ${src}`)\n}\n\nasync function onFile (srcStat, destStat, src, dest, opts) {\n  if (!destStat) return copyFile(srcStat, src, dest, opts)\n\n  if (opts.overwrite) {\n    await fs.unlink(dest)\n    return copyFile(srcStat, src, dest, opts)\n  }\n  if (opts.errorOnExist) {\n    throw new Error(`'${dest}' already exists`)\n  }\n}\n\nasync function copyFile (srcStat, src, dest, opts) {\n  await fs.copyFile(src, dest)\n  if (opts.preserveTimestamps) {\n    // Make sure the file is writable before setting the timestamp\n    // otherwise open fails with EPERM when invoked with 'r+'\n    // (through utimes call)\n    if (fileIsNotWritable(srcStat.mode)) {\n      await makeFileWritable(dest, srcStat.mode)\n    }\n\n    // Set timestamps and mode correspondingly\n\n    // Note that The initial srcStat.atime cannot be trusted\n    // because it is modified by the read(2) system call\n    // (See https://nodejs.org/api/fs.html#fs_stat_time_values)\n    const updatedSrcStat = await fs.stat(src)\n    await utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime)\n  }\n\n  return fs.chmod(dest, srcStat.mode)\n}\n\nfunction fileIsNotWritable (srcMode) {\n  return (srcMode & 0o200) === 0\n}\n\nfunction makeFileWritable (dest, srcMode) {\n  return fs.chmod(dest, srcMode | 0o200)\n}\n\nasync function onDir (srcStat, destStat, src, dest, opts) {\n  // the dest directory might not exist, create it\n  if (!destStat) {\n    await fs.mkdir(dest)\n  }\n\n  const promises = []\n\n  // loop through the files in the current directory to copy everything\n  for await (const item of await fs.opendir(src)) {\n    const srcItem = path.join(src, item.name)\n    const destItem = path.join(dest, item.name)\n\n    promises.push(\n      runFilter(srcItem, destItem, opts).then(include => {\n        if (include) {\n          // only copy the item if it matches the filter function\n          return stat.checkPaths(srcItem, destItem, 'copy', opts).then(({ destStat }) => {\n            // If the item is a copyable file, `getStatsAndPerformCopy` will copy it\n            // If the item is a directory, `getStatsAndPerformCopy` will call `onDir` recursively\n            return getStatsAndPerformCopy(destStat, srcItem, destItem, opts)\n          })\n        }\n      })\n    )\n  }\n\n  await Promise.all(promises)\n\n  if (!destStat) {\n    await fs.chmod(dest, srcStat.mode)\n  }\n}\n\nasync function onLink (destStat, src, dest, opts) {\n  let resolvedSrc = await fs.readlink(src)\n  if (opts.dereference) {\n    resolvedSrc = path.resolve(process.cwd(), resolvedSrc)\n  }\n  if (!destStat) {\n    return fs.symlink(resolvedSrc, dest)\n  }\n\n  let resolvedDest = null\n  try {\n    resolvedDest = await fs.readlink(dest)\n  } catch (e) {\n    // dest exists and is a regular file or directory,\n    // Windows may throw UNKNOWN error. If dest already exists,\n    // fs throws error anyway, so no need to guard against it here.\n    if (e.code === 'EINVAL' || e.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest)\n    throw e\n  }\n  if (opts.dereference) {\n    resolvedDest = path.resolve(process.cwd(), resolvedDest)\n  }\n  if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {\n    throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)\n  }\n\n  // do not copy if src is a subdir of dest since unlinking\n  // dest in this case would result in removing src contents\n  // and therefore a broken symlink would be created.\n  if (stat.isSrcSubdir(resolvedDest, resolvedSrc)) {\n    throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)\n  }\n\n  // copy the link\n  await fs.unlink(dest)\n  return fs.symlink(resolvedSrc, dest)\n}\n\nmodule.exports = copy\n","'use strict'\n\nconst fs = require('graceful-fs')\nconst path = require('path')\nconst mkdirsSync = require('../mkdirs').mkdirsSync\nconst utimesMillisSync = require('../util/utimes').utimesMillisSync\nconst stat = require('../util/stat')\n\nfunction copySync (src, dest, opts) {\n  if (typeof opts === 'function') {\n    opts = { filter: opts }\n  }\n\n  opts = opts || {}\n  opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now\n  opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber\n\n  // Warn about using preserveTimestamps on 32-bit node\n  if (opts.preserveTimestamps && process.arch === 'ia32') {\n    process.emitWarning(\n      'Using the preserveTimestamps option in 32-bit node is not recommended;\\n\\n' +\n      '\\tsee https://github.com/jprichardson/node-fs-extra/issues/269',\n      'Warning', 'fs-extra-WARN0002'\n    )\n  }\n\n  const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy', opts)\n  stat.checkParentPathsSync(src, srcStat, dest, 'copy')\n  if (opts.filter && !opts.filter(src, dest)) return\n  const destParent = path.dirname(dest)\n  if (!fs.existsSync(destParent)) mkdirsSync(destParent)\n  return getStats(destStat, src, dest, opts)\n}\n\nfunction getStats (destStat, src, dest, opts) {\n  const statSync = opts.dereference ? fs.statSync : fs.lstatSync\n  const srcStat = statSync(src)\n\n  if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts)\n  else if (srcStat.isFile() ||\n           srcStat.isCharacterDevice() ||\n           srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts)\n  else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts)\n  else if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`)\n  else if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`)\n  throw new Error(`Unknown file: ${src}`)\n}\n\nfunction onFile (srcStat, destStat, src, dest, opts) {\n  if (!destStat) return copyFile(srcStat, src, dest, opts)\n  return mayCopyFile(srcStat, src, dest, opts)\n}\n\nfunction mayCopyFile (srcStat, src, dest, opts) {\n  if (opts.overwrite) {\n    fs.unlinkSync(dest)\n    return copyFile(srcStat, src, dest, opts)\n  } else if (opts.errorOnExist) {\n    throw new Error(`'${dest}' already exists`)\n  }\n}\n\nfunction copyFile (srcStat, src, dest, opts) {\n  fs.copyFileSync(src, dest)\n  if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest)\n  return setDestMode(dest, srcStat.mode)\n}\n\nfunction handleTimestamps (srcMode, src, dest) {\n  // Make sure the file is writable before setting the timestamp\n  // otherwise open fails with EPERM when invoked with 'r+'\n  // (through utimes call)\n  if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode)\n  return setDestTimestamps(src, dest)\n}\n\nfunction fileIsNotWritable (srcMode) {\n  return (srcMode & 0o200) === 0\n}\n\nfunction makeFileWritable (dest, srcMode) {\n  return setDestMode(dest, srcMode | 0o200)\n}\n\nfunction setDestMode (dest, srcMode) {\n  return fs.chmodSync(dest, srcMode)\n}\n\nfunction setDestTimestamps (src, dest) {\n  // The initial srcStat.atime cannot be trusted\n  // because it is modified by the read(2) system call\n  // (See https://nodejs.org/api/fs.html#fs_stat_time_values)\n  const updatedSrcStat = fs.statSync(src)\n  return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime)\n}\n\nfunction onDir (srcStat, destStat, src, dest, opts) {\n  if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts)\n  return copyDir(src, dest, opts)\n}\n\nfunction mkDirAndCopy (srcMode, src, dest, opts) {\n  fs.mkdirSync(dest)\n  copyDir(src, dest, opts)\n  return setDestMode(dest, srcMode)\n}\n\nfunction copyDir (src, dest, opts) {\n  const dir = fs.opendirSync(src)\n\n  try {\n    let dirent\n\n    while ((dirent = dir.readSync()) !== null) {\n      copyDirItem(dirent.name, src, dest, opts)\n    }\n  } finally {\n    dir.closeSync()\n  }\n}\n\nfunction copyDirItem (item, src, dest, opts) {\n  const srcItem = path.join(src, item)\n  const destItem = path.join(dest, item)\n  if (opts.filter && !opts.filter(srcItem, destItem)) return\n  const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy', opts)\n  return getStats(destStat, srcItem, destItem, opts)\n}\n\nfunction onLink (destStat, src, dest, opts) {\n  let resolvedSrc = fs.readlinkSync(src)\n  if (opts.dereference) {\n    resolvedSrc = path.resolve(process.cwd(), resolvedSrc)\n  }\n\n  if (!destStat) {\n    return fs.symlinkSync(resolvedSrc, dest)\n  } else {\n    let resolvedDest\n    try {\n      resolvedDest = fs.readlinkSync(dest)\n    } catch (err) {\n      // dest exists and is a regular file or directory,\n      // Windows may throw UNKNOWN error. If dest already exists,\n      // fs throws error anyway, so no need to guard against it here.\n      if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest)\n      throw err\n    }\n    if (opts.dereference) {\n      resolvedDest = path.resolve(process.cwd(), resolvedDest)\n    }\n    if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {\n      throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)\n    }\n\n    // prevent copy if src is a subdir of dest since unlinking\n    // dest in this case would result in removing src contents\n    // and therefore a broken symlink would be created.\n    if (stat.isSrcSubdir(resolvedDest, resolvedSrc)) {\n      throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)\n    }\n    return copyLink(resolvedSrc, dest)\n  }\n}\n\nfunction copyLink (resolvedSrc, dest) {\n  fs.unlinkSync(dest)\n  return fs.symlinkSync(resolvedSrc, dest)\n}\n\nmodule.exports = copySync\n","'use strict'\n\nconst u = require('universalify').fromPromise\nmodule.exports = {\n  copy: u(require('./copy')),\n  copySync: require('./copy-sync')\n}\n","'use strict'\n\nconst fs = require('graceful-fs')\nconst u = require('universalify').fromCallback\n\nfunction remove (path, callback) {\n  fs.rm(path, { recursive: true, force: true }, callback)\n}\n\nfunction removeSync (path) {\n  fs.rmSync(path, { recursive: true, force: true })\n}\n\nmodule.exports = {\n  remove: u(remove),\n  removeSync\n}\n","'use strict'\n\nconst u = require('universalify').fromPromise\nconst fs = require('../fs')\nconst path = require('path')\nconst mkdir = require('../mkdirs')\nconst remove = require('../remove')\n\nconst emptyDir = u(async function emptyDir (dir) {\n  let items\n  try {\n    items = await fs.readdir(dir)\n  } catch {\n    return mkdir.mkdirs(dir)\n  }\n\n  return Promise.all(items.map(item => remove.remove(path.join(dir, item))))\n})\n\nfunction emptyDirSync (dir) {\n  let items\n  try {\n    items = fs.readdirSync(dir)\n  } catch {\n    return mkdir.mkdirsSync(dir)\n  }\n\n  items.forEach(item => {\n    item = path.join(dir, item)\n    remove.removeSync(item)\n  })\n}\n\nmodule.exports = {\n  emptyDirSync,\n  emptydirSync: emptyDirSync,\n  emptyDir,\n  emptydir: emptyDir\n}\n","'use strict'\n\nconst u = require('universalify').fromPromise\nconst path = require('path')\nconst fs = require('../fs')\nconst mkdir = require('../mkdirs')\n\nasync function createFile (file) {\n  let stats\n  try {\n    stats = await fs.stat(file)\n  } catch { }\n  if (stats && stats.isFile()) return\n\n  const dir = path.dirname(file)\n\n  let dirStats = null\n  try {\n    dirStats = await fs.stat(dir)\n  } catch (err) {\n    // if the directory doesn't exist, make it\n    if (err.code === 'ENOENT') {\n      await mkdir.mkdirs(dir)\n      await fs.writeFile(file, '')\n      return\n    } else {\n      throw err\n    }\n  }\n\n  if (dirStats.isDirectory()) {\n    await fs.writeFile(file, '')\n  } else {\n    // parent is not a directory\n    // This is just to cause an internal ENOTDIR error to be thrown\n    await fs.readdir(dir)\n  }\n}\n\nfunction createFileSync (file) {\n  let stats\n  try {\n    stats = fs.statSync(file)\n  } catch { }\n  if (stats && stats.isFile()) return\n\n  const dir = path.dirname(file)\n  try {\n    if (!fs.statSync(dir).isDirectory()) {\n      // parent is not a directory\n      // This is just to cause an internal ENOTDIR error to be thrown\n      fs.readdirSync(dir)\n    }\n  } catch (err) {\n    // If the stat call above failed because the directory doesn't exist, create it\n    if (err && err.code === 'ENOENT') mkdir.mkdirsSync(dir)\n    else throw err\n  }\n\n  fs.writeFileSync(file, '')\n}\n\nmodule.exports = {\n  createFile: u(createFile),\n  createFileSync\n}\n","'use strict'\n\nconst u = require('universalify').fromPromise\nconst path = require('path')\nconst fs = require('../fs')\nconst mkdir = require('../mkdirs')\nconst { pathExists } = require('../path-exists')\nconst { areIdentical } = require('../util/stat')\n\nasync function createLink (srcpath, dstpath) {\n  let dstStat\n  try {\n    dstStat = await fs.lstat(dstpath)\n  } catch {\n    // ignore error\n  }\n\n  let srcStat\n  try {\n    srcStat = await fs.lstat(srcpath)\n  } catch (err) {\n    err.message = err.message.replace('lstat', 'ensureLink')\n    throw err\n  }\n\n  if (dstStat && areIdentical(srcStat, dstStat)) return\n\n  const dir = path.dirname(dstpath)\n\n  const dirExists = await pathExists(dir)\n\n  if (!dirExists) {\n    await mkdir.mkdirs(dir)\n  }\n\n  await fs.link(srcpath, dstpath)\n}\n\nfunction createLinkSync (srcpath, dstpath) {\n  let dstStat\n  try {\n    dstStat = fs.lstatSync(dstpath)\n  } catch {}\n\n  try {\n    const srcStat = fs.lstatSync(srcpath)\n    if (dstStat && areIdentical(srcStat, dstStat)) return\n  } catch (err) {\n    err.message = err.message.replace('lstat', 'ensureLink')\n    throw err\n  }\n\n  const dir = path.dirname(dstpath)\n  const dirExists = fs.existsSync(dir)\n  if (dirExists) return fs.linkSync(srcpath, dstpath)\n  mkdir.mkdirsSync(dir)\n\n  return fs.linkSync(srcpath, dstpath)\n}\n\nmodule.exports = {\n  createLink: u(createLink),\n  createLinkSync\n}\n","'use strict'\n\nconst path = require('path')\nconst fs = require('../fs')\nconst { pathExists } = require('../path-exists')\n\nconst u = require('universalify').fromPromise\n\n/**\n * Function that returns two types of paths, one relative to symlink, and one\n * relative to the current working directory. Checks if path is absolute or\n * relative. If the path is relative, this function checks if the path is\n * relative to symlink or relative to current working directory. This is an\n * initiative to find a smarter `srcpath` to supply when building symlinks.\n * This allows you to determine which path to use out of one of three possible\n * types of source paths. The first is an absolute path. This is detected by\n * `path.isAbsolute()`. When an absolute path is provided, it is checked to\n * see if it exists. If it does it's used, if not an error is returned\n * (callback)/ thrown (sync). The other two options for `srcpath` are a\n * relative url. By default Node's `fs.symlink` works by creating a symlink\n * using `dstpath` and expects the `srcpath` to be relative to the newly\n * created symlink. If you provide a `srcpath` that does not exist on the file\n * system it results in a broken symlink. To minimize this, the function\n * checks to see if the 'relative to symlink' source file exists, and if it\n * does it will use it. If it does not, it checks if there's a file that\n * exists that is relative to the current working directory, if does its used.\n * This preserves the expectations of the original fs.symlink spec and adds\n * the ability to pass in `relative to current working direcotry` paths.\n */\n\nasync function symlinkPaths (srcpath, dstpath) {\n  if (path.isAbsolute(srcpath)) {\n    try {\n      await fs.lstat(srcpath)\n    } catch (err) {\n      err.message = err.message.replace('lstat', 'ensureSymlink')\n      throw err\n    }\n\n    return {\n      toCwd: srcpath,\n      toDst: srcpath\n    }\n  }\n\n  const dstdir = path.dirname(dstpath)\n  const relativeToDst = path.join(dstdir, srcpath)\n\n  const exists = await pathExists(relativeToDst)\n  if (exists) {\n    return {\n      toCwd: relativeToDst,\n      toDst: srcpath\n    }\n  }\n\n  try {\n    await fs.lstat(srcpath)\n  } catch (err) {\n    err.message = err.message.replace('lstat', 'ensureSymlink')\n    throw err\n  }\n\n  return {\n    toCwd: srcpath,\n    toDst: path.relative(dstdir, srcpath)\n  }\n}\n\nfunction symlinkPathsSync (srcpath, dstpath) {\n  if (path.isAbsolute(srcpath)) {\n    const exists = fs.existsSync(srcpath)\n    if (!exists) throw new Error('absolute srcpath does not exist')\n    return {\n      toCwd: srcpath,\n      toDst: srcpath\n    }\n  }\n\n  const dstdir = path.dirname(dstpath)\n  const relativeToDst = path.join(dstdir, srcpath)\n  const exists = fs.existsSync(relativeToDst)\n  if (exists) {\n    return {\n      toCwd: relativeToDst,\n      toDst: srcpath\n    }\n  }\n\n  const srcExists = fs.existsSync(srcpath)\n  if (!srcExists) throw new Error('relative srcpath does not exist')\n  return {\n    toCwd: srcpath,\n    toDst: path.relative(dstdir, srcpath)\n  }\n}\n\nmodule.exports = {\n  symlinkPaths: u(symlinkPaths),\n  symlinkPathsSync\n}\n","'use strict'\n\nconst fs = require('../fs')\nconst u = require('universalify').fromPromise\n\nasync function symlinkType (srcpath, type) {\n  if (type) return type\n\n  let stats\n  try {\n    stats = await fs.lstat(srcpath)\n  } catch {\n    return 'file'\n  }\n\n  return (stats && stats.isDirectory()) ? 'dir' : 'file'\n}\n\nfunction symlinkTypeSync (srcpath, type) {\n  if (type) return type\n\n  let stats\n  try {\n    stats = fs.lstatSync(srcpath)\n  } catch {\n    return 'file'\n  }\n  return (stats && stats.isDirectory()) ? 'dir' : 'file'\n}\n\nmodule.exports = {\n  symlinkType: u(symlinkType),\n  symlinkTypeSync\n}\n","'use strict'\n\nconst u = require('universalify').fromPromise\nconst path = require('path')\nconst fs = require('../fs')\n\nconst { mkdirs, mkdirsSync } = require('../mkdirs')\n\nconst { symlinkPaths, symlinkPathsSync } = require('./symlink-paths')\nconst { symlinkType, symlinkTypeSync } = require('./symlink-type')\n\nconst { pathExists } = require('../path-exists')\n\nconst { areIdentical } = require('../util/stat')\n\nasync function createSymlink (srcpath, dstpath, type) {\n  let stats\n  try {\n    stats = await fs.lstat(dstpath)\n  } catch { }\n\n  if (stats && stats.isSymbolicLink()) {\n    const [srcStat, dstStat] = await Promise.all([\n      fs.stat(srcpath),\n      fs.stat(dstpath)\n    ])\n\n    if (areIdentical(srcStat, dstStat)) return\n  }\n\n  const relative = await symlinkPaths(srcpath, dstpath)\n  srcpath = relative.toDst\n  const toType = await symlinkType(relative.toCwd, type)\n  const dir = path.dirname(dstpath)\n\n  if (!(await pathExists(dir))) {\n    await mkdirs(dir)\n  }\n\n  return fs.symlink(srcpath, dstpath, toType)\n}\n\nfunction createSymlinkSync (srcpath, dstpath, type) {\n  let stats\n  try {\n    stats = fs.lstatSync(dstpath)\n  } catch { }\n  if (stats && stats.isSymbolicLink()) {\n    const srcStat = fs.statSync(srcpath)\n    const dstStat = fs.statSync(dstpath)\n    if (areIdentical(srcStat, dstStat)) return\n  }\n\n  const relative = symlinkPathsSync(srcpath, dstpath)\n  srcpath = relative.toDst\n  type = symlinkTypeSync(relative.toCwd, type)\n  const dir = path.dirname(dstpath)\n  const exists = fs.existsSync(dir)\n  if (exists) return fs.symlinkSync(srcpath, dstpath, type)\n  mkdirsSync(dir)\n  return fs.symlinkSync(srcpath, dstpath, type)\n}\n\nmodule.exports = {\n  createSymlink: u(createSymlink),\n  createSymlinkSync\n}\n","'use strict'\n\nconst { createFile, createFileSync } = require('./file')\nconst { createLink, createLinkSync } = require('./link')\nconst { createSymlink, createSymlinkSync } = require('./symlink')\n\nmodule.exports = {\n  // file\n  createFile,\n  createFileSync,\n  ensureFile: createFile,\n  ensureFileSync: createFileSync,\n  // link\n  createLink,\n  createLinkSync,\n  ensureLink: createLink,\n  ensureLinkSync: createLinkSync,\n  // symlink\n  createSymlink,\n  createSymlinkSync,\n  ensureSymlink: createSymlink,\n  ensureSymlinkSync: createSymlinkSync\n}\n","function stringify (obj, { EOL = '\\n', finalEOL = true, replacer = null, spaces } = {}) {\n  const EOF = finalEOL ? EOL : ''\n  const str = JSON.stringify(obj, replacer, spaces)\n\n  return str.replace(/\\n/g, EOL) + EOF\n}\n\nfunction stripBom (content) {\n  // we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified\n  if (Buffer.isBuffer(content)) content = content.toString('utf8')\n  return content.replace(/^\\uFEFF/, '')\n}\n\nmodule.exports = { stringify, stripBom }\n","let _fs\ntry {\n  _fs = require('graceful-fs')\n} catch (_) {\n  _fs = require('fs')\n}\nconst universalify = require('universalify')\nconst { stringify, stripBom } = require('./utils')\n\nasync function _readFile (file, options = {}) {\n  if (typeof options === 'string') {\n    options = { encoding: options }\n  }\n\n  const fs = options.fs || _fs\n\n  const shouldThrow = 'throws' in options ? options.throws : true\n\n  let data = await universalify.fromCallback(fs.readFile)(file, options)\n\n  data = stripBom(data)\n\n  let obj\n  try {\n    obj = JSON.parse(data, options ? options.reviver : null)\n  } catch (err) {\n    if (shouldThrow) {\n      err.message = `${file}: ${err.message}`\n      throw err\n    } else {\n      return null\n    }\n  }\n\n  return obj\n}\n\nconst readFile = universalify.fromPromise(_readFile)\n\nfunction readFileSync (file, options = {}) {\n  if (typeof options === 'string') {\n    options = { encoding: options }\n  }\n\n  const fs = options.fs || _fs\n\n  const shouldThrow = 'throws' in options ? options.throws : true\n\n  try {\n    let content = fs.readFileSync(file, options)\n    content = stripBom(content)\n    return JSON.parse(content, options.reviver)\n  } catch (err) {\n    if (shouldThrow) {\n      err.message = `${file}: ${err.message}`\n      throw err\n    } else {\n      return null\n    }\n  }\n}\n\nasync function _writeFile (file, obj, options = {}) {\n  const fs = options.fs || _fs\n\n  const str = stringify(obj, options)\n\n  await universalify.fromCallback(fs.writeFile)(file, str, options)\n}\n\nconst writeFile = universalify.fromPromise(_writeFile)\n\nfunction writeFileSync (file, obj, options = {}) {\n  const fs = options.fs || _fs\n\n  const str = stringify(obj, options)\n  // not sure if fs.writeFileSync returns anything, but just in case\n  return fs.writeFileSync(file, str, options)\n}\n\nconst jsonfile = {\n  readFile,\n  readFileSync,\n  writeFile,\n  writeFileSync\n}\n\nmodule.exports = jsonfile\n","'use strict'\n\nconst jsonFile = require('jsonfile')\n\nmodule.exports = {\n  // jsonfile exports\n  readJson: jsonFile.readFile,\n  readJsonSync: jsonFile.readFileSync,\n  writeJson: jsonFile.writeFile,\n  writeJsonSync: jsonFile.writeFileSync\n}\n","'use strict'\n\nconst u = require('universalify').fromPromise\nconst fs = require('../fs')\nconst path = require('path')\nconst mkdir = require('../mkdirs')\nconst pathExists = require('../path-exists').pathExists\n\nasync function outputFile (file, data, encoding = 'utf-8') {\n  const dir = path.dirname(file)\n\n  if (!(await pathExists(dir))) {\n    await mkdir.mkdirs(dir)\n  }\n\n  return fs.writeFile(file, data, encoding)\n}\n\nfunction outputFileSync (file, ...args) {\n  const dir = path.dirname(file)\n  if (!fs.existsSync(dir)) {\n    mkdir.mkdirsSync(dir)\n  }\n\n  fs.writeFileSync(file, ...args)\n}\n\nmodule.exports = {\n  outputFile: u(outputFile),\n  outputFileSync\n}\n","'use strict'\n\nconst { stringify } = require('jsonfile/utils')\nconst { outputFile } = require('../output-file')\n\nasync function outputJson (file, data, options = {}) {\n  const str = stringify(data, options)\n\n  await outputFile(file, str, options)\n}\n\nmodule.exports = outputJson\n","'use strict'\n\nconst { stringify } = require('jsonfile/utils')\nconst { outputFileSync } = require('../output-file')\n\nfunction outputJsonSync (file, data, options) {\n  const str = stringify(data, options)\n\n  outputFileSync(file, str, options)\n}\n\nmodule.exports = outputJsonSync\n","'use strict'\n\nconst u = require('universalify').fromPromise\nconst jsonFile = require('./jsonfile')\n\njsonFile.outputJson = u(require('./output-json'))\njsonFile.outputJsonSync = require('./output-json-sync')\n// aliases\njsonFile.outputJSON = jsonFile.outputJson\njsonFile.outputJSONSync = jsonFile.outputJsonSync\njsonFile.writeJSON = jsonFile.writeJson\njsonFile.writeJSONSync = jsonFile.writeJsonSync\njsonFile.readJSON = jsonFile.readJson\njsonFile.readJSONSync = jsonFile.readJsonSync\n\nmodule.exports = jsonFile\n","'use strict'\n\nconst fs = require('../fs')\nconst path = require('path')\nconst { copy } = require('../copy')\nconst { remove } = require('../remove')\nconst { mkdirp } = require('../mkdirs')\nconst { pathExists } = require('../path-exists')\nconst stat = require('../util/stat')\n\nasync function move (src, dest, opts = {}) {\n  const overwrite = opts.overwrite || opts.clobber || false\n\n  const { srcStat, isChangingCase = false } = await stat.checkPaths(src, dest, 'move', opts)\n\n  await stat.checkParentPaths(src, srcStat, dest, 'move')\n\n  // If the parent of dest is not root, make sure it exists before proceeding\n  const destParent = path.dirname(dest)\n  const parsedParentPath = path.parse(destParent)\n  if (parsedParentPath.root !== destParent) {\n    await mkdirp(destParent)\n  }\n\n  return doRename(src, dest, overwrite, isChangingCase)\n}\n\nasync function doRename (src, dest, overwrite, isChangingCase) {\n  if (!isChangingCase) {\n    if (overwrite) {\n      await remove(dest)\n    } else if (await pathExists(dest)) {\n      throw new Error('dest already exists.')\n    }\n  }\n\n  try {\n    // Try w/ rename first, and try copy + remove if EXDEV\n    await fs.rename(src, dest)\n  } catch (err) {\n    if (err.code !== 'EXDEV') {\n      throw err\n    }\n    await moveAcrossDevice(src, dest, overwrite)\n  }\n}\n\nasync function moveAcrossDevice (src, dest, overwrite) {\n  const opts = {\n    overwrite,\n    errorOnExist: true,\n    preserveTimestamps: true\n  }\n\n  await copy(src, dest, opts)\n  return remove(src)\n}\n\nmodule.exports = move\n","'use strict'\n\nconst fs = require('graceful-fs')\nconst path = require('path')\nconst copySync = require('../copy').copySync\nconst removeSync = require('../remove').removeSync\nconst mkdirpSync = require('../mkdirs').mkdirpSync\nconst stat = require('../util/stat')\n\nfunction moveSync (src, dest, opts) {\n  opts = opts || {}\n  const overwrite = opts.overwrite || opts.clobber || false\n\n  const { srcStat, isChangingCase = false } = stat.checkPathsSync(src, dest, 'move', opts)\n  stat.checkParentPathsSync(src, srcStat, dest, 'move')\n  if (!isParentRoot(dest)) mkdirpSync(path.dirname(dest))\n  return doRename(src, dest, overwrite, isChangingCase)\n}\n\nfunction isParentRoot (dest) {\n  const parent = path.dirname(dest)\n  const parsedPath = path.parse(parent)\n  return parsedPath.root === parent\n}\n\nfunction doRename (src, dest, overwrite, isChangingCase) {\n  if (isChangingCase) return rename(src, dest, overwrite)\n  if (overwrite) {\n    removeSync(dest)\n    return rename(src, dest, overwrite)\n  }\n  if (fs.existsSync(dest)) throw new Error('dest already exists.')\n  return rename(src, dest, overwrite)\n}\n\nfunction rename (src, dest, overwrite) {\n  try {\n    fs.renameSync(src, dest)\n  } catch (err) {\n    if (err.code !== 'EXDEV') throw err\n    return moveAcrossDevice(src, dest, overwrite)\n  }\n}\n\nfunction moveAcrossDevice (src, dest, overwrite) {\n  const opts = {\n    overwrite,\n    errorOnExist: true,\n    preserveTimestamps: true\n  }\n  copySync(src, dest, opts)\n  return removeSync(src)\n}\n\nmodule.exports = moveSync\n","'use strict'\n\nconst u = require('universalify').fromPromise\nmodule.exports = {\n  move: u(require('./move')),\n  moveSync: require('./move-sync')\n}\n","'use strict'\n\nmodule.exports = {\n  // Export promiseified graceful-fs:\n  ...require('./fs'),\n  // Export extra methods:\n  ...require('./copy'),\n  ...require('./empty'),\n  ...require('./ensure'),\n  ...require('./json'),\n  ...require('./mkdirs'),\n  ...require('./move'),\n  ...require('./output-file'),\n  ...require('./path-exists'),\n  ...require('./remove')\n}\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  exports.defaults = {\n    \"0.1\": {\n      explicitCharkey: false,\n      trim: true,\n      normalize: true,\n      normalizeTags: false,\n      attrkey: \"@\",\n      charkey: \"#\",\n      explicitArray: false,\n      ignoreAttrs: false,\n      mergeAttrs: false,\n      explicitRoot: false,\n      validator: null,\n      xmlns: false,\n      explicitChildren: false,\n      childkey: '@@',\n      charsAsChildren: false,\n      includeWhiteChars: false,\n      async: false,\n      strict: true,\n      attrNameProcessors: null,\n      attrValueProcessors: null,\n      tagNameProcessors: null,\n      valueProcessors: null,\n      emptyTag: ''\n    },\n    \"0.2\": {\n      explicitCharkey: false,\n      trim: false,\n      normalize: false,\n      normalizeTags: false,\n      attrkey: \"$\",\n      charkey: \"_\",\n      explicitArray: true,\n      ignoreAttrs: false,\n      mergeAttrs: false,\n      explicitRoot: true,\n      validator: null,\n      xmlns: false,\n      explicitChildren: false,\n      preserveChildrenOrder: false,\n      childkey: '$$',\n      charsAsChildren: false,\n      includeWhiteChars: false,\n      async: false,\n      strict: true,\n      attrNameProcessors: null,\n      attrValueProcessors: null,\n      tagNameProcessors: null,\n      valueProcessors: null,\n      rootName: 'root',\n      xmldec: {\n        'version': '1.0',\n        'encoding': 'UTF-8',\n        'standalone': true\n      },\n      doctype: null,\n      renderOpts: {\n        'pretty': true,\n        'indent': '  ',\n        'newline': '\\n'\n      },\n      headless: false,\n      chunkSize: 10000,\n      emptyTag: '',\n      cdata: false\n    }\n  };\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var assign, getValue, isArray, isEmpty, isFunction, isObject, isPlainObject,\n    slice = [].slice,\n    hasProp = {}.hasOwnProperty;\n\n  assign = function() {\n    var i, key, len, source, sources, target;\n    target = arguments[0], sources = 2 <= arguments.length ? slice.call(arguments, 1) : [];\n    if (isFunction(Object.assign)) {\n      Object.assign.apply(null, arguments);\n    } else {\n      for (i = 0, len = sources.length; i < len; i++) {\n        source = sources[i];\n        if (source != null) {\n          for (key in source) {\n            if (!hasProp.call(source, key)) continue;\n            target[key] = source[key];\n          }\n        }\n      }\n    }\n    return target;\n  };\n\n  isFunction = function(val) {\n    return !!val && Object.prototype.toString.call(val) === '[object Function]';\n  };\n\n  isObject = function(val) {\n    var ref;\n    return !!val && ((ref = typeof val) === 'function' || ref === 'object');\n  };\n\n  isArray = function(val) {\n    if (isFunction(Array.isArray)) {\n      return Array.isArray(val);\n    } else {\n      return Object.prototype.toString.call(val) === '[object Array]';\n    }\n  };\n\n  isEmpty = function(val) {\n    var key;\n    if (isArray(val)) {\n      return !val.length;\n    } else {\n      for (key in val) {\n        if (!hasProp.call(val, key)) continue;\n        return false;\n      }\n      return true;\n    }\n  };\n\n  isPlainObject = function(val) {\n    var ctor, proto;\n    return isObject(val) && (proto = Object.getPrototypeOf(val)) && (ctor = proto.constructor) && (typeof ctor === 'function') && (ctor instanceof ctor) && (Function.prototype.toString.call(ctor) === Function.prototype.toString.call(Object));\n  };\n\n  getValue = function(obj) {\n    if (isFunction(obj.valueOf)) {\n      return obj.valueOf();\n    } else {\n      return obj;\n    }\n  };\n\n  module.exports.assign = assign;\n\n  module.exports.isFunction = isFunction;\n\n  module.exports.isObject = isObject;\n\n  module.exports.isArray = isArray;\n\n  module.exports.isEmpty = isEmpty;\n\n  module.exports.isPlainObject = isPlainObject;\n\n  module.exports.getValue = getValue;\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var XMLDOMImplementation;\n\n  module.exports = XMLDOMImplementation = (function() {\n    function XMLDOMImplementation() {}\n\n    XMLDOMImplementation.prototype.hasFeature = function(feature, version) {\n      return true;\n    };\n\n    XMLDOMImplementation.prototype.createDocumentType = function(qualifiedName, publicId, systemId) {\n      throw new Error(\"This DOM method is not implemented.\");\n    };\n\n    XMLDOMImplementation.prototype.createDocument = function(namespaceURI, qualifiedName, doctype) {\n      throw new Error(\"This DOM method is not implemented.\");\n    };\n\n    XMLDOMImplementation.prototype.createHTMLDocument = function(title) {\n      throw new Error(\"This DOM method is not implemented.\");\n    };\n\n    XMLDOMImplementation.prototype.getFeature = function(feature, version) {\n      throw new Error(\"This DOM method is not implemented.\");\n    };\n\n    return XMLDOMImplementation;\n\n  })();\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var XMLDOMErrorHandler;\n\n  module.exports = XMLDOMErrorHandler = (function() {\n    function XMLDOMErrorHandler() {}\n\n    XMLDOMErrorHandler.prototype.handleError = function(error) {\n      throw new Error(error);\n    };\n\n    return XMLDOMErrorHandler;\n\n  })();\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var XMLDOMStringList;\n\n  module.exports = XMLDOMStringList = (function() {\n    function XMLDOMStringList(arr) {\n      this.arr = arr || [];\n    }\n\n    Object.defineProperty(XMLDOMStringList.prototype, 'length', {\n      get: function() {\n        return this.arr.length;\n      }\n    });\n\n    XMLDOMStringList.prototype.item = function(index) {\n      return this.arr[index] || null;\n    };\n\n    XMLDOMStringList.prototype.contains = function(str) {\n      return this.arr.indexOf(str) !== -1;\n    };\n\n    return XMLDOMStringList;\n\n  })();\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var XMLDOMConfiguration, XMLDOMErrorHandler, XMLDOMStringList;\n\n  XMLDOMErrorHandler = require('./XMLDOMErrorHandler');\n\n  XMLDOMStringList = require('./XMLDOMStringList');\n\n  module.exports = XMLDOMConfiguration = (function() {\n    function XMLDOMConfiguration() {\n      var clonedSelf;\n      this.defaultParams = {\n        \"canonical-form\": false,\n        \"cdata-sections\": false,\n        \"comments\": false,\n        \"datatype-normalization\": false,\n        \"element-content-whitespace\": true,\n        \"entities\": true,\n        \"error-handler\": new XMLDOMErrorHandler(),\n        \"infoset\": true,\n        \"validate-if-schema\": false,\n        \"namespaces\": true,\n        \"namespace-declarations\": true,\n        \"normalize-characters\": false,\n        \"schema-location\": '',\n        \"schema-type\": '',\n        \"split-cdata-sections\": true,\n        \"validate\": false,\n        \"well-formed\": true\n      };\n      this.params = clonedSelf = Object.create(this.defaultParams);\n    }\n\n    Object.defineProperty(XMLDOMConfiguration.prototype, 'parameterNames', {\n      get: function() {\n        return new XMLDOMStringList(Object.keys(this.defaultParams));\n      }\n    });\n\n    XMLDOMConfiguration.prototype.getParameter = function(name) {\n      if (this.params.hasOwnProperty(name)) {\n        return this.params[name];\n      } else {\n        return null;\n      }\n    };\n\n    XMLDOMConfiguration.prototype.canSetParameter = function(name, value) {\n      return true;\n    };\n\n    XMLDOMConfiguration.prototype.setParameter = function(name, value) {\n      if (value != null) {\n        return this.params[name] = value;\n      } else {\n        return delete this.params[name];\n      }\n    };\n\n    return XMLDOMConfiguration;\n\n  })();\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  module.exports = {\n    Element: 1,\n    Attribute: 2,\n    Text: 3,\n    CData: 4,\n    EntityReference: 5,\n    EntityDeclaration: 6,\n    ProcessingInstruction: 7,\n    Comment: 8,\n    Document: 9,\n    DocType: 10,\n    DocumentFragment: 11,\n    NotationDeclaration: 12,\n    Declaration: 201,\n    Raw: 202,\n    AttributeDeclaration: 203,\n    ElementDeclaration: 204,\n    Dummy: 205\n  };\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var NodeType, XMLAttribute, XMLNode;\n\n  NodeType = require('./NodeType');\n\n  XMLNode = require('./XMLNode');\n\n  module.exports = XMLAttribute = (function() {\n    function XMLAttribute(parent, name, value) {\n      this.parent = parent;\n      if (this.parent) {\n        this.options = this.parent.options;\n        this.stringify = this.parent.stringify;\n      }\n      if (name == null) {\n        throw new Error(\"Missing attribute name. \" + this.debugInfo(name));\n      }\n      this.name = this.stringify.name(name);\n      this.value = this.stringify.attValue(value);\n      this.type = NodeType.Attribute;\n      this.isId = false;\n      this.schemaTypeInfo = null;\n    }\n\n    Object.defineProperty(XMLAttribute.prototype, 'nodeType', {\n      get: function() {\n        return this.type;\n      }\n    });\n\n    Object.defineProperty(XMLAttribute.prototype, 'ownerElement', {\n      get: function() {\n        return this.parent;\n      }\n    });\n\n    Object.defineProperty(XMLAttribute.prototype, 'textContent', {\n      get: function() {\n        return this.value;\n      },\n      set: function(value) {\n        return this.value = value || '';\n      }\n    });\n\n    Object.defineProperty(XMLAttribute.prototype, 'namespaceURI', {\n      get: function() {\n        return '';\n      }\n    });\n\n    Object.defineProperty(XMLAttribute.prototype, 'prefix', {\n      get: function() {\n        return '';\n      }\n    });\n\n    Object.defineProperty(XMLAttribute.prototype, 'localName', {\n      get: function() {\n        return this.name;\n      }\n    });\n\n    Object.defineProperty(XMLAttribute.prototype, 'specified', {\n      get: function() {\n        return true;\n      }\n    });\n\n    XMLAttribute.prototype.clone = function() {\n      return Object.create(this);\n    };\n\n    XMLAttribute.prototype.toString = function(options) {\n      return this.options.writer.attribute(this, this.options.writer.filterOptions(options));\n    };\n\n    XMLAttribute.prototype.debugInfo = function(name) {\n      name = name || this.name;\n      if (name == null) {\n        return \"parent: <\" + this.parent.name + \">\";\n      } else {\n        return \"attribute: {\" + name + \"}, parent: <\" + this.parent.name + \">\";\n      }\n    };\n\n    XMLAttribute.prototype.isEqualNode = function(node) {\n      if (node.namespaceURI !== this.namespaceURI) {\n        return false;\n      }\n      if (node.prefix !== this.prefix) {\n        return false;\n      }\n      if (node.localName !== this.localName) {\n        return false;\n      }\n      if (node.value !== this.value) {\n        return false;\n      }\n      return true;\n    };\n\n    return XMLAttribute;\n\n  })();\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var XMLNamedNodeMap;\n\n  module.exports = XMLNamedNodeMap = (function() {\n    function XMLNamedNodeMap(nodes) {\n      this.nodes = nodes;\n    }\n\n    Object.defineProperty(XMLNamedNodeMap.prototype, 'length', {\n      get: function() {\n        return Object.keys(this.nodes).length || 0;\n      }\n    });\n\n    XMLNamedNodeMap.prototype.clone = function() {\n      return this.nodes = null;\n    };\n\n    XMLNamedNodeMap.prototype.getNamedItem = function(name) {\n      return this.nodes[name];\n    };\n\n    XMLNamedNodeMap.prototype.setNamedItem = function(node) {\n      var oldNode;\n      oldNode = this.nodes[node.nodeName];\n      this.nodes[node.nodeName] = node;\n      return oldNode || null;\n    };\n\n    XMLNamedNodeMap.prototype.removeNamedItem = function(name) {\n      var oldNode;\n      oldNode = this.nodes[name];\n      delete this.nodes[name];\n      return oldNode || null;\n    };\n\n    XMLNamedNodeMap.prototype.item = function(index) {\n      return this.nodes[Object.keys(this.nodes)[index]] || null;\n    };\n\n    XMLNamedNodeMap.prototype.getNamedItemNS = function(namespaceURI, localName) {\n      throw new Error(\"This DOM method is not implemented.\");\n    };\n\n    XMLNamedNodeMap.prototype.setNamedItemNS = function(node) {\n      throw new Error(\"This DOM method is not implemented.\");\n    };\n\n    XMLNamedNodeMap.prototype.removeNamedItemNS = function(namespaceURI, localName) {\n      throw new Error(\"This DOM method is not implemented.\");\n    };\n\n    return XMLNamedNodeMap;\n\n  })();\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var NodeType, XMLAttribute, XMLElement, XMLNamedNodeMap, XMLNode, getValue, isFunction, isObject, ref,\n    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\n    hasProp = {}.hasOwnProperty;\n\n  ref = require('./Utility'), isObject = ref.isObject, isFunction = ref.isFunction, getValue = ref.getValue;\n\n  XMLNode = require('./XMLNode');\n\n  NodeType = require('./NodeType');\n\n  XMLAttribute = require('./XMLAttribute');\n\n  XMLNamedNodeMap = require('./XMLNamedNodeMap');\n\n  module.exports = XMLElement = (function(superClass) {\n    extend(XMLElement, superClass);\n\n    function XMLElement(parent, name, attributes) {\n      var child, j, len, ref1;\n      XMLElement.__super__.constructor.call(this, parent);\n      if (name == null) {\n        throw new Error(\"Missing element name. \" + this.debugInfo());\n      }\n      this.name = this.stringify.name(name);\n      this.type = NodeType.Element;\n      this.attribs = {};\n      this.schemaTypeInfo = null;\n      if (attributes != null) {\n        this.attribute(attributes);\n      }\n      if (parent.type === NodeType.Document) {\n        this.isRoot = true;\n        this.documentObject = parent;\n        parent.rootObject = this;\n        if (parent.children) {\n          ref1 = parent.children;\n          for (j = 0, len = ref1.length; j < len; j++) {\n            child = ref1[j];\n            if (child.type === NodeType.DocType) {\n              child.name = this.name;\n              break;\n            }\n          }\n        }\n      }\n    }\n\n    Object.defineProperty(XMLElement.prototype, 'tagName', {\n      get: function() {\n        return this.name;\n      }\n    });\n\n    Object.defineProperty(XMLElement.prototype, 'namespaceURI', {\n      get: function() {\n        return '';\n      }\n    });\n\n    Object.defineProperty(XMLElement.prototype, 'prefix', {\n      get: function() {\n        return '';\n      }\n    });\n\n    Object.defineProperty(XMLElement.prototype, 'localName', {\n      get: function() {\n        return this.name;\n      }\n    });\n\n    Object.defineProperty(XMLElement.prototype, 'id', {\n      get: function() {\n        throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n      }\n    });\n\n    Object.defineProperty(XMLElement.prototype, 'className', {\n      get: function() {\n        throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n      }\n    });\n\n    Object.defineProperty(XMLElement.prototype, 'classList', {\n      get: function() {\n        throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n      }\n    });\n\n    Object.defineProperty(XMLElement.prototype, 'attributes', {\n      get: function() {\n        if (!this.attributeMap || !this.attributeMap.nodes) {\n          this.attributeMap = new XMLNamedNodeMap(this.attribs);\n        }\n        return this.attributeMap;\n      }\n    });\n\n    XMLElement.prototype.clone = function() {\n      var att, attName, clonedSelf, ref1;\n      clonedSelf = Object.create(this);\n      if (clonedSelf.isRoot) {\n        clonedSelf.documentObject = null;\n      }\n      clonedSelf.attribs = {};\n      ref1 = this.attribs;\n      for (attName in ref1) {\n        if (!hasProp.call(ref1, attName)) continue;\n        att = ref1[attName];\n        clonedSelf.attribs[attName] = att.clone();\n      }\n      clonedSelf.children = [];\n      this.children.forEach(function(child) {\n        var clonedChild;\n        clonedChild = child.clone();\n        clonedChild.parent = clonedSelf;\n        return clonedSelf.children.push(clonedChild);\n      });\n      return clonedSelf;\n    };\n\n    XMLElement.prototype.attribute = function(name, value) {\n      var attName, attValue;\n      if (name != null) {\n        name = getValue(name);\n      }\n      if (isObject(name)) {\n        for (attName in name) {\n          if (!hasProp.call(name, attName)) continue;\n          attValue = name[attName];\n          this.attribute(attName, attValue);\n        }\n      } else {\n        if (isFunction(value)) {\n          value = value.apply();\n        }\n        if (this.options.keepNullAttributes && (value == null)) {\n          this.attribs[name] = new XMLAttribute(this, name, \"\");\n        } else if (value != null) {\n          this.attribs[name] = new XMLAttribute(this, name, value);\n        }\n      }\n      return this;\n    };\n\n    XMLElement.prototype.removeAttribute = function(name) {\n      var attName, j, len;\n      if (name == null) {\n        throw new Error(\"Missing attribute name. \" + this.debugInfo());\n      }\n      name = getValue(name);\n      if (Array.isArray(name)) {\n        for (j = 0, len = name.length; j < len; j++) {\n          attName = name[j];\n          delete this.attribs[attName];\n        }\n      } else {\n        delete this.attribs[name];\n      }\n      return this;\n    };\n\n    XMLElement.prototype.toString = function(options) {\n      return this.options.writer.element(this, this.options.writer.filterOptions(options));\n    };\n\n    XMLElement.prototype.att = function(name, value) {\n      return this.attribute(name, value);\n    };\n\n    XMLElement.prototype.a = function(name, value) {\n      return this.attribute(name, value);\n    };\n\n    XMLElement.prototype.getAttribute = function(name) {\n      if (this.attribs.hasOwnProperty(name)) {\n        return this.attribs[name].value;\n      } else {\n        return null;\n      }\n    };\n\n    XMLElement.prototype.setAttribute = function(name, value) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLElement.prototype.getAttributeNode = function(name) {\n      if (this.attribs.hasOwnProperty(name)) {\n        return this.attribs[name];\n      } else {\n        return null;\n      }\n    };\n\n    XMLElement.prototype.setAttributeNode = function(newAttr) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLElement.prototype.removeAttributeNode = function(oldAttr) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLElement.prototype.getElementsByTagName = function(name) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLElement.prototype.getAttributeNS = function(namespaceURI, localName) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLElement.prototype.setAttributeNS = function(namespaceURI, qualifiedName, value) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLElement.prototype.removeAttributeNS = function(namespaceURI, localName) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLElement.prototype.getAttributeNodeNS = function(namespaceURI, localName) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLElement.prototype.setAttributeNodeNS = function(newAttr) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLElement.prototype.getElementsByTagNameNS = function(namespaceURI, localName) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLElement.prototype.hasAttribute = function(name) {\n      return this.attribs.hasOwnProperty(name);\n    };\n\n    XMLElement.prototype.hasAttributeNS = function(namespaceURI, localName) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLElement.prototype.setIdAttribute = function(name, isId) {\n      if (this.attribs.hasOwnProperty(name)) {\n        return this.attribs[name].isId;\n      } else {\n        return isId;\n      }\n    };\n\n    XMLElement.prototype.setIdAttributeNS = function(namespaceURI, localName, isId) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLElement.prototype.setIdAttributeNode = function(idAttr, isId) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLElement.prototype.getElementsByTagName = function(tagname) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLElement.prototype.getElementsByTagNameNS = function(namespaceURI, localName) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLElement.prototype.getElementsByClassName = function(classNames) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLElement.prototype.isEqualNode = function(node) {\n      var i, j, ref1;\n      if (!XMLElement.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) {\n        return false;\n      }\n      if (node.namespaceURI !== this.namespaceURI) {\n        return false;\n      }\n      if (node.prefix !== this.prefix) {\n        return false;\n      }\n      if (node.localName !== this.localName) {\n        return false;\n      }\n      if (node.attribs.length !== this.attribs.length) {\n        return false;\n      }\n      for (i = j = 0, ref1 = this.attribs.length - 1; 0 <= ref1 ? j <= ref1 : j >= ref1; i = 0 <= ref1 ? ++j : --j) {\n        if (!this.attribs[i].isEqualNode(node.attribs[i])) {\n          return false;\n        }\n      }\n      return true;\n    };\n\n    return XMLElement;\n\n  })(XMLNode);\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var XMLCharacterData, XMLNode,\n    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\n    hasProp = {}.hasOwnProperty;\n\n  XMLNode = require('./XMLNode');\n\n  module.exports = XMLCharacterData = (function(superClass) {\n    extend(XMLCharacterData, superClass);\n\n    function XMLCharacterData(parent) {\n      XMLCharacterData.__super__.constructor.call(this, parent);\n      this.value = '';\n    }\n\n    Object.defineProperty(XMLCharacterData.prototype, 'data', {\n      get: function() {\n        return this.value;\n      },\n      set: function(value) {\n        return this.value = value || '';\n      }\n    });\n\n    Object.defineProperty(XMLCharacterData.prototype, 'length', {\n      get: function() {\n        return this.value.length;\n      }\n    });\n\n    Object.defineProperty(XMLCharacterData.prototype, 'textContent', {\n      get: function() {\n        return this.value;\n      },\n      set: function(value) {\n        return this.value = value || '';\n      }\n    });\n\n    XMLCharacterData.prototype.clone = function() {\n      return Object.create(this);\n    };\n\n    XMLCharacterData.prototype.substringData = function(offset, count) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLCharacterData.prototype.appendData = function(arg) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLCharacterData.prototype.insertData = function(offset, arg) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLCharacterData.prototype.deleteData = function(offset, count) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLCharacterData.prototype.replaceData = function(offset, count, arg) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLCharacterData.prototype.isEqualNode = function(node) {\n      if (!XMLCharacterData.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) {\n        return false;\n      }\n      if (node.data !== this.data) {\n        return false;\n      }\n      return true;\n    };\n\n    return XMLCharacterData;\n\n  })(XMLNode);\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var NodeType, XMLCData, XMLCharacterData,\n    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\n    hasProp = {}.hasOwnProperty;\n\n  NodeType = require('./NodeType');\n\n  XMLCharacterData = require('./XMLCharacterData');\n\n  module.exports = XMLCData = (function(superClass) {\n    extend(XMLCData, superClass);\n\n    function XMLCData(parent, text) {\n      XMLCData.__super__.constructor.call(this, parent);\n      if (text == null) {\n        throw new Error(\"Missing CDATA text. \" + this.debugInfo());\n      }\n      this.name = \"#cdata-section\";\n      this.type = NodeType.CData;\n      this.value = this.stringify.cdata(text);\n    }\n\n    XMLCData.prototype.clone = function() {\n      return Object.create(this);\n    };\n\n    XMLCData.prototype.toString = function(options) {\n      return this.options.writer.cdata(this, this.options.writer.filterOptions(options));\n    };\n\n    return XMLCData;\n\n  })(XMLCharacterData);\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var NodeType, XMLCharacterData, XMLComment,\n    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\n    hasProp = {}.hasOwnProperty;\n\n  NodeType = require('./NodeType');\n\n  XMLCharacterData = require('./XMLCharacterData');\n\n  module.exports = XMLComment = (function(superClass) {\n    extend(XMLComment, superClass);\n\n    function XMLComment(parent, text) {\n      XMLComment.__super__.constructor.call(this, parent);\n      if (text == null) {\n        throw new Error(\"Missing comment text. \" + this.debugInfo());\n      }\n      this.name = \"#comment\";\n      this.type = NodeType.Comment;\n      this.value = this.stringify.comment(text);\n    }\n\n    XMLComment.prototype.clone = function() {\n      return Object.create(this);\n    };\n\n    XMLComment.prototype.toString = function(options) {\n      return this.options.writer.comment(this, this.options.writer.filterOptions(options));\n    };\n\n    return XMLComment;\n\n  })(XMLCharacterData);\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var NodeType, XMLDeclaration, XMLNode, isObject,\n    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\n    hasProp = {}.hasOwnProperty;\n\n  isObject = require('./Utility').isObject;\n\n  XMLNode = require('./XMLNode');\n\n  NodeType = require('./NodeType');\n\n  module.exports = XMLDeclaration = (function(superClass) {\n    extend(XMLDeclaration, superClass);\n\n    function XMLDeclaration(parent, version, encoding, standalone) {\n      var ref;\n      XMLDeclaration.__super__.constructor.call(this, parent);\n      if (isObject(version)) {\n        ref = version, version = ref.version, encoding = ref.encoding, standalone = ref.standalone;\n      }\n      if (!version) {\n        version = '1.0';\n      }\n      this.type = NodeType.Declaration;\n      this.version = this.stringify.xmlVersion(version);\n      if (encoding != null) {\n        this.encoding = this.stringify.xmlEncoding(encoding);\n      }\n      if (standalone != null) {\n        this.standalone = this.stringify.xmlStandalone(standalone);\n      }\n    }\n\n    XMLDeclaration.prototype.toString = function(options) {\n      return this.options.writer.declaration(this, this.options.writer.filterOptions(options));\n    };\n\n    return XMLDeclaration;\n\n  })(XMLNode);\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var NodeType, XMLDTDAttList, XMLNode,\n    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\n    hasProp = {}.hasOwnProperty;\n\n  XMLNode = require('./XMLNode');\n\n  NodeType = require('./NodeType');\n\n  module.exports = XMLDTDAttList = (function(superClass) {\n    extend(XMLDTDAttList, superClass);\n\n    function XMLDTDAttList(parent, elementName, attributeName, attributeType, defaultValueType, defaultValue) {\n      XMLDTDAttList.__super__.constructor.call(this, parent);\n      if (elementName == null) {\n        throw new Error(\"Missing DTD element name. \" + this.debugInfo());\n      }\n      if (attributeName == null) {\n        throw new Error(\"Missing DTD attribute name. \" + this.debugInfo(elementName));\n      }\n      if (!attributeType) {\n        throw new Error(\"Missing DTD attribute type. \" + this.debugInfo(elementName));\n      }\n      if (!defaultValueType) {\n        throw new Error(\"Missing DTD attribute default. \" + this.debugInfo(elementName));\n      }\n      if (defaultValueType.indexOf('#') !== 0) {\n        defaultValueType = '#' + defaultValueType;\n      }\n      if (!defaultValueType.match(/^(#REQUIRED|#IMPLIED|#FIXED|#DEFAULT)$/)) {\n        throw new Error(\"Invalid default value type; expected: #REQUIRED, #IMPLIED, #FIXED or #DEFAULT. \" + this.debugInfo(elementName));\n      }\n      if (defaultValue && !defaultValueType.match(/^(#FIXED|#DEFAULT)$/)) {\n        throw new Error(\"Default value only applies to #FIXED or #DEFAULT. \" + this.debugInfo(elementName));\n      }\n      this.elementName = this.stringify.name(elementName);\n      this.type = NodeType.AttributeDeclaration;\n      this.attributeName = this.stringify.name(attributeName);\n      this.attributeType = this.stringify.dtdAttType(attributeType);\n      if (defaultValue) {\n        this.defaultValue = this.stringify.dtdAttDefault(defaultValue);\n      }\n      this.defaultValueType = defaultValueType;\n    }\n\n    XMLDTDAttList.prototype.toString = function(options) {\n      return this.options.writer.dtdAttList(this, this.options.writer.filterOptions(options));\n    };\n\n    return XMLDTDAttList;\n\n  })(XMLNode);\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var NodeType, XMLDTDEntity, XMLNode, isObject,\n    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\n    hasProp = {}.hasOwnProperty;\n\n  isObject = require('./Utility').isObject;\n\n  XMLNode = require('./XMLNode');\n\n  NodeType = require('./NodeType');\n\n  module.exports = XMLDTDEntity = (function(superClass) {\n    extend(XMLDTDEntity, superClass);\n\n    function XMLDTDEntity(parent, pe, name, value) {\n      XMLDTDEntity.__super__.constructor.call(this, parent);\n      if (name == null) {\n        throw new Error(\"Missing DTD entity name. \" + this.debugInfo(name));\n      }\n      if (value == null) {\n        throw new Error(\"Missing DTD entity value. \" + this.debugInfo(name));\n      }\n      this.pe = !!pe;\n      this.name = this.stringify.name(name);\n      this.type = NodeType.EntityDeclaration;\n      if (!isObject(value)) {\n        this.value = this.stringify.dtdEntityValue(value);\n        this.internal = true;\n      } else {\n        if (!value.pubID && !value.sysID) {\n          throw new Error(\"Public and/or system identifiers are required for an external entity. \" + this.debugInfo(name));\n        }\n        if (value.pubID && !value.sysID) {\n          throw new Error(\"System identifier is required for a public external entity. \" + this.debugInfo(name));\n        }\n        this.internal = false;\n        if (value.pubID != null) {\n          this.pubID = this.stringify.dtdPubID(value.pubID);\n        }\n        if (value.sysID != null) {\n          this.sysID = this.stringify.dtdSysID(value.sysID);\n        }\n        if (value.nData != null) {\n          this.nData = this.stringify.dtdNData(value.nData);\n        }\n        if (this.pe && this.nData) {\n          throw new Error(\"Notation declaration is not allowed in a parameter entity. \" + this.debugInfo(name));\n        }\n      }\n    }\n\n    Object.defineProperty(XMLDTDEntity.prototype, 'publicId', {\n      get: function() {\n        return this.pubID;\n      }\n    });\n\n    Object.defineProperty(XMLDTDEntity.prototype, 'systemId', {\n      get: function() {\n        return this.sysID;\n      }\n    });\n\n    Object.defineProperty(XMLDTDEntity.prototype, 'notationName', {\n      get: function() {\n        return this.nData || null;\n      }\n    });\n\n    Object.defineProperty(XMLDTDEntity.prototype, 'inputEncoding', {\n      get: function() {\n        return null;\n      }\n    });\n\n    Object.defineProperty(XMLDTDEntity.prototype, 'xmlEncoding', {\n      get: function() {\n        return null;\n      }\n    });\n\n    Object.defineProperty(XMLDTDEntity.prototype, 'xmlVersion', {\n      get: function() {\n        return null;\n      }\n    });\n\n    XMLDTDEntity.prototype.toString = function(options) {\n      return this.options.writer.dtdEntity(this, this.options.writer.filterOptions(options));\n    };\n\n    return XMLDTDEntity;\n\n  })(XMLNode);\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var NodeType, XMLDTDElement, XMLNode,\n    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\n    hasProp = {}.hasOwnProperty;\n\n  XMLNode = require('./XMLNode');\n\n  NodeType = require('./NodeType');\n\n  module.exports = XMLDTDElement = (function(superClass) {\n    extend(XMLDTDElement, superClass);\n\n    function XMLDTDElement(parent, name, value) {\n      XMLDTDElement.__super__.constructor.call(this, parent);\n      if (name == null) {\n        throw new Error(\"Missing DTD element name. \" + this.debugInfo());\n      }\n      if (!value) {\n        value = '(#PCDATA)';\n      }\n      if (Array.isArray(value)) {\n        value = '(' + value.join(',') + ')';\n      }\n      this.name = this.stringify.name(name);\n      this.type = NodeType.ElementDeclaration;\n      this.value = this.stringify.dtdElementValue(value);\n    }\n\n    XMLDTDElement.prototype.toString = function(options) {\n      return this.options.writer.dtdElement(this, this.options.writer.filterOptions(options));\n    };\n\n    return XMLDTDElement;\n\n  })(XMLNode);\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var NodeType, XMLDTDNotation, XMLNode,\n    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\n    hasProp = {}.hasOwnProperty;\n\n  XMLNode = require('./XMLNode');\n\n  NodeType = require('./NodeType');\n\n  module.exports = XMLDTDNotation = (function(superClass) {\n    extend(XMLDTDNotation, superClass);\n\n    function XMLDTDNotation(parent, name, value) {\n      XMLDTDNotation.__super__.constructor.call(this, parent);\n      if (name == null) {\n        throw new Error(\"Missing DTD notation name. \" + this.debugInfo(name));\n      }\n      if (!value.pubID && !value.sysID) {\n        throw new Error(\"Public or system identifiers are required for an external entity. \" + this.debugInfo(name));\n      }\n      this.name = this.stringify.name(name);\n      this.type = NodeType.NotationDeclaration;\n      if (value.pubID != null) {\n        this.pubID = this.stringify.dtdPubID(value.pubID);\n      }\n      if (value.sysID != null) {\n        this.sysID = this.stringify.dtdSysID(value.sysID);\n      }\n    }\n\n    Object.defineProperty(XMLDTDNotation.prototype, 'publicId', {\n      get: function() {\n        return this.pubID;\n      }\n    });\n\n    Object.defineProperty(XMLDTDNotation.prototype, 'systemId', {\n      get: function() {\n        return this.sysID;\n      }\n    });\n\n    XMLDTDNotation.prototype.toString = function(options) {\n      return this.options.writer.dtdNotation(this, this.options.writer.filterOptions(options));\n    };\n\n    return XMLDTDNotation;\n\n  })(XMLNode);\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var NodeType, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDocType, XMLNamedNodeMap, XMLNode, isObject,\n    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\n    hasProp = {}.hasOwnProperty;\n\n  isObject = require('./Utility').isObject;\n\n  XMLNode = require('./XMLNode');\n\n  NodeType = require('./NodeType');\n\n  XMLDTDAttList = require('./XMLDTDAttList');\n\n  XMLDTDEntity = require('./XMLDTDEntity');\n\n  XMLDTDElement = require('./XMLDTDElement');\n\n  XMLDTDNotation = require('./XMLDTDNotation');\n\n  XMLNamedNodeMap = require('./XMLNamedNodeMap');\n\n  module.exports = XMLDocType = (function(superClass) {\n    extend(XMLDocType, superClass);\n\n    function XMLDocType(parent, pubID, sysID) {\n      var child, i, len, ref, ref1, ref2;\n      XMLDocType.__super__.constructor.call(this, parent);\n      this.type = NodeType.DocType;\n      if (parent.children) {\n        ref = parent.children;\n        for (i = 0, len = ref.length; i < len; i++) {\n          child = ref[i];\n          if (child.type === NodeType.Element) {\n            this.name = child.name;\n            break;\n          }\n        }\n      }\n      this.documentObject = parent;\n      if (isObject(pubID)) {\n        ref1 = pubID, pubID = ref1.pubID, sysID = ref1.sysID;\n      }\n      if (sysID == null) {\n        ref2 = [pubID, sysID], sysID = ref2[0], pubID = ref2[1];\n      }\n      if (pubID != null) {\n        this.pubID = this.stringify.dtdPubID(pubID);\n      }\n      if (sysID != null) {\n        this.sysID = this.stringify.dtdSysID(sysID);\n      }\n    }\n\n    Object.defineProperty(XMLDocType.prototype, 'entities', {\n      get: function() {\n        var child, i, len, nodes, ref;\n        nodes = {};\n        ref = this.children;\n        for (i = 0, len = ref.length; i < len; i++) {\n          child = ref[i];\n          if ((child.type === NodeType.EntityDeclaration) && !child.pe) {\n            nodes[child.name] = child;\n          }\n        }\n        return new XMLNamedNodeMap(nodes);\n      }\n    });\n\n    Object.defineProperty(XMLDocType.prototype, 'notations', {\n      get: function() {\n        var child, i, len, nodes, ref;\n        nodes = {};\n        ref = this.children;\n        for (i = 0, len = ref.length; i < len; i++) {\n          child = ref[i];\n          if (child.type === NodeType.NotationDeclaration) {\n            nodes[child.name] = child;\n          }\n        }\n        return new XMLNamedNodeMap(nodes);\n      }\n    });\n\n    Object.defineProperty(XMLDocType.prototype, 'publicId', {\n      get: function() {\n        return this.pubID;\n      }\n    });\n\n    Object.defineProperty(XMLDocType.prototype, 'systemId', {\n      get: function() {\n        return this.sysID;\n      }\n    });\n\n    Object.defineProperty(XMLDocType.prototype, 'internalSubset', {\n      get: function() {\n        throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n      }\n    });\n\n    XMLDocType.prototype.element = function(name, value) {\n      var child;\n      child = new XMLDTDElement(this, name, value);\n      this.children.push(child);\n      return this;\n    };\n\n    XMLDocType.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {\n      var child;\n      child = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue);\n      this.children.push(child);\n      return this;\n    };\n\n    XMLDocType.prototype.entity = function(name, value) {\n      var child;\n      child = new XMLDTDEntity(this, false, name, value);\n      this.children.push(child);\n      return this;\n    };\n\n    XMLDocType.prototype.pEntity = function(name, value) {\n      var child;\n      child = new XMLDTDEntity(this, true, name, value);\n      this.children.push(child);\n      return this;\n    };\n\n    XMLDocType.prototype.notation = function(name, value) {\n      var child;\n      child = new XMLDTDNotation(this, name, value);\n      this.children.push(child);\n      return this;\n    };\n\n    XMLDocType.prototype.toString = function(options) {\n      return this.options.writer.docType(this, this.options.writer.filterOptions(options));\n    };\n\n    XMLDocType.prototype.ele = function(name, value) {\n      return this.element(name, value);\n    };\n\n    XMLDocType.prototype.att = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {\n      return this.attList(elementName, attributeName, attributeType, defaultValueType, defaultValue);\n    };\n\n    XMLDocType.prototype.ent = function(name, value) {\n      return this.entity(name, value);\n    };\n\n    XMLDocType.prototype.pent = function(name, value) {\n      return this.pEntity(name, value);\n    };\n\n    XMLDocType.prototype.not = function(name, value) {\n      return this.notation(name, value);\n    };\n\n    XMLDocType.prototype.up = function() {\n      return this.root() || this.documentObject;\n    };\n\n    XMLDocType.prototype.isEqualNode = function(node) {\n      if (!XMLDocType.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) {\n        return false;\n      }\n      if (node.name !== this.name) {\n        return false;\n      }\n      if (node.publicId !== this.publicId) {\n        return false;\n      }\n      if (node.systemId !== this.systemId) {\n        return false;\n      }\n      return true;\n    };\n\n    return XMLDocType;\n\n  })(XMLNode);\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var NodeType, XMLNode, XMLRaw,\n    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\n    hasProp = {}.hasOwnProperty;\n\n  NodeType = require('./NodeType');\n\n  XMLNode = require('./XMLNode');\n\n  module.exports = XMLRaw = (function(superClass) {\n    extend(XMLRaw, superClass);\n\n    function XMLRaw(parent, text) {\n      XMLRaw.__super__.constructor.call(this, parent);\n      if (text == null) {\n        throw new Error(\"Missing raw text. \" + this.debugInfo());\n      }\n      this.type = NodeType.Raw;\n      this.value = this.stringify.raw(text);\n    }\n\n    XMLRaw.prototype.clone = function() {\n      return Object.create(this);\n    };\n\n    XMLRaw.prototype.toString = function(options) {\n      return this.options.writer.raw(this, this.options.writer.filterOptions(options));\n    };\n\n    return XMLRaw;\n\n  })(XMLNode);\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var NodeType, XMLCharacterData, XMLText,\n    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\n    hasProp = {}.hasOwnProperty;\n\n  NodeType = require('./NodeType');\n\n  XMLCharacterData = require('./XMLCharacterData');\n\n  module.exports = XMLText = (function(superClass) {\n    extend(XMLText, superClass);\n\n    function XMLText(parent, text) {\n      XMLText.__super__.constructor.call(this, parent);\n      if (text == null) {\n        throw new Error(\"Missing element text. \" + this.debugInfo());\n      }\n      this.name = \"#text\";\n      this.type = NodeType.Text;\n      this.value = this.stringify.text(text);\n    }\n\n    Object.defineProperty(XMLText.prototype, 'isElementContentWhitespace', {\n      get: function() {\n        throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n      }\n    });\n\n    Object.defineProperty(XMLText.prototype, 'wholeText', {\n      get: function() {\n        var next, prev, str;\n        str = '';\n        prev = this.previousSibling;\n        while (prev) {\n          str = prev.data + str;\n          prev = prev.previousSibling;\n        }\n        str += this.data;\n        next = this.nextSibling;\n        while (next) {\n          str = str + next.data;\n          next = next.nextSibling;\n        }\n        return str;\n      }\n    });\n\n    XMLText.prototype.clone = function() {\n      return Object.create(this);\n    };\n\n    XMLText.prototype.toString = function(options) {\n      return this.options.writer.text(this, this.options.writer.filterOptions(options));\n    };\n\n    XMLText.prototype.splitText = function(offset) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLText.prototype.replaceWholeText = function(content) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    return XMLText;\n\n  })(XMLCharacterData);\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var NodeType, XMLCharacterData, XMLProcessingInstruction,\n    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\n    hasProp = {}.hasOwnProperty;\n\n  NodeType = require('./NodeType');\n\n  XMLCharacterData = require('./XMLCharacterData');\n\n  module.exports = XMLProcessingInstruction = (function(superClass) {\n    extend(XMLProcessingInstruction, superClass);\n\n    function XMLProcessingInstruction(parent, target, value) {\n      XMLProcessingInstruction.__super__.constructor.call(this, parent);\n      if (target == null) {\n        throw new Error(\"Missing instruction target. \" + this.debugInfo());\n      }\n      this.type = NodeType.ProcessingInstruction;\n      this.target = this.stringify.insTarget(target);\n      this.name = this.target;\n      if (value) {\n        this.value = this.stringify.insValue(value);\n      }\n    }\n\n    XMLProcessingInstruction.prototype.clone = function() {\n      return Object.create(this);\n    };\n\n    XMLProcessingInstruction.prototype.toString = function(options) {\n      return this.options.writer.processingInstruction(this, this.options.writer.filterOptions(options));\n    };\n\n    XMLProcessingInstruction.prototype.isEqualNode = function(node) {\n      if (!XMLProcessingInstruction.__super__.isEqualNode.apply(this, arguments).isEqualNode(node)) {\n        return false;\n      }\n      if (node.target !== this.target) {\n        return false;\n      }\n      return true;\n    };\n\n    return XMLProcessingInstruction;\n\n  })(XMLCharacterData);\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var NodeType, XMLDummy, XMLNode,\n    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\n    hasProp = {}.hasOwnProperty;\n\n  XMLNode = require('./XMLNode');\n\n  NodeType = require('./NodeType');\n\n  module.exports = XMLDummy = (function(superClass) {\n    extend(XMLDummy, superClass);\n\n    function XMLDummy(parent) {\n      XMLDummy.__super__.constructor.call(this, parent);\n      this.type = NodeType.Dummy;\n    }\n\n    XMLDummy.prototype.clone = function() {\n      return Object.create(this);\n    };\n\n    XMLDummy.prototype.toString = function(options) {\n      return '';\n    };\n\n    return XMLDummy;\n\n  })(XMLNode);\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var XMLNodeList;\n\n  module.exports = XMLNodeList = (function() {\n    function XMLNodeList(nodes) {\n      this.nodes = nodes;\n    }\n\n    Object.defineProperty(XMLNodeList.prototype, 'length', {\n      get: function() {\n        return this.nodes.length || 0;\n      }\n    });\n\n    XMLNodeList.prototype.clone = function() {\n      return this.nodes = null;\n    };\n\n    XMLNodeList.prototype.item = function(index) {\n      return this.nodes[index] || null;\n    };\n\n    return XMLNodeList;\n\n  })();\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  module.exports = {\n    Disconnected: 1,\n    Preceding: 2,\n    Following: 4,\n    Contains: 8,\n    ContainedBy: 16,\n    ImplementationSpecific: 32\n  };\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var DocumentPosition, NodeType, XMLCData, XMLComment, XMLDeclaration, XMLDocType, XMLDummy, XMLElement, XMLNamedNodeMap, XMLNode, XMLNodeList, XMLProcessingInstruction, XMLRaw, XMLText, getValue, isEmpty, isFunction, isObject, ref1,\n    hasProp = {}.hasOwnProperty;\n\n  ref1 = require('./Utility'), isObject = ref1.isObject, isFunction = ref1.isFunction, isEmpty = ref1.isEmpty, getValue = ref1.getValue;\n\n  XMLElement = null;\n\n  XMLCData = null;\n\n  XMLComment = null;\n\n  XMLDeclaration = null;\n\n  XMLDocType = null;\n\n  XMLRaw = null;\n\n  XMLText = null;\n\n  XMLProcessingInstruction = null;\n\n  XMLDummy = null;\n\n  NodeType = null;\n\n  XMLNodeList = null;\n\n  XMLNamedNodeMap = null;\n\n  DocumentPosition = null;\n\n  module.exports = XMLNode = (function() {\n    function XMLNode(parent1) {\n      this.parent = parent1;\n      if (this.parent) {\n        this.options = this.parent.options;\n        this.stringify = this.parent.stringify;\n      }\n      this.value = null;\n      this.children = [];\n      this.baseURI = null;\n      if (!XMLElement) {\n        XMLElement = require('./XMLElement');\n        XMLCData = require('./XMLCData');\n        XMLComment = require('./XMLComment');\n        XMLDeclaration = require('./XMLDeclaration');\n        XMLDocType = require('./XMLDocType');\n        XMLRaw = require('./XMLRaw');\n        XMLText = require('./XMLText');\n        XMLProcessingInstruction = require('./XMLProcessingInstruction');\n        XMLDummy = require('./XMLDummy');\n        NodeType = require('./NodeType');\n        XMLNodeList = require('./XMLNodeList');\n        XMLNamedNodeMap = require('./XMLNamedNodeMap');\n        DocumentPosition = require('./DocumentPosition');\n      }\n    }\n\n    Object.defineProperty(XMLNode.prototype, 'nodeName', {\n      get: function() {\n        return this.name;\n      }\n    });\n\n    Object.defineProperty(XMLNode.prototype, 'nodeType', {\n      get: function() {\n        return this.type;\n      }\n    });\n\n    Object.defineProperty(XMLNode.prototype, 'nodeValue', {\n      get: function() {\n        return this.value;\n      }\n    });\n\n    Object.defineProperty(XMLNode.prototype, 'parentNode', {\n      get: function() {\n        return this.parent;\n      }\n    });\n\n    Object.defineProperty(XMLNode.prototype, 'childNodes', {\n      get: function() {\n        if (!this.childNodeList || !this.childNodeList.nodes) {\n          this.childNodeList = new XMLNodeList(this.children);\n        }\n        return this.childNodeList;\n      }\n    });\n\n    Object.defineProperty(XMLNode.prototype, 'firstChild', {\n      get: function() {\n        return this.children[0] || null;\n      }\n    });\n\n    Object.defineProperty(XMLNode.prototype, 'lastChild', {\n      get: function() {\n        return this.children[this.children.length - 1] || null;\n      }\n    });\n\n    Object.defineProperty(XMLNode.prototype, 'previousSibling', {\n      get: function() {\n        var i;\n        i = this.parent.children.indexOf(this);\n        return this.parent.children[i - 1] || null;\n      }\n    });\n\n    Object.defineProperty(XMLNode.prototype, 'nextSibling', {\n      get: function() {\n        var i;\n        i = this.parent.children.indexOf(this);\n        return this.parent.children[i + 1] || null;\n      }\n    });\n\n    Object.defineProperty(XMLNode.prototype, 'ownerDocument', {\n      get: function() {\n        return this.document() || null;\n      }\n    });\n\n    Object.defineProperty(XMLNode.prototype, 'textContent', {\n      get: function() {\n        var child, j, len, ref2, str;\n        if (this.nodeType === NodeType.Element || this.nodeType === NodeType.DocumentFragment) {\n          str = '';\n          ref2 = this.children;\n          for (j = 0, len = ref2.length; j < len; j++) {\n            child = ref2[j];\n            if (child.textContent) {\n              str += child.textContent;\n            }\n          }\n          return str;\n        } else {\n          return null;\n        }\n      },\n      set: function(value) {\n        throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n      }\n    });\n\n    XMLNode.prototype.setParent = function(parent) {\n      var child, j, len, ref2, results;\n      this.parent = parent;\n      if (parent) {\n        this.options = parent.options;\n        this.stringify = parent.stringify;\n      }\n      ref2 = this.children;\n      results = [];\n      for (j = 0, len = ref2.length; j < len; j++) {\n        child = ref2[j];\n        results.push(child.setParent(this));\n      }\n      return results;\n    };\n\n    XMLNode.prototype.element = function(name, attributes, text) {\n      var childNode, item, j, k, key, lastChild, len, len1, ref2, ref3, val;\n      lastChild = null;\n      if (attributes === null && (text == null)) {\n        ref2 = [{}, null], attributes = ref2[0], text = ref2[1];\n      }\n      if (attributes == null) {\n        attributes = {};\n      }\n      attributes = getValue(attributes);\n      if (!isObject(attributes)) {\n        ref3 = [attributes, text], text = ref3[0], attributes = ref3[1];\n      }\n      if (name != null) {\n        name = getValue(name);\n      }\n      if (Array.isArray(name)) {\n        for (j = 0, len = name.length; j < len; j++) {\n          item = name[j];\n          lastChild = this.element(item);\n        }\n      } else if (isFunction(name)) {\n        lastChild = this.element(name.apply());\n      } else if (isObject(name)) {\n        for (key in name) {\n          if (!hasProp.call(name, key)) continue;\n          val = name[key];\n          if (isFunction(val)) {\n            val = val.apply();\n          }\n          if (!this.options.ignoreDecorators && this.stringify.convertAttKey && key.indexOf(this.stringify.convertAttKey) === 0) {\n            lastChild = this.attribute(key.substr(this.stringify.convertAttKey.length), val);\n          } else if (!this.options.separateArrayItems && Array.isArray(val) && isEmpty(val)) {\n            lastChild = this.dummy();\n          } else if (isObject(val) && isEmpty(val)) {\n            lastChild = this.element(key);\n          } else if (!this.options.keepNullNodes && (val == null)) {\n            lastChild = this.dummy();\n          } else if (!this.options.separateArrayItems && Array.isArray(val)) {\n            for (k = 0, len1 = val.length; k < len1; k++) {\n              item = val[k];\n              childNode = {};\n              childNode[key] = item;\n              lastChild = this.element(childNode);\n            }\n          } else if (isObject(val)) {\n            if (!this.options.ignoreDecorators && this.stringify.convertTextKey && key.indexOf(this.stringify.convertTextKey) === 0) {\n              lastChild = this.element(val);\n            } else {\n              lastChild = this.element(key);\n              lastChild.element(val);\n            }\n          } else {\n            lastChild = this.element(key, val);\n          }\n        }\n      } else if (!this.options.keepNullNodes && text === null) {\n        lastChild = this.dummy();\n      } else {\n        if (!this.options.ignoreDecorators && this.stringify.convertTextKey && name.indexOf(this.stringify.convertTextKey) === 0) {\n          lastChild = this.text(text);\n        } else if (!this.options.ignoreDecorators && this.stringify.convertCDataKey && name.indexOf(this.stringify.convertCDataKey) === 0) {\n          lastChild = this.cdata(text);\n        } else if (!this.options.ignoreDecorators && this.stringify.convertCommentKey && name.indexOf(this.stringify.convertCommentKey) === 0) {\n          lastChild = this.comment(text);\n        } else if (!this.options.ignoreDecorators && this.stringify.convertRawKey && name.indexOf(this.stringify.convertRawKey) === 0) {\n          lastChild = this.raw(text);\n        } else if (!this.options.ignoreDecorators && this.stringify.convertPIKey && name.indexOf(this.stringify.convertPIKey) === 0) {\n          lastChild = this.instruction(name.substr(this.stringify.convertPIKey.length), text);\n        } else {\n          lastChild = this.node(name, attributes, text);\n        }\n      }\n      if (lastChild == null) {\n        throw new Error(\"Could not create any elements with: \" + name + \". \" + this.debugInfo());\n      }\n      return lastChild;\n    };\n\n    XMLNode.prototype.insertBefore = function(name, attributes, text) {\n      var child, i, newChild, refChild, removed;\n      if (name != null ? name.type : void 0) {\n        newChild = name;\n        refChild = attributes;\n        newChild.setParent(this);\n        if (refChild) {\n          i = children.indexOf(refChild);\n          removed = children.splice(i);\n          children.push(newChild);\n          Array.prototype.push.apply(children, removed);\n        } else {\n          children.push(newChild);\n        }\n        return newChild;\n      } else {\n        if (this.isRoot) {\n          throw new Error(\"Cannot insert elements at root level. \" + this.debugInfo(name));\n        }\n        i = this.parent.children.indexOf(this);\n        removed = this.parent.children.splice(i);\n        child = this.parent.element(name, attributes, text);\n        Array.prototype.push.apply(this.parent.children, removed);\n        return child;\n      }\n    };\n\n    XMLNode.prototype.insertAfter = function(name, attributes, text) {\n      var child, i, removed;\n      if (this.isRoot) {\n        throw new Error(\"Cannot insert elements at root level. \" + this.debugInfo(name));\n      }\n      i = this.parent.children.indexOf(this);\n      removed = this.parent.children.splice(i + 1);\n      child = this.parent.element(name, attributes, text);\n      Array.prototype.push.apply(this.parent.children, removed);\n      return child;\n    };\n\n    XMLNode.prototype.remove = function() {\n      var i, ref2;\n      if (this.isRoot) {\n        throw new Error(\"Cannot remove the root element. \" + this.debugInfo());\n      }\n      i = this.parent.children.indexOf(this);\n      [].splice.apply(this.parent.children, [i, i - i + 1].concat(ref2 = [])), ref2;\n      return this.parent;\n    };\n\n    XMLNode.prototype.node = function(name, attributes, text) {\n      var child, ref2;\n      if (name != null) {\n        name = getValue(name);\n      }\n      attributes || (attributes = {});\n      attributes = getValue(attributes);\n      if (!isObject(attributes)) {\n        ref2 = [attributes, text], text = ref2[0], attributes = ref2[1];\n      }\n      child = new XMLElement(this, name, attributes);\n      if (text != null) {\n        child.text(text);\n      }\n      this.children.push(child);\n      return child;\n    };\n\n    XMLNode.prototype.text = function(value) {\n      var child;\n      if (isObject(value)) {\n        this.element(value);\n      }\n      child = new XMLText(this, value);\n      this.children.push(child);\n      return this;\n    };\n\n    XMLNode.prototype.cdata = function(value) {\n      var child;\n      child = new XMLCData(this, value);\n      this.children.push(child);\n      return this;\n    };\n\n    XMLNode.prototype.comment = function(value) {\n      var child;\n      child = new XMLComment(this, value);\n      this.children.push(child);\n      return this;\n    };\n\n    XMLNode.prototype.commentBefore = function(value) {\n      var child, i, removed;\n      i = this.parent.children.indexOf(this);\n      removed = this.parent.children.splice(i);\n      child = this.parent.comment(value);\n      Array.prototype.push.apply(this.parent.children, removed);\n      return this;\n    };\n\n    XMLNode.prototype.commentAfter = function(value) {\n      var child, i, removed;\n      i = this.parent.children.indexOf(this);\n      removed = this.parent.children.splice(i + 1);\n      child = this.parent.comment(value);\n      Array.prototype.push.apply(this.parent.children, removed);\n      return this;\n    };\n\n    XMLNode.prototype.raw = function(value) {\n      var child;\n      child = new XMLRaw(this, value);\n      this.children.push(child);\n      return this;\n    };\n\n    XMLNode.prototype.dummy = function() {\n      var child;\n      child = new XMLDummy(this);\n      return child;\n    };\n\n    XMLNode.prototype.instruction = function(target, value) {\n      var insTarget, insValue, instruction, j, len;\n      if (target != null) {\n        target = getValue(target);\n      }\n      if (value != null) {\n        value = getValue(value);\n      }\n      if (Array.isArray(target)) {\n        for (j = 0, len = target.length; j < len; j++) {\n          insTarget = target[j];\n          this.instruction(insTarget);\n        }\n      } else if (isObject(target)) {\n        for (insTarget in target) {\n          if (!hasProp.call(target, insTarget)) continue;\n          insValue = target[insTarget];\n          this.instruction(insTarget, insValue);\n        }\n      } else {\n        if (isFunction(value)) {\n          value = value.apply();\n        }\n        instruction = new XMLProcessingInstruction(this, target, value);\n        this.children.push(instruction);\n      }\n      return this;\n    };\n\n    XMLNode.prototype.instructionBefore = function(target, value) {\n      var child, i, removed;\n      i = this.parent.children.indexOf(this);\n      removed = this.parent.children.splice(i);\n      child = this.parent.instruction(target, value);\n      Array.prototype.push.apply(this.parent.children, removed);\n      return this;\n    };\n\n    XMLNode.prototype.instructionAfter = function(target, value) {\n      var child, i, removed;\n      i = this.parent.children.indexOf(this);\n      removed = this.parent.children.splice(i + 1);\n      child = this.parent.instruction(target, value);\n      Array.prototype.push.apply(this.parent.children, removed);\n      return this;\n    };\n\n    XMLNode.prototype.declaration = function(version, encoding, standalone) {\n      var doc, xmldec;\n      doc = this.document();\n      xmldec = new XMLDeclaration(doc, version, encoding, standalone);\n      if (doc.children.length === 0) {\n        doc.children.unshift(xmldec);\n      } else if (doc.children[0].type === NodeType.Declaration) {\n        doc.children[0] = xmldec;\n      } else {\n        doc.children.unshift(xmldec);\n      }\n      return doc.root() || doc;\n    };\n\n    XMLNode.prototype.dtd = function(pubID, sysID) {\n      var child, doc, doctype, i, j, k, len, len1, ref2, ref3;\n      doc = this.document();\n      doctype = new XMLDocType(doc, pubID, sysID);\n      ref2 = doc.children;\n      for (i = j = 0, len = ref2.length; j < len; i = ++j) {\n        child = ref2[i];\n        if (child.type === NodeType.DocType) {\n          doc.children[i] = doctype;\n          return doctype;\n        }\n      }\n      ref3 = doc.children;\n      for (i = k = 0, len1 = ref3.length; k < len1; i = ++k) {\n        child = ref3[i];\n        if (child.isRoot) {\n          doc.children.splice(i, 0, doctype);\n          return doctype;\n        }\n      }\n      doc.children.push(doctype);\n      return doctype;\n    };\n\n    XMLNode.prototype.up = function() {\n      if (this.isRoot) {\n        throw new Error(\"The root node has no parent. Use doc() if you need to get the document object.\");\n      }\n      return this.parent;\n    };\n\n    XMLNode.prototype.root = function() {\n      var node;\n      node = this;\n      while (node) {\n        if (node.type === NodeType.Document) {\n          return node.rootObject;\n        } else if (node.isRoot) {\n          return node;\n        } else {\n          node = node.parent;\n        }\n      }\n    };\n\n    XMLNode.prototype.document = function() {\n      var node;\n      node = this;\n      while (node) {\n        if (node.type === NodeType.Document) {\n          return node;\n        } else {\n          node = node.parent;\n        }\n      }\n    };\n\n    XMLNode.prototype.end = function(options) {\n      return this.document().end(options);\n    };\n\n    XMLNode.prototype.prev = function() {\n      var i;\n      i = this.parent.children.indexOf(this);\n      if (i < 1) {\n        throw new Error(\"Already at the first node. \" + this.debugInfo());\n      }\n      return this.parent.children[i - 1];\n    };\n\n    XMLNode.prototype.next = function() {\n      var i;\n      i = this.parent.children.indexOf(this);\n      if (i === -1 || i === this.parent.children.length - 1) {\n        throw new Error(\"Already at the last node. \" + this.debugInfo());\n      }\n      return this.parent.children[i + 1];\n    };\n\n    XMLNode.prototype.importDocument = function(doc) {\n      var clonedRoot;\n      clonedRoot = doc.root().clone();\n      clonedRoot.parent = this;\n      clonedRoot.isRoot = false;\n      this.children.push(clonedRoot);\n      return this;\n    };\n\n    XMLNode.prototype.debugInfo = function(name) {\n      var ref2, ref3;\n      name = name || this.name;\n      if ((name == null) && !((ref2 = this.parent) != null ? ref2.name : void 0)) {\n        return \"\";\n      } else if (name == null) {\n        return \"parent: <\" + this.parent.name + \">\";\n      } else if (!((ref3 = this.parent) != null ? ref3.name : void 0)) {\n        return \"node: <\" + name + \">\";\n      } else {\n        return \"node: <\" + name + \">, parent: <\" + this.parent.name + \">\";\n      }\n    };\n\n    XMLNode.prototype.ele = function(name, attributes, text) {\n      return this.element(name, attributes, text);\n    };\n\n    XMLNode.prototype.nod = function(name, attributes, text) {\n      return this.node(name, attributes, text);\n    };\n\n    XMLNode.prototype.txt = function(value) {\n      return this.text(value);\n    };\n\n    XMLNode.prototype.dat = function(value) {\n      return this.cdata(value);\n    };\n\n    XMLNode.prototype.com = function(value) {\n      return this.comment(value);\n    };\n\n    XMLNode.prototype.ins = function(target, value) {\n      return this.instruction(target, value);\n    };\n\n    XMLNode.prototype.doc = function() {\n      return this.document();\n    };\n\n    XMLNode.prototype.dec = function(version, encoding, standalone) {\n      return this.declaration(version, encoding, standalone);\n    };\n\n    XMLNode.prototype.e = function(name, attributes, text) {\n      return this.element(name, attributes, text);\n    };\n\n    XMLNode.prototype.n = function(name, attributes, text) {\n      return this.node(name, attributes, text);\n    };\n\n    XMLNode.prototype.t = function(value) {\n      return this.text(value);\n    };\n\n    XMLNode.prototype.d = function(value) {\n      return this.cdata(value);\n    };\n\n    XMLNode.prototype.c = function(value) {\n      return this.comment(value);\n    };\n\n    XMLNode.prototype.r = function(value) {\n      return this.raw(value);\n    };\n\n    XMLNode.prototype.i = function(target, value) {\n      return this.instruction(target, value);\n    };\n\n    XMLNode.prototype.u = function() {\n      return this.up();\n    };\n\n    XMLNode.prototype.importXMLBuilder = function(doc) {\n      return this.importDocument(doc);\n    };\n\n    XMLNode.prototype.replaceChild = function(newChild, oldChild) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLNode.prototype.removeChild = function(oldChild) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLNode.prototype.appendChild = function(newChild) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLNode.prototype.hasChildNodes = function() {\n      return this.children.length !== 0;\n    };\n\n    XMLNode.prototype.cloneNode = function(deep) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLNode.prototype.normalize = function() {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLNode.prototype.isSupported = function(feature, version) {\n      return true;\n    };\n\n    XMLNode.prototype.hasAttributes = function() {\n      return this.attribs.length !== 0;\n    };\n\n    XMLNode.prototype.compareDocumentPosition = function(other) {\n      var ref, res;\n      ref = this;\n      if (ref === other) {\n        return 0;\n      } else if (this.document() !== other.document()) {\n        res = DocumentPosition.Disconnected | DocumentPosition.ImplementationSpecific;\n        if (Math.random() < 0.5) {\n          res |= DocumentPosition.Preceding;\n        } else {\n          res |= DocumentPosition.Following;\n        }\n        return res;\n      } else if (ref.isAncestor(other)) {\n        return DocumentPosition.Contains | DocumentPosition.Preceding;\n      } else if (ref.isDescendant(other)) {\n        return DocumentPosition.Contains | DocumentPosition.Following;\n      } else if (ref.isPreceding(other)) {\n        return DocumentPosition.Preceding;\n      } else {\n        return DocumentPosition.Following;\n      }\n    };\n\n    XMLNode.prototype.isSameNode = function(other) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLNode.prototype.lookupPrefix = function(namespaceURI) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLNode.prototype.isDefaultNamespace = function(namespaceURI) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLNode.prototype.lookupNamespaceURI = function(prefix) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLNode.prototype.isEqualNode = function(node) {\n      var i, j, ref2;\n      if (node.nodeType !== this.nodeType) {\n        return false;\n      }\n      if (node.children.length !== this.children.length) {\n        return false;\n      }\n      for (i = j = 0, ref2 = this.children.length - 1; 0 <= ref2 ? j <= ref2 : j >= ref2; i = 0 <= ref2 ? ++j : --j) {\n        if (!this.children[i].isEqualNode(node.children[i])) {\n          return false;\n        }\n      }\n      return true;\n    };\n\n    XMLNode.prototype.getFeature = function(feature, version) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLNode.prototype.setUserData = function(key, data, handler) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLNode.prototype.getUserData = function(key) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLNode.prototype.contains = function(other) {\n      if (!other) {\n        return false;\n      }\n      return other === this || this.isDescendant(other);\n    };\n\n    XMLNode.prototype.isDescendant = function(node) {\n      var child, isDescendantChild, j, len, ref2;\n      ref2 = this.children;\n      for (j = 0, len = ref2.length; j < len; j++) {\n        child = ref2[j];\n        if (node === child) {\n          return true;\n        }\n        isDescendantChild = child.isDescendant(node);\n        if (isDescendantChild) {\n          return true;\n        }\n      }\n      return false;\n    };\n\n    XMLNode.prototype.isAncestor = function(node) {\n      return node.isDescendant(this);\n    };\n\n    XMLNode.prototype.isPreceding = function(node) {\n      var nodePos, thisPos;\n      nodePos = this.treePosition(node);\n      thisPos = this.treePosition(this);\n      if (nodePos === -1 || thisPos === -1) {\n        return false;\n      } else {\n        return nodePos < thisPos;\n      }\n    };\n\n    XMLNode.prototype.isFollowing = function(node) {\n      var nodePos, thisPos;\n      nodePos = this.treePosition(node);\n      thisPos = this.treePosition(this);\n      if (nodePos === -1 || thisPos === -1) {\n        return false;\n      } else {\n        return nodePos > thisPos;\n      }\n    };\n\n    XMLNode.prototype.treePosition = function(node) {\n      var found, pos;\n      pos = 0;\n      found = false;\n      this.foreachTreeNode(this.document(), function(childNode) {\n        pos++;\n        if (!found && childNode === node) {\n          return found = true;\n        }\n      });\n      if (found) {\n        return pos;\n      } else {\n        return -1;\n      }\n    };\n\n    XMLNode.prototype.foreachTreeNode = function(node, func) {\n      var child, j, len, ref2, res;\n      node || (node = this.document());\n      ref2 = node.children;\n      for (j = 0, len = ref2.length; j < len; j++) {\n        child = ref2[j];\n        if (res = func(child)) {\n          return res;\n        } else {\n          res = this.foreachTreeNode(child, func);\n          if (res) {\n            return res;\n          }\n        }\n      }\n    };\n\n    return XMLNode;\n\n  })();\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var XMLStringifier,\n    bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },\n    hasProp = {}.hasOwnProperty;\n\n  module.exports = XMLStringifier = (function() {\n    function XMLStringifier(options) {\n      this.assertLegalName = bind(this.assertLegalName, this);\n      this.assertLegalChar = bind(this.assertLegalChar, this);\n      var key, ref, value;\n      options || (options = {});\n      this.options = options;\n      if (!this.options.version) {\n        this.options.version = '1.0';\n      }\n      ref = options.stringify || {};\n      for (key in ref) {\n        if (!hasProp.call(ref, key)) continue;\n        value = ref[key];\n        this[key] = value;\n      }\n    }\n\n    XMLStringifier.prototype.name = function(val) {\n      if (this.options.noValidation) {\n        return val;\n      }\n      return this.assertLegalName('' + val || '');\n    };\n\n    XMLStringifier.prototype.text = function(val) {\n      if (this.options.noValidation) {\n        return val;\n      }\n      return this.assertLegalChar(this.textEscape('' + val || ''));\n    };\n\n    XMLStringifier.prototype.cdata = function(val) {\n      if (this.options.noValidation) {\n        return val;\n      }\n      val = '' + val || '';\n      val = val.replace(']]>', ']]]]>');\n      return this.assertLegalChar(val);\n    };\n\n    XMLStringifier.prototype.comment = function(val) {\n      if (this.options.noValidation) {\n        return val;\n      }\n      val = '' + val || '';\n      if (val.match(/--/)) {\n        throw new Error(\"Comment text cannot contain double-hypen: \" + val);\n      }\n      return this.assertLegalChar(val);\n    };\n\n    XMLStringifier.prototype.raw = function(val) {\n      if (this.options.noValidation) {\n        return val;\n      }\n      return '' + val || '';\n    };\n\n    XMLStringifier.prototype.attValue = function(val) {\n      if (this.options.noValidation) {\n        return val;\n      }\n      return this.assertLegalChar(this.attEscape(val = '' + val || ''));\n    };\n\n    XMLStringifier.prototype.insTarget = function(val) {\n      if (this.options.noValidation) {\n        return val;\n      }\n      return this.assertLegalChar('' + val || '');\n    };\n\n    XMLStringifier.prototype.insValue = function(val) {\n      if (this.options.noValidation) {\n        return val;\n      }\n      val = '' + val || '';\n      if (val.match(/\\?>/)) {\n        throw new Error(\"Invalid processing instruction value: \" + val);\n      }\n      return this.assertLegalChar(val);\n    };\n\n    XMLStringifier.prototype.xmlVersion = function(val) {\n      if (this.options.noValidation) {\n        return val;\n      }\n      val = '' + val || '';\n      if (!val.match(/1\\.[0-9]+/)) {\n        throw new Error(\"Invalid version number: \" + val);\n      }\n      return val;\n    };\n\n    XMLStringifier.prototype.xmlEncoding = function(val) {\n      if (this.options.noValidation) {\n        return val;\n      }\n      val = '' + val || '';\n      if (!val.match(/^[A-Za-z](?:[A-Za-z0-9._-])*$/)) {\n        throw new Error(\"Invalid encoding: \" + val);\n      }\n      return this.assertLegalChar(val);\n    };\n\n    XMLStringifier.prototype.xmlStandalone = function(val) {\n      if (this.options.noValidation) {\n        return val;\n      }\n      if (val) {\n        return \"yes\";\n      } else {\n        return \"no\";\n      }\n    };\n\n    XMLStringifier.prototype.dtdPubID = function(val) {\n      if (this.options.noValidation) {\n        return val;\n      }\n      return this.assertLegalChar('' + val || '');\n    };\n\n    XMLStringifier.prototype.dtdSysID = function(val) {\n      if (this.options.noValidation) {\n        return val;\n      }\n      return this.assertLegalChar('' + val || '');\n    };\n\n    XMLStringifier.prototype.dtdElementValue = function(val) {\n      if (this.options.noValidation) {\n        return val;\n      }\n      return this.assertLegalChar('' + val || '');\n    };\n\n    XMLStringifier.prototype.dtdAttType = function(val) {\n      if (this.options.noValidation) {\n        return val;\n      }\n      return this.assertLegalChar('' + val || '');\n    };\n\n    XMLStringifier.prototype.dtdAttDefault = function(val) {\n      if (this.options.noValidation) {\n        return val;\n      }\n      return this.assertLegalChar('' + val || '');\n    };\n\n    XMLStringifier.prototype.dtdEntityValue = function(val) {\n      if (this.options.noValidation) {\n        return val;\n      }\n      return this.assertLegalChar('' + val || '');\n    };\n\n    XMLStringifier.prototype.dtdNData = function(val) {\n      if (this.options.noValidation) {\n        return val;\n      }\n      return this.assertLegalChar('' + val || '');\n    };\n\n    XMLStringifier.prototype.convertAttKey = '@';\n\n    XMLStringifier.prototype.convertPIKey = '?';\n\n    XMLStringifier.prototype.convertTextKey = '#text';\n\n    XMLStringifier.prototype.convertCDataKey = '#cdata';\n\n    XMLStringifier.prototype.convertCommentKey = '#comment';\n\n    XMLStringifier.prototype.convertRawKey = '#raw';\n\n    XMLStringifier.prototype.assertLegalChar = function(str) {\n      var regex, res;\n      if (this.options.noValidation) {\n        return str;\n      }\n      regex = '';\n      if (this.options.version === '1.0') {\n        regex = /[\\0-\\x08\\x0B\\f\\x0E-\\x1F\\uFFFE\\uFFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]/;\n        if (res = str.match(regex)) {\n          throw new Error(\"Invalid character in string: \" + str + \" at index \" + res.index);\n        }\n      } else if (this.options.version === '1.1') {\n        regex = /[\\0\\uFFFE\\uFFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]/;\n        if (res = str.match(regex)) {\n          throw new Error(\"Invalid character in string: \" + str + \" at index \" + res.index);\n        }\n      }\n      return str;\n    };\n\n    XMLStringifier.prototype.assertLegalName = function(str) {\n      var regex;\n      if (this.options.noValidation) {\n        return str;\n      }\n      this.assertLegalChar(str);\n      regex = /^([:A-Z_a-z\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]|[\\uD800-\\uDB7F][\\uDC00-\\uDFFF])([\\x2D\\.0-:A-Z_a-z\\xB7\\xC0-\\xD6\\xD8-\\xF6\\xF8-\\u037D\\u037F-\\u1FFF\\u200C\\u200D\\u203F\\u2040\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]|[\\uD800-\\uDB7F][\\uDC00-\\uDFFF])*$/;\n      if (!str.match(regex)) {\n        throw new Error(\"Invalid character in name\");\n      }\n      return str;\n    };\n\n    XMLStringifier.prototype.textEscape = function(str) {\n      var ampregex;\n      if (this.options.noValidation) {\n        return str;\n      }\n      ampregex = this.options.noDoubleEncoding ? /(?!&\\S+;)&/g : /&/g;\n      return str.replace(ampregex, '&').replace(//g, '>').replace(/\\r/g, '
');\n    };\n\n    XMLStringifier.prototype.attEscape = function(str) {\n      var ampregex;\n      if (this.options.noValidation) {\n        return str;\n      }\n      ampregex = this.options.noDoubleEncoding ? /(?!&\\S+;)&/g : /&/g;\n      return str.replace(ampregex, '&').replace(/ 0) {\n          return new Array(indentLevel).join(options.indent);\n        }\n      }\n      return '';\n    };\n\n    XMLWriterBase.prototype.endline = function(node, options, level) {\n      if (!options.pretty || options.suppressPrettyCount) {\n        return '';\n      } else {\n        return options.newline;\n      }\n    };\n\n    XMLWriterBase.prototype.attribute = function(att, options, level) {\n      var r;\n      this.openAttribute(att, options, level);\n      r = ' ' + att.name + '=\"' + att.value + '\"';\n      this.closeAttribute(att, options, level);\n      return r;\n    };\n\n    XMLWriterBase.prototype.cdata = function(node, options, level) {\n      var r;\n      this.openNode(node, options, level);\n      options.state = WriterState.OpenTag;\n      r = this.indent(node, options, level) + '' + this.endline(node, options, level);\n      options.state = WriterState.None;\n      this.closeNode(node, options, level);\n      return r;\n    };\n\n    XMLWriterBase.prototype.comment = function(node, options, level) {\n      var r;\n      this.openNode(node, options, level);\n      options.state = WriterState.OpenTag;\n      r = this.indent(node, options, level) + '' + this.endline(node, options, level);\n      options.state = WriterState.None;\n      this.closeNode(node, options, level);\n      return r;\n    };\n\n    XMLWriterBase.prototype.declaration = function(node, options, level) {\n      var r;\n      this.openNode(node, options, level);\n      options.state = WriterState.OpenTag;\n      r = this.indent(node, options, level) + '';\n      r += this.endline(node, options, level);\n      options.state = WriterState.None;\n      this.closeNode(node, options, level);\n      return r;\n    };\n\n    XMLWriterBase.prototype.docType = function(node, options, level) {\n      var child, i, len, r, ref;\n      level || (level = 0);\n      this.openNode(node, options, level);\n      options.state = WriterState.OpenTag;\n      r = this.indent(node, options, level);\n      r += ' 0) {\n        r += ' [';\n        r += this.endline(node, options, level);\n        options.state = WriterState.InsideTag;\n        ref = node.children;\n        for (i = 0, len = ref.length; i < len; i++) {\n          child = ref[i];\n          r += this.writeChildNode(child, options, level + 1);\n        }\n        options.state = WriterState.CloseTag;\n        r += ']';\n      }\n      options.state = WriterState.CloseTag;\n      r += options.spaceBeforeSlash + '>';\n      r += this.endline(node, options, level);\n      options.state = WriterState.None;\n      this.closeNode(node, options, level);\n      return r;\n    };\n\n    XMLWriterBase.prototype.element = function(node, options, level) {\n      var att, child, childNodeCount, firstChildNode, i, j, len, len1, name, prettySuppressed, r, ref, ref1, ref2;\n      level || (level = 0);\n      prettySuppressed = false;\n      r = '';\n      this.openNode(node, options, level);\n      options.state = WriterState.OpenTag;\n      r += this.indent(node, options, level) + '<' + node.name;\n      ref = node.attribs;\n      for (name in ref) {\n        if (!hasProp.call(ref, name)) continue;\n        att = ref[name];\n        r += this.attribute(att, options, level);\n      }\n      childNodeCount = node.children.length;\n      firstChildNode = childNodeCount === 0 ? null : node.children[0];\n      if (childNodeCount === 0 || node.children.every(function(e) {\n        return (e.type === NodeType.Text || e.type === NodeType.Raw) && e.value === '';\n      })) {\n        if (options.allowEmpty) {\n          r += '>';\n          options.state = WriterState.CloseTag;\n          r += '' + this.endline(node, options, level);\n        } else {\n          options.state = WriterState.CloseTag;\n          r += options.spaceBeforeSlash + '/>' + this.endline(node, options, level);\n        }\n      } else if (options.pretty && childNodeCount === 1 && (firstChildNode.type === NodeType.Text || firstChildNode.type === NodeType.Raw) && (firstChildNode.value != null)) {\n        r += '>';\n        options.state = WriterState.InsideTag;\n        options.suppressPrettyCount++;\n        prettySuppressed = true;\n        r += this.writeChildNode(firstChildNode, options, level + 1);\n        options.suppressPrettyCount--;\n        prettySuppressed = false;\n        options.state = WriterState.CloseTag;\n        r += '' + this.endline(node, options, level);\n      } else {\n        if (options.dontPrettyTextNodes) {\n          ref1 = node.children;\n          for (i = 0, len = ref1.length; i < len; i++) {\n            child = ref1[i];\n            if ((child.type === NodeType.Text || child.type === NodeType.Raw) && (child.value != null)) {\n              options.suppressPrettyCount++;\n              prettySuppressed = true;\n              break;\n            }\n          }\n        }\n        r += '>' + this.endline(node, options, level);\n        options.state = WriterState.InsideTag;\n        ref2 = node.children;\n        for (j = 0, len1 = ref2.length; j < len1; j++) {\n          child = ref2[j];\n          r += this.writeChildNode(child, options, level + 1);\n        }\n        options.state = WriterState.CloseTag;\n        r += this.indent(node, options, level) + '';\n        if (prettySuppressed) {\n          options.suppressPrettyCount--;\n        }\n        r += this.endline(node, options, level);\n        options.state = WriterState.None;\n      }\n      this.closeNode(node, options, level);\n      return r;\n    };\n\n    XMLWriterBase.prototype.writeChildNode = function(node, options, level) {\n      switch (node.type) {\n        case NodeType.CData:\n          return this.cdata(node, options, level);\n        case NodeType.Comment:\n          return this.comment(node, options, level);\n        case NodeType.Element:\n          return this.element(node, options, level);\n        case NodeType.Raw:\n          return this.raw(node, options, level);\n        case NodeType.Text:\n          return this.text(node, options, level);\n        case NodeType.ProcessingInstruction:\n          return this.processingInstruction(node, options, level);\n        case NodeType.Dummy:\n          return '';\n        case NodeType.Declaration:\n          return this.declaration(node, options, level);\n        case NodeType.DocType:\n          return this.docType(node, options, level);\n        case NodeType.AttributeDeclaration:\n          return this.dtdAttList(node, options, level);\n        case NodeType.ElementDeclaration:\n          return this.dtdElement(node, options, level);\n        case NodeType.EntityDeclaration:\n          return this.dtdEntity(node, options, level);\n        case NodeType.NotationDeclaration:\n          return this.dtdNotation(node, options, level);\n        default:\n          throw new Error(\"Unknown XML node type: \" + node.constructor.name);\n      }\n    };\n\n    XMLWriterBase.prototype.processingInstruction = function(node, options, level) {\n      var r;\n      this.openNode(node, options, level);\n      options.state = WriterState.OpenTag;\n      r = this.indent(node, options, level) + '';\n      r += this.endline(node, options, level);\n      options.state = WriterState.None;\n      this.closeNode(node, options, level);\n      return r;\n    };\n\n    XMLWriterBase.prototype.raw = function(node, options, level) {\n      var r;\n      this.openNode(node, options, level);\n      options.state = WriterState.OpenTag;\n      r = this.indent(node, options, level);\n      options.state = WriterState.InsideTag;\n      r += node.value;\n      options.state = WriterState.CloseTag;\n      r += this.endline(node, options, level);\n      options.state = WriterState.None;\n      this.closeNode(node, options, level);\n      return r;\n    };\n\n    XMLWriterBase.prototype.text = function(node, options, level) {\n      var r;\n      this.openNode(node, options, level);\n      options.state = WriterState.OpenTag;\n      r = this.indent(node, options, level);\n      options.state = WriterState.InsideTag;\n      r += node.value;\n      options.state = WriterState.CloseTag;\n      r += this.endline(node, options, level);\n      options.state = WriterState.None;\n      this.closeNode(node, options, level);\n      return r;\n    };\n\n    XMLWriterBase.prototype.dtdAttList = function(node, options, level) {\n      var r;\n      this.openNode(node, options, level);\n      options.state = WriterState.OpenTag;\n      r = this.indent(node, options, level) + '' + this.endline(node, options, level);\n      options.state = WriterState.None;\n      this.closeNode(node, options, level);\n      return r;\n    };\n\n    XMLWriterBase.prototype.dtdElement = function(node, options, level) {\n      var r;\n      this.openNode(node, options, level);\n      options.state = WriterState.OpenTag;\n      r = this.indent(node, options, level) + '' + this.endline(node, options, level);\n      options.state = WriterState.None;\n      this.closeNode(node, options, level);\n      return r;\n    };\n\n    XMLWriterBase.prototype.dtdEntity = function(node, options, level) {\n      var r;\n      this.openNode(node, options, level);\n      options.state = WriterState.OpenTag;\n      r = this.indent(node, options, level) + '' + this.endline(node, options, level);\n      options.state = WriterState.None;\n      this.closeNode(node, options, level);\n      return r;\n    };\n\n    XMLWriterBase.prototype.dtdNotation = function(node, options, level) {\n      var r;\n      this.openNode(node, options, level);\n      options.state = WriterState.OpenTag;\n      r = this.indent(node, options, level) + '' + this.endline(node, options, level);\n      options.state = WriterState.None;\n      this.closeNode(node, options, level);\n      return r;\n    };\n\n    XMLWriterBase.prototype.openNode = function(node, options, level) {};\n\n    XMLWriterBase.prototype.closeNode = function(node, options, level) {};\n\n    XMLWriterBase.prototype.openAttribute = function(att, options, level) {};\n\n    XMLWriterBase.prototype.closeAttribute = function(att, options, level) {};\n\n    return XMLWriterBase;\n\n  })();\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var XMLStringWriter, XMLWriterBase,\n    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\n    hasProp = {}.hasOwnProperty;\n\n  XMLWriterBase = require('./XMLWriterBase');\n\n  module.exports = XMLStringWriter = (function(superClass) {\n    extend(XMLStringWriter, superClass);\n\n    function XMLStringWriter(options) {\n      XMLStringWriter.__super__.constructor.call(this, options);\n    }\n\n    XMLStringWriter.prototype.document = function(doc, options) {\n      var child, i, len, r, ref;\n      options = this.filterOptions(options);\n      r = '';\n      ref = doc.children;\n      for (i = 0, len = ref.length; i < len; i++) {\n        child = ref[i];\n        r += this.writeChildNode(child, options, 0);\n      }\n      if (options.pretty && r.slice(-options.newline.length) === options.newline) {\n        r = r.slice(0, -options.newline.length);\n      }\n      return r;\n    };\n\n    return XMLStringWriter;\n\n  })(XMLWriterBase);\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var NodeType, XMLDOMConfiguration, XMLDOMImplementation, XMLDocument, XMLNode, XMLStringWriter, XMLStringifier, isPlainObject,\n    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\n    hasProp = {}.hasOwnProperty;\n\n  isPlainObject = require('./Utility').isPlainObject;\n\n  XMLDOMImplementation = require('./XMLDOMImplementation');\n\n  XMLDOMConfiguration = require('./XMLDOMConfiguration');\n\n  XMLNode = require('./XMLNode');\n\n  NodeType = require('./NodeType');\n\n  XMLStringifier = require('./XMLStringifier');\n\n  XMLStringWriter = require('./XMLStringWriter');\n\n  module.exports = XMLDocument = (function(superClass) {\n    extend(XMLDocument, superClass);\n\n    function XMLDocument(options) {\n      XMLDocument.__super__.constructor.call(this, null);\n      this.name = \"#document\";\n      this.type = NodeType.Document;\n      this.documentURI = null;\n      this.domConfig = new XMLDOMConfiguration();\n      options || (options = {});\n      if (!options.writer) {\n        options.writer = new XMLStringWriter();\n      }\n      this.options = options;\n      this.stringify = new XMLStringifier(options);\n    }\n\n    Object.defineProperty(XMLDocument.prototype, 'implementation', {\n      value: new XMLDOMImplementation()\n    });\n\n    Object.defineProperty(XMLDocument.prototype, 'doctype', {\n      get: function() {\n        var child, i, len, ref;\n        ref = this.children;\n        for (i = 0, len = ref.length; i < len; i++) {\n          child = ref[i];\n          if (child.type === NodeType.DocType) {\n            return child;\n          }\n        }\n        return null;\n      }\n    });\n\n    Object.defineProperty(XMLDocument.prototype, 'documentElement', {\n      get: function() {\n        return this.rootObject || null;\n      }\n    });\n\n    Object.defineProperty(XMLDocument.prototype, 'inputEncoding', {\n      get: function() {\n        return null;\n      }\n    });\n\n    Object.defineProperty(XMLDocument.prototype, 'strictErrorChecking', {\n      get: function() {\n        return false;\n      }\n    });\n\n    Object.defineProperty(XMLDocument.prototype, 'xmlEncoding', {\n      get: function() {\n        if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) {\n          return this.children[0].encoding;\n        } else {\n          return null;\n        }\n      }\n    });\n\n    Object.defineProperty(XMLDocument.prototype, 'xmlStandalone', {\n      get: function() {\n        if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) {\n          return this.children[0].standalone === 'yes';\n        } else {\n          return false;\n        }\n      }\n    });\n\n    Object.defineProperty(XMLDocument.prototype, 'xmlVersion', {\n      get: function() {\n        if (this.children.length !== 0 && this.children[0].type === NodeType.Declaration) {\n          return this.children[0].version;\n        } else {\n          return \"1.0\";\n        }\n      }\n    });\n\n    Object.defineProperty(XMLDocument.prototype, 'URL', {\n      get: function() {\n        return this.documentURI;\n      }\n    });\n\n    Object.defineProperty(XMLDocument.prototype, 'origin', {\n      get: function() {\n        return null;\n      }\n    });\n\n    Object.defineProperty(XMLDocument.prototype, 'compatMode', {\n      get: function() {\n        return null;\n      }\n    });\n\n    Object.defineProperty(XMLDocument.prototype, 'characterSet', {\n      get: function() {\n        return null;\n      }\n    });\n\n    Object.defineProperty(XMLDocument.prototype, 'contentType', {\n      get: function() {\n        return null;\n      }\n    });\n\n    XMLDocument.prototype.end = function(writer) {\n      var writerOptions;\n      writerOptions = {};\n      if (!writer) {\n        writer = this.options.writer;\n      } else if (isPlainObject(writer)) {\n        writerOptions = writer;\n        writer = this.options.writer;\n      }\n      return writer.document(this, writer.filterOptions(writerOptions));\n    };\n\n    XMLDocument.prototype.toString = function(options) {\n      return this.options.writer.document(this, this.options.writer.filterOptions(options));\n    };\n\n    XMLDocument.prototype.createElement = function(tagName) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.createDocumentFragment = function() {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.createTextNode = function(data) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.createComment = function(data) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.createCDATASection = function(data) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.createProcessingInstruction = function(target, data) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.createAttribute = function(name) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.createEntityReference = function(name) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.getElementsByTagName = function(tagname) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.importNode = function(importedNode, deep) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.createElementNS = function(namespaceURI, qualifiedName) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.createAttributeNS = function(namespaceURI, qualifiedName) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.getElementsByTagNameNS = function(namespaceURI, localName) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.getElementById = function(elementId) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.adoptNode = function(source) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.normalizeDocument = function() {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.renameNode = function(node, namespaceURI, qualifiedName) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.getElementsByClassName = function(classNames) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.createEvent = function(eventInterface) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.createRange = function() {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.createNodeIterator = function(root, whatToShow, filter) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    XMLDocument.prototype.createTreeWalker = function(root, whatToShow, filter) {\n      throw new Error(\"This DOM method is not implemented.\" + this.debugInfo());\n    };\n\n    return XMLDocument;\n\n  })(XMLNode);\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var NodeType, WriterState, XMLAttribute, XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLDocument, XMLDocumentCB, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStringWriter, XMLStringifier, XMLText, getValue, isFunction, isObject, isPlainObject, ref,\n    hasProp = {}.hasOwnProperty;\n\n  ref = require('./Utility'), isObject = ref.isObject, isFunction = ref.isFunction, isPlainObject = ref.isPlainObject, getValue = ref.getValue;\n\n  NodeType = require('./NodeType');\n\n  XMLDocument = require('./XMLDocument');\n\n  XMLElement = require('./XMLElement');\n\n  XMLCData = require('./XMLCData');\n\n  XMLComment = require('./XMLComment');\n\n  XMLRaw = require('./XMLRaw');\n\n  XMLText = require('./XMLText');\n\n  XMLProcessingInstruction = require('./XMLProcessingInstruction');\n\n  XMLDeclaration = require('./XMLDeclaration');\n\n  XMLDocType = require('./XMLDocType');\n\n  XMLDTDAttList = require('./XMLDTDAttList');\n\n  XMLDTDEntity = require('./XMLDTDEntity');\n\n  XMLDTDElement = require('./XMLDTDElement');\n\n  XMLDTDNotation = require('./XMLDTDNotation');\n\n  XMLAttribute = require('./XMLAttribute');\n\n  XMLStringifier = require('./XMLStringifier');\n\n  XMLStringWriter = require('./XMLStringWriter');\n\n  WriterState = require('./WriterState');\n\n  module.exports = XMLDocumentCB = (function() {\n    function XMLDocumentCB(options, onData, onEnd) {\n      var writerOptions;\n      this.name = \"?xml\";\n      this.type = NodeType.Document;\n      options || (options = {});\n      writerOptions = {};\n      if (!options.writer) {\n        options.writer = new XMLStringWriter();\n      } else if (isPlainObject(options.writer)) {\n        writerOptions = options.writer;\n        options.writer = new XMLStringWriter();\n      }\n      this.options = options;\n      this.writer = options.writer;\n      this.writerOptions = this.writer.filterOptions(writerOptions);\n      this.stringify = new XMLStringifier(options);\n      this.onDataCallback = onData || function() {};\n      this.onEndCallback = onEnd || function() {};\n      this.currentNode = null;\n      this.currentLevel = -1;\n      this.openTags = {};\n      this.documentStarted = false;\n      this.documentCompleted = false;\n      this.root = null;\n    }\n\n    XMLDocumentCB.prototype.createChildNode = function(node) {\n      var att, attName, attributes, child, i, len, ref1, ref2;\n      switch (node.type) {\n        case NodeType.CData:\n          this.cdata(node.value);\n          break;\n        case NodeType.Comment:\n          this.comment(node.value);\n          break;\n        case NodeType.Element:\n          attributes = {};\n          ref1 = node.attribs;\n          for (attName in ref1) {\n            if (!hasProp.call(ref1, attName)) continue;\n            att = ref1[attName];\n            attributes[attName] = att.value;\n          }\n          this.node(node.name, attributes);\n          break;\n        case NodeType.Dummy:\n          this.dummy();\n          break;\n        case NodeType.Raw:\n          this.raw(node.value);\n          break;\n        case NodeType.Text:\n          this.text(node.value);\n          break;\n        case NodeType.ProcessingInstruction:\n          this.instruction(node.target, node.value);\n          break;\n        default:\n          throw new Error(\"This XML node type is not supported in a JS object: \" + node.constructor.name);\n      }\n      ref2 = node.children;\n      for (i = 0, len = ref2.length; i < len; i++) {\n        child = ref2[i];\n        this.createChildNode(child);\n        if (child.type === NodeType.Element) {\n          this.up();\n        }\n      }\n      return this;\n    };\n\n    XMLDocumentCB.prototype.dummy = function() {\n      return this;\n    };\n\n    XMLDocumentCB.prototype.node = function(name, attributes, text) {\n      var ref1;\n      if (name == null) {\n        throw new Error(\"Missing node name.\");\n      }\n      if (this.root && this.currentLevel === -1) {\n        throw new Error(\"Document can only have one root node. \" + this.debugInfo(name));\n      }\n      this.openCurrent();\n      name = getValue(name);\n      if (attributes == null) {\n        attributes = {};\n      }\n      attributes = getValue(attributes);\n      if (!isObject(attributes)) {\n        ref1 = [attributes, text], text = ref1[0], attributes = ref1[1];\n      }\n      this.currentNode = new XMLElement(this, name, attributes);\n      this.currentNode.children = false;\n      this.currentLevel++;\n      this.openTags[this.currentLevel] = this.currentNode;\n      if (text != null) {\n        this.text(text);\n      }\n      return this;\n    };\n\n    XMLDocumentCB.prototype.element = function(name, attributes, text) {\n      var child, i, len, oldValidationFlag, ref1, root;\n      if (this.currentNode && this.currentNode.type === NodeType.DocType) {\n        this.dtdElement.apply(this, arguments);\n      } else {\n        if (Array.isArray(name) || isObject(name) || isFunction(name)) {\n          oldValidationFlag = this.options.noValidation;\n          this.options.noValidation = true;\n          root = new XMLDocument(this.options).element('TEMP_ROOT');\n          root.element(name);\n          this.options.noValidation = oldValidationFlag;\n          ref1 = root.children;\n          for (i = 0, len = ref1.length; i < len; i++) {\n            child = ref1[i];\n            this.createChildNode(child);\n            if (child.type === NodeType.Element) {\n              this.up();\n            }\n          }\n        } else {\n          this.node(name, attributes, text);\n        }\n      }\n      return this;\n    };\n\n    XMLDocumentCB.prototype.attribute = function(name, value) {\n      var attName, attValue;\n      if (!this.currentNode || this.currentNode.children) {\n        throw new Error(\"att() can only be used immediately after an ele() call in callback mode. \" + this.debugInfo(name));\n      }\n      if (name != null) {\n        name = getValue(name);\n      }\n      if (isObject(name)) {\n        for (attName in name) {\n          if (!hasProp.call(name, attName)) continue;\n          attValue = name[attName];\n          this.attribute(attName, attValue);\n        }\n      } else {\n        if (isFunction(value)) {\n          value = value.apply();\n        }\n        if (this.options.keepNullAttributes && (value == null)) {\n          this.currentNode.attribs[name] = new XMLAttribute(this, name, \"\");\n        } else if (value != null) {\n          this.currentNode.attribs[name] = new XMLAttribute(this, name, value);\n        }\n      }\n      return this;\n    };\n\n    XMLDocumentCB.prototype.text = function(value) {\n      var node;\n      this.openCurrent();\n      node = new XMLText(this, value);\n      this.onData(this.writer.text(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);\n      return this;\n    };\n\n    XMLDocumentCB.prototype.cdata = function(value) {\n      var node;\n      this.openCurrent();\n      node = new XMLCData(this, value);\n      this.onData(this.writer.cdata(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);\n      return this;\n    };\n\n    XMLDocumentCB.prototype.comment = function(value) {\n      var node;\n      this.openCurrent();\n      node = new XMLComment(this, value);\n      this.onData(this.writer.comment(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);\n      return this;\n    };\n\n    XMLDocumentCB.prototype.raw = function(value) {\n      var node;\n      this.openCurrent();\n      node = new XMLRaw(this, value);\n      this.onData(this.writer.raw(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);\n      return this;\n    };\n\n    XMLDocumentCB.prototype.instruction = function(target, value) {\n      var i, insTarget, insValue, len, node;\n      this.openCurrent();\n      if (target != null) {\n        target = getValue(target);\n      }\n      if (value != null) {\n        value = getValue(value);\n      }\n      if (Array.isArray(target)) {\n        for (i = 0, len = target.length; i < len; i++) {\n          insTarget = target[i];\n          this.instruction(insTarget);\n        }\n      } else if (isObject(target)) {\n        for (insTarget in target) {\n          if (!hasProp.call(target, insTarget)) continue;\n          insValue = target[insTarget];\n          this.instruction(insTarget, insValue);\n        }\n      } else {\n        if (isFunction(value)) {\n          value = value.apply();\n        }\n        node = new XMLProcessingInstruction(this, target, value);\n        this.onData(this.writer.processingInstruction(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);\n      }\n      return this;\n    };\n\n    XMLDocumentCB.prototype.declaration = function(version, encoding, standalone) {\n      var node;\n      this.openCurrent();\n      if (this.documentStarted) {\n        throw new Error(\"declaration() must be the first node.\");\n      }\n      node = new XMLDeclaration(this, version, encoding, standalone);\n      this.onData(this.writer.declaration(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);\n      return this;\n    };\n\n    XMLDocumentCB.prototype.doctype = function(root, pubID, sysID) {\n      this.openCurrent();\n      if (root == null) {\n        throw new Error(\"Missing root node name.\");\n      }\n      if (this.root) {\n        throw new Error(\"dtd() must come before the root node.\");\n      }\n      this.currentNode = new XMLDocType(this, pubID, sysID);\n      this.currentNode.rootNodeName = root;\n      this.currentNode.children = false;\n      this.currentLevel++;\n      this.openTags[this.currentLevel] = this.currentNode;\n      return this;\n    };\n\n    XMLDocumentCB.prototype.dtdElement = function(name, value) {\n      var node;\n      this.openCurrent();\n      node = new XMLDTDElement(this, name, value);\n      this.onData(this.writer.dtdElement(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);\n      return this;\n    };\n\n    XMLDocumentCB.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {\n      var node;\n      this.openCurrent();\n      node = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue);\n      this.onData(this.writer.dtdAttList(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);\n      return this;\n    };\n\n    XMLDocumentCB.prototype.entity = function(name, value) {\n      var node;\n      this.openCurrent();\n      node = new XMLDTDEntity(this, false, name, value);\n      this.onData(this.writer.dtdEntity(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);\n      return this;\n    };\n\n    XMLDocumentCB.prototype.pEntity = function(name, value) {\n      var node;\n      this.openCurrent();\n      node = new XMLDTDEntity(this, true, name, value);\n      this.onData(this.writer.dtdEntity(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);\n      return this;\n    };\n\n    XMLDocumentCB.prototype.notation = function(name, value) {\n      var node;\n      this.openCurrent();\n      node = new XMLDTDNotation(this, name, value);\n      this.onData(this.writer.dtdNotation(node, this.writerOptions, this.currentLevel + 1), this.currentLevel + 1);\n      return this;\n    };\n\n    XMLDocumentCB.prototype.up = function() {\n      if (this.currentLevel < 0) {\n        throw new Error(\"The document node has no parent.\");\n      }\n      if (this.currentNode) {\n        if (this.currentNode.children) {\n          this.closeNode(this.currentNode);\n        } else {\n          this.openNode(this.currentNode);\n        }\n        this.currentNode = null;\n      } else {\n        this.closeNode(this.openTags[this.currentLevel]);\n      }\n      delete this.openTags[this.currentLevel];\n      this.currentLevel--;\n      return this;\n    };\n\n    XMLDocumentCB.prototype.end = function() {\n      while (this.currentLevel >= 0) {\n        this.up();\n      }\n      return this.onEnd();\n    };\n\n    XMLDocumentCB.prototype.openCurrent = function() {\n      if (this.currentNode) {\n        this.currentNode.children = true;\n        return this.openNode(this.currentNode);\n      }\n    };\n\n    XMLDocumentCB.prototype.openNode = function(node) {\n      var att, chunk, name, ref1;\n      if (!node.isOpen) {\n        if (!this.root && this.currentLevel === 0 && node.type === NodeType.Element) {\n          this.root = node;\n        }\n        chunk = '';\n        if (node.type === NodeType.Element) {\n          this.writerOptions.state = WriterState.OpenTag;\n          chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + '<' + node.name;\n          ref1 = node.attribs;\n          for (name in ref1) {\n            if (!hasProp.call(ref1, name)) continue;\n            att = ref1[name];\n            chunk += this.writer.attribute(att, this.writerOptions, this.currentLevel);\n          }\n          chunk += (node.children ? '>' : '/>') + this.writer.endline(node, this.writerOptions, this.currentLevel);\n          this.writerOptions.state = WriterState.InsideTag;\n        } else {\n          this.writerOptions.state = WriterState.OpenTag;\n          chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + '';\n          }\n          chunk += this.writer.endline(node, this.writerOptions, this.currentLevel);\n        }\n        this.onData(chunk, this.currentLevel);\n        return node.isOpen = true;\n      }\n    };\n\n    XMLDocumentCB.prototype.closeNode = function(node) {\n      var chunk;\n      if (!node.isClosed) {\n        chunk = '';\n        this.writerOptions.state = WriterState.CloseTag;\n        if (node.type === NodeType.Element) {\n          chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + '' + this.writer.endline(node, this.writerOptions, this.currentLevel);\n        } else {\n          chunk = this.writer.indent(node, this.writerOptions, this.currentLevel) + ']>' + this.writer.endline(node, this.writerOptions, this.currentLevel);\n        }\n        this.writerOptions.state = WriterState.None;\n        this.onData(chunk, this.currentLevel);\n        return node.isClosed = true;\n      }\n    };\n\n    XMLDocumentCB.prototype.onData = function(chunk, level) {\n      this.documentStarted = true;\n      return this.onDataCallback(chunk, level + 1);\n    };\n\n    XMLDocumentCB.prototype.onEnd = function() {\n      this.documentCompleted = true;\n      return this.onEndCallback();\n    };\n\n    XMLDocumentCB.prototype.debugInfo = function(name) {\n      if (name == null) {\n        return \"\";\n      } else {\n        return \"node: <\" + name + \">\";\n      }\n    };\n\n    XMLDocumentCB.prototype.ele = function() {\n      return this.element.apply(this, arguments);\n    };\n\n    XMLDocumentCB.prototype.nod = function(name, attributes, text) {\n      return this.node(name, attributes, text);\n    };\n\n    XMLDocumentCB.prototype.txt = function(value) {\n      return this.text(value);\n    };\n\n    XMLDocumentCB.prototype.dat = function(value) {\n      return this.cdata(value);\n    };\n\n    XMLDocumentCB.prototype.com = function(value) {\n      return this.comment(value);\n    };\n\n    XMLDocumentCB.prototype.ins = function(target, value) {\n      return this.instruction(target, value);\n    };\n\n    XMLDocumentCB.prototype.dec = function(version, encoding, standalone) {\n      return this.declaration(version, encoding, standalone);\n    };\n\n    XMLDocumentCB.prototype.dtd = function(root, pubID, sysID) {\n      return this.doctype(root, pubID, sysID);\n    };\n\n    XMLDocumentCB.prototype.e = function(name, attributes, text) {\n      return this.element(name, attributes, text);\n    };\n\n    XMLDocumentCB.prototype.n = function(name, attributes, text) {\n      return this.node(name, attributes, text);\n    };\n\n    XMLDocumentCB.prototype.t = function(value) {\n      return this.text(value);\n    };\n\n    XMLDocumentCB.prototype.d = function(value) {\n      return this.cdata(value);\n    };\n\n    XMLDocumentCB.prototype.c = function(value) {\n      return this.comment(value);\n    };\n\n    XMLDocumentCB.prototype.r = function(value) {\n      return this.raw(value);\n    };\n\n    XMLDocumentCB.prototype.i = function(target, value) {\n      return this.instruction(target, value);\n    };\n\n    XMLDocumentCB.prototype.att = function() {\n      if (this.currentNode && this.currentNode.type === NodeType.DocType) {\n        return this.attList.apply(this, arguments);\n      } else {\n        return this.attribute.apply(this, arguments);\n      }\n    };\n\n    XMLDocumentCB.prototype.a = function() {\n      if (this.currentNode && this.currentNode.type === NodeType.DocType) {\n        return this.attList.apply(this, arguments);\n      } else {\n        return this.attribute.apply(this, arguments);\n      }\n    };\n\n    XMLDocumentCB.prototype.ent = function(name, value) {\n      return this.entity(name, value);\n    };\n\n    XMLDocumentCB.prototype.pent = function(name, value) {\n      return this.pEntity(name, value);\n    };\n\n    XMLDocumentCB.prototype.not = function(name, value) {\n      return this.notation(name, value);\n    };\n\n    return XMLDocumentCB;\n\n  })();\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var NodeType, WriterState, XMLStreamWriter, XMLWriterBase,\n    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },\n    hasProp = {}.hasOwnProperty;\n\n  NodeType = require('./NodeType');\n\n  XMLWriterBase = require('./XMLWriterBase');\n\n  WriterState = require('./WriterState');\n\n  module.exports = XMLStreamWriter = (function(superClass) {\n    extend(XMLStreamWriter, superClass);\n\n    function XMLStreamWriter(stream, options) {\n      this.stream = stream;\n      XMLStreamWriter.__super__.constructor.call(this, options);\n    }\n\n    XMLStreamWriter.prototype.endline = function(node, options, level) {\n      if (node.isLastRootNode && options.state === WriterState.CloseTag) {\n        return '';\n      } else {\n        return XMLStreamWriter.__super__.endline.call(this, node, options, level);\n      }\n    };\n\n    XMLStreamWriter.prototype.document = function(doc, options) {\n      var child, i, j, k, len, len1, ref, ref1, results;\n      ref = doc.children;\n      for (i = j = 0, len = ref.length; j < len; i = ++j) {\n        child = ref[i];\n        child.isLastRootNode = i === doc.children.length - 1;\n      }\n      options = this.filterOptions(options);\n      ref1 = doc.children;\n      results = [];\n      for (k = 0, len1 = ref1.length; k < len1; k++) {\n        child = ref1[k];\n        results.push(this.writeChildNode(child, options, 0));\n      }\n      return results;\n    };\n\n    XMLStreamWriter.prototype.attribute = function(att, options, level) {\n      return this.stream.write(XMLStreamWriter.__super__.attribute.call(this, att, options, level));\n    };\n\n    XMLStreamWriter.prototype.cdata = function(node, options, level) {\n      return this.stream.write(XMLStreamWriter.__super__.cdata.call(this, node, options, level));\n    };\n\n    XMLStreamWriter.prototype.comment = function(node, options, level) {\n      return this.stream.write(XMLStreamWriter.__super__.comment.call(this, node, options, level));\n    };\n\n    XMLStreamWriter.prototype.declaration = function(node, options, level) {\n      return this.stream.write(XMLStreamWriter.__super__.declaration.call(this, node, options, level));\n    };\n\n    XMLStreamWriter.prototype.docType = function(node, options, level) {\n      var child, j, len, ref;\n      level || (level = 0);\n      this.openNode(node, options, level);\n      options.state = WriterState.OpenTag;\n      this.stream.write(this.indent(node, options, level));\n      this.stream.write(' 0) {\n        this.stream.write(' [');\n        this.stream.write(this.endline(node, options, level));\n        options.state = WriterState.InsideTag;\n        ref = node.children;\n        for (j = 0, len = ref.length; j < len; j++) {\n          child = ref[j];\n          this.writeChildNode(child, options, level + 1);\n        }\n        options.state = WriterState.CloseTag;\n        this.stream.write(']');\n      }\n      options.state = WriterState.CloseTag;\n      this.stream.write(options.spaceBeforeSlash + '>');\n      this.stream.write(this.endline(node, options, level));\n      options.state = WriterState.None;\n      return this.closeNode(node, options, level);\n    };\n\n    XMLStreamWriter.prototype.element = function(node, options, level) {\n      var att, child, childNodeCount, firstChildNode, j, len, name, prettySuppressed, ref, ref1;\n      level || (level = 0);\n      this.openNode(node, options, level);\n      options.state = WriterState.OpenTag;\n      this.stream.write(this.indent(node, options, level) + '<' + node.name);\n      ref = node.attribs;\n      for (name in ref) {\n        if (!hasProp.call(ref, name)) continue;\n        att = ref[name];\n        this.attribute(att, options, level);\n      }\n      childNodeCount = node.children.length;\n      firstChildNode = childNodeCount === 0 ? null : node.children[0];\n      if (childNodeCount === 0 || node.children.every(function(e) {\n        return (e.type === NodeType.Text || e.type === NodeType.Raw) && e.value === '';\n      })) {\n        if (options.allowEmpty) {\n          this.stream.write('>');\n          options.state = WriterState.CloseTag;\n          this.stream.write('');\n        } else {\n          options.state = WriterState.CloseTag;\n          this.stream.write(options.spaceBeforeSlash + '/>');\n        }\n      } else if (options.pretty && childNodeCount === 1 && (firstChildNode.type === NodeType.Text || firstChildNode.type === NodeType.Raw) && (firstChildNode.value != null)) {\n        this.stream.write('>');\n        options.state = WriterState.InsideTag;\n        options.suppressPrettyCount++;\n        prettySuppressed = true;\n        this.writeChildNode(firstChildNode, options, level + 1);\n        options.suppressPrettyCount--;\n        prettySuppressed = false;\n        options.state = WriterState.CloseTag;\n        this.stream.write('');\n      } else {\n        this.stream.write('>' + this.endline(node, options, level));\n        options.state = WriterState.InsideTag;\n        ref1 = node.children;\n        for (j = 0, len = ref1.length; j < len; j++) {\n          child = ref1[j];\n          this.writeChildNode(child, options, level + 1);\n        }\n        options.state = WriterState.CloseTag;\n        this.stream.write(this.indent(node, options, level) + '');\n      }\n      this.stream.write(this.endline(node, options, level));\n      options.state = WriterState.None;\n      return this.closeNode(node, options, level);\n    };\n\n    XMLStreamWriter.prototype.processingInstruction = function(node, options, level) {\n      return this.stream.write(XMLStreamWriter.__super__.processingInstruction.call(this, node, options, level));\n    };\n\n    XMLStreamWriter.prototype.raw = function(node, options, level) {\n      return this.stream.write(XMLStreamWriter.__super__.raw.call(this, node, options, level));\n    };\n\n    XMLStreamWriter.prototype.text = function(node, options, level) {\n      return this.stream.write(XMLStreamWriter.__super__.text.call(this, node, options, level));\n    };\n\n    XMLStreamWriter.prototype.dtdAttList = function(node, options, level) {\n      return this.stream.write(XMLStreamWriter.__super__.dtdAttList.call(this, node, options, level));\n    };\n\n    XMLStreamWriter.prototype.dtdElement = function(node, options, level) {\n      return this.stream.write(XMLStreamWriter.__super__.dtdElement.call(this, node, options, level));\n    };\n\n    XMLStreamWriter.prototype.dtdEntity = function(node, options, level) {\n      return this.stream.write(XMLStreamWriter.__super__.dtdEntity.call(this, node, options, level));\n    };\n\n    XMLStreamWriter.prototype.dtdNotation = function(node, options, level) {\n      return this.stream.write(XMLStreamWriter.__super__.dtdNotation.call(this, node, options, level));\n    };\n\n    return XMLStreamWriter;\n\n  })(XMLWriterBase);\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  var NodeType, WriterState, XMLDOMImplementation, XMLDocument, XMLDocumentCB, XMLStreamWriter, XMLStringWriter, assign, isFunction, ref;\n\n  ref = require('./Utility'), assign = ref.assign, isFunction = ref.isFunction;\n\n  XMLDOMImplementation = require('./XMLDOMImplementation');\n\n  XMLDocument = require('./XMLDocument');\n\n  XMLDocumentCB = require('./XMLDocumentCB');\n\n  XMLStringWriter = require('./XMLStringWriter');\n\n  XMLStreamWriter = require('./XMLStreamWriter');\n\n  NodeType = require('./NodeType');\n\n  WriterState = require('./WriterState');\n\n  module.exports.create = function(name, xmldec, doctype, options) {\n    var doc, root;\n    if (name == null) {\n      throw new Error(\"Root element needs a name.\");\n    }\n    options = assign({}, xmldec, doctype, options);\n    doc = new XMLDocument(options);\n    root = doc.element(name);\n    if (!options.headless) {\n      doc.declaration(options);\n      if ((options.pubID != null) || (options.sysID != null)) {\n        doc.dtd(options);\n      }\n    }\n    return root;\n  };\n\n  module.exports.begin = function(options, onData, onEnd) {\n    var ref1;\n    if (isFunction(options)) {\n      ref1 = [options, onData], onData = ref1[0], onEnd = ref1[1];\n      options = {};\n    }\n    if (onData) {\n      return new XMLDocumentCB(options, onData, onEnd);\n    } else {\n      return new XMLDocument(options);\n    }\n  };\n\n  module.exports.stringWriter = function(options) {\n    return new XMLStringWriter(options);\n  };\n\n  module.exports.streamWriter = function(stream, options) {\n    return new XMLStreamWriter(stream, options);\n  };\n\n  module.exports.implementation = new XMLDOMImplementation();\n\n  module.exports.nodeType = NodeType;\n\n  module.exports.writerState = WriterState;\n\n}).call(this);\n","// Generated by CoffeeScript 1.12.7\n(function() {\n  \"use strict\";\n  var builder, defaults, escapeCDATA, requiresCDATA, wrapCDATA,\n    hasProp = {}.hasOwnProperty;\n\n  builder = require('xmlbuilder');\n\n  defaults = require('./defaults').defaults;\n\n  requiresCDATA = function(entry) {\n    return typeof entry === \"string\" && (entry.indexOf('&') >= 0 || entry.indexOf('>') >= 0 || entry.indexOf('<') >= 0);\n  };\n\n  wrapCDATA = function(entry) {\n    return \"\";\n  };\n\n  escapeCDATA = function(entry) {\n    return entry.replace(']]>', ']]]]>');\n  };\n\n  exports.Builder = (function() {\n    function Builder(opts) {\n      var key, ref, value;\n      this.options = {};\n      ref = defaults[\"0.2\"];\n      for (key in ref) {\n        if (!hasProp.call(ref, key)) continue;\n        value = ref[key];\n        this.options[key] = value;\n      }\n      for (key in opts) {\n        if (!hasProp.call(opts, key)) continue;\n        value = opts[key];\n        this.options[key] = value;\n      }\n    }\n\n    Builder.prototype.buildObject = function(rootObj) {\n      var attrkey, charkey, render, rootElement, rootName;\n      attrkey = this.options.attrkey;\n      charkey = this.options.charkey;\n      if ((Object.keys(rootObj).length === 1) && (this.options.rootName === defaults['0.2'].rootName)) {\n        rootName = Object.keys(rootObj)[0];\n        rootObj = rootObj[rootName];\n      } else {\n        rootName = this.options.rootName;\n      }\n      render = (function(_this) {\n        return function(element, obj) {\n          var attr, child, entry, index, key, value;\n          if (typeof obj !== 'object') {\n            if (_this.options.cdata && requiresCDATA(obj)) {\n              element.raw(wrapCDATA(obj));\n            } else {\n              element.txt(obj);\n            }\n          } else if (Array.isArray(obj)) {\n            for (index in obj) {\n              if (!hasProp.call(obj, index)) continue;\n              child = obj[index];\n              for (key in child) {\n                entry = child[key];\n                element = render(element.ele(key), entry).up();\n              }\n            }\n          } else {\n            for (key in obj) {\n              if (!hasProp.call(obj, key)) continue;\n              child = obj[key];\n              if (key === attrkey) {\n                if (typeof child === \"object\") {\n                  for (attr in child) {\n                    value = child[attr];\n                    element = element.att(attr, value);\n                  }\n                }\n              } else if (key === charkey) {\n                if (_this.options.cdata && requiresCDATA(child)) {\n                  element = element.raw(wrapCDATA(child));\n                } else {\n                  element = element.txt(child);\n                }\n              } else if (Array.isArray(child)) {\n                for (index in child) {\n                  if (!hasProp.call(child, index)) continue;\n                  entry = child[index];\n                  if (typeof entry === 'string') {\n                    if (_this.options.cdata && requiresCDATA(entry)) {\n                      element = element.ele(key).raw(wrapCDATA(entry)).up();\n                    } else {\n                      element = element.ele(key, entry).up();\n                    }\n                  } else {\n                    element = render(element.ele(key), entry).up();\n                  }\n                }\n              } else if (typeof child === \"object\") {\n                element = render(element.ele(key), child).up();\n              } else {\n                if (typeof child === 'string' && _this.options.cdata && requiresCDATA(child)) {\n                  element = element.ele(key).raw(wrapCDATA(child)).up();\n                } else {\n                  if (child == null) {\n                    child = '';\n                  }\n                  element = element.ele(key, child.toString()).up();\n                }\n              }\n            }\n          }\n          return element;\n        };\n      })(this);\n      rootElement = builder.create(rootName, this.options.xmldec, this.options.doctype, {\n        headless: this.options.headless,\n        allowSurrogateChars: this.options.allowSurrogateChars\n      });\n      return render(rootElement, rootObj).end(this.options.renderOpts);\n    };\n\n    return Builder;\n\n  })();\n\n}).call(this);\n",";(function (sax) { // wrapper for non-node envs\n  sax.parser = function (strict, opt) { return new SAXParser(strict, opt) }\n  sax.SAXParser = SAXParser\n  sax.SAXStream = SAXStream\n  sax.createStream = createStream\n\n  // When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns.\n  // When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)),\n  // since that's the earliest that a buffer overrun could occur.  This way, checks are\n  // as rare as required, but as often as necessary to ensure never crossing this bound.\n  // Furthermore, buffers are only tested at most once per write(), so passing a very\n  // large string into write() might have undesirable effects, but this is manageable by\n  // the caller, so it is assumed to be safe.  Thus, a call to write() may, in the extreme\n  // edge case, result in creating at most one complete copy of the string passed in.\n  // Set to Infinity to have unlimited buffers.\n  sax.MAX_BUFFER_LENGTH = 64 * 1024\n\n  var buffers = [\n    'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype',\n    'procInstName', 'procInstBody', 'entity', 'attribName',\n    'attribValue', 'cdata', 'script'\n  ]\n\n  sax.EVENTS = [\n    'text',\n    'processinginstruction',\n    'sgmldeclaration',\n    'doctype',\n    'comment',\n    'opentagstart',\n    'attribute',\n    'opentag',\n    'closetag',\n    'opencdata',\n    'cdata',\n    'closecdata',\n    'error',\n    'end',\n    'ready',\n    'script',\n    'opennamespace',\n    'closenamespace'\n  ]\n\n  function SAXParser (strict, opt) {\n    if (!(this instanceof SAXParser)) {\n      return new SAXParser(strict, opt)\n    }\n\n    var parser = this\n    clearBuffers(parser)\n    parser.q = parser.c = ''\n    parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH\n    parser.opt = opt || {}\n    parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags\n    parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase'\n    parser.tags = []\n    parser.closed = parser.closedRoot = parser.sawRoot = false\n    parser.tag = parser.error = null\n    parser.strict = !!strict\n    parser.noscript = !!(strict || parser.opt.noscript)\n    parser.state = S.BEGIN\n    parser.strictEntities = parser.opt.strictEntities\n    parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES)\n    parser.attribList = []\n\n    // namespaces form a prototype chain.\n    // it always points at the current tag,\n    // which protos to its parent tag.\n    if (parser.opt.xmlns) {\n      parser.ns = Object.create(rootNS)\n    }\n\n    // disallow unquoted attribute values if not otherwise configured\n    // and strict mode is true\n    if (parser.opt.unquotedAttributeValues === undefined) {\n      parser.opt.unquotedAttributeValues = !strict;\n    }\n\n    // mostly just for error reporting\n    parser.trackPosition = parser.opt.position !== false\n    if (parser.trackPosition) {\n      parser.position = parser.line = parser.column = 0\n    }\n    emit(parser, 'onready')\n  }\n\n  if (!Object.create) {\n    Object.create = function (o) {\n      function F () {}\n      F.prototype = o\n      var newf = new F()\n      return newf\n    }\n  }\n\n  if (!Object.keys) {\n    Object.keys = function (o) {\n      var a = []\n      for (var i in o) if (o.hasOwnProperty(i)) a.push(i)\n      return a\n    }\n  }\n\n  function checkBufferLength (parser) {\n    var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10)\n    var maxActual = 0\n    for (var i = 0, l = buffers.length; i < l; i++) {\n      var len = parser[buffers[i]].length\n      if (len > maxAllowed) {\n        // Text/cdata nodes can get big, and since they're buffered,\n        // we can get here under normal conditions.\n        // Avoid issues by emitting the text node now,\n        // so at least it won't get any bigger.\n        switch (buffers[i]) {\n          case 'textNode':\n            closeText(parser)\n            break\n\n          case 'cdata':\n            emitNode(parser, 'oncdata', parser.cdata)\n            parser.cdata = ''\n            break\n\n          case 'script':\n            emitNode(parser, 'onscript', parser.script)\n            parser.script = ''\n            break\n\n          default:\n            error(parser, 'Max buffer length exceeded: ' + buffers[i])\n        }\n      }\n      maxActual = Math.max(maxActual, len)\n    }\n    // schedule the next check for the earliest possible buffer overrun.\n    var m = sax.MAX_BUFFER_LENGTH - maxActual\n    parser.bufferCheckPosition = m + parser.position\n  }\n\n  function clearBuffers (parser) {\n    for (var i = 0, l = buffers.length; i < l; i++) {\n      parser[buffers[i]] = ''\n    }\n  }\n\n  function flushBuffers (parser) {\n    closeText(parser)\n    if (parser.cdata !== '') {\n      emitNode(parser, 'oncdata', parser.cdata)\n      parser.cdata = ''\n    }\n    if (parser.script !== '') {\n      emitNode(parser, 'onscript', parser.script)\n      parser.script = ''\n    }\n  }\n\n  SAXParser.prototype = {\n    end: function () { end(this) },\n    write: write,\n    resume: function () { this.error = null; return this },\n    close: function () { return this.write(null) },\n    flush: function () { flushBuffers(this) }\n  }\n\n  var Stream\n  try {\n    Stream = require('stream').Stream\n  } catch (ex) {\n    Stream = function () {}\n  }\n  if (!Stream) Stream = function () {}\n\n  var streamWraps = sax.EVENTS.filter(function (ev) {\n    return ev !== 'error' && ev !== 'end'\n  })\n\n  function createStream (strict, opt) {\n    return new SAXStream(strict, opt)\n  }\n\n  function SAXStream (strict, opt) {\n    if (!(this instanceof SAXStream)) {\n      return new SAXStream(strict, opt)\n    }\n\n    Stream.apply(this)\n\n    this._parser = new SAXParser(strict, opt)\n    this.writable = true\n    this.readable = true\n\n    var me = this\n\n    this._parser.onend = function () {\n      me.emit('end')\n    }\n\n    this._parser.onerror = function (er) {\n      me.emit('error', er)\n\n      // if didn't throw, then means error was handled.\n      // go ahead and clear error, so we can write again.\n      me._parser.error = null\n    }\n\n    this._decoder = null\n\n    streamWraps.forEach(function (ev) {\n      Object.defineProperty(me, 'on' + ev, {\n        get: function () {\n          return me._parser['on' + ev]\n        },\n        set: function (h) {\n          if (!h) {\n            me.removeAllListeners(ev)\n            me._parser['on' + ev] = h\n            return h\n          }\n          me.on(ev, h)\n        },\n        enumerable: true,\n        configurable: false\n      })\n    })\n  }\n\n  SAXStream.prototype = Object.create(Stream.prototype, {\n    constructor: {\n      value: SAXStream\n    }\n  })\n\n  SAXStream.prototype.write = function (data) {\n    if (typeof Buffer === 'function' &&\n      typeof Buffer.isBuffer === 'function' &&\n      Buffer.isBuffer(data)) {\n      if (!this._decoder) {\n        var SD = require('string_decoder').StringDecoder\n        this._decoder = new SD('utf8')\n      }\n      data = this._decoder.write(data)\n    }\n\n    this._parser.write(data.toString())\n    this.emit('data', data)\n    return true\n  }\n\n  SAXStream.prototype.end = function (chunk) {\n    if (chunk && chunk.length) {\n      this.write(chunk)\n    }\n    this._parser.end()\n    return true\n  }\n\n  SAXStream.prototype.on = function (ev, handler) {\n    var me = this\n    if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) {\n      me._parser['on' + ev] = function () {\n        var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments)\n        args.splice(0, 0, ev)\n        me.emit.apply(me, args)\n      }\n    }\n\n    return Stream.prototype.on.call(me, ev, handler)\n  }\n\n  // this really needs to be replaced with character classes.\n  // XML allows all manner of ridiculous numbers and digits.\n  var CDATA = '[CDATA['\n  var DOCTYPE = 'DOCTYPE'\n  var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'\n  var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/'\n  var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE }\n\n  // http://www.w3.org/TR/REC-xml/#NT-NameStartChar\n  // This implementation works on strings, a single character at a time\n  // as such, it cannot ever support astral-plane characters (10000-EFFFF)\n  // without a significant breaking change to either this  parser, or the\n  // JavaScript language.  Implementation of an emoji-capable xml parser\n  // is left as an exercise for the reader.\n  var nameStart = /[:_A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]/\n\n  var nameBody = /[:_A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u00B7\\u0300-\\u036F\\u203F-\\u2040.\\d-]/\n\n  var entityStart = /[#:_A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]/\n  var entityBody = /[#:_A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u00B7\\u0300-\\u036F\\u203F-\\u2040.\\d-]/\n\n  function isWhitespace (c) {\n    return c === ' ' || c === '\\n' || c === '\\r' || c === '\\t'\n  }\n\n  function isQuote (c) {\n    return c === '\"' || c === '\\''\n  }\n\n  function isAttribEnd (c) {\n    return c === '>' || isWhitespace(c)\n  }\n\n  function isMatch (regex, c) {\n    return regex.test(c)\n  }\n\n  function notMatch (regex, c) {\n    return !isMatch(regex, c)\n  }\n\n  var S = 0\n  sax.STATE = {\n    BEGIN: S++, // leading byte order mark or whitespace\n    BEGIN_WHITESPACE: S++, // leading whitespace\n    TEXT: S++, // general stuff\n    TEXT_ENTITY: S++, // & and such.\n    OPEN_WAKA: S++, // <\n    SGML_DECL: S++, // \n    SCRIPT: S++, //